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 |
|---|---|---|---|---|---|
from __future__ import absolute_import
from django.core.management import call_command
from teams.models import Team, TeamMember, Workflow
from widget.rpc import Rpc
def refresh_obj(m):
return m.__class__._default_manager.get(pk=m.pk)
def reset_solr():
# cause the default site to load
from haystack import backend
sb = backend.SearchBackend()
sb.clear()
call_command('update_index')
rpc = Rpc()
| ofer43211/unisubs | apps/teams/tests/teamstestsutils.py | Python | agpl-3.0 | 425 |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 22 09:47:41 2015
@author: thomas.douenne
"""
from __future__ import division
import statsmodels.formula.api as smf
from openfisca_france_indirect_taxation.examples.utils_example import simulate_df_calee_by_grosposte
if __name__ == '__main__':
import logging
log = logging.getLogger(__name__)
import sys
logging.basicConfig(level = logging.INFO, stream = sys.stdout)
simulated_variables = [
'pondmen',
'revtot',
'rev_disp_loyerimput',
'depenses_carburants',
'depenses_essence',
'depenses_diesel',
'strate',
'nenfants',
'nadultes',
'situacj',
'situapr',
'niveau_vie_decile'
]
for year in [2005]:
data_for_reg = simulate_df_calee_by_grosposte(simulated_variables = simulated_variables, year = year)
# In 2005 3 people consume fuel while their rev_disp_loyerimput is 0. Creates inf number in part_carburants
data_for_reg = data_for_reg[data_for_reg['rev_disp_loyerimput'] > 0]
data_for_reg['rev_disp_loyerimput_2'] = data_for_reg['rev_disp_loyerimput'] ** 2
data_for_reg['part_carburants'] = data_for_reg['depenses_carburants'] / data_for_reg['rev_disp_loyerimput']
data_for_reg['part_diesel'] = data_for_reg['depenses_diesel'] / data_for_reg['rev_disp_loyerimput']
data_for_reg['part_essence'] = data_for_reg['depenses_essence'] / data_for_reg['rev_disp_loyerimput']
data_for_reg['rural'] = 0
data_for_reg['petite_villes'] = 0
data_for_reg['villes_moyennes'] = 0
data_for_reg['grandes_villes'] = 0
data_for_reg['agglo_paris'] = 0
data_for_reg.loc[data_for_reg['strate'] == 0, 'rural'] = 1
data_for_reg.loc[data_for_reg['strate'] == 1, 'petite_villes'] = 1
data_for_reg.loc[data_for_reg['strate'] == 2, 'villes_moyennes'] = 1
data_for_reg.loc[data_for_reg['strate'] == 3, 'grandes_villes'] = 1
data_for_reg.loc[data_for_reg['strate'] == 4, 'agglo_paris'] = 1
deciles = ['decile_1', 'decile_2', 'decile_3', 'decile_4', 'decile_5', 'decile_6', 'decile_7', 'decile_8',
'decile_9', 'decile_10']
for decile in deciles:
data_for_reg[decile] = 0
number = decile.replace('decile_', '')
data_for_reg.loc[data_for_reg['niveau_vie_decile'] == int(number), decile] = 1
# Situation vis-à-vis de l'emploi :
# Travaille : emploi, stage, étudiant
# Autres : chômeurs, retraités, personnes au foyer, autres
data_for_reg['cj_travaille'] = 0
data_for_reg['pr_travaille'] = 0
data_for_reg.loc[data_for_reg['situacj'] < 4, 'cj_travaille'] = 1
data_for_reg.loc[data_for_reg['situacj'] == 0, 'cj_travaille'] = 0
data_for_reg.loc[data_for_reg['situapr'] < 4, 'pr_travaille'] = 1
data_for_reg['travaille'] = data_for_reg['cj_travaille'] + data_for_reg['pr_travaille']
regression_carburants = smf.ols(formula = 'part_carburants ~ \
decile_1 + decile_2 + decile_3 + decile_4 + decile_5 + decile_6 + decile_7 + decile_8 + decile_9 + \
rural + petite_villes + grandes_villes + agglo_paris + \
nenfants + nadultes + travaille',
data = data_for_reg).fit()
print regression_carburants.summary()
regression_diesel = smf.ols(formula = 'part_diesel ~ \
decile_1 + decile_2 + decile_3 + decile_4 + decile_5 + decile_6 + decile_7 + decile_8 + decile_9 + \
rural + petite_villes + grandes_villes + agglo_paris + \
nenfants + nadultes + travaille',
data = data_for_reg).fit()
print regression_diesel.summary()
regression_essence = smf.ols(formula = 'part_essence ~ \
decile_1 + decile_2 + decile_3 + decile_4 + decile_5 + decile_6 + decile_7 + decile_8 + decile_9 + \
rural + petite_villes + grandes_villes + agglo_paris + \
nenfants + nadultes + travaille',
data = data_for_reg).fit()
print regression_essence.summary()
# It is tempting to add a variable 'vehicule'. However, I think it is a case of bad control. It captures part
# of the effect we actually want to estimate.
| thomasdouenne/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/examples/transports/regress/regress_determinants_ticpe.py | Python | agpl-3.0 | 4,104 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2010-2014 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.systemreport;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.apache.commons.io.IOUtils;
import org.opennms.core.soa.ServiceRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SystemReport {
private static final Logger LOG = LoggerFactory.getLogger(SystemReport.class);
final static Pattern m_pattern = Pattern.compile("^-D(.*?)=(.*)$");
/**
* @param args
*/
public static void main(final String[] args) throws Exception {
final String tempdir = System.getProperty("java.io.tmpdir");
// pull out -D defines first
for (final String arg : args) {
if (arg.startsWith("-D") && arg.contains("=")) {
final Matcher m = m_pattern.matcher(arg);
if (m.matches()) {
System.setProperty(m.group(1), m.group(2));
}
}
}
if (System.getProperty("opennms.home") == null) {
System.setProperty("opennms.home", tempdir);
}
if (System.getProperty("rrd.base.dir") == null) {
System.setProperty("rrd.base.dir", tempdir);
}
if (System.getProperty("rrd.binary") == null) {
System.setProperty("rrd.binary", "/usr/bin/rrdtool");
}
final CommandLineParser parser = new PosixParser();
final Options options = new Options();
options.addOption("h", "help", false, "this help");
options.addOption("D", "define", true, "define a java property");
options.addOption("p", "list-plugins", false, "list the available system report plugins");
options.addOption("u", "use-plugins", true, "select the plugins to output");
options.addOption("l", "list-formats", false, "list the available output formats");
options.addOption("f", "format", true, "the format to output");
options.addOption("o", "output", true, "the file to write output to");
final CommandLine line = parser.parse(options, args, false);
final Set<String> plugins = new LinkedHashSet<String>();
final SystemReport report = new SystemReport();
// help
if (line.hasOption("h")) {
final HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("system-report.sh [options]", options);
System.exit(0);
}
// format and output file
if (line.hasOption("f")) {
report.setFormat(line.getOptionValue("f"));
}
if (line.hasOption("o")) {
report.setOutput(line.getOptionValue("o"));
}
if (line.hasOption("u")) {
final String value = line.getOptionValue("u");
if (value != null) {
for (final String s : value.split(",+")) {
plugins.add(s);
}
}
}
// final command
if (line.hasOption("p")) {
report.listPlugins();
} else if (line.hasOption("l")) {
report.listFormats();
} else {
report.writePluginData(plugins);
}
}
private ServiceRegistry m_serviceRegistry;
private ClassPathXmlApplicationContext m_context;
private String m_output = "-";
private String m_format = "text";
private void setOutput(final String file) {
m_output = file;
}
private void setFormat(final String format) {
m_format = format;
}
private void writePluginData(final Collection<String> plugins) {
initializeSpring();
SystemReportFormatter formatter = null;
for (final SystemReportFormatter f : getFormatters()) {
if (m_format.equals(f.getName())) {
formatter = f;
break;
}
}
if (formatter == null) {
LOG.error("Unknown format '{}'!", m_format);
System.exit(1);
}
formatter.setOutput(m_output);
OutputStream stream = null;
if (formatter.needsOutputStream()) {
if (m_output.equals("-")) {
stream = System.out;
} else {
try {
final File f = new File(m_output);
if(!f.delete()) {
LOG.warn("Could not delete file: {}", f.getPath());
}
stream = new FileOutputStream(f, false);
} catch (final FileNotFoundException e) {
LOG.error("Unable to write to '{}'", m_output, e);
System.exit(1);
}
}
if (m_output.equals("-") && !formatter.canStdout()) {
LOG.error("{} formatter does not support writing to STDOUT!", formatter.getName());
System.exit(1);
}
formatter.setOutputStream(stream);
}
final int pluginSize = plugins.size();
final Map<String,SystemReportPlugin> pluginMap = new HashMap<String,SystemReportPlugin>();
for (final SystemReportPlugin plugin : getPlugins()) {
final String name = plugin.getName();
if (pluginSize == 0) plugins.add(name);
pluginMap.put(name, plugin);
}
try {
formatter.begin();
if (stream != null) stream.flush();
for (final String pluginName : plugins) {
final SystemReportPlugin plugin = pluginMap.get(pluginName);
if (plugin == null) {
LOG.warn("No plugin named '{}' found, skipping.", pluginName);
} else {
try {
formatter.write(plugin);
} catch (final Exception e) {
LOG.error("An error occurred calling plugin '{}'", plugin.getName(), e);
}
if (stream != null) stream.flush();
}
}
formatter.end();
if (stream != null) stream.flush();
} catch (final Exception e) {
LOG.error("An error occurred writing plugin data to output.", e);
System.exit(1);
}
IOUtils.closeQuietly(stream);
}
private void listPlugins() {
for (final SystemReportPlugin plugin : getPlugins()) {
System.err.println(plugin.getName() + ": " + plugin.getDescription());
}
}
private void listFormats() {
for (final SystemReportFormatter formatter : getFormatters()) {
System.err.println(formatter.getName() + ": " + formatter.getDescription());
}
}
public List<SystemReportPlugin> getPlugins() {
initializeSpring();
final List<SystemReportPlugin> plugins = new ArrayList<SystemReportPlugin>(m_serviceRegistry.findProviders(SystemReportPlugin.class));
Collections.sort(plugins);
return plugins;
}
public List<SystemReportFormatter> getFormatters() {
initializeSpring();
final List<SystemReportFormatter> formatters = new ArrayList<SystemReportFormatter>(m_serviceRegistry.findProviders(SystemReportFormatter.class));
Collections.sort(formatters);
return formatters;
}
private void initializeSpring() {
if (m_serviceRegistry == null) {
List<String> configs = new ArrayList<String>();
configs.add("classpath:/META-INF/opennms/applicationContext-soa.xml");
configs.add("classpath:/META-INF/opennms/applicationContext-commonConfigs.xml");
configs.add("classpath:/META-INF/opennms/applicationContext-dao.xml");
configs.add("classpath*:/META-INF/opennms/component-dao.xml");
configs.add("classpath:/META-INF/opennms/applicationContext-systemReport.xml");
m_context = new ClassPathXmlApplicationContext(configs.toArray(new String[0]));
m_serviceRegistry = (ServiceRegistry) m_context.getBean("serviceRegistry");
}
}
public void setServiceRegistry(final ServiceRegistry registry) {
m_serviceRegistry = registry;
}
}
| tdefilip/opennms | features/system-report/src/main/java/org/opennms/systemreport/SystemReport.java | Java | agpl-3.0 | 10,041 |
import copy
import json
import logging
import os
import sys
from lxml import etree
from lxml.etree import Element, ElementTree, XMLParser
from xblock.core import XML_NAMESPACES
from xblock.fields import Dict, Scope, ScopeIds
from xblock.runtime import KvsFieldData
import dogstats_wrapper as dog_stats_api
from xmodule.modulestore import EdxJSONEncoder
from xmodule.modulestore.inheritance import InheritanceKeyValueStore, own_metadata
from xmodule.x_module import DEPRECATION_VSCOMPAT_EVENT, XModuleDescriptor
log = logging.getLogger(__name__)
# assume all XML files are persisted as utf-8.
EDX_XML_PARSER = XMLParser(dtd_validation=False, load_dtd=False,
remove_comments=True, remove_blank_text=True,
encoding='utf-8')
def name_to_pathname(name):
"""
Convert a location name for use in a path: replace ':' with '/'.
This allows users of the xml format to organize content into directories
"""
return name.replace(':', '/')
def is_pointer_tag(xml_obj):
"""
Check if xml_obj is a pointer tag: <blah url_name="something" />.
No children, one attribute named url_name, no text.
Special case for course roots: the pointer is
<course url_name="something" org="myorg" course="course">
xml_obj: an etree Element
Returns a bool.
"""
if xml_obj.tag != "course":
expected_attr = set(['url_name'])
else:
expected_attr = set(['url_name', 'course', 'org'])
actual_attr = set(xml_obj.attrib.keys())
has_text = xml_obj.text is not None and len(xml_obj.text.strip()) > 0
return len(xml_obj) == 0 and actual_attr == expected_attr and not has_text
def serialize_field(value):
"""
Return a string version of the value (where value is the JSON-formatted, internally stored value).
If the value is a string, then we simply return what was passed in.
Otherwise, we return json.dumps on the input value.
"""
if isinstance(value, basestring):
return value
return json.dumps(value, cls=EdxJSONEncoder)
def deserialize_field(field, value):
"""
Deserialize the string version to the value stored internally.
Note that this is not the same as the value returned by from_json, as model types typically store
their value internally as JSON. By default, this method will return the result of calling json.loads
on the supplied value, unless json.loads throws a TypeError, or the type of the value returned by json.loads
is not supported for this class (from_json throws an Error). In either of those cases, this method returns
the input value.
"""
try:
deserialized = json.loads(value)
if deserialized is None:
return deserialized
try:
field.from_json(deserialized)
return deserialized
except (ValueError, TypeError):
# Support older serialized version, which was just a string, not result of json.dumps.
# If the deserialized version cannot be converted to the type (via from_json),
# just return the original value. For example, if a string value of '3.4' was
# stored for a String field (before we started storing the result of json.dumps),
# then it would be deserialized as 3.4, but 3.4 is not supported for a String
# field. Therefore field.from_json(3.4) will throw an Error, and we should
# actually return the original value of '3.4'.
return value
except (ValueError, TypeError):
# Support older serialized version.
return value
class XmlParserMixin(object):
"""
Class containing XML parsing functionality shared between XBlock and XModuleDescriptor.
"""
# Extension to append to filename paths
filename_extension = 'xml'
xml_attributes = Dict(help="Map of unhandled xml attributes, used only for storage between import and export",
default={}, scope=Scope.settings)
# VS[compat]. Backwards compatibility code that can go away after
# importing 2012 courses.
# A set of metadata key conversions that we want to make
metadata_translations = {
'slug': 'url_name',
'name': 'display_name',
}
@classmethod
def _translate(cls, key):
"""
VS[compat]
"""
return cls.metadata_translations.get(key, key)
# The attributes will be removed from the definition xml passed
# to definition_from_xml, and from the xml returned by definition_to_xml
# Note -- url_name isn't in this list because it's handled specially on
# import and export.
metadata_to_strip = ('data_dir',
'tabs', 'grading_policy',
'discussion_blackouts',
# VS[compat] -- remove the below attrs once everything is in the CMS
'course', 'org', 'url_name', 'filename',
# Used for storing xml attributes between import and export, for roundtrips
'xml_attributes')
metadata_to_export_to_policy = ('discussion_topics',)
@staticmethod
def _get_metadata_from_xml(xml_object, remove=True):
"""
Extract the metadata from the XML.
"""
meta = xml_object.find('meta')
if meta is None:
return ''
dmdata = meta.text
if remove:
xml_object.remove(meta)
return dmdata
@classmethod
def definition_from_xml(cls, xml_object, system):
"""
Return the definition to be passed to the newly created descriptor
during from_xml
xml_object: An etree Element
"""
raise NotImplementedError("%s does not implement definition_from_xml" % cls.__name__)
@classmethod
def clean_metadata_from_xml(cls, xml_object):
"""
Remove any attribute named for a field with scope Scope.settings from the supplied
xml_object
"""
for field_name, field in cls.fields.items():
if field.scope == Scope.settings and xml_object.get(field_name) is not None:
del xml_object.attrib[field_name]
@classmethod
def file_to_xml(cls, file_object):
"""
Used when this module wants to parse a file object to xml
that will be converted to the definition.
Returns an lxml Element
"""
return etree.parse(file_object, parser=EDX_XML_PARSER).getroot()
@classmethod
def load_file(cls, filepath, fs, def_id): # pylint: disable=invalid-name
"""
Open the specified file in fs, and call cls.file_to_xml on it,
returning the lxml object.
Add details and reraise on error.
"""
try:
with fs.open(filepath) as xml_file:
return cls.file_to_xml(xml_file)
except Exception as err:
# Add info about where we are, but keep the traceback
msg = 'Unable to load file contents at path %s for item %s: %s ' % (
filepath, def_id, err)
raise Exception, msg, sys.exc_info()[2]
@classmethod
def load_definition(cls, xml_object, system, def_id, id_generator):
"""
Load a descriptor definition from the specified xml_object.
Subclasses should not need to override this except in special
cases (e.g. html module)
Args:
xml_object: an lxml.etree._Element containing the definition to load
system: the modulestore system (aka, runtime) which accesses data and provides access to services
def_id: the definition id for the block--used to compute the usage id and asides ids
id_generator: used to generate the usage_id
"""
# VS[compat] -- the filename attr should go away once everything is
# converted. (note: make sure html files still work once this goes away)
filename = xml_object.get('filename')
if filename is None:
definition_xml = copy.deepcopy(xml_object)
filepath = ''
aside_children = []
else:
dog_stats_api.increment(
DEPRECATION_VSCOMPAT_EVENT,
tags=["location:xmlparser_util_mixin_load_definition_filename"]
)
filepath = cls._format_filepath(xml_object.tag, filename)
# VS[compat]
# TODO (cpennington): If the file doesn't exist at the right path,
# give the class a chance to fix it up. The file will be written out
# again in the correct format. This should go away once the CMS is
# online and has imported all current (fall 2012) courses from xml
if not system.resources_fs.exists(filepath) and hasattr(cls, 'backcompat_paths'):
dog_stats_api.increment(
DEPRECATION_VSCOMPAT_EVENT,
tags=["location:xmlparser_util_mixin_load_definition_backcompat"]
)
candidates = cls.backcompat_paths(filepath)
for candidate in candidates:
if system.resources_fs.exists(candidate):
filepath = candidate
break
definition_xml = cls.load_file(filepath, system.resources_fs, def_id)
usage_id = id_generator.create_usage(def_id)
aside_children = system.parse_asides(definition_xml, def_id, usage_id, id_generator)
# Add the attributes from the pointer node
definition_xml.attrib.update(xml_object.attrib)
definition_metadata = cls._get_metadata_from_xml(definition_xml)
cls.clean_metadata_from_xml(definition_xml)
definition, children = cls.definition_from_xml(definition_xml, system)
if definition_metadata:
definition['definition_metadata'] = definition_metadata
definition['filename'] = [filepath, filename]
if aside_children:
definition['aside_children'] = aside_children
return definition, children
@classmethod
def load_metadata(cls, xml_object):
"""
Read the metadata attributes from this xml_object.
Returns a dictionary {key: value}.
"""
metadata = {'xml_attributes': {}}
for attr, val in xml_object.attrib.iteritems():
# VS[compat]. Remove after all key translations done
attr = cls._translate(attr)
if attr in cls.metadata_to_strip:
if attr in ('course', 'org', 'url_name', 'filename'):
dog_stats_api.increment(
DEPRECATION_VSCOMPAT_EVENT,
tags=(
"location:xmlparser_util_mixin_load_metadata",
"metadata:{}".format(attr),
)
)
# don't load these
continue
if attr not in cls.fields:
metadata['xml_attributes'][attr] = val
else:
metadata[attr] = deserialize_field(cls.fields[attr], val)
return metadata
@classmethod
def apply_policy(cls, metadata, policy):
"""
Add the keys in policy to metadata, after processing them
through the attrmap. Updates the metadata dict in place.
"""
for attr, value in policy.iteritems():
attr = cls._translate(attr)
if attr not in cls.fields:
# Store unknown attributes coming from policy.json
# in such a way that they will export to xml unchanged
metadata['xml_attributes'][attr] = value
else:
metadata[attr] = value
@classmethod
def parse_xml(cls, node, runtime, keys, id_generator): # pylint: disable=unused-argument
"""
Use `node` to construct a new block.
Arguments:
node (etree.Element): The xml node to parse into an xblock.
runtime (:class:`.Runtime`): The runtime to use while parsing.
keys (:class:`.ScopeIds`): The keys identifying where this block
will store its data.
id_generator (:class:`.IdGenerator`): An object that will allow the
runtime to generate correct definition and usage ids for
children of this block.
Returns (XBlock): The newly parsed XBlock
"""
# VS[compat] -- just have the url_name lookup, once translation is done
url_name = cls._get_url_name(node)
def_id = id_generator.create_definition(node.tag, url_name)
usage_id = id_generator.create_usage(def_id)
aside_children = []
# VS[compat] -- detect new-style each-in-a-file mode
if is_pointer_tag(node):
# new style:
# read the actual definition file--named using url_name.replace(':','/')
definition_xml, filepath = cls.load_definition_xml(node, runtime, def_id)
aside_children = runtime.parse_asides(definition_xml, def_id, usage_id, id_generator)
else:
filepath = None
definition_xml = node
dog_stats_api.increment(
DEPRECATION_VSCOMPAT_EVENT,
tags=["location:xmlparser_util_mixin_parse_xml"]
)
# Note: removes metadata.
definition, children = cls.load_definition(definition_xml, runtime, def_id, id_generator)
# VS[compat] -- make Ike's github preview links work in both old and
# new file layouts
if is_pointer_tag(node):
# new style -- contents actually at filepath
definition['filename'] = [filepath, filepath]
metadata = cls.load_metadata(definition_xml)
# move definition metadata into dict
dmdata = definition.get('definition_metadata', '')
if dmdata:
metadata['definition_metadata_raw'] = dmdata
try:
metadata.update(json.loads(dmdata))
except Exception as err:
log.debug('Error in loading metadata %r', dmdata, exc_info=True)
metadata['definition_metadata_err'] = str(err)
definition_aside_children = definition.pop('aside_children', None)
if definition_aside_children:
aside_children.extend(definition_aside_children)
# Set/override any metadata specified by policy
cls.apply_policy(metadata, runtime.get_policy(usage_id))
field_data = {}
field_data.update(metadata)
field_data.update(definition)
field_data['children'] = children
field_data['xml_attributes']['filename'] = definition.get('filename', ['', None]) # for git link
kvs = InheritanceKeyValueStore(initial_values=field_data)
field_data = KvsFieldData(kvs)
xblock = runtime.construct_xblock_from_class(
cls,
# We're loading a descriptor, so student_id is meaningless
ScopeIds(None, node.tag, def_id, usage_id),
field_data,
)
if aside_children:
asides_tags = [x.tag for x in aside_children]
asides = runtime.get_asides(xblock)
for asd in asides:
if asd.scope_ids.block_type in asides_tags:
xblock.add_aside(asd)
return xblock
@classmethod
def _get_url_name(cls, node):
"""
Reads url_name attribute from the node
"""
return node.get('url_name', node.get('slug'))
@classmethod
def load_definition_xml(cls, node, runtime, def_id):
"""
Loads definition_xml stored in a dedicated file
"""
url_name = cls._get_url_name(node)
filepath = cls._format_filepath(node.tag, name_to_pathname(url_name))
definition_xml = cls.load_file(filepath, runtime.resources_fs, def_id)
return definition_xml, filepath
@classmethod
def _format_filepath(cls, category, name):
return u'{category}/{name}.{ext}'.format(category=category,
name=name,
ext=cls.filename_extension)
def export_to_file(self):
"""If this returns True, write the definition of this descriptor to a separate
file.
NOTE: Do not override this without a good reason. It is here
specifically for customtag...
"""
return True
def add_xml_to_node(self, node):
"""
For exporting, set data on `node` from ourselves.
"""
# Get the definition
xml_object = self.definition_to_xml(self.runtime.export_fs)
for aside in self.runtime.get_asides(self):
if aside.needs_serialization():
aside_node = etree.Element("unknown_root", nsmap=XML_NAMESPACES)
aside.add_xml_to_node(aside_node)
xml_object.append(aside_node)
self.clean_metadata_from_xml(xml_object)
# Set the tag on both nodes so we get the file path right.
xml_object.tag = self.category
node.tag = self.category
# Add the non-inherited metadata
for attr in sorted(own_metadata(self)):
# don't want e.g. data_dir
if attr not in self.metadata_to_strip and attr not in self.metadata_to_export_to_policy:
val = serialize_field(self._field_data.get(self, attr))
try:
xml_object.set(attr, val)
except Exception:
logging.exception(
u'Failed to serialize metadata attribute %s with value %s in module %s. This could mean data loss!!!',
attr, val, self.url_name
)
for key, value in self.xml_attributes.items():
if key not in self.metadata_to_strip:
xml_object.set(key, serialize_field(value))
if self.export_to_file():
# Write the definition to a file
url_path = name_to_pathname(self.url_name)
filepath = self._format_filepath(self.category, url_path)
self.runtime.export_fs.makedirs(os.path.dirname(filepath), recreate=True)
with self.runtime.export_fs.open(filepath, 'wb') as fileobj:
ElementTree(xml_object).write(fileobj, pretty_print=True, encoding='utf-8')
else:
# Write all attributes from xml_object onto node
node.clear()
node.tag = xml_object.tag
node.text = xml_object.text
node.tail = xml_object.tail
node.attrib.update(xml_object.attrib)
node.extend(xml_object)
node.set('url_name', self.url_name)
# Special case for course pointers:
if self.category == 'course':
# add org and course attributes on the pointer tag
node.set('org', self.location.org)
node.set('course', self.location.course)
def definition_to_xml(self, resource_fs):
"""
Return a new etree Element object created from this modules definition.
"""
raise NotImplementedError(
"%s does not implement definition_to_xml" % self.__class__.__name__)
@property
def non_editable_metadata_fields(self):
"""
Return a list of all metadata fields that cannot be edited.
"""
non_editable_fields = super(XmlParserMixin, self).non_editable_metadata_fields
non_editable_fields.append(XmlParserMixin.xml_attributes)
return non_editable_fields
class XmlDescriptor(XmlParserMixin, XModuleDescriptor): # pylint: disable=abstract-method
"""
Mixin class for standardized parsing of XModule xml.
"""
resources_dir = None
@classmethod
def from_xml(cls, xml_data, system, id_generator):
"""
Creates an instance of this descriptor from the supplied xml_data.
This may be overridden by subclasses.
Args:
xml_data (str): A string of xml that will be translated into data and children
for this module
system (:class:`.XMLParsingSystem):
id_generator (:class:`xblock.runtime.IdGenerator`): Used to generate the
usage_ids and definition_ids when loading this xml
"""
# Shim from from_xml to the parse_xml defined in XmlParserMixin.
# This only exists to satisfy subclasses that both:
# a) define from_xml themselves
# b) call super(..).from_xml(..)
return super(XmlDescriptor, cls).parse_xml(
etree.fromstring(xml_data),
system,
None, # This is ignored by XmlParserMixin
id_generator,
)
@classmethod
def parse_xml(cls, node, runtime, keys, id_generator):
"""
Interpret the parsed XML in `node`, creating an XModuleDescriptor.
"""
if cls.from_xml != XmlDescriptor.from_xml:
# Skip the parse_xml from XmlParserMixin to get the shim parse_xml
# from XModuleDescriptor, which actually calls `from_xml`.
return super(XmlParserMixin, cls).parse_xml(node, runtime, keys, id_generator) # pylint: disable=bad-super-call
else:
return super(XmlDescriptor, cls).parse_xml(node, runtime, keys, id_generator)
def export_to_xml(self, resource_fs):
"""
Returns an xml string representing this module, and all modules
underneath it. May also write required resources out to resource_fs.
Assumes that modules have single parentage (that no module appears twice
in the same course), and that it is thus safe to nest modules as xml
children as appropriate.
The returned XML should be able to be parsed back into an identical
XModuleDescriptor using the from_xml method with the same system, org,
and course
"""
# Shim from export_to_xml to the add_xml_to_node defined in XmlParserMixin.
# This only exists to satisfy subclasses that both:
# a) define export_to_xml themselves
# b) call super(..).export_to_xml(..)
node = Element(self.category)
super(XmlDescriptor, self).add_xml_to_node(node)
return etree.tostring(node)
def add_xml_to_node(self, node):
"""
Export this :class:`XModuleDescriptor` as XML, by setting attributes on the provided
`node`.
"""
if self.export_to_xml != XmlDescriptor.export_to_xml:
# Skip the add_xml_to_node from XmlParserMixin to get the shim add_xml_to_node
# from XModuleDescriptor, which actually calls `export_to_xml`.
super(XmlParserMixin, self).add_xml_to_node(node) # pylint: disable=bad-super-call
else:
super(XmlDescriptor, self).add_xml_to_node(node)
| hastexo/edx-platform | common/lib/xmodule/xmodule/xml_module.py | Python | agpl-3.0 | 23,039 |
/*
* This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
*
* Copyright 2008-2013 Geosparc nv, http://www.geosparc.com/, Belgium.
*
* The program is available in open source according to the GNU Affero
* General Public License. All contributions in this program are covered
* by the Geomajas Contributors License Agreement. For full licensing
* details, see LICENSE.txt in the project root.
*/
package org.geomajas.gwt.client.map.event;
import org.geomajas.annotation.Api;
import org.geomajas.gwt.client.map.layer.Layer;
import com.google.gwt.event.shared.GwtEvent;
/**
* Event that reports the selection of a layer.
*
* @author Pieter De Graef
* @since 1.6.0
*/
@Api(allMethods = true)
public class LayerSelectedEvent extends GwtEvent<LayerSelectionHandler> {
private Layer<?> layer;
/**
* Constructor.
*
* @param layer selected layer
*/
public LayerSelectedEvent(Layer<?> layer) {
this.layer = layer;
}
@Override
public Type<LayerSelectionHandler> getAssociatedType() {
return LayerSelectionHandler.TYPE;
}
@Override
protected void dispatch(LayerSelectionHandler selectLayerHandler) {
selectLayerHandler.onSelectLayer(this);
}
/**
* Get selected layer.
*
* @return selected layer
*/
public Layer<?> getLayer() {
return layer;
}
}
| olivermay/geomajas | face/geomajas-face-gwt/client/src/main/java/org/geomajas/gwt/client/map/event/LayerSelectedEvent.java | Java | agpl-3.0 | 1,307 |
require=(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){
module.exports=[
{
"constant": true,
"inputs": [
{
"name": "_owner",
"type": "address"
}
],
"name": "name",
"outputs": [
{
"name": "o_name",
"type": "bytes32"
}
],
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_name",
"type": "bytes32"
}
],
"name": "owner",
"outputs": [
{
"name": "",
"type": "address"
}
],
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_name",
"type": "bytes32"
}
],
"name": "content",
"outputs": [
{
"name": "",
"type": "bytes32"
}
],
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_name",
"type": "bytes32"
}
],
"name": "addr",
"outputs": [
{
"name": "",
"type": "address"
}
],
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_name",
"type": "bytes32"
}
],
"name": "reserve",
"outputs": [],
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_name",
"type": "bytes32"
}
],
"name": "subRegistrar",
"outputs": [
{
"name": "",
"type": "address"
}
],
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_name",
"type": "bytes32"
},
{
"name": "_newOwner",
"type": "address"
}
],
"name": "transfer",
"outputs": [],
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_name",
"type": "bytes32"
},
{
"name": "_registrar",
"type": "address"
}
],
"name": "setSubRegistrar",
"outputs": [],
"type": "function"
},
{
"constant": false,
"inputs": [],
"name": "Registrar",
"outputs": [],
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_name",
"type": "bytes32"
},
{
"name": "_a",
"type": "address"
},
{
"name": "_primary",
"type": "bool"
}
],
"name": "setAddress",
"outputs": [],
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_name",
"type": "bytes32"
},
{
"name": "_content",
"type": "bytes32"
}
],
"name": "setContent",
"outputs": [],
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_name",
"type": "bytes32"
}
],
"name": "disown",
"outputs": [],
"type": "function"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "_name",
"type": "bytes32"
},
{
"indexed": false,
"name": "_winner",
"type": "address"
}
],
"name": "AuctionEnded",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "_name",
"type": "bytes32"
},
{
"indexed": false,
"name": "_bidder",
"type": "address"
},
{
"indexed": false,
"name": "_value",
"type": "uint256"
}
],
"name": "NewBid",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "name",
"type": "bytes32"
}
],
"name": "Changed",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "name",
"type": "bytes32"
},
{
"indexed": true,
"name": "addr",
"type": "address"
}
],
"name": "PrimaryChanged",
"type": "event"
}
]
},{}],2:[function(require,module,exports){
module.exports=[
{
"constant": true,
"inputs": [
{
"name": "_name",
"type": "bytes32"
}
],
"name": "owner",
"outputs": [
{
"name": "",
"type": "address"
}
],
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_name",
"type": "bytes32"
},
{
"name": "_refund",
"type": "address"
}
],
"name": "disown",
"outputs": [],
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_name",
"type": "bytes32"
}
],
"name": "addr",
"outputs": [
{
"name": "",
"type": "address"
}
],
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_name",
"type": "bytes32"
}
],
"name": "reserve",
"outputs": [],
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_name",
"type": "bytes32"
},
{
"name": "_newOwner",
"type": "address"
}
],
"name": "transfer",
"outputs": [],
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_name",
"type": "bytes32"
},
{
"name": "_a",
"type": "address"
}
],
"name": "setAddr",
"outputs": [],
"type": "function"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "name",
"type": "bytes32"
}
],
"name": "Changed",
"type": "event"
}
]
},{}],3:[function(require,module,exports){
module.exports=[
{
"constant": false,
"inputs": [
{
"name": "from",
"type": "bytes32"
},
{
"name": "to",
"type": "address"
},
{
"name": "value",
"type": "uint256"
}
],
"name": "transfer",
"outputs": [],
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "from",
"type": "bytes32"
},
{
"name": "to",
"type": "address"
},
{
"name": "indirectId",
"type": "bytes32"
},
{
"name": "value",
"type": "uint256"
}
],
"name": "icapTransfer",
"outputs": [],
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "to",
"type": "bytes32"
}
],
"name": "deposit",
"outputs": [],
"payable": true,
"type": "function"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "from",
"type": "address"
},
{
"indexed": false,
"name": "value",
"type": "uint256"
}
],
"name": "AnonymousDeposit",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "from",
"type": "address"
},
{
"indexed": true,
"name": "to",
"type": "bytes32"
},
{
"indexed": false,
"name": "value",
"type": "uint256"
}
],
"name": "Deposit",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "from",
"type": "bytes32"
},
{
"indexed": true,
"name": "to",
"type": "address"
},
{
"indexed": false,
"name": "value",
"type": "uint256"
}
],
"name": "Transfer",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "from",
"type": "bytes32"
},
{
"indexed": true,
"name": "to",
"type": "address"
},
{
"indexed": false,
"name": "indirectId",
"type": "bytes32"
},
{
"indexed": false,
"name": "value",
"type": "uint256"
}
],
"name": "IcapTransfer",
"type": "event"
}
]
},{}],4:[function(require,module,exports){
var f = require('./formatters');
var SolidityType = require('./type');
/**
* SolidityTypeAddress is a prootype that represents address type
* It matches:
* address
* address[]
* address[4]
* address[][]
* address[3][]
* address[][6][], ...
*/
var SolidityTypeAddress = function () {
this._inputFormatter = f.formatInputInt;
this._outputFormatter = f.formatOutputAddress;
};
SolidityTypeAddress.prototype = new SolidityType({});
SolidityTypeAddress.prototype.constructor = SolidityTypeAddress;
SolidityTypeAddress.prototype.isType = function (name) {
return !!name.match(/address(\[([0-9]*)\])?/);
};
module.exports = SolidityTypeAddress;
},{"./formatters":9,"./type":14}],5:[function(require,module,exports){
var f = require('./formatters');
var SolidityType = require('./type');
/**
* SolidityTypeBool is a prootype that represents bool type
* It matches:
* bool
* bool[]
* bool[4]
* bool[][]
* bool[3][]
* bool[][6][], ...
*/
var SolidityTypeBool = function () {
this._inputFormatter = f.formatInputBool;
this._outputFormatter = f.formatOutputBool;
};
SolidityTypeBool.prototype = new SolidityType({});
SolidityTypeBool.prototype.constructor = SolidityTypeBool;
SolidityTypeBool.prototype.isType = function (name) {
return !!name.match(/^bool(\[([0-9]*)\])*$/);
};
module.exports = SolidityTypeBool;
},{"./formatters":9,"./type":14}],6:[function(require,module,exports){
var f = require('./formatters');
var SolidityType = require('./type');
/**
* SolidityTypeBytes is a prototype that represents the bytes type.
* It matches:
* bytes
* bytes[]
* bytes[4]
* bytes[][]
* bytes[3][]
* bytes[][6][], ...
* bytes32
* bytes8[4]
* bytes[3][]
*/
var SolidityTypeBytes = function () {
this._inputFormatter = f.formatInputBytes;
this._outputFormatter = f.formatOutputBytes;
};
SolidityTypeBytes.prototype = new SolidityType({});
SolidityTypeBytes.prototype.constructor = SolidityTypeBytes;
SolidityTypeBytes.prototype.isType = function (name) {
return !!name.match(/^bytes([0-9]{1,})(\[([0-9]*)\])*$/);
};
module.exports = SolidityTypeBytes;
},{"./formatters":9,"./type":14}],7:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file coder.js
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
var f = require('./formatters');
var SolidityTypeAddress = require('./address');
var SolidityTypeBool = require('./bool');
var SolidityTypeInt = require('./int');
var SolidityTypeUInt = require('./uint');
var SolidityTypeDynamicBytes = require('./dynamicbytes');
var SolidityTypeString = require('./string');
var SolidityTypeReal = require('./real');
var SolidityTypeUReal = require('./ureal');
var SolidityTypeBytes = require('./bytes');
var isDynamic = function (solidityType, type) {
return solidityType.isDynamicType(type) ||
solidityType.isDynamicArray(type);
};
/**
* SolidityCoder prototype should be used to encode/decode solidity params of any type
*/
var SolidityCoder = function (types) {
this._types = types;
};
/**
* This method should be used to transform type to SolidityType
*
* @method _requireType
* @param {String} type
* @returns {SolidityType}
* @throws {Error} throws if no matching type is found
*/
SolidityCoder.prototype._requireType = function (type) {
var solidityType = this._types.filter(function (t) {
return t.isType(type);
})[0];
if (!solidityType) {
throw Error('invalid solidity type!: ' + type);
}
return solidityType;
};
/**
* Should be used to encode plain param
*
* @method encodeParam
* @param {String} type
* @param {Object} plain param
* @return {String} encoded plain param
*/
SolidityCoder.prototype.encodeParam = function (type, param) {
return this.encodeParams([type], [param]);
};
/**
* Should be used to encode list of params
*
* @method encodeParams
* @param {Array} types
* @param {Array} params
* @return {String} encoded list of params
*/
SolidityCoder.prototype.encodeParams = function (types, params) {
var solidityTypes = this.getSolidityTypes(types);
var encodeds = solidityTypes.map(function (solidityType, index) {
return solidityType.encode(params[index], types[index]);
});
var dynamicOffset = solidityTypes.reduce(function (acc, solidityType, index) {
var staticPartLength = solidityType.staticPartLength(types[index]);
var roundedStaticPartLength = Math.floor((staticPartLength + 31) / 32) * 32;
return acc + (isDynamic(solidityTypes[index], types[index]) ?
32 :
roundedStaticPartLength);
}, 0);
var result = this.encodeMultiWithOffset(types, solidityTypes, encodeds, dynamicOffset);
return result;
};
SolidityCoder.prototype.encodeMultiWithOffset = function (types, solidityTypes, encodeds, dynamicOffset) {
var result = "";
var self = this;
types.forEach(function (type, i) {
if (isDynamic(solidityTypes[i], types[i])) {
result += f.formatInputInt(dynamicOffset).encode();
var e = self.encodeWithOffset(types[i], solidityTypes[i], encodeds[i], dynamicOffset);
dynamicOffset += e.length / 2;
} else {
// don't add length to dynamicOffset. it's already counted
result += self.encodeWithOffset(types[i], solidityTypes[i], encodeds[i], dynamicOffset);
}
// TODO: figure out nested arrays
});
types.forEach(function (type, i) {
if (isDynamic(solidityTypes[i], types[i])) {
var e = self.encodeWithOffset(types[i], solidityTypes[i], encodeds[i], dynamicOffset);
dynamicOffset += e.length / 2;
result += e;
}
});
return result;
};
SolidityCoder.prototype.encodeWithOffset = function (type, solidityType, encoded, offset) {
/* jshint maxcomplexity: 17 */
/* jshint maxdepth: 5 */
var self = this;
var encodingMode={dynamic:1,static:2,other:3};
var mode=(solidityType.isDynamicArray(type)?encodingMode.dynamic:(solidityType.isStaticArray(type)?encodingMode.static:encodingMode.other));
if(mode !== encodingMode.other){
var nestedName = solidityType.nestedName(type);
var nestedStaticPartLength = solidityType.staticPartLength(nestedName);
var result = (mode === encodingMode.dynamic ? encoded[0] : '');
if (solidityType.isDynamicArray(nestedName)) {
var previousLength = (mode === encodingMode.dynamic ? 2 : 0);
for (var i = 0; i < encoded.length; i++) {
// calculate length of previous item
if(mode === encodingMode.dynamic){
previousLength += +(encoded[i - 1])[0] || 0;
}
else if(mode === encodingMode.static){
previousLength += +(encoded[i - 1] || [])[0] || 0;
}
result += f.formatInputInt(offset + i * nestedStaticPartLength + previousLength * 32).encode();
}
}
var len= (mode === encodingMode.dynamic ? encoded.length-1 : encoded.length);
for (var c = 0; c < len; c++) {
var additionalOffset = result / 2;
if(mode === encodingMode.dynamic){
result += self.encodeWithOffset(nestedName, solidityType, encoded[c + 1], offset + additionalOffset);
}
else if(mode === encodingMode.static){
result += self.encodeWithOffset(nestedName, solidityType, encoded[c], offset + additionalOffset);
}
}
return result;
}
return encoded;
};
/**
* Should be used to decode bytes to plain param
*
* @method decodeParam
* @param {String} type
* @param {String} bytes
* @return {Object} plain param
*/
SolidityCoder.prototype.decodeParam = function (type, bytes) {
return this.decodeParams([type], bytes)[0];
};
/**
* Should be used to decode list of params
*
* @method decodeParam
* @param {Array} types
* @param {String} bytes
* @return {Array} array of plain params
*/
SolidityCoder.prototype.decodeParams = function (types, bytes) {
var solidityTypes = this.getSolidityTypes(types);
var offsets = this.getOffsets(types, solidityTypes);
return solidityTypes.map(function (solidityType, index) {
return solidityType.decode(bytes, offsets[index], types[index], index);
});
};
SolidityCoder.prototype.getOffsets = function (types, solidityTypes) {
var lengths = solidityTypes.map(function (solidityType, index) {
return solidityType.staticPartLength(types[index]);
});
for (var i = 1; i < lengths.length; i++) {
// sum with length of previous element
lengths[i] += lengths[i - 1];
}
return lengths.map(function (length, index) {
// remove the current length, so the length is sum of previous elements
var staticPartLength = solidityTypes[index].staticPartLength(types[index]);
return length - staticPartLength;
});
};
SolidityCoder.prototype.getSolidityTypes = function (types) {
var self = this;
return types.map(function (type) {
return self._requireType(type);
});
};
var coder = new SolidityCoder([
new SolidityTypeAddress(),
new SolidityTypeBool(),
new SolidityTypeInt(),
new SolidityTypeUInt(),
new SolidityTypeDynamicBytes(),
new SolidityTypeBytes(),
new SolidityTypeString(),
new SolidityTypeReal(),
new SolidityTypeUReal()
]);
module.exports = coder;
},{"./address":4,"./bool":5,"./bytes":6,"./dynamicbytes":8,"./formatters":9,"./int":10,"./real":12,"./string":13,"./uint":15,"./ureal":16}],8:[function(require,module,exports){
var f = require('./formatters');
var SolidityType = require('./type');
var SolidityTypeDynamicBytes = function () {
this._inputFormatter = f.formatInputDynamicBytes;
this._outputFormatter = f.formatOutputDynamicBytes;
};
SolidityTypeDynamicBytes.prototype = new SolidityType({});
SolidityTypeDynamicBytes.prototype.constructor = SolidityTypeDynamicBytes;
SolidityTypeDynamicBytes.prototype.isType = function (name) {
return !!name.match(/^bytes(\[([0-9]*)\])*$/);
};
SolidityTypeDynamicBytes.prototype.isDynamicType = function () {
return true;
};
module.exports = SolidityTypeDynamicBytes;
},{"./formatters":9,"./type":14}],9:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file formatters.js
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
var BigNumber = require('bignumber.js');
var utils = require('../utils/utils');
var c = require('../utils/config');
var SolidityParam = require('./param');
/**
* Formats input value to byte representation of int
* If value is negative, return it's two's complement
* If the value is floating point, round it down
*
* @method formatInputInt
* @param {String|Number|BigNumber} value that needs to be formatted
* @returns {SolidityParam}
*/
var formatInputInt = function (value) {
BigNumber.config(c.ETH_BIGNUMBER_ROUNDING_MODE);
var result = utils.padLeft(utils.toTwosComplement(value).toString(16), 64);
return new SolidityParam(result);
};
/**
* Formats input bytes
*
* @method formatInputBytes
* @param {String}
* @returns {SolidityParam}
*/
var formatInputBytes = function (value) {
var result = utils.toHex(value).substr(2);
var l = Math.floor((result.length + 63) / 64);
result = utils.padRight(result, l * 64);
return new SolidityParam(result);
};
/**
* Formats input bytes
*
* @method formatDynamicInputBytes
* @param {String}
* @returns {SolidityParam}
*/
var formatInputDynamicBytes = function (value) {
var result = utils.toHex(value).substr(2);
var length = result.length / 2;
var l = Math.floor((result.length + 63) / 64);
result = utils.padRight(result, l * 64);
return new SolidityParam(formatInputInt(length).value + result);
};
/**
* Formats input value to byte representation of string
*
* @method formatInputString
* @param {String}
* @returns {SolidityParam}
*/
var formatInputString = function (value) {
var result = utils.fromUtf8(value).substr(2);
var length = result.length / 2;
var l = Math.floor((result.length + 63) / 64);
result = utils.padRight(result, l * 64);
return new SolidityParam(formatInputInt(length).value + result);
};
/**
* Formats input value to byte representation of bool
*
* @method formatInputBool
* @param {Boolean}
* @returns {SolidityParam}
*/
var formatInputBool = function (value) {
var result = '000000000000000000000000000000000000000000000000000000000000000' + (value ? '1' : '0');
return new SolidityParam(result);
};
/**
* Formats input value to byte representation of real
* Values are multiplied by 2^m and encoded as integers
*
* @method formatInputReal
* @param {String|Number|BigNumber}
* @returns {SolidityParam}
*/
var formatInputReal = function (value) {
return formatInputInt(new BigNumber(value).times(new BigNumber(2).pow(128)));
};
/**
* Check if input value is negative
*
* @method signedIsNegative
* @param {String} value is hex format
* @returns {Boolean} true if it is negative, otherwise false
*/
var signedIsNegative = function (value) {
return (new BigNumber(value.substr(0, 1), 16).toString(2).substr(0, 1)) === '1';
};
/**
* Formats right-aligned output bytes to int
*
* @method formatOutputInt
* @param {SolidityParam} param
* @returns {BigNumber} right-aligned output bytes formatted to big number
*/
var formatOutputInt = function (param) {
var value = param.staticPart() || "0";
// check if it's negative number
// it it is, return two's complement
if (signedIsNegative(value)) {
return new BigNumber(value, 16).minus(new BigNumber('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16)).minus(1);
}
return new BigNumber(value, 16);
};
/**
* Formats right-aligned output bytes to uint
*
* @method formatOutputUInt
* @param {SolidityParam}
* @returns {BigNumeber} right-aligned output bytes formatted to uint
*/
var formatOutputUInt = function (param) {
var value = param.staticPart() || "0";
return new BigNumber(value, 16);
};
/**
* Formats right-aligned output bytes to real
*
* @method formatOutputReal
* @param {SolidityParam}
* @returns {BigNumber} input bytes formatted to real
*/
var formatOutputReal = function (param) {
return formatOutputInt(param).dividedBy(new BigNumber(2).pow(128));
};
/**
* Formats right-aligned output bytes to ureal
*
* @method formatOutputUReal
* @param {SolidityParam}
* @returns {BigNumber} input bytes formatted to ureal
*/
var formatOutputUReal = function (param) {
return formatOutputUInt(param).dividedBy(new BigNumber(2).pow(128));
};
/**
* Should be used to format output bool
*
* @method formatOutputBool
* @param {SolidityParam}
* @returns {Boolean} right-aligned input bytes formatted to bool
*/
var formatOutputBool = function (param) {
return param.staticPart() === '0000000000000000000000000000000000000000000000000000000000000001' ? true : false;
};
/**
* Should be used to format output bytes
*
* @method formatOutputBytes
* @param {SolidityParam} left-aligned hex representation of string
* @param {String} name type name
* @returns {String} hex string
*/
var formatOutputBytes = function (param, name) {
var matches = name.match(/^bytes([0-9]*)/);
var size = parseInt(matches[1]);
return '0x' + param.staticPart().slice(0, 2 * size);
};
/**
* Should be used to format output bytes
*
* @method formatOutputDynamicBytes
* @param {SolidityParam} left-aligned hex representation of string
* @returns {String} hex string
*/
var formatOutputDynamicBytes = function (param) {
var length = (new BigNumber(param.dynamicPart().slice(0, 64), 16)).toNumber() * 2;
return '0x' + param.dynamicPart().substr(64, length);
};
/**
* Should be used to format output string
*
* @method formatOutputString
* @param {SolidityParam} left-aligned hex representation of string
* @returns {String} ascii string
*/
var formatOutputString = function (param) {
var length = (new BigNumber(param.dynamicPart().slice(0, 64), 16)).toNumber() * 2;
return utils.toUtf8(param.dynamicPart().substr(64, length));
};
/**
* Should be used to format output address
*
* @method formatOutputAddress
* @param {SolidityParam} right-aligned input bytes
* @returns {String} address
*/
var formatOutputAddress = function (param) {
var value = param.staticPart();
return "0x" + value.slice(value.length - 40, value.length);
};
module.exports = {
formatInputInt: formatInputInt,
formatInputBytes: formatInputBytes,
formatInputDynamicBytes: formatInputDynamicBytes,
formatInputString: formatInputString,
formatInputBool: formatInputBool,
formatInputReal: formatInputReal,
formatOutputInt: formatOutputInt,
formatOutputUInt: formatOutputUInt,
formatOutputReal: formatOutputReal,
formatOutputUReal: formatOutputUReal,
formatOutputBool: formatOutputBool,
formatOutputBytes: formatOutputBytes,
formatOutputDynamicBytes: formatOutputDynamicBytes,
formatOutputString: formatOutputString,
formatOutputAddress: formatOutputAddress
};
},{"../utils/config":18,"../utils/utils":20,"./param":11,"bignumber.js":"bignumber.js"}],10:[function(require,module,exports){
var f = require('./formatters');
var SolidityType = require('./type');
/**
* SolidityTypeInt is a prootype that represents int type
* It matches:
* int
* int[]
* int[4]
* int[][]
* int[3][]
* int[][6][], ...
* int32
* int64[]
* int8[4]
* int256[][]
* int[3][]
* int64[][6][], ...
*/
var SolidityTypeInt = function () {
this._inputFormatter = f.formatInputInt;
this._outputFormatter = f.formatOutputInt;
};
SolidityTypeInt.prototype = new SolidityType({});
SolidityTypeInt.prototype.constructor = SolidityTypeInt;
SolidityTypeInt.prototype.isType = function (name) {
return !!name.match(/^int([0-9]*)?(\[([0-9]*)\])*$/);
};
module.exports = SolidityTypeInt;
},{"./formatters":9,"./type":14}],11:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file param.js
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
var utils = require('../utils/utils');
/**
* SolidityParam object prototype.
* Should be used when encoding, decoding solidity bytes
*/
var SolidityParam = function (value, offset) {
this.value = value || '';
this.offset = offset; // offset in bytes
};
/**
* This method should be used to get length of params's dynamic part
*
* @method dynamicPartLength
* @returns {Number} length of dynamic part (in bytes)
*/
SolidityParam.prototype.dynamicPartLength = function () {
return this.dynamicPart().length / 2;
};
/**
* This method should be used to create copy of solidity param with different offset
*
* @method withOffset
* @param {Number} offset length in bytes
* @returns {SolidityParam} new solidity param with applied offset
*/
SolidityParam.prototype.withOffset = function (offset) {
return new SolidityParam(this.value, offset);
};
/**
* This method should be used to combine solidity params together
* eg. when appending an array
*
* @method combine
* @param {SolidityParam} param with which we should combine
* @param {SolidityParam} result of combination
*/
SolidityParam.prototype.combine = function (param) {
return new SolidityParam(this.value + param.value);
};
/**
* This method should be called to check if param has dynamic size.
* If it has, it returns true, otherwise false
*
* @method isDynamic
* @returns {Boolean}
*/
SolidityParam.prototype.isDynamic = function () {
return this.offset !== undefined;
};
/**
* This method should be called to transform offset to bytes
*
* @method offsetAsBytes
* @returns {String} bytes representation of offset
*/
SolidityParam.prototype.offsetAsBytes = function () {
return !this.isDynamic() ? '' : utils.padLeft(utils.toTwosComplement(this.offset).toString(16), 64);
};
/**
* This method should be called to get static part of param
*
* @method staticPart
* @returns {String} offset if it is a dynamic param, otherwise value
*/
SolidityParam.prototype.staticPart = function () {
if (!this.isDynamic()) {
return this.value;
}
return this.offsetAsBytes();
};
/**
* This method should be called to get dynamic part of param
*
* @method dynamicPart
* @returns {String} returns a value if it is a dynamic param, otherwise empty string
*/
SolidityParam.prototype.dynamicPart = function () {
return this.isDynamic() ? this.value : '';
};
/**
* This method should be called to encode param
*
* @method encode
* @returns {String}
*/
SolidityParam.prototype.encode = function () {
return this.staticPart() + this.dynamicPart();
};
/**
* This method should be called to encode array of params
*
* @method encodeList
* @param {Array[SolidityParam]} params
* @returns {String}
*/
SolidityParam.encodeList = function (params) {
// updating offsets
var totalOffset = params.length * 32;
var offsetParams = params.map(function (param) {
if (!param.isDynamic()) {
return param;
}
var offset = totalOffset;
totalOffset += param.dynamicPartLength();
return param.withOffset(offset);
});
// encode everything!
return offsetParams.reduce(function (result, param) {
return result + param.dynamicPart();
}, offsetParams.reduce(function (result, param) {
return result + param.staticPart();
}, ''));
};
module.exports = SolidityParam;
},{"../utils/utils":20}],12:[function(require,module,exports){
var f = require('./formatters');
var SolidityType = require('./type');
/**
* SolidityTypeReal is a prootype that represents real type
* It matches:
* real
* real[]
* real[4]
* real[][]
* real[3][]
* real[][6][], ...
* real32
* real64[]
* real8[4]
* real256[][]
* real[3][]
* real64[][6][], ...
*/
var SolidityTypeReal = function () {
this._inputFormatter = f.formatInputReal;
this._outputFormatter = f.formatOutputReal;
};
SolidityTypeReal.prototype = new SolidityType({});
SolidityTypeReal.prototype.constructor = SolidityTypeReal;
SolidityTypeReal.prototype.isType = function (name) {
return !!name.match(/real([0-9]*)?(\[([0-9]*)\])?/);
};
module.exports = SolidityTypeReal;
},{"./formatters":9,"./type":14}],13:[function(require,module,exports){
var f = require('./formatters');
var SolidityType = require('./type');
var SolidityTypeString = function () {
this._inputFormatter = f.formatInputString;
this._outputFormatter = f.formatOutputString;
};
SolidityTypeString.prototype = new SolidityType({});
SolidityTypeString.prototype.constructor = SolidityTypeString;
SolidityTypeString.prototype.isType = function (name) {
return !!name.match(/^string(\[([0-9]*)\])*$/);
};
SolidityTypeString.prototype.isDynamicType = function () {
return true;
};
module.exports = SolidityTypeString;
},{"./formatters":9,"./type":14}],14:[function(require,module,exports){
var f = require('./formatters');
var SolidityParam = require('./param');
/**
* SolidityType prototype is used to encode/decode solidity params of certain type
*/
var SolidityType = function (config) {
this._inputFormatter = config.inputFormatter;
this._outputFormatter = config.outputFormatter;
};
/**
* Should be used to determine if this SolidityType do match given name
*
* @method isType
* @param {String} name
* @return {Bool} true if type match this SolidityType, otherwise false
*/
SolidityType.prototype.isType = function (name) {
throw "this method should be overrwritten for type " + name;
};
/**
* Should be used to determine what is the length of static part in given type
*
* @method staticPartLength
* @param {String} name
* @return {Number} length of static part in bytes
*/
SolidityType.prototype.staticPartLength = function (name) {
// If name isn't an array then treat it like a single element array.
return (this.nestedTypes(name) || ['[1]'])
.map(function (type) {
// the length of the nested array
return parseInt(type.slice(1, -1), 10) || 1;
})
.reduce(function (previous, current) {
return previous * current;
// all basic types are 32 bytes long
}, 32);
};
/**
* Should be used to determine if type is dynamic array
* eg:
* "type[]" => true
* "type[4]" => false
*
* @method isDynamicArray
* @param {String} name
* @return {Bool} true if the type is dynamic array
*/
SolidityType.prototype.isDynamicArray = function (name) {
var nestedTypes = this.nestedTypes(name);
return !!nestedTypes && !nestedTypes[nestedTypes.length - 1].match(/[0-9]{1,}/g);
};
/**
* Should be used to determine if type is static array
* eg:
* "type[]" => false
* "type[4]" => true
*
* @method isStaticArray
* @param {String} name
* @return {Bool} true if the type is static array
*/
SolidityType.prototype.isStaticArray = function (name) {
var nestedTypes = this.nestedTypes(name);
return !!nestedTypes && !!nestedTypes[nestedTypes.length - 1].match(/[0-9]{1,}/g);
};
/**
* Should return length of static array
* eg.
* "int[32]" => 32
* "int256[14]" => 14
* "int[2][3]" => 3
* "int" => 1
* "int[1]" => 1
* "int[]" => 1
*
* @method staticArrayLength
* @param {String} name
* @return {Number} static array length
*/
SolidityType.prototype.staticArrayLength = function (name) {
var nestedTypes = this.nestedTypes(name);
if (nestedTypes) {
return parseInt(nestedTypes[nestedTypes.length - 1].match(/[0-9]{1,}/g) || 1);
}
return 1;
};
/**
* Should return nested type
* eg.
* "int[32]" => "int"
* "int256[14]" => "int256"
* "int[2][3]" => "int[2]"
* "int" => "int"
* "int[]" => "int"
*
* @method nestedName
* @param {String} name
* @return {String} nested name
*/
SolidityType.prototype.nestedName = function (name) {
// remove last [] in name
var nestedTypes = this.nestedTypes(name);
if (!nestedTypes) {
return name;
}
return name.substr(0, name.length - nestedTypes[nestedTypes.length - 1].length);
};
/**
* Should return true if type has dynamic size by default
* such types are "string", "bytes"
*
* @method isDynamicType
* @param {String} name
* @return {Bool} true if is dynamic, otherwise false
*/
SolidityType.prototype.isDynamicType = function () {
return false;
};
/**
* Should return array of nested types
* eg.
* "int[2][3][]" => ["[2]", "[3]", "[]"]
* "int[] => ["[]"]
* "int" => null
*
* @method nestedTypes
* @param {String} name
* @return {Array} array of nested types
*/
SolidityType.prototype.nestedTypes = function (name) {
// return list of strings eg. "[]", "[3]", "[]", "[2]"
return name.match(/(\[[0-9]*\])/g);
};
/**
* Should be used to encode the value
*
* @method encode
* @param {Object} value
* @param {String} name
* @return {String} encoded value
*/
SolidityType.prototype.encode = function (value, name) {
var self = this;
if (this.isDynamicArray(name)) {
return (function () {
var length = value.length; // in int
var nestedName = self.nestedName(name);
var result = [];
result.push(f.formatInputInt(length).encode());
value.forEach(function (v) {
result.push(self.encode(v, nestedName));
});
return result;
})();
} else if (this.isStaticArray(name)) {
return (function () {
var length = self.staticArrayLength(name); // in int
var nestedName = self.nestedName(name);
var result = [];
for (var i = 0; i < length; i++) {
result.push(self.encode(value[i], nestedName));
}
return result;
})();
}
return this._inputFormatter(value, name).encode();
};
/**
* Should be used to decode value from bytes
*
* @method decode
* @param {String} bytes
* @param {Number} offset in bytes
* @param {String} name type name
* @returns {Object} decoded value
*/
SolidityType.prototype.decode = function (bytes, offset, name) {
var self = this;
if (this.isDynamicArray(name)) {
return (function () {
var arrayOffset = parseInt('0x' + bytes.substr(offset * 2, 64)); // in bytes
var length = parseInt('0x' + bytes.substr(arrayOffset * 2, 64)); // in int
var arrayStart = arrayOffset + 32; // array starts after length; // in bytes
var nestedName = self.nestedName(name);
var nestedStaticPartLength = self.staticPartLength(nestedName); // in bytes
var roundedNestedStaticPartLength = Math.floor((nestedStaticPartLength + 31) / 32) * 32;
var result = [];
for (var i = 0; i < length * roundedNestedStaticPartLength; i += roundedNestedStaticPartLength) {
result.push(self.decode(bytes, arrayStart + i, nestedName));
}
return result;
})();
} else if (this.isStaticArray(name)) {
return (function () {
var length = self.staticArrayLength(name); // in int
var arrayStart = offset; // in bytes
var nestedName = self.nestedName(name);
var nestedStaticPartLength = self.staticPartLength(nestedName); // in bytes
var roundedNestedStaticPartLength = Math.floor((nestedStaticPartLength + 31) / 32) * 32;
var result = [];
for (var i = 0; i < length * roundedNestedStaticPartLength; i += roundedNestedStaticPartLength) {
result.push(self.decode(bytes, arrayStart + i, nestedName));
}
return result;
})();
} else if (this.isDynamicType(name)) {
return (function () {
var dynamicOffset = parseInt('0x' + bytes.substr(offset * 2, 64)); // in bytes
var length = parseInt('0x' + bytes.substr(dynamicOffset * 2, 64)); // in bytes
var roundedLength = Math.floor((length + 31) / 32); // in int
var param = new SolidityParam(bytes.substr(dynamicOffset * 2, ( 1 + roundedLength) * 64), 0);
return self._outputFormatter(param, name);
})();
}
var length = this.staticPartLength(name);
var param = new SolidityParam(bytes.substr(offset * 2, length * 2));
return this._outputFormatter(param, name);
};
module.exports = SolidityType;
},{"./formatters":9,"./param":11}],15:[function(require,module,exports){
var f = require('./formatters');
var SolidityType = require('./type');
/**
* SolidityTypeUInt is a prootype that represents uint type
* It matches:
* uint
* uint[]
* uint[4]
* uint[][]
* uint[3][]
* uint[][6][], ...
* uint32
* uint64[]
* uint8[4]
* uint256[][]
* uint[3][]
* uint64[][6][], ...
*/
var SolidityTypeUInt = function () {
this._inputFormatter = f.formatInputInt;
this._outputFormatter = f.formatOutputUInt;
};
SolidityTypeUInt.prototype = new SolidityType({});
SolidityTypeUInt.prototype.constructor = SolidityTypeUInt;
SolidityTypeUInt.prototype.isType = function (name) {
return !!name.match(/^uint([0-9]*)?(\[([0-9]*)\])*$/);
};
module.exports = SolidityTypeUInt;
},{"./formatters":9,"./type":14}],16:[function(require,module,exports){
var f = require('./formatters');
var SolidityType = require('./type');
/**
* SolidityTypeUReal is a prootype that represents ureal type
* It matches:
* ureal
* ureal[]
* ureal[4]
* ureal[][]
* ureal[3][]
* ureal[][6][], ...
* ureal32
* ureal64[]
* ureal8[4]
* ureal256[][]
* ureal[3][]
* ureal64[][6][], ...
*/
var SolidityTypeUReal = function () {
this._inputFormatter = f.formatInputReal;
this._outputFormatter = f.formatOutputUReal;
};
SolidityTypeUReal.prototype = new SolidityType({});
SolidityTypeUReal.prototype.constructor = SolidityTypeUReal;
SolidityTypeUReal.prototype.isType = function (name) {
return !!name.match(/^ureal([0-9]*)?(\[([0-9]*)\])*$/);
};
module.exports = SolidityTypeUReal;
},{"./formatters":9,"./type":14}],17:[function(require,module,exports){
'use strict';
// go env doesn't have and need XMLHttpRequest
if (typeof XMLHttpRequest === 'undefined') {
exports.XMLHttpRequest = {};
} else {
exports.XMLHttpRequest = XMLHttpRequest; // jshint ignore:line
}
},{}],18:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file config.js
* @authors:
* Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
/**
* Utils
*
* @module utils
*/
/**
* Utility functions
*
* @class [utils] config
* @constructor
*/
/// required to define ETH_BIGNUMBER_ROUNDING_MODE
var BigNumber = require('bignumber.js');
var ETH_UNITS = [
'wei',
'kwei',
'Mwei',
'Gwei',
'szabo',
'finney',
'femtoether',
'picoether',
'nanoether',
'microether',
'milliether',
'nano',
'micro',
'milli',
'ether',
'grand',
'Mether',
'Gether',
'Tether',
'Pether',
'Eether',
'Zether',
'Yether',
'Nether',
'Dether',
'Vether',
'Uether'
];
module.exports = {
ETH_PADDING: 32,
ETH_SIGNATURE_LENGTH: 4,
ETH_UNITS: ETH_UNITS,
ETH_BIGNUMBER_ROUNDING_MODE: { ROUNDING_MODE: BigNumber.ROUND_DOWN },
ETH_POLLING_TIMEOUT: 1000/2,
defaultBlock: 'latest',
defaultAccount: undefined
};
},{"bignumber.js":"bignumber.js"}],19:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file sha3.js
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
var CryptoJS = require('crypto-js');
var sha3 = require('crypto-js/sha3');
module.exports = function (value, options) {
if (options && options.encoding === 'hex') {
if (value.length > 2 && value.substr(0, 2) === '0x') {
value = value.substr(2);
}
value = CryptoJS.enc.Hex.parse(value);
}
return sha3(value, {
outputLength: 256
}).toString();
};
},{"crypto-js":58,"crypto-js/sha3":79}],20:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file utils.js
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
/**
* Utils
*
* @module utils
*/
/**
* Utility functions
*
* @class [utils] utils
* @constructor
*/
var BigNumber = require('bignumber.js');
var sha3 = require('./sha3.js');
var utf8 = require('utf8');
var unitMap = {
'noether': '0',
'wei': '1',
'kwei': '1000',
'Kwei': '1000',
'babbage': '1000',
'femtoether': '1000',
'mwei': '1000000',
'Mwei': '1000000',
'lovelace': '1000000',
'picoether': '1000000',
'gwei': '1000000000',
'Gwei': '1000000000',
'shannon': '1000000000',
'nanoether': '1000000000',
'nano': '1000000000',
'szabo': '1000000000000',
'microether': '1000000000000',
'micro': '1000000000000',
'finney': '1000000000000000',
'milliether': '1000000000000000',
'milli': '1000000000000000',
'ether': '1000000000000000000',
'kether': '1000000000000000000000',
'grand': '1000000000000000000000',
'mether': '1000000000000000000000000',
'gether': '1000000000000000000000000000',
'tether': '1000000000000000000000000000000'
};
/**
* Should be called to pad string to expected length
*
* @method padLeft
* @param {String} string to be padded
* @param {Number} characters that result string should have
* @param {String} sign, by default 0
* @returns {String} right aligned string
*/
var padLeft = function (string, chars, sign) {
return new Array(chars - string.length + 1).join(sign ? sign : "0") + string;
};
/**
* Should be called to pad string to expected length
*
* @method padRight
* @param {String} string to be padded
* @param {Number} characters that result string should have
* @param {String} sign, by default 0
* @returns {String} right aligned string
*/
var padRight = function (string, chars, sign) {
return string + (new Array(chars - string.length + 1).join(sign ? sign : "0"));
};
/**
* Should be called to get utf8 from it's hex representation
*
* @method toUtf8
* @param {String} string in hex
* @returns {String} ascii string representation of hex value
*/
var toUtf8 = function(hex) {
// Find termination
var str = "";
var i = 0, l = hex.length;
if (hex.substring(0, 2) === '0x') {
i = 2;
}
for (; i < l; i+=2) {
var code = parseInt(hex.substr(i, 2), 16);
if (code === 0)
break;
str += String.fromCharCode(code);
}
return utf8.decode(str);
};
/**
* Should be called to get ascii from it's hex representation
*
* @method toAscii
* @param {String} string in hex
* @returns {String} ascii string representation of hex value
*/
var toAscii = function(hex) {
// Find termination
var str = "";
var i = 0, l = hex.length;
if (hex.substring(0, 2) === '0x') {
i = 2;
}
for (; i < l; i+=2) {
var code = parseInt(hex.substr(i, 2), 16);
str += String.fromCharCode(code);
}
return str;
};
/**
* Should be called to get hex representation (prefixed by 0x) of utf8 string
*
* @method fromUtf8
* @param {String} string
* @param {Number} optional padding
* @returns {String} hex representation of input string
*/
var fromUtf8 = function(str) {
str = utf8.encode(str);
var hex = "";
for(var i = 0; i < str.length; i++) {
var code = str.charCodeAt(i);
if (code === 0)
break;
var n = code.toString(16);
hex += n.length < 2 ? '0' + n : n;
}
return "0x" + hex;
};
/**
* Should be called to get hex representation (prefixed by 0x) of ascii string
*
* @method fromAscii
* @param {String} string
* @param {Number} optional padding
* @returns {String} hex representation of input string
*/
var fromAscii = function(str) {
var hex = "";
for(var i = 0; i < str.length; i++) {
var code = str.charCodeAt(i);
var n = code.toString(16);
hex += n.length < 2 ? '0' + n : n;
}
return "0x" + hex;
};
/**
* Should be used to create full function/event name from json abi
*
* @method transformToFullName
* @param {Object} json-abi
* @return {String} full fnction/event name
*/
var transformToFullName = function (json) {
if (json.name.indexOf('(') !== -1) {
return json.name;
}
var typeName = json.inputs.map(function(i){return i.type; }).join();
return json.name + '(' + typeName + ')';
};
/**
* Should be called to get display name of contract function
*
* @method extractDisplayName
* @param {String} name of function/event
* @returns {String} display name for function/event eg. multiply(uint256) -> multiply
*/
var extractDisplayName = function (name) {
var length = name.indexOf('(');
return length !== -1 ? name.substr(0, length) : name;
};
/// @returns overloaded part of function/event name
var extractTypeName = function (name) {
/// TODO: make it invulnerable
var length = name.indexOf('(');
return length !== -1 ? name.substr(length + 1, name.length - 1 - (length + 1)).replace(' ', '') : "";
};
/**
* Converts value to it's decimal representation in string
*
* @method toDecimal
* @param {String|Number|BigNumber}
* @return {String}
*/
var toDecimal = function (value) {
return toBigNumber(value).toNumber();
};
/**
* Converts value to it's hex representation
*
* @method fromDecimal
* @param {String|Number|BigNumber}
* @return {String}
*/
var fromDecimal = function (value) {
var number = toBigNumber(value);
var result = number.toString(16);
return number.lessThan(0) ? '-0x' + result.substr(1) : '0x' + result;
};
/**
* Auto converts any given value into it's hex representation.
*
* And even stringifys objects before.
*
* @method toHex
* @param {String|Number|BigNumber|Object}
* @return {String}
*/
var toHex = function (val) {
/*jshint maxcomplexity: 8 */
if (isBoolean(val))
return fromDecimal(+val);
if (isBigNumber(val))
return fromDecimal(val);
if (typeof val === 'object')
return fromUtf8(JSON.stringify(val));
// if its a negative number, pass it through fromDecimal
if (isString(val)) {
if (val.indexOf('-0x') === 0)
return fromDecimal(val);
else if(val.indexOf('0x') === 0)
return val;
else if (!isFinite(val))
return fromAscii(val);
}
return fromDecimal(val);
};
/**
* Returns value of unit in Wei
*
* @method getValueOfUnit
* @param {String} unit the unit to convert to, default ether
* @returns {BigNumber} value of the unit (in Wei)
* @throws error if the unit is not correct:w
*/
var getValueOfUnit = function (unit) {
unit = unit ? unit.toLowerCase() : 'ether';
var unitValue = unitMap[unit];
if (unitValue === undefined) {
throw new Error('This unit doesn\'t exists, please use the one of the following units' + JSON.stringify(unitMap, null, 2));
}
return new BigNumber(unitValue, 10);
};
/**
* Takes a number of wei and converts it to any other ether unit.
*
* Possible units are:
* SI Short SI Full Effigy Other
* - kwei femtoether babbage
* - mwei picoether lovelace
* - gwei nanoether shannon nano
* - -- microether szabo micro
* - -- milliether finney milli
* - ether -- --
* - kether -- grand
* - mether
* - gether
* - tether
*
* @method fromWei
* @param {Number|String} number can be a number, number string or a HEX of a decimal
* @param {String} unit the unit to convert to, default ether
* @return {String|Object} When given a BigNumber object it returns one as well, otherwise a number
*/
var fromWei = function(number, unit) {
var returnValue = toBigNumber(number).dividedBy(getValueOfUnit(unit));
return isBigNumber(number) ? returnValue : returnValue.toString(10);
};
/**
* Takes a number of a unit and converts it to wei.
*
* Possible units are:
* SI Short SI Full Effigy Other
* - kwei femtoether babbage
* - mwei picoether lovelace
* - gwei nanoether shannon nano
* - -- microether szabo micro
* - -- microether szabo micro
* - -- milliether finney milli
* - ether -- --
* - kether -- grand
* - mether
* - gether
* - tether
*
* @method toWei
* @param {Number|String|BigNumber} number can be a number, number string or a HEX of a decimal
* @param {String} unit the unit to convert from, default ether
* @return {String|Object} When given a BigNumber object it returns one as well, otherwise a number
*/
var toWei = function(number, unit) {
var returnValue = toBigNumber(number).times(getValueOfUnit(unit));
return isBigNumber(number) ? returnValue : returnValue.toString(10);
};
/**
* Takes an input and transforms it into an bignumber
*
* @method toBigNumber
* @param {Number|String|BigNumber} a number, string, HEX string or BigNumber
* @return {BigNumber} BigNumber
*/
var toBigNumber = function(number) {
/*jshint maxcomplexity:5 */
number = number || 0;
if (isBigNumber(number))
return number;
if (isString(number) && (number.indexOf('0x') === 0 || number.indexOf('-0x') === 0)) {
return new BigNumber(number.replace('0x',''), 16);
}
return new BigNumber(number.toString(10), 10);
};
/**
* Takes and input transforms it into bignumber and if it is negative value, into two's complement
*
* @method toTwosComplement
* @param {Number|String|BigNumber}
* @return {BigNumber}
*/
var toTwosComplement = function (number) {
var bigNumber = toBigNumber(number).round();
if (bigNumber.lessThan(0)) {
return new BigNumber("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16).plus(bigNumber).plus(1);
}
return bigNumber;
};
/**
* Checks if the given string is strictly an address
*
* @method isStrictAddress
* @param {String} address the given HEX adress
* @return {Boolean}
*/
var isStrictAddress = function (address) {
return /^0x[0-9a-f]{40}$/i.test(address);
};
/**
* Checks if the given string is an address
*
* @method isAddress
* @param {String} address the given HEX adress
* @return {Boolean}
*/
var isAddress = function (address) {
if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) {
// check if it has the basic requirements of an address
return false;
} else if (/^(0x)?[0-9a-f]{40}$/.test(address) || /^(0x)?[0-9A-F]{40}$/.test(address)) {
// If it's all small caps or all all caps, return true
return true;
} else {
// Otherwise check each case
return isChecksumAddress(address);
}
};
/**
* Checks if the given string is a checksummed address
*
* @method isChecksumAddress
* @param {String} address the given HEX adress
* @return {Boolean}
*/
var isChecksumAddress = function (address) {
// Check each case
address = address.replace('0x','');
var addressHash = sha3(address.toLowerCase());
for (var i = 0; i < 40; i++ ) {
// the nth letter should be uppercase if the nth digit of casemap is 1
if ((parseInt(addressHash[i], 16) > 7 && address[i].toUpperCase() !== address[i]) || (parseInt(addressHash[i], 16) <= 7 && address[i].toLowerCase() !== address[i])) {
return false;
}
}
return true;
};
/**
* Makes a checksum address
*
* @method toChecksumAddress
* @param {String} address the given HEX adress
* @return {String}
*/
var toChecksumAddress = function (address) {
if (typeof address === 'undefined') return '';
address = address.toLowerCase().replace('0x','');
var addressHash = sha3(address);
var checksumAddress = '0x';
for (var i = 0; i < address.length; i++ ) {
// If ith character is 9 to f then make it uppercase
if (parseInt(addressHash[i], 16) > 7) {
checksumAddress += address[i].toUpperCase();
} else {
checksumAddress += address[i];
}
}
return checksumAddress;
};
/**
* Transforms given string to valid 20 bytes-length addres with 0x prefix
*
* @method toAddress
* @param {String} address
* @return {String} formatted address
*/
var toAddress = function (address) {
if (isStrictAddress(address)) {
return address;
}
if (/^[0-9a-f]{40}$/.test(address)) {
return '0x' + address;
}
return '0x' + padLeft(toHex(address).substr(2), 40);
};
/**
* Returns true if object is BigNumber, otherwise false
*
* @method isBigNumber
* @param {Object}
* @return {Boolean}
*/
var isBigNumber = function (object) {
return object instanceof BigNumber ||
(object && object.constructor && object.constructor.name === 'BigNumber');
};
/**
* Returns true if object is string, otherwise false
*
* @method isString
* @param {Object}
* @return {Boolean}
*/
var isString = function (object) {
return typeof object === 'string' ||
(object && object.constructor && object.constructor.name === 'String');
};
/**
* Returns true if object is function, otherwise false
*
* @method isFunction
* @param {Object}
* @return {Boolean}
*/
var isFunction = function (object) {
return typeof object === 'function';
};
/**
* Returns true if object is Objet, otherwise false
*
* @method isObject
* @param {Object}
* @return {Boolean}
*/
var isObject = function (object) {
return object !== null && !(Array.isArray(object)) && typeof object === 'object';
};
/**
* Returns true if object is boolean, otherwise false
*
* @method isBoolean
* @param {Object}
* @return {Boolean}
*/
var isBoolean = function (object) {
return typeof object === 'boolean';
};
/**
* Returns true if object is array, otherwise false
*
* @method isArray
* @param {Object}
* @return {Boolean}
*/
var isArray = function (object) {
return Array.isArray(object);
};
/**
* Returns true if given string is valid json object
*
* @method isJson
* @param {String}
* @return {Boolean}
*/
var isJson = function (str) {
try {
return !!JSON.parse(str);
} catch (e) {
return false;
}
};
/**
* Returns true if given string is a valid Ethereum block header bloom.
*
* @method isBloom
* @param {String} hex encoded bloom filter
* @return {Boolean}
*/
var isBloom = function (bloom) {
if (!/^(0x)?[0-9a-f]{512}$/i.test(bloom)) {
return false;
} else if (/^(0x)?[0-9a-f]{512}$/.test(bloom) || /^(0x)?[0-9A-F]{512}$/.test(bloom)) {
return true;
}
return false;
};
/**
* Returns true if given string is a valid log topic.
*
* @method isTopic
* @param {String} hex encoded topic
* @return {Boolean}
*/
var isTopic = function (topic) {
if (!/^(0x)?[0-9a-f]{64}$/i.test(topic)) {
return false;
} else if (/^(0x)?[0-9a-f]{64}$/.test(topic) || /^(0x)?[0-9A-F]{64}$/.test(topic)) {
return true;
}
return false;
};
module.exports = {
padLeft: padLeft,
padRight: padRight,
toHex: toHex,
toDecimal: toDecimal,
fromDecimal: fromDecimal,
toUtf8: toUtf8,
toAscii: toAscii,
fromUtf8: fromUtf8,
fromAscii: fromAscii,
transformToFullName: transformToFullName,
extractDisplayName: extractDisplayName,
extractTypeName: extractTypeName,
toWei: toWei,
fromWei: fromWei,
toBigNumber: toBigNumber,
toTwosComplement: toTwosComplement,
toAddress: toAddress,
isBigNumber: isBigNumber,
isStrictAddress: isStrictAddress,
isAddress: isAddress,
isChecksumAddress: isChecksumAddress,
toChecksumAddress: toChecksumAddress,
isFunction: isFunction,
isString: isString,
isObject: isObject,
isBoolean: isBoolean,
isArray: isArray,
isJson: isJson,
isBloom: isBloom,
isTopic: isTopic,
};
},{"./sha3.js":19,"bignumber.js":"bignumber.js","utf8":84}],21:[function(require,module,exports){
module.exports={
"version": "0.20.2"
}
},{}],22:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file web3.js
* @authors:
* Jeffrey Wilcke <jeff@ethdev.com>
* Marek Kotewicz <marek@ethdev.com>
* Marian Oancea <marian@ethdev.com>
* Fabian Vogelsteller <fabian@ethdev.com>
* Gav Wood <g@ethdev.com>
* @date 2014
*/
var RequestManager = require('./web3/requestmanager');
var Iban = require('./web3/iban');
var Eth = require('./web3/methods/eth');
var DB = require('./web3/methods/db');
var Shh = require('./web3/methods/shh');
var Net = require('./web3/methods/net');
var Personal = require('./web3/methods/personal');
var Swarm = require('./web3/methods/swarm');
var Settings = require('./web3/settings');
var version = require('./version.json');
var utils = require('./utils/utils');
var sha3 = require('./utils/sha3');
var extend = require('./web3/extend');
var Batch = require('./web3/batch');
var Property = require('./web3/property');
var HttpProvider = require('./web3/httpprovider');
var IpcProvider = require('./web3/ipcprovider');
var BigNumber = require('bignumber.js');
function Web3 (provider) {
this._requestManager = new RequestManager(provider);
this.currentProvider = provider;
this.eth = new Eth(this);
this.db = new DB(this);
this.shh = new Shh(this);
this.net = new Net(this);
this.personal = new Personal(this);
this.bzz = new Swarm(this);
this.settings = new Settings();
this.version = {
api: version.version
};
this.providers = {
HttpProvider: HttpProvider,
IpcProvider: IpcProvider
};
this._extend = extend(this);
this._extend({
properties: properties()
});
}
// expose providers on the class
Web3.providers = {
HttpProvider: HttpProvider,
IpcProvider: IpcProvider
};
Web3.prototype.setProvider = function (provider) {
this._requestManager.setProvider(provider);
this.currentProvider = provider;
};
Web3.prototype.reset = function (keepIsSyncing) {
this._requestManager.reset(keepIsSyncing);
this.settings = new Settings();
};
Web3.prototype.BigNumber = BigNumber;
Web3.prototype.toHex = utils.toHex;
Web3.prototype.toAscii = utils.toAscii;
Web3.prototype.toUtf8 = utils.toUtf8;
Web3.prototype.fromAscii = utils.fromAscii;
Web3.prototype.fromUtf8 = utils.fromUtf8;
Web3.prototype.toDecimal = utils.toDecimal;
Web3.prototype.fromDecimal = utils.fromDecimal;
Web3.prototype.toBigNumber = utils.toBigNumber;
Web3.prototype.toWei = utils.toWei;
Web3.prototype.fromWei = utils.fromWei;
Web3.prototype.isAddress = utils.isAddress;
Web3.prototype.isChecksumAddress = utils.isChecksumAddress;
Web3.prototype.toChecksumAddress = utils.toChecksumAddress;
Web3.prototype.isIBAN = utils.isIBAN;
Web3.prototype.padLeft = utils.padLeft;
Web3.prototype.padRight = utils.padRight;
Web3.prototype.sha3 = function(string, options) {
return '0x' + sha3(string, options);
};
/**
* Transforms direct icap to address
*/
Web3.prototype.fromICAP = function (icap) {
var iban = new Iban(icap);
return iban.address();
};
var properties = function () {
return [
new Property({
name: 'version.node',
getter: 'web3_clientVersion'
}),
new Property({
name: 'version.network',
getter: 'net_version',
inputFormatter: utils.toDecimal
}),
new Property({
name: 'version.ethereum',
getter: 'eth_protocolVersion',
inputFormatter: utils.toDecimal
}),
new Property({
name: 'version.whisper',
getter: 'shh_version',
inputFormatter: utils.toDecimal
})
];
};
Web3.prototype.isConnected = function(){
return (this.currentProvider && this.currentProvider.isConnected());
};
Web3.prototype.createBatch = function () {
return new Batch(this);
};
module.exports = Web3;
},{"./utils/sha3":19,"./utils/utils":20,"./version.json":21,"./web3/batch":24,"./web3/extend":28,"./web3/httpprovider":32,"./web3/iban":33,"./web3/ipcprovider":34,"./web3/methods/db":37,"./web3/methods/eth":38,"./web3/methods/net":39,"./web3/methods/personal":40,"./web3/methods/shh":41,"./web3/methods/swarm":42,"./web3/property":45,"./web3/requestmanager":46,"./web3/settings":47,"bignumber.js":"bignumber.js"}],23:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file allevents.js
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2014
*/
var sha3 = require('../utils/sha3');
var SolidityEvent = require('./event');
var formatters = require('./formatters');
var utils = require('../utils/utils');
var Filter = require('./filter');
var watches = require('./methods/watches');
var AllSolidityEvents = function (requestManager, json, address) {
this._requestManager = requestManager;
this._json = json;
this._address = address;
};
AllSolidityEvents.prototype.encode = function (options) {
options = options || {};
var result = {};
['fromBlock', 'toBlock'].filter(function (f) {
return options[f] !== undefined;
}).forEach(function (f) {
result[f] = formatters.inputBlockNumberFormatter(options[f]);
});
result.address = this._address;
return result;
};
AllSolidityEvents.prototype.decode = function (data) {
data.data = data.data || '';
data.topics = data.topics || [];
var eventTopic = data.topics[0].slice(2);
var match = this._json.filter(function (j) {
return eventTopic === sha3(utils.transformToFullName(j));
})[0];
if (!match) { // cannot find matching event?
console.warn('cannot find event for log');
return data;
}
var event = new SolidityEvent(this._requestManager, match, this._address);
return event.decode(data);
};
AllSolidityEvents.prototype.execute = function (options, callback) {
if (utils.isFunction(arguments[arguments.length - 1])) {
callback = arguments[arguments.length - 1];
if(arguments.length === 1)
options = null;
}
var o = this.encode(options);
var formatter = this.decode.bind(this);
return new Filter(o, 'eth', this._requestManager, watches.eth(), formatter, callback);
};
AllSolidityEvents.prototype.attachToContract = function (contract) {
var execute = this.execute.bind(this);
contract.allEvents = execute;
};
module.exports = AllSolidityEvents;
},{"../utils/sha3":19,"../utils/utils":20,"./event":27,"./filter":29,"./formatters":30,"./methods/watches":43}],24:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file batch.js
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
var Jsonrpc = require('./jsonrpc');
var errors = require('./errors');
var Batch = function (web3) {
this.requestManager = web3._requestManager;
this.requests = [];
};
/**
* Should be called to add create new request to batch request
*
* @method add
* @param {Object} jsonrpc requet object
*/
Batch.prototype.add = function (request) {
this.requests.push(request);
};
/**
* Should be called to execute batch request
*
* @method execute
*/
Batch.prototype.execute = function () {
var requests = this.requests;
this.requestManager.sendBatch(requests, function (err, results) {
results = results || [];
requests.map(function (request, index) {
return results[index] || {};
}).forEach(function (result, index) {
if (requests[index].callback) {
if (!Jsonrpc.isValidResponse(result)) {
return requests[index].callback(errors.InvalidResponse(result));
}
requests[index].callback(null, (requests[index].format ? requests[index].format(result.result) : result.result));
}
});
});
};
module.exports = Batch;
},{"./errors":26,"./jsonrpc":35}],25:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file contract.js
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2014
*/
var utils = require('../utils/utils');
var coder = require('../solidity/coder');
var SolidityEvent = require('./event');
var SolidityFunction = require('./function');
var AllEvents = require('./allevents');
/**
* Should be called to encode constructor params
*
* @method encodeConstructorParams
* @param {Array} abi
* @param {Array} constructor params
*/
var encodeConstructorParams = function (abi, params) {
return abi.filter(function (json) {
return json.type === 'constructor' && json.inputs.length === params.length;
}).map(function (json) {
return json.inputs.map(function (input) {
return input.type;
});
}).map(function (types) {
return coder.encodeParams(types, params);
})[0] || '';
};
/**
* Should be called to add functions to contract object
*
* @method addFunctionsToContract
* @param {Contract} contract
* @param {Array} abi
*/
var addFunctionsToContract = function (contract) {
contract.abi.filter(function (json) {
return json.type === 'function';
}).map(function (json) {
return new SolidityFunction(contract._eth, json, contract.address);
}).forEach(function (f) {
f.attachToContract(contract);
});
};
/**
* Should be called to add events to contract object
*
* @method addEventsToContract
* @param {Contract} contract
* @param {Array} abi
*/
var addEventsToContract = function (contract) {
var events = contract.abi.filter(function (json) {
return json.type === 'event';
});
var All = new AllEvents(contract._eth._requestManager, events, contract.address);
All.attachToContract(contract);
events.map(function (json) {
return new SolidityEvent(contract._eth._requestManager, json, contract.address);
}).forEach(function (e) {
e.attachToContract(contract);
});
};
/**
* Should be called to check if the contract gets properly deployed on the blockchain.
*
* @method checkForContractAddress
* @param {Object} contract
* @param {Function} callback
* @returns {Undefined}
*/
var checkForContractAddress = function(contract, callback){
var count = 0,
callbackFired = false;
// wait for receipt
var filter = contract._eth.filter('latest', function(e){
if (!e && !callbackFired) {
count++;
// stop watching after 50 blocks (timeout)
if (count > 50) {
filter.stopWatching(function() {});
callbackFired = true;
if (callback)
callback(new Error('Contract transaction couldn\'t be found after 50 blocks'));
else
throw new Error('Contract transaction couldn\'t be found after 50 blocks');
} else {
contract._eth.getTransactionReceipt(contract.transactionHash, function(e, receipt){
if(receipt && !callbackFired) {
contract._eth.getCode(receipt.contractAddress, function(e, code){
/*jshint maxcomplexity: 6 */
if(callbackFired || !code)
return;
filter.stopWatching(function() {});
callbackFired = true;
if(code.length > 3) {
// console.log('Contract code deployed!');
contract.address = receipt.contractAddress;
// attach events and methods again after we have
addFunctionsToContract(contract);
addEventsToContract(contract);
// call callback for the second time
if(callback)
callback(null, contract);
} else {
if(callback)
callback(new Error('The contract code couldn\'t be stored, please check your gas amount.'));
else
throw new Error('The contract code couldn\'t be stored, please check your gas amount.');
}
});
}
});
}
}
});
};
/**
* Should be called to create new ContractFactory instance
*
* @method ContractFactory
* @param {Array} abi
*/
var ContractFactory = function (eth, abi) {
this.eth = eth;
this.abi = abi;
/**
* Should be called to create new contract on a blockchain
*
* @method new
* @param {Any} contract constructor param1 (optional)
* @param {Any} contract constructor param2 (optional)
* @param {Object} contract transaction object (required)
* @param {Function} callback
* @returns {Contract} returns contract instance
*/
this.new = function () {
/*jshint maxcomplexity: 7 */
var contract = new Contract(this.eth, this.abi);
// parse arguments
var options = {}; // required!
var callback;
var args = Array.prototype.slice.call(arguments);
if (utils.isFunction(args[args.length - 1])) {
callback = args.pop();
}
var last = args[args.length - 1];
if (utils.isObject(last) && !utils.isArray(last)) {
options = args.pop();
}
if (options.value > 0) {
var constructorAbi = abi.filter(function (json) {
return json.type === 'constructor' && json.inputs.length === args.length;
})[0] || {};
if (!constructorAbi.payable) {
throw new Error('Cannot send value to non-payable constructor');
}
}
var bytes = encodeConstructorParams(this.abi, args);
options.data += bytes;
if (callback) {
// wait for the contract address adn check if the code was deployed
this.eth.sendTransaction(options, function (err, hash) {
if (err) {
callback(err);
} else {
// add the transaction hash
contract.transactionHash = hash;
// call callback for the first time
callback(null, contract);
checkForContractAddress(contract, callback);
}
});
} else {
var hash = this.eth.sendTransaction(options);
// add the transaction hash
contract.transactionHash = hash;
checkForContractAddress(contract);
}
return contract;
};
this.new.getData = this.getData.bind(this);
};
/**
* Should be called to create new ContractFactory
*
* @method contract
* @param {Array} abi
* @returns {ContractFactory} new contract factory
*/
//var contract = function (abi) {
//return new ContractFactory(abi);
//};
/**
* Should be called to get access to existing contract on a blockchain
*
* @method at
* @param {Address} contract address (required)
* @param {Function} callback {optional)
* @returns {Contract} returns contract if no callback was passed,
* otherwise calls callback function (err, contract)
*/
ContractFactory.prototype.at = function (address, callback) {
var contract = new Contract(this.eth, this.abi, address);
// this functions are not part of prototype,
// because we dont want to spoil the interface
addFunctionsToContract(contract);
addEventsToContract(contract);
if (callback) {
callback(null, contract);
}
return contract;
};
/**
* Gets the data, which is data to deploy plus constructor params
*
* @method getData
*/
ContractFactory.prototype.getData = function () {
var options = {}; // required!
var args = Array.prototype.slice.call(arguments);
var last = args[args.length - 1];
if (utils.isObject(last) && !utils.isArray(last)) {
options = args.pop();
}
var bytes = encodeConstructorParams(this.abi, args);
options.data += bytes;
return options.data;
};
/**
* Should be called to create new contract instance
*
* @method Contract
* @param {Array} abi
* @param {Address} contract address
*/
var Contract = function (eth, abi, address) {
this._eth = eth;
this.transactionHash = null;
this.address = address;
this.abi = abi;
};
module.exports = ContractFactory;
},{"../solidity/coder":7,"../utils/utils":20,"./allevents":23,"./event":27,"./function":31}],26:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file errors.js
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
module.exports = {
InvalidNumberOfSolidityArgs: function () {
return new Error('Invalid number of arguments to Solidity function');
},
InvalidNumberOfRPCParams: function () {
return new Error('Invalid number of input parameters to RPC method');
},
InvalidConnection: function (host){
return new Error('CONNECTION ERROR: Couldn\'t connect to node '+ host +'.');
},
InvalidProvider: function () {
return new Error('Provider not set or invalid');
},
InvalidResponse: function (result){
var message = !!result && !!result.error && !!result.error.message ? result.error.message : 'Invalid JSON RPC response: ' + JSON.stringify(result);
return new Error(message);
},
ConnectionTimeout: function (ms){
return new Error('CONNECTION TIMEOUT: timeout of ' + ms + ' ms achived');
}
};
},{}],27:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file event.js
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2014
*/
var utils = require('../utils/utils');
var coder = require('../solidity/coder');
var formatters = require('./formatters');
var sha3 = require('../utils/sha3');
var Filter = require('./filter');
var watches = require('./methods/watches');
/**
* This prototype should be used to create event filters
*/
var SolidityEvent = function (requestManager, json, address) {
this._requestManager = requestManager;
this._params = json.inputs;
this._name = utils.transformToFullName(json);
this._address = address;
this._anonymous = json.anonymous;
};
/**
* Should be used to get filtered param types
*
* @method types
* @param {Bool} decide if returned typed should be indexed
* @return {Array} array of types
*/
SolidityEvent.prototype.types = function (indexed) {
return this._params.filter(function (i) {
return i.indexed === indexed;
}).map(function (i) {
return i.type;
});
};
/**
* Should be used to get event display name
*
* @method displayName
* @return {String} event display name
*/
SolidityEvent.prototype.displayName = function () {
return utils.extractDisplayName(this._name);
};
/**
* Should be used to get event type name
*
* @method typeName
* @return {String} event type name
*/
SolidityEvent.prototype.typeName = function () {
return utils.extractTypeName(this._name);
};
/**
* Should be used to get event signature
*
* @method signature
* @return {String} event signature
*/
SolidityEvent.prototype.signature = function () {
return sha3(this._name);
};
/**
* Should be used to encode indexed params and options to one final object
*
* @method encode
* @param {Object} indexed
* @param {Object} options
* @return {Object} everything combined together and encoded
*/
SolidityEvent.prototype.encode = function (indexed, options) {
indexed = indexed || {};
options = options || {};
var result = {};
['fromBlock', 'toBlock'].filter(function (f) {
return options[f] !== undefined;
}).forEach(function (f) {
result[f] = formatters.inputBlockNumberFormatter(options[f]);
});
result.topics = [];
result.address = this._address;
if (!this._anonymous) {
result.topics.push('0x' + this.signature());
}
var indexedTopics = this._params.filter(function (i) {
return i.indexed === true;
}).map(function (i) {
var value = indexed[i.name];
if (value === undefined || value === null) {
return null;
}
if (utils.isArray(value)) {
return value.map(function (v) {
return '0x' + coder.encodeParam(i.type, v);
});
}
return '0x' + coder.encodeParam(i.type, value);
});
result.topics = result.topics.concat(indexedTopics);
return result;
};
/**
* Should be used to decode indexed params and options
*
* @method decode
* @param {Object} data
* @return {Object} result object with decoded indexed && not indexed params
*/
SolidityEvent.prototype.decode = function (data) {
data.data = data.data || '';
data.topics = data.topics || [];
var argTopics = this._anonymous ? data.topics : data.topics.slice(1);
var indexedData = argTopics.map(function (topics) { return topics.slice(2); }).join("");
var indexedParams = coder.decodeParams(this.types(true), indexedData);
var notIndexedData = data.data.slice(2);
var notIndexedParams = coder.decodeParams(this.types(false), notIndexedData);
var result = formatters.outputLogFormatter(data);
result.event = this.displayName();
result.address = data.address;
result.args = this._params.reduce(function (acc, current) {
acc[current.name] = current.indexed ? indexedParams.shift() : notIndexedParams.shift();
return acc;
}, {});
delete result.data;
delete result.topics;
return result;
};
/**
* Should be used to create new filter object from event
*
* @method execute
* @param {Object} indexed
* @param {Object} options
* @return {Object} filter object
*/
SolidityEvent.prototype.execute = function (indexed, options, callback) {
if (utils.isFunction(arguments[arguments.length - 1])) {
callback = arguments[arguments.length - 1];
if(arguments.length === 2)
options = null;
if(arguments.length === 1) {
options = null;
indexed = {};
}
}
var o = this.encode(indexed, options);
var formatter = this.decode.bind(this);
return new Filter(o, 'eth', this._requestManager, watches.eth(), formatter, callback);
};
/**
* Should be used to attach event to contract object
*
* @method attachToContract
* @param {Contract}
*/
SolidityEvent.prototype.attachToContract = function (contract) {
var execute = this.execute.bind(this);
var displayName = this.displayName();
if (!contract[displayName]) {
contract[displayName] = execute;
}
contract[displayName][this.typeName()] = this.execute.bind(this, contract);
};
module.exports = SolidityEvent;
},{"../solidity/coder":7,"../utils/sha3":19,"../utils/utils":20,"./filter":29,"./formatters":30,"./methods/watches":43}],28:[function(require,module,exports){
var formatters = require('./formatters');
var utils = require('./../utils/utils');
var Method = require('./method');
var Property = require('./property');
// TODO: refactor, so the input params are not altered.
// it's necessary to make same 'extension' work with multiple providers
var extend = function (web3) {
/* jshint maxcomplexity:5 */
var ex = function (extension) {
var extendedObject;
if (extension.property) {
if (!web3[extension.property]) {
web3[extension.property] = {};
}
extendedObject = web3[extension.property];
} else {
extendedObject = web3;
}
if (extension.methods) {
extension.methods.forEach(function (method) {
method.attachToObject(extendedObject);
method.setRequestManager(web3._requestManager);
});
}
if (extension.properties) {
extension.properties.forEach(function (property) {
property.attachToObject(extendedObject);
property.setRequestManager(web3._requestManager);
});
}
};
ex.formatters = formatters;
ex.utils = utils;
ex.Method = Method;
ex.Property = Property;
return ex;
};
module.exports = extend;
},{"./../utils/utils":20,"./formatters":30,"./method":36,"./property":45}],29:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file filter.js
* @authors:
* Jeffrey Wilcke <jeff@ethdev.com>
* Marek Kotewicz <marek@ethdev.com>
* Marian Oancea <marian@ethdev.com>
* Fabian Vogelsteller <fabian@ethdev.com>
* Gav Wood <g@ethdev.com>
* @date 2014
*/
var formatters = require('./formatters');
var utils = require('../utils/utils');
/**
* Converts a given topic to a hex string, but also allows null values.
*
* @param {Mixed} value
* @return {String}
*/
var toTopic = function(value){
if(value === null || typeof value === 'undefined')
return null;
value = String(value);
if(value.indexOf('0x') === 0)
return value;
else
return utils.fromUtf8(value);
};
/// This method should be called on options object, to verify deprecated properties && lazy load dynamic ones
/// @param should be string or object
/// @returns options string or object
var getOptions = function (options, type) {
/*jshint maxcomplexity: 6 */
if (utils.isString(options)) {
return options;
}
options = options || {};
switch(type) {
case 'eth':
// make sure topics, get converted to hex
options.topics = options.topics || [];
options.topics = options.topics.map(function(topic){
return (utils.isArray(topic)) ? topic.map(toTopic) : toTopic(topic);
});
return {
topics: options.topics,
from: options.from,
to: options.to,
address: options.address,
fromBlock: formatters.inputBlockNumberFormatter(options.fromBlock),
toBlock: formatters.inputBlockNumberFormatter(options.toBlock)
};
case 'shh':
return options;
}
};
/**
Adds the callback and sets up the methods, to iterate over the results.
@method getLogsAtStart
@param {Object} self
@param {function} callback
*/
var getLogsAtStart = function(self, callback){
// call getFilterLogs for the first watch callback start
if (!utils.isString(self.options)) {
self.get(function (err, messages) {
// don't send all the responses to all the watches again... just to self one
if (err) {
callback(err);
}
if(utils.isArray(messages)) {
messages.forEach(function (message) {
callback(null, message);
});
}
});
}
};
/**
Adds the callback and sets up the methods, to iterate over the results.
@method pollFilter
@param {Object} self
*/
var pollFilter = function(self) {
var onMessage = function (error, messages) {
if (error) {
return self.callbacks.forEach(function (callback) {
callback(error);
});
}
if(utils.isArray(messages)) {
messages.forEach(function (message) {
message = self.formatter ? self.formatter(message) : message;
self.callbacks.forEach(function (callback) {
callback(null, message);
});
});
}
};
self.requestManager.startPolling({
method: self.implementation.poll.call,
params: [self.filterId],
}, self.filterId, onMessage, self.stopWatching.bind(self));
};
var Filter = function (options, type, requestManager, methods, formatter, callback, filterCreationErrorCallback) {
var self = this;
var implementation = {};
methods.forEach(function (method) {
method.setRequestManager(requestManager);
method.attachToObject(implementation);
});
this.requestManager = requestManager;
this.options = getOptions(options, type);
this.implementation = implementation;
this.filterId = null;
this.callbacks = [];
this.getLogsCallbacks = [];
this.pollFilters = [];
this.formatter = formatter;
this.implementation.newFilter(this.options, function(error, id){
if(error) {
self.callbacks.forEach(function(cb){
cb(error);
});
if (typeof filterCreationErrorCallback === 'function') {
filterCreationErrorCallback(error);
}
} else {
self.filterId = id;
// check if there are get pending callbacks as a consequence
// of calling get() with filterId unassigned.
self.getLogsCallbacks.forEach(function (cb){
self.get(cb);
});
self.getLogsCallbacks = [];
// get filter logs for the already existing watch calls
self.callbacks.forEach(function(cb){
getLogsAtStart(self, cb);
});
if(self.callbacks.length > 0)
pollFilter(self);
// start to watch immediately
if(typeof callback === 'function') {
return self.watch(callback);
}
}
});
return this;
};
Filter.prototype.watch = function (callback) {
this.callbacks.push(callback);
if(this.filterId) {
getLogsAtStart(this, callback);
pollFilter(this);
}
return this;
};
Filter.prototype.stopWatching = function (callback) {
this.requestManager.stopPolling(this.filterId);
this.callbacks = [];
// remove filter async
if (callback) {
this.implementation.uninstallFilter(this.filterId, callback);
} else {
return this.implementation.uninstallFilter(this.filterId);
}
};
Filter.prototype.get = function (callback) {
var self = this;
if (utils.isFunction(callback)) {
if (this.filterId === null) {
// If filterId is not set yet, call it back
// when newFilter() assigns it.
this.getLogsCallbacks.push(callback);
} else {
this.implementation.getLogs(this.filterId, function(err, res){
if (err) {
callback(err);
} else {
callback(null, res.map(function (log) {
return self.formatter ? self.formatter(log) : log;
}));
}
});
}
} else {
if (this.filterId === null) {
throw new Error('Filter ID Error: filter().get() can\'t be chained synchronous, please provide a callback for the get() method.');
}
var logs = this.implementation.getLogs(this.filterId);
return logs.map(function (log) {
return self.formatter ? self.formatter(log) : log;
});
}
return this;
};
module.exports = Filter;
},{"../utils/utils":20,"./formatters":30}],30:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file formatters.js
* @author Marek Kotewicz <marek@ethdev.com>
* @author Fabian Vogelsteller <fabian@ethdev.com>
* @date 2015
*/
'use strict';
var utils = require('../utils/utils');
var config = require('../utils/config');
var Iban = require('./iban');
/**
* Should the format output to a big number
*
* @method outputBigNumberFormatter
* @param {String|Number|BigNumber}
* @returns {BigNumber} object
*/
var outputBigNumberFormatter = function (number) {
return utils.toBigNumber(number);
};
var isPredefinedBlockNumber = function (blockNumber) {
return blockNumber === 'latest' || blockNumber === 'pending' || blockNumber === 'earliest';
};
var inputDefaultBlockNumberFormatter = function (blockNumber) {
if (blockNumber === undefined) {
return config.defaultBlock;
}
return inputBlockNumberFormatter(blockNumber);
};
var inputBlockNumberFormatter = function (blockNumber) {
if (blockNumber === undefined) {
return undefined;
} else if (isPredefinedBlockNumber(blockNumber)) {
return blockNumber;
}
return utils.toHex(blockNumber);
};
/**
* Formats the input of a transaction and converts all values to HEX
*
* @method inputCallFormatter
* @param {Object} transaction options
* @returns object
*/
var inputCallFormatter = function (options){
options.from = options.from || config.defaultAccount;
if (options.from) {
options.from = inputAddressFormatter(options.from);
}
if (options.to) { // it might be contract creation
options.to = inputAddressFormatter(options.to);
}
['gasPrice', 'gas', 'value', 'nonce'].filter(function (key) {
return options[key] !== undefined;
}).forEach(function(key){
options[key] = utils.fromDecimal(options[key]);
});
return options;
};
/**
* Formats the input of a transaction and converts all values to HEX
*
* @method inputTransactionFormatter
* @param {Object} transaction options
* @returns object
*/
var inputTransactionFormatter = function (options){
options.from = options.from || config.defaultAccount;
options.from = inputAddressFormatter(options.from);
if (options.to) { // it might be contract creation
options.to = inputAddressFormatter(options.to);
}
['gasPrice', 'gas', 'value', 'nonce'].filter(function (key) {
return options[key] !== undefined;
}).forEach(function(key){
options[key] = utils.fromDecimal(options[key]);
});
return options;
};
/**
* Formats the output of a transaction to its proper values
*
* @method outputTransactionFormatter
* @param {Object} tx
* @returns {Object}
*/
var outputTransactionFormatter = function (tx){
if(tx.blockNumber !== null)
tx.blockNumber = utils.toDecimal(tx.blockNumber);
if(tx.transactionIndex !== null)
tx.transactionIndex = utils.toDecimal(tx.transactionIndex);
tx.nonce = utils.toDecimal(tx.nonce);
tx.gas = utils.toDecimal(tx.gas);
tx.gasPrice = utils.toBigNumber(tx.gasPrice);
tx.value = utils.toBigNumber(tx.value);
return tx;
};
/**
* Formats the output of a transaction receipt to its proper values
*
* @method outputTransactionReceiptFormatter
* @param {Object} receipt
* @returns {Object}
*/
var outputTransactionReceiptFormatter = function (receipt){
if(receipt.blockNumber !== null)
receipt.blockNumber = utils.toDecimal(receipt.blockNumber);
if(receipt.transactionIndex !== null)
receipt.transactionIndex = utils.toDecimal(receipt.transactionIndex);
receipt.cumulativeGasUsed = utils.toDecimal(receipt.cumulativeGasUsed);
receipt.gasUsed = utils.toDecimal(receipt.gasUsed);
if(utils.isArray(receipt.logs)) {
receipt.logs = receipt.logs.map(function(log){
return outputLogFormatter(log);
});
}
return receipt;
};
/**
* Formats the output of a block to its proper values
*
* @method outputBlockFormatter
* @param {Object} block
* @returns {Object}
*/
var outputBlockFormatter = function(block) {
// transform to number
block.gasLimit = utils.toDecimal(block.gasLimit);
block.gasUsed = utils.toDecimal(block.gasUsed);
block.size = utils.toDecimal(block.size);
block.timestamp = utils.toDecimal(block.timestamp);
if(block.number !== null)
block.number = utils.toDecimal(block.number);
block.difficulty = utils.toBigNumber(block.difficulty);
block.totalDifficulty = utils.toBigNumber(block.totalDifficulty);
if (utils.isArray(block.transactions)) {
block.transactions.forEach(function(item){
if(!utils.isString(item))
return outputTransactionFormatter(item);
});
}
return block;
};
/**
* Formats the output of a log
*
* @method outputLogFormatter
* @param {Object} log object
* @returns {Object} log
*/
var outputLogFormatter = function(log) {
if(log.blockNumber)
log.blockNumber = utils.toDecimal(log.blockNumber);
if(log.transactionIndex)
log.transactionIndex = utils.toDecimal(log.transactionIndex);
if(log.logIndex)
log.logIndex = utils.toDecimal(log.logIndex);
return log;
};
/**
* Formats the input of a whisper post and converts all values to HEX
*
* @method inputPostFormatter
* @param {Object} transaction object
* @returns {Object}
*/
var inputPostFormatter = function(post) {
// post.payload = utils.toHex(post.payload);
post.ttl = utils.fromDecimal(post.ttl);
post.workToProve = utils.fromDecimal(post.workToProve);
post.priority = utils.fromDecimal(post.priority);
// fallback
if (!utils.isArray(post.topics)) {
post.topics = post.topics ? [post.topics] : [];
}
// format the following options
post.topics = post.topics.map(function(topic){
// convert only if not hex
return (topic.indexOf('0x') === 0) ? topic : utils.fromUtf8(topic);
});
return post;
};
/**
* Formats the output of a received post message
*
* @method outputPostFormatter
* @param {Object}
* @returns {Object}
*/
var outputPostFormatter = function(post){
post.expiry = utils.toDecimal(post.expiry);
post.sent = utils.toDecimal(post.sent);
post.ttl = utils.toDecimal(post.ttl);
post.workProved = utils.toDecimal(post.workProved);
// post.payloadRaw = post.payload;
// post.payload = utils.toAscii(post.payload);
// if (utils.isJson(post.payload)) {
// post.payload = JSON.parse(post.payload);
// }
// format the following options
if (!post.topics) {
post.topics = [];
}
post.topics = post.topics.map(function(topic){
return utils.toAscii(topic);
});
return post;
};
var inputAddressFormatter = function (address) {
var iban = new Iban(address);
if (iban.isValid() && iban.isDirect()) {
return '0x' + iban.address();
} else if (utils.isStrictAddress(address)) {
return address;
} else if (utils.isAddress(address)) {
return '0x' + address;
}
throw new Error('invalid address');
};
var outputSyncingFormatter = function(result) {
if (!result) {
return result;
}
result.startingBlock = utils.toDecimal(result.startingBlock);
result.currentBlock = utils.toDecimal(result.currentBlock);
result.highestBlock = utils.toDecimal(result.highestBlock);
if (result.knownStates) {
result.knownStates = utils.toDecimal(result.knownStates);
result.pulledStates = utils.toDecimal(result.pulledStates);
}
return result;
};
module.exports = {
inputDefaultBlockNumberFormatter: inputDefaultBlockNumberFormatter,
inputBlockNumberFormatter: inputBlockNumberFormatter,
inputCallFormatter: inputCallFormatter,
inputTransactionFormatter: inputTransactionFormatter,
inputAddressFormatter: inputAddressFormatter,
inputPostFormatter: inputPostFormatter,
outputBigNumberFormatter: outputBigNumberFormatter,
outputTransactionFormatter: outputTransactionFormatter,
outputTransactionReceiptFormatter: outputTransactionReceiptFormatter,
outputBlockFormatter: outputBlockFormatter,
outputLogFormatter: outputLogFormatter,
outputPostFormatter: outputPostFormatter,
outputSyncingFormatter: outputSyncingFormatter
};
},{"../utils/config":18,"../utils/utils":20,"./iban":33}],31:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file function.js
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
var coder = require('../solidity/coder');
var utils = require('../utils/utils');
var errors = require('./errors');
var formatters = require('./formatters');
var sha3 = require('../utils/sha3');
/**
* This prototype should be used to call/sendTransaction to solidity functions
*/
var SolidityFunction = function (eth, json, address) {
this._eth = eth;
this._inputTypes = json.inputs.map(function (i) {
return i.type;
});
this._outputTypes = json.outputs.map(function (i) {
return i.type;
});
this._constant = json.constant;
this._payable = json.payable;
this._name = utils.transformToFullName(json);
this._address = address;
};
SolidityFunction.prototype.extractCallback = function (args) {
if (utils.isFunction(args[args.length - 1])) {
return args.pop(); // modify the args array!
}
};
SolidityFunction.prototype.extractDefaultBlock = function (args) {
if (args.length > this._inputTypes.length && !utils.isObject(args[args.length -1])) {
return formatters.inputDefaultBlockNumberFormatter(args.pop()); // modify the args array!
}
};
/**
* Should be called to check if the number of arguments is correct
*
* @method validateArgs
* @param {Array} arguments
* @throws {Error} if it is not
*/
SolidityFunction.prototype.validateArgs = function (args) {
var inputArgs = args.filter(function (a) {
// filter the options object but not arguments that are arrays
return !( (utils.isObject(a) === true) &&
(utils.isArray(a) === false) &&
(utils.isBigNumber(a) === false)
);
});
if (inputArgs.length !== this._inputTypes.length) {
throw errors.InvalidNumberOfSolidityArgs();
}
};
/**
* Should be used to create payload from arguments
*
* @method toPayload
* @param {Array} solidity function params
* @param {Object} optional payload options
*/
SolidityFunction.prototype.toPayload = function (args) {
var options = {};
if (args.length > this._inputTypes.length && utils.isObject(args[args.length -1])) {
options = args[args.length - 1];
}
this.validateArgs(args);
options.to = this._address;
options.data = '0x' + this.signature() + coder.encodeParams(this._inputTypes, args);
return options;
};
/**
* Should be used to get function signature
*
* @method signature
* @return {String} function signature
*/
SolidityFunction.prototype.signature = function () {
return sha3(this._name).slice(0, 8);
};
SolidityFunction.prototype.unpackOutput = function (output) {
if (!output) {
return;
}
output = output.length >= 2 ? output.slice(2) : output;
var result = coder.decodeParams(this._outputTypes, output);
return result.length === 1 ? result[0] : result;
};
/**
* Calls a contract function.
*
* @method call
* @param {...Object} Contract function arguments
* @param {function} If the last argument is a function, the contract function
* call will be asynchronous, and the callback will be passed the
* error and result.
* @return {String} output bytes
*/
SolidityFunction.prototype.call = function () {
var args = Array.prototype.slice.call(arguments).filter(function (a) {return a !== undefined; });
var callback = this.extractCallback(args);
var defaultBlock = this.extractDefaultBlock(args);
var payload = this.toPayload(args);
if (!callback) {
var output = this._eth.call(payload, defaultBlock);
return this.unpackOutput(output);
}
var self = this;
this._eth.call(payload, defaultBlock, function (error, output) {
if (error) return callback(error, null);
var unpacked = null;
try {
unpacked = self.unpackOutput(output);
}
catch (e) {
error = e;
}
callback(error, unpacked);
});
};
/**
* Should be used to sendTransaction to solidity function
*
* @method sendTransaction
*/
SolidityFunction.prototype.sendTransaction = function () {
var args = Array.prototype.slice.call(arguments).filter(function (a) {return a !== undefined; });
var callback = this.extractCallback(args);
var payload = this.toPayload(args);
if (payload.value > 0 && !this._payable) {
throw new Error('Cannot send value to non-payable function');
}
if (!callback) {
return this._eth.sendTransaction(payload);
}
this._eth.sendTransaction(payload, callback);
};
/**
* Should be used to estimateGas of solidity function
*
* @method estimateGas
*/
SolidityFunction.prototype.estimateGas = function () {
var args = Array.prototype.slice.call(arguments);
var callback = this.extractCallback(args);
var payload = this.toPayload(args);
if (!callback) {
return this._eth.estimateGas(payload);
}
this._eth.estimateGas(payload, callback);
};
/**
* Return the encoded data of the call
*
* @method getData
* @return {String} the encoded data
*/
SolidityFunction.prototype.getData = function () {
var args = Array.prototype.slice.call(arguments);
var payload = this.toPayload(args);
return payload.data;
};
/**
* Should be used to get function display name
*
* @method displayName
* @return {String} display name of the function
*/
SolidityFunction.prototype.displayName = function () {
return utils.extractDisplayName(this._name);
};
/**
* Should be used to get function type name
*
* @method typeName
* @return {String} type name of the function
*/
SolidityFunction.prototype.typeName = function () {
return utils.extractTypeName(this._name);
};
/**
* Should be called to get rpc requests from solidity function
*
* @method request
* @returns {Object}
*/
SolidityFunction.prototype.request = function () {
var args = Array.prototype.slice.call(arguments);
var callback = this.extractCallback(args);
var payload = this.toPayload(args);
var format = this.unpackOutput.bind(this);
return {
method: this._constant ? 'eth_call' : 'eth_sendTransaction',
callback: callback,
params: [payload],
format: format
};
};
/**
* Should be called to execute function
*
* @method execute
*/
SolidityFunction.prototype.execute = function () {
var transaction = !this._constant;
// send transaction
if (transaction) {
return this.sendTransaction.apply(this, Array.prototype.slice.call(arguments));
}
// call
return this.call.apply(this, Array.prototype.slice.call(arguments));
};
/**
* Should be called to attach function to contract
*
* @method attachToContract
* @param {Contract}
*/
SolidityFunction.prototype.attachToContract = function (contract) {
var execute = this.execute.bind(this);
execute.request = this.request.bind(this);
execute.call = this.call.bind(this);
execute.sendTransaction = this.sendTransaction.bind(this);
execute.estimateGas = this.estimateGas.bind(this);
execute.getData = this.getData.bind(this);
var displayName = this.displayName();
if (!contract[displayName]) {
contract[displayName] = execute;
}
contract[displayName][this.typeName()] = execute; // circular!!!!
};
module.exports = SolidityFunction;
},{"../solidity/coder":7,"../utils/sha3":19,"../utils/utils":20,"./errors":26,"./formatters":30}],32:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file httpprovider.js
* @authors:
* Marek Kotewicz <marek@ethdev.com>
* Marian Oancea <marian@ethdev.com>
* Fabian Vogelsteller <fabian@ethdev.com>
* @date 2015
*/
var errors = require('./errors');
// workaround to use httpprovider in different envs
// browser
if (typeof window !== 'undefined' && window.XMLHttpRequest) {
XMLHttpRequest = window.XMLHttpRequest; // jshint ignore: line
// node
} else {
XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; // jshint ignore: line
}
var XHR2 = require('xhr2'); // jshint ignore: line
/**
* HttpProvider should be used to send rpc calls over http
*/
var HttpProvider = function (host, timeout, user, password) {
this.host = host || 'http://localhost:8545';
this.timeout = timeout || 0;
this.user = user;
this.password = password;
};
/**
* Should be called to prepare new XMLHttpRequest
*
* @method prepareRequest
* @param {Boolean} true if request should be async
* @return {XMLHttpRequest} object
*/
HttpProvider.prototype.prepareRequest = function (async) {
var request;
if (async) {
request = new XHR2();
request.timeout = this.timeout;
} else {
request = new XMLHttpRequest();
}
request.open('POST', this.host, async);
if (this.user && this.password) {
var auth = 'Basic ' + new Buffer(this.user + ':' + this.password).toString('base64');
request.setRequestHeader('Authorization', auth);
} request.setRequestHeader('Content-Type', 'application/json');
return request;
};
/**
* Should be called to make sync request
*
* @method send
* @param {Object} payload
* @return {Object} result
*/
HttpProvider.prototype.send = function (payload) {
var request = this.prepareRequest(false);
try {
request.send(JSON.stringify(payload));
} catch (error) {
throw errors.InvalidConnection(this.host);
}
var result = request.responseText;
try {
result = JSON.parse(result);
} catch (e) {
throw errors.InvalidResponse(request.responseText);
}
return result;
};
/**
* Should be used to make async request
*
* @method sendAsync
* @param {Object} payload
* @param {Function} callback triggered on end with (err, result)
*/
HttpProvider.prototype.sendAsync = function (payload, callback) {
var request = this.prepareRequest(true);
request.onreadystatechange = function () {
if (request.readyState === 4 && request.timeout !== 1) {
var result = request.responseText;
var error = null;
try {
result = JSON.parse(result);
} catch (e) {
error = errors.InvalidResponse(request.responseText);
}
callback(error, result);
}
};
request.ontimeout = function () {
callback(errors.ConnectionTimeout(this.timeout));
};
try {
request.send(JSON.stringify(payload));
} catch (error) {
callback(errors.InvalidConnection(this.host));
}
};
/**
* Synchronously tries to make Http request
*
* @method isConnected
* @return {Boolean} returns true if request haven't failed. Otherwise false
*/
HttpProvider.prototype.isConnected = function () {
try {
this.send({
id: 9999999999,
jsonrpc: '2.0',
method: 'net_listening',
params: []
});
return true;
} catch (e) {
return false;
}
};
module.exports = HttpProvider;
},{"./errors":26,"xhr2":85,"xmlhttprequest":17}],33:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file iban.js
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
var BigNumber = require('bignumber.js');
var padLeft = function (string, bytes) {
var result = string;
while (result.length < bytes * 2) {
result = '0' + result;
}
return result;
};
/**
* Prepare an IBAN for mod 97 computation by moving the first 4 chars to the end and transforming the letters to
* numbers (A = 10, B = 11, ..., Z = 35), as specified in ISO13616.
*
* @method iso13616Prepare
* @param {String} iban the IBAN
* @returns {String} the prepared IBAN
*/
var iso13616Prepare = function (iban) {
var A = 'A'.charCodeAt(0);
var Z = 'Z'.charCodeAt(0);
iban = iban.toUpperCase();
iban = iban.substr(4) + iban.substr(0,4);
return iban.split('').map(function(n){
var code = n.charCodeAt(0);
if (code >= A && code <= Z){
// A = 10, B = 11, ... Z = 35
return code - A + 10;
} else {
return n;
}
}).join('');
};
/**
* Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064.
*
* @method mod9710
* @param {String} iban
* @returns {Number}
*/
var mod9710 = function (iban) {
var remainder = iban,
block;
while (remainder.length > 2){
block = remainder.slice(0, 9);
remainder = parseInt(block, 10) % 97 + remainder.slice(block.length);
}
return parseInt(remainder, 10) % 97;
};
/**
* This prototype should be used to create iban object from iban correct string
*
* @param {String} iban
*/
var Iban = function (iban) {
this._iban = iban;
};
/**
* This method should be used to create iban object from ethereum address
*
* @method fromAddress
* @param {String} address
* @return {Iban} the IBAN object
*/
Iban.fromAddress = function (address) {
var asBn = new BigNumber(address, 16);
var base36 = asBn.toString(36);
var padded = padLeft(base36, 15);
return Iban.fromBban(padded.toUpperCase());
};
/**
* Convert the passed BBAN to an IBAN for this country specification.
* Please note that <i>"generation of the IBAN shall be the exclusive responsibility of the bank/branch servicing the account"</i>.
* This method implements the preferred algorithm described in http://en.wikipedia.org/wiki/International_Bank_Account_Number#Generating_IBAN_check_digits
*
* @method fromBban
* @param {String} bban the BBAN to convert to IBAN
* @returns {Iban} the IBAN object
*/
Iban.fromBban = function (bban) {
var countryCode = 'XE';
var remainder = mod9710(iso13616Prepare(countryCode + '00' + bban));
var checkDigit = ('0' + (98 - remainder)).slice(-2);
return new Iban(countryCode + checkDigit + bban);
};
/**
* Should be used to create IBAN object for given institution and identifier
*
* @method createIndirect
* @param {Object} options, required options are "institution" and "identifier"
* @return {Iban} the IBAN object
*/
Iban.createIndirect = function (options) {
return Iban.fromBban('ETH' + options.institution + options.identifier);
};
/**
* Thos method should be used to check if given string is valid iban object
*
* @method isValid
* @param {String} iban string
* @return {Boolean} true if it is valid IBAN
*/
Iban.isValid = function (iban) {
var i = new Iban(iban);
return i.isValid();
};
/**
* Should be called to check if iban is correct
*
* @method isValid
* @returns {Boolean} true if it is, otherwise false
*/
Iban.prototype.isValid = function () {
return /^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$/.test(this._iban) &&
mod9710(iso13616Prepare(this._iban)) === 1;
};
/**
* Should be called to check if iban number is direct
*
* @method isDirect
* @returns {Boolean} true if it is, otherwise false
*/
Iban.prototype.isDirect = function () {
return this._iban.length === 34 || this._iban.length === 35;
};
/**
* Should be called to check if iban number if indirect
*
* @method isIndirect
* @returns {Boolean} true if it is, otherwise false
*/
Iban.prototype.isIndirect = function () {
return this._iban.length === 20;
};
/**
* Should be called to get iban checksum
* Uses the mod-97-10 checksumming protocol (ISO/IEC 7064:2003)
*
* @method checksum
* @returns {String} checksum
*/
Iban.prototype.checksum = function () {
return this._iban.substr(2, 2);
};
/**
* Should be called to get institution identifier
* eg. XREG
*
* @method institution
* @returns {String} institution identifier
*/
Iban.prototype.institution = function () {
return this.isIndirect() ? this._iban.substr(7, 4) : '';
};
/**
* Should be called to get client identifier within institution
* eg. GAVOFYORK
*
* @method client
* @returns {String} client identifier
*/
Iban.prototype.client = function () {
return this.isIndirect() ? this._iban.substr(11) : '';
};
/**
* Should be called to get client direct address
*
* @method address
* @returns {String} client direct address
*/
Iban.prototype.address = function () {
if (this.isDirect()) {
var base36 = this._iban.substr(4);
var asBn = new BigNumber(base36, 36);
return padLeft(asBn.toString(16), 20);
}
return '';
};
Iban.prototype.toString = function () {
return this._iban;
};
module.exports = Iban;
},{"bignumber.js":"bignumber.js"}],34:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file ipcprovider.js
* @authors:
* Fabian Vogelsteller <fabian@ethdev.com>
* @date 2015
*/
"use strict";
var utils = require('../utils/utils');
var errors = require('./errors');
var IpcProvider = function (path, net) {
var _this = this;
this.responseCallbacks = {};
this.path = path;
this.connection = net.connect({path: this.path});
this.connection.on('error', function(e){
console.error('IPC Connection Error', e);
_this._timeout();
});
this.connection.on('end', function(){
_this._timeout();
});
// LISTEN FOR CONNECTION RESPONSES
this.connection.on('data', function(data) {
/*jshint maxcomplexity: 6 */
_this._parseResponse(data.toString()).forEach(function(result){
var id = null;
// get the id which matches the returned id
if(utils.isArray(result)) {
result.forEach(function(load){
if(_this.responseCallbacks[load.id])
id = load.id;
});
} else {
id = result.id;
}
// fire the callback
if(_this.responseCallbacks[id]) {
_this.responseCallbacks[id](null, result);
delete _this.responseCallbacks[id];
}
});
});
};
/**
Will parse the response and make an array out of it.
@method _parseResponse
@param {String} data
*/
IpcProvider.prototype._parseResponse = function(data) {
var _this = this,
returnValues = [];
// DE-CHUNKER
var dechunkedData = data
.replace(/\}[\n\r]?\{/g,'}|--|{') // }{
.replace(/\}\][\n\r]?\[\{/g,'}]|--|[{') // }][{
.replace(/\}[\n\r]?\[\{/g,'}|--|[{') // }[{
.replace(/\}\][\n\r]?\{/g,'}]|--|{') // }]{
.split('|--|');
dechunkedData.forEach(function(data){
// prepend the last chunk
if(_this.lastChunk)
data = _this.lastChunk + data;
var result = null;
try {
result = JSON.parse(data);
} catch(e) {
_this.lastChunk = data;
// start timeout to cancel all requests
clearTimeout(_this.lastChunkTimeout);
_this.lastChunkTimeout = setTimeout(function(){
_this._timeout();
throw errors.InvalidResponse(data);
}, 1000 * 15);
return;
}
// cancel timeout and set chunk to null
clearTimeout(_this.lastChunkTimeout);
_this.lastChunk = null;
if(result)
returnValues.push(result);
});
return returnValues;
};
/**
Get the adds a callback to the responseCallbacks object,
which will be called if a response matching the response Id will arrive.
@method _addResponseCallback
*/
IpcProvider.prototype._addResponseCallback = function(payload, callback) {
var id = payload.id || payload[0].id;
var method = payload.method || payload[0].method;
this.responseCallbacks[id] = callback;
this.responseCallbacks[id].method = method;
};
/**
Timeout all requests when the end/error event is fired
@method _timeout
*/
IpcProvider.prototype._timeout = function() {
for(var key in this.responseCallbacks) {
if(this.responseCallbacks.hasOwnProperty(key)){
this.responseCallbacks[key](errors.InvalidConnection('on IPC'));
delete this.responseCallbacks[key];
}
}
};
/**
Check if the current connection is still valid.
@method isConnected
*/
IpcProvider.prototype.isConnected = function() {
var _this = this;
// try reconnect, when connection is gone
if(!_this.connection.writable)
_this.connection.connect({path: _this.path});
return !!this.connection.writable;
};
IpcProvider.prototype.send = function (payload) {
if(this.connection.writeSync) {
var result;
// try reconnect, when connection is gone
if(!this.connection.writable)
this.connection.connect({path: this.path});
var data = this.connection.writeSync(JSON.stringify(payload));
try {
result = JSON.parse(data);
} catch(e) {
throw errors.InvalidResponse(data);
}
return result;
} else {
throw new Error('You tried to send "'+ payload.method +'" synchronously. Synchronous requests are not supported by the IPC provider.');
}
};
IpcProvider.prototype.sendAsync = function (payload, callback) {
// try reconnect, when connection is gone
if(!this.connection.writable)
this.connection.connect({path: this.path});
this.connection.write(JSON.stringify(payload));
this._addResponseCallback(payload, callback);
};
module.exports = IpcProvider;
},{"../utils/utils":20,"./errors":26}],35:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file jsonrpc.js
* @authors:
* Marek Kotewicz <marek@ethdev.com>
* Aaron Kumavis <aaron@kumavis.me>
* @date 2015
*/
// Initialize Jsonrpc as a simple object with utility functions.
var Jsonrpc = {
messageId: 0
};
/**
* Should be called to valid json create payload object
*
* @method toPayload
* @param {Function} method of jsonrpc call, required
* @param {Array} params, an array of method params, optional
* @returns {Object} valid jsonrpc payload object
*/
Jsonrpc.toPayload = function (method, params) {
if (!method)
console.error('jsonrpc method should be specified!');
// advance message ID
Jsonrpc.messageId++;
return {
jsonrpc: '2.0',
id: Jsonrpc.messageId,
method: method,
params: params || []
};
};
/**
* Should be called to check if jsonrpc response is valid
*
* @method isValidResponse
* @param {Object}
* @returns {Boolean} true if response is valid, otherwise false
*/
Jsonrpc.isValidResponse = function (response) {
return Array.isArray(response) ? response.every(validateSingleMessage) : validateSingleMessage(response);
function validateSingleMessage(message){
return !!message &&
!message.error &&
message.jsonrpc === '2.0' &&
typeof message.id === 'number' &&
message.result !== undefined; // only undefined is not valid json object
}
};
/**
* Should be called to create batch payload object
*
* @method toBatchPayload
* @param {Array} messages, an array of objects with method (required) and params (optional) fields
* @returns {Array} batch payload
*/
Jsonrpc.toBatchPayload = function (messages) {
return messages.map(function (message) {
return Jsonrpc.toPayload(message.method, message.params);
});
};
module.exports = Jsonrpc;
},{}],36:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file method.js
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
var utils = require('../utils/utils');
var errors = require('./errors');
var Method = function (options) {
this.name = options.name;
this.call = options.call;
this.params = options.params || 0;
this.inputFormatter = options.inputFormatter;
this.outputFormatter = options.outputFormatter;
this.requestManager = null;
};
Method.prototype.setRequestManager = function (rm) {
this.requestManager = rm;
};
/**
* Should be used to determine name of the jsonrpc method based on arguments
*
* @method getCall
* @param {Array} arguments
* @return {String} name of jsonrpc method
*/
Method.prototype.getCall = function (args) {
return utils.isFunction(this.call) ? this.call(args) : this.call;
};
/**
* Should be used to extract callback from array of arguments. Modifies input param
*
* @method extractCallback
* @param {Array} arguments
* @return {Function|Null} callback, if exists
*/
Method.prototype.extractCallback = function (args) {
if (utils.isFunction(args[args.length - 1])) {
return args.pop(); // modify the args array!
}
};
/**
* Should be called to check if the number of arguments is correct
*
* @method validateArgs
* @param {Array} arguments
* @throws {Error} if it is not
*/
Method.prototype.validateArgs = function (args) {
if (args.length !== this.params) {
throw errors.InvalidNumberOfRPCParams();
}
};
/**
* Should be called to format input args of method
*
* @method formatInput
* @param {Array}
* @return {Array}
*/
Method.prototype.formatInput = function (args) {
if (!this.inputFormatter) {
return args;
}
return this.inputFormatter.map(function (formatter, index) {
return formatter ? formatter(args[index]) : args[index];
});
};
/**
* Should be called to format output(result) of method
*
* @method formatOutput
* @param {Object}
* @return {Object}
*/
Method.prototype.formatOutput = function (result) {
return this.outputFormatter && result ? this.outputFormatter(result) : result;
};
/**
* Should create payload from given input args
*
* @method toPayload
* @param {Array} args
* @return {Object}
*/
Method.prototype.toPayload = function (args) {
var call = this.getCall(args);
var callback = this.extractCallback(args);
var params = this.formatInput(args);
this.validateArgs(params);
return {
method: call,
params: params,
callback: callback
};
};
Method.prototype.attachToObject = function (obj) {
var func = this.buildCall();
func.call = this.call; // TODO!!! that's ugly. filter.js uses it
var name = this.name.split('.');
if (name.length > 1) {
obj[name[0]] = obj[name[0]] || {};
obj[name[0]][name[1]] = func;
} else {
obj[name[0]] = func;
}
};
Method.prototype.buildCall = function() {
var method = this;
var send = function () {
var payload = method.toPayload(Array.prototype.slice.call(arguments));
if (payload.callback) {
return method.requestManager.sendAsync(payload, function (err, result) {
payload.callback(err, method.formatOutput(result));
});
}
return method.formatOutput(method.requestManager.send(payload));
};
send.request = this.request.bind(this);
return send;
};
/**
* Should be called to create pure JSONRPC request which can be used in batch request
*
* @method request
* @param {...} params
* @return {Object} jsonrpc request
*/
Method.prototype.request = function () {
var payload = this.toPayload(Array.prototype.slice.call(arguments));
payload.format = this.formatOutput.bind(this);
return payload;
};
module.exports = Method;
},{"../utils/utils":20,"./errors":26}],37:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file db.js
* @authors:
* Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
var Method = require('../method');
var DB = function (web3) {
this._requestManager = web3._requestManager;
var self = this;
methods().forEach(function(method) {
method.attachToObject(self);
method.setRequestManager(web3._requestManager);
});
};
var methods = function () {
var putString = new Method({
name: 'putString',
call: 'db_putString',
params: 3
});
var getString = new Method({
name: 'getString',
call: 'db_getString',
params: 2
});
var putHex = new Method({
name: 'putHex',
call: 'db_putHex',
params: 3
});
var getHex = new Method({
name: 'getHex',
call: 'db_getHex',
params: 2
});
return [
putString, getString, putHex, getHex
];
};
module.exports = DB;
},{"../method":36}],38:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file eth.js
* @author Marek Kotewicz <marek@ethdev.com>
* @author Fabian Vogelsteller <fabian@ethdev.com>
* @date 2015
*/
"use strict";
var formatters = require('../formatters');
var utils = require('../../utils/utils');
var Method = require('../method');
var Property = require('../property');
var c = require('../../utils/config');
var Contract = require('../contract');
var watches = require('./watches');
var Filter = require('../filter');
var IsSyncing = require('../syncing');
var namereg = require('../namereg');
var Iban = require('../iban');
var transfer = require('../transfer');
var blockCall = function (args) {
return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? "eth_getBlockByHash" : "eth_getBlockByNumber";
};
var transactionFromBlockCall = function (args) {
return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getTransactionByBlockHashAndIndex' : 'eth_getTransactionByBlockNumberAndIndex';
};
var uncleCall = function (args) {
return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getUncleByBlockHashAndIndex' : 'eth_getUncleByBlockNumberAndIndex';
};
var getBlockTransactionCountCall = function (args) {
return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getBlockTransactionCountByHash' : 'eth_getBlockTransactionCountByNumber';
};
var uncleCountCall = function (args) {
return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getUncleCountByBlockHash' : 'eth_getUncleCountByBlockNumber';
};
function Eth(web3) {
this._requestManager = web3._requestManager;
var self = this;
methods().forEach(function(method) {
method.attachToObject(self);
method.setRequestManager(self._requestManager);
});
properties().forEach(function(p) {
p.attachToObject(self);
p.setRequestManager(self._requestManager);
});
this.iban = Iban;
this.sendIBANTransaction = transfer.bind(null, this);
}
Object.defineProperty(Eth.prototype, 'defaultBlock', {
get: function () {
return c.defaultBlock;
},
set: function (val) {
c.defaultBlock = val;
return val;
}
});
Object.defineProperty(Eth.prototype, 'defaultAccount', {
get: function () {
return c.defaultAccount;
},
set: function (val) {
c.defaultAccount = val;
return val;
}
});
var methods = function () {
var getBalance = new Method({
name: 'getBalance',
call: 'eth_getBalance',
params: 2,
inputFormatter: [formatters.inputAddressFormatter, formatters.inputDefaultBlockNumberFormatter],
outputFormatter: formatters.outputBigNumberFormatter
});
var getStorageAt = new Method({
name: 'getStorageAt',
call: 'eth_getStorageAt',
params: 3,
inputFormatter: [null, utils.toHex, formatters.inputDefaultBlockNumberFormatter]
});
var getCode = new Method({
name: 'getCode',
call: 'eth_getCode',
params: 2,
inputFormatter: [formatters.inputAddressFormatter, formatters.inputDefaultBlockNumberFormatter]
});
var getBlock = new Method({
name: 'getBlock',
call: blockCall,
params: 2,
inputFormatter: [formatters.inputBlockNumberFormatter, function (val) { return !!val; }],
outputFormatter: formatters.outputBlockFormatter
});
var getUncle = new Method({
name: 'getUncle',
call: uncleCall,
params: 2,
inputFormatter: [formatters.inputBlockNumberFormatter, utils.toHex],
outputFormatter: formatters.outputBlockFormatter,
});
var getCompilers = new Method({
name: 'getCompilers',
call: 'eth_getCompilers',
params: 0
});
var getBlockTransactionCount = new Method({
name: 'getBlockTransactionCount',
call: getBlockTransactionCountCall,
params: 1,
inputFormatter: [formatters.inputBlockNumberFormatter],
outputFormatter: utils.toDecimal
});
var getBlockUncleCount = new Method({
name: 'getBlockUncleCount',
call: uncleCountCall,
params: 1,
inputFormatter: [formatters.inputBlockNumberFormatter],
outputFormatter: utils.toDecimal
});
var getTransaction = new Method({
name: 'getTransaction',
call: 'eth_getTransactionByHash',
params: 1,
outputFormatter: formatters.outputTransactionFormatter
});
var getTransactionFromBlock = new Method({
name: 'getTransactionFromBlock',
call: transactionFromBlockCall,
params: 2,
inputFormatter: [formatters.inputBlockNumberFormatter, utils.toHex],
outputFormatter: formatters.outputTransactionFormatter
});
var getTransactionReceipt = new Method({
name: 'getTransactionReceipt',
call: 'eth_getTransactionReceipt',
params: 1,
outputFormatter: formatters.outputTransactionReceiptFormatter
});
var getTransactionCount = new Method({
name: 'getTransactionCount',
call: 'eth_getTransactionCount',
params: 2,
inputFormatter: [null, formatters.inputDefaultBlockNumberFormatter],
outputFormatter: utils.toDecimal
});
var sendRawTransaction = new Method({
name: 'sendRawTransaction',
call: 'eth_sendRawTransaction',
params: 1,
inputFormatter: [null]
});
var sendTransaction = new Method({
name: 'sendTransaction',
call: 'eth_sendTransaction',
params: 1,
inputFormatter: [formatters.inputTransactionFormatter]
});
var signTransaction = new Method({
name: 'signTransaction',
call: 'eth_signTransaction',
params: 1,
inputFormatter: [formatters.inputTransactionFormatter]
});
var sign = new Method({
name: 'sign',
call: 'eth_sign',
params: 2,
inputFormatter: [formatters.inputAddressFormatter, null]
});
var call = new Method({
name: 'call',
call: 'eth_call',
params: 2,
inputFormatter: [formatters.inputCallFormatter, formatters.inputDefaultBlockNumberFormatter]
});
var estimateGas = new Method({
name: 'estimateGas',
call: 'eth_estimateGas',
params: 1,
inputFormatter: [formatters.inputCallFormatter],
outputFormatter: utils.toDecimal
});
var compileSolidity = new Method({
name: 'compile.solidity',
call: 'eth_compileSolidity',
params: 1
});
var compileLLL = new Method({
name: 'compile.lll',
call: 'eth_compileLLL',
params: 1
});
var compileSerpent = new Method({
name: 'compile.serpent',
call: 'eth_compileSerpent',
params: 1
});
var submitWork = new Method({
name: 'submitWork',
call: 'eth_submitWork',
params: 3
});
var getWork = new Method({
name: 'getWork',
call: 'eth_getWork',
params: 0
});
return [
getBalance,
getStorageAt,
getCode,
getBlock,
getUncle,
getCompilers,
getBlockTransactionCount,
getBlockUncleCount,
getTransaction,
getTransactionFromBlock,
getTransactionReceipt,
getTransactionCount,
call,
estimateGas,
sendRawTransaction,
signTransaction,
sendTransaction,
sign,
compileSolidity,
compileLLL,
compileSerpent,
submitWork,
getWork
];
};
var properties = function () {
return [
new Property({
name: 'coinbase',
getter: 'eth_coinbase'
}),
new Property({
name: 'mining',
getter: 'eth_mining'
}),
new Property({
name: 'hashrate',
getter: 'eth_hashrate',
outputFormatter: utils.toDecimal
}),
new Property({
name: 'syncing',
getter: 'eth_syncing',
outputFormatter: formatters.outputSyncingFormatter
}),
new Property({
name: 'gasPrice',
getter: 'eth_gasPrice',
outputFormatter: formatters.outputBigNumberFormatter
}),
new Property({
name: 'accounts',
getter: 'eth_accounts'
}),
new Property({
name: 'blockNumber',
getter: 'eth_blockNumber',
outputFormatter: utils.toDecimal
}),
new Property({
name: 'protocolVersion',
getter: 'eth_protocolVersion'
})
];
};
Eth.prototype.contract = function (abi) {
var factory = new Contract(this, abi);
return factory;
};
Eth.prototype.filter = function (options, callback, filterCreationErrorCallback) {
return new Filter(options, 'eth', this._requestManager, watches.eth(), formatters.outputLogFormatter, callback, filterCreationErrorCallback);
};
Eth.prototype.namereg = function () {
return this.contract(namereg.global.abi).at(namereg.global.address);
};
Eth.prototype.icapNamereg = function () {
return this.contract(namereg.icap.abi).at(namereg.icap.address);
};
Eth.prototype.isSyncing = function (callback) {
return new IsSyncing(this._requestManager, callback);
};
module.exports = Eth;
},{"../../utils/config":18,"../../utils/utils":20,"../contract":25,"../filter":29,"../formatters":30,"../iban":33,"../method":36,"../namereg":44,"../property":45,"../syncing":48,"../transfer":49,"./watches":43}],39:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file eth.js
* @authors:
* Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
var utils = require('../../utils/utils');
var Property = require('../property');
var Net = function (web3) {
this._requestManager = web3._requestManager;
var self = this;
properties().forEach(function(p) {
p.attachToObject(self);
p.setRequestManager(web3._requestManager);
});
};
/// @returns an array of objects describing web3.eth api properties
var properties = function () {
return [
new Property({
name: 'listening',
getter: 'net_listening'
}),
new Property({
name: 'peerCount',
getter: 'net_peerCount',
outputFormatter: utils.toDecimal
})
];
};
module.exports = Net;
},{"../../utils/utils":20,"../property":45}],40:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file eth.js
* @author Marek Kotewicz <marek@ethdev.com>
* @author Fabian Vogelsteller <fabian@ethdev.com>
* @date 2015
*/
"use strict";
var Method = require('../method');
var Property = require('../property');
var formatters = require('../formatters');
function Personal(web3) {
this._requestManager = web3._requestManager;
var self = this;
methods().forEach(function(method) {
method.attachToObject(self);
method.setRequestManager(self._requestManager);
});
properties().forEach(function(p) {
p.attachToObject(self);
p.setRequestManager(self._requestManager);
});
}
var methods = function () {
var newAccount = new Method({
name: 'newAccount',
call: 'personal_newAccount',
params: 1,
inputFormatter: [null]
});
var importRawKey = new Method({
name: 'importRawKey',
call: 'personal_importRawKey',
params: 2
});
var sign = new Method({
name: 'sign',
call: 'personal_sign',
params: 3,
inputFormatter: [null, formatters.inputAddressFormatter, null]
});
var ecRecover = new Method({
name: 'ecRecover',
call: 'personal_ecRecover',
params: 2
});
var unlockAccount = new Method({
name: 'unlockAccount',
call: 'personal_unlockAccount',
params: 3,
inputFormatter: [formatters.inputAddressFormatter, null, null]
});
var sendTransaction = new Method({
name: 'sendTransaction',
call: 'personal_sendTransaction',
params: 2,
inputFormatter: [formatters.inputTransactionFormatter, null]
});
var lockAccount = new Method({
name: 'lockAccount',
call: 'personal_lockAccount',
params: 1,
inputFormatter: [formatters.inputAddressFormatter]
});
return [
newAccount,
importRawKey,
unlockAccount,
ecRecover,
sign,
sendTransaction,
lockAccount
];
};
var properties = function () {
return [
new Property({
name: 'listAccounts',
getter: 'personal_listAccounts'
})
];
};
module.exports = Personal;
},{"../formatters":30,"../method":36,"../property":45}],41:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file shh.js
* @authors:
* Fabian Vogelsteller <fabian@ethereum.org>
* Marek Kotewicz <marek@ethcore.io>
* @date 2017
*/
var Method = require('../method');
var Filter = require('../filter');
var watches = require('./watches');
var Shh = function (web3) {
this._requestManager = web3._requestManager;
var self = this;
methods().forEach(function(method) {
method.attachToObject(self);
method.setRequestManager(self._requestManager);
});
};
Shh.prototype.newMessageFilter = function (options, callback, filterCreationErrorCallback) {
return new Filter(options, 'shh', this._requestManager, watches.shh(), null, callback, filterCreationErrorCallback);
};
var methods = function () {
return [
new Method({
name: 'version',
call: 'shh_version',
params: 0
}),
new Method({
name: 'info',
call: 'shh_info',
params: 0
}),
new Method({
name: 'setMaxMessageSize',
call: 'shh_setMaxMessageSize',
params: 1
}),
new Method({
name: 'setMinPoW',
call: 'shh_setMinPoW',
params: 1
}),
new Method({
name: 'markTrustedPeer',
call: 'shh_markTrustedPeer',
params: 1
}),
new Method({
name: 'newKeyPair',
call: 'shh_newKeyPair',
params: 0
}),
new Method({
name: 'addPrivateKey',
call: 'shh_addPrivateKey',
params: 1
}),
new Method({
name: 'deleteKeyPair',
call: 'shh_deleteKeyPair',
params: 1
}),
new Method({
name: 'hasKeyPair',
call: 'shh_hasKeyPair',
params: 1
}),
new Method({
name: 'getPublicKey',
call: 'shh_getPublicKey',
params: 1
}),
new Method({
name: 'getPrivateKey',
call: 'shh_getPrivateKey',
params: 1
}),
new Method({
name: 'newSymKey',
call: 'shh_newSymKey',
params: 0
}),
new Method({
name: 'addSymKey',
call: 'shh_addSymKey',
params: 1
}),
new Method({
name: 'generateSymKeyFromPassword',
call: 'shh_generateSymKeyFromPassword',
params: 1
}),
new Method({
name: 'hasSymKey',
call: 'shh_hasSymKey',
params: 1
}),
new Method({
name: 'getSymKey',
call: 'shh_getSymKey',
params: 1
}),
new Method({
name: 'deleteSymKey',
call: 'shh_deleteSymKey',
params: 1
}),
// subscribe and unsubscribe missing
new Method({
name: 'post',
call: 'shh_post',
params: 1,
inputFormatter: [null]
})
];
};
module.exports = Shh;
},{"../filter":29,"../method":36,"./watches":43}],42:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file bzz.js
* @author Alex Beregszaszi <alex@rtfs.hu>
* @date 2016
*
* Reference: https://github.com/ethereum/go-ethereum/blob/swarm/internal/web3ext/web3ext.go#L33
*/
"use strict";
var Method = require('../method');
var Property = require('../property');
function Swarm(web3) {
this._requestManager = web3._requestManager;
var self = this;
methods().forEach(function(method) {
method.attachToObject(self);
method.setRequestManager(self._requestManager);
});
properties().forEach(function(p) {
p.attachToObject(self);
p.setRequestManager(self._requestManager);
});
}
var methods = function () {
var blockNetworkRead = new Method({
name: 'blockNetworkRead',
call: 'bzz_blockNetworkRead',
params: 1,
inputFormatter: [null]
});
var syncEnabled = new Method({
name: 'syncEnabled',
call: 'bzz_syncEnabled',
params: 1,
inputFormatter: [null]
});
var swapEnabled = new Method({
name: 'swapEnabled',
call: 'bzz_swapEnabled',
params: 1,
inputFormatter: [null]
});
var download = new Method({
name: 'download',
call: 'bzz_download',
params: 2,
inputFormatter: [null, null]
});
var upload = new Method({
name: 'upload',
call: 'bzz_upload',
params: 2,
inputFormatter: [null, null]
});
var retrieve = new Method({
name: 'retrieve',
call: 'bzz_retrieve',
params: 1,
inputFormatter: [null]
});
var store = new Method({
name: 'store',
call: 'bzz_store',
params: 2,
inputFormatter: [null, null]
});
var get = new Method({
name: 'get',
call: 'bzz_get',
params: 1,
inputFormatter: [null]
});
var put = new Method({
name: 'put',
call: 'bzz_put',
params: 2,
inputFormatter: [null, null]
});
var modify = new Method({
name: 'modify',
call: 'bzz_modify',
params: 4,
inputFormatter: [null, null, null, null]
});
return [
blockNetworkRead,
syncEnabled,
swapEnabled,
download,
upload,
retrieve,
store,
get,
put,
modify
];
};
var properties = function () {
return [
new Property({
name: 'hive',
getter: 'bzz_hive'
}),
new Property({
name: 'info',
getter: 'bzz_info'
})
];
};
module.exports = Swarm;
},{"../method":36,"../property":45}],43:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file watches.js
* @authors:
* Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
var Method = require('../method');
/// @returns an array of objects describing web3.eth.filter api methods
var eth = function () {
var newFilterCall = function (args) {
var type = args[0];
switch(type) {
case 'latest':
args.shift();
this.params = 0;
return 'eth_newBlockFilter';
case 'pending':
args.shift();
this.params = 0;
return 'eth_newPendingTransactionFilter';
default:
return 'eth_newFilter';
}
};
var newFilter = new Method({
name: 'newFilter',
call: newFilterCall,
params: 1
});
var uninstallFilter = new Method({
name: 'uninstallFilter',
call: 'eth_uninstallFilter',
params: 1
});
var getLogs = new Method({
name: 'getLogs',
call: 'eth_getFilterLogs',
params: 1
});
var poll = new Method({
name: 'poll',
call: 'eth_getFilterChanges',
params: 1
});
return [
newFilter,
uninstallFilter,
getLogs,
poll
];
};
/// @returns an array of objects describing web3.shh.watch api methods
var shh = function () {
return [
new Method({
name: 'newFilter',
call: 'shh_newMessageFilter',
params: 1
}),
new Method({
name: 'uninstallFilter',
call: 'shh_deleteMessageFilter',
params: 1
}),
new Method({
name: 'getLogs',
call: 'shh_getFilterMessages',
params: 1
}),
new Method({
name: 'poll',
call: 'shh_getFilterMessages',
params: 1
})
];
};
module.exports = {
eth: eth,
shh: shh
};
},{"../method":36}],44:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file namereg.js
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
var globalRegistrarAbi = require('../contracts/GlobalRegistrar.json');
var icapRegistrarAbi= require('../contracts/ICAPRegistrar.json');
var globalNameregAddress = '0xc6d9d2cd449a754c494264e1809c50e34d64562b';
var icapNameregAddress = '0xa1a111bc074c9cfa781f0c38e63bd51c91b8af00';
module.exports = {
global: {
abi: globalRegistrarAbi,
address: globalNameregAddress
},
icap: {
abi: icapRegistrarAbi,
address: icapNameregAddress
}
};
},{"../contracts/GlobalRegistrar.json":1,"../contracts/ICAPRegistrar.json":2}],45:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file property.js
* @author Fabian Vogelsteller <fabian@frozeman.de>
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
var utils = require('../utils/utils');
var Property = function (options) {
this.name = options.name;
this.getter = options.getter;
this.setter = options.setter;
this.outputFormatter = options.outputFormatter;
this.inputFormatter = options.inputFormatter;
this.requestManager = null;
};
Property.prototype.setRequestManager = function (rm) {
this.requestManager = rm;
};
/**
* Should be called to format input args of method
*
* @method formatInput
* @param {Array}
* @return {Array}
*/
Property.prototype.formatInput = function (arg) {
return this.inputFormatter ? this.inputFormatter(arg) : arg;
};
/**
* Should be called to format output(result) of method
*
* @method formatOutput
* @param {Object}
* @return {Object}
*/
Property.prototype.formatOutput = function (result) {
return this.outputFormatter && result !== null && result !== undefined ? this.outputFormatter(result) : result;
};
/**
* Should be used to extract callback from array of arguments. Modifies input param
*
* @method extractCallback
* @param {Array} arguments
* @return {Function|Null} callback, if exists
*/
Property.prototype.extractCallback = function (args) {
if (utils.isFunction(args[args.length - 1])) {
return args.pop(); // modify the args array!
}
};
/**
* Should attach function to method
*
* @method attachToObject
* @param {Object}
* @param {Function}
*/
Property.prototype.attachToObject = function (obj) {
var proto = {
get: this.buildGet(),
enumerable: true
};
var names = this.name.split('.');
var name = names[0];
if (names.length > 1) {
obj[names[0]] = obj[names[0]] || {};
obj = obj[names[0]];
name = names[1];
}
Object.defineProperty(obj, name, proto);
obj[asyncGetterName(name)] = this.buildAsyncGet();
};
var asyncGetterName = function (name) {
return 'get' + name.charAt(0).toUpperCase() + name.slice(1);
};
Property.prototype.buildGet = function () {
var property = this;
return function get() {
return property.formatOutput(property.requestManager.send({
method: property.getter
}));
};
};
Property.prototype.buildAsyncGet = function () {
var property = this;
var get = function (callback) {
property.requestManager.sendAsync({
method: property.getter
}, function (err, result) {
callback(err, property.formatOutput(result));
});
};
get.request = this.request.bind(this);
return get;
};
/**
* Should be called to create pure JSONRPC request which can be used in batch request
*
* @method request
* @param {...} params
* @return {Object} jsonrpc request
*/
Property.prototype.request = function () {
var payload = {
method: this.getter,
params: [],
callback: this.extractCallback(Array.prototype.slice.call(arguments))
};
payload.format = this.formatOutput.bind(this);
return payload;
};
module.exports = Property;
},{"../utils/utils":20}],46:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file requestmanager.js
* @author Jeffrey Wilcke <jeff@ethdev.com>
* @author Marek Kotewicz <marek@ethdev.com>
* @author Marian Oancea <marian@ethdev.com>
* @author Fabian Vogelsteller <fabian@ethdev.com>
* @author Gav Wood <g@ethdev.com>
* @date 2014
*/
var Jsonrpc = require('./jsonrpc');
var utils = require('../utils/utils');
var c = require('../utils/config');
var errors = require('./errors');
/**
* It's responsible for passing messages to providers
* It's also responsible for polling the ethereum node for incoming messages
* Default poll timeout is 1 second
* Singleton
*/
var RequestManager = function (provider) {
this.provider = provider;
this.polls = {};
this.timeout = null;
};
/**
* Should be used to synchronously send request
*
* @method send
* @param {Object} data
* @return {Object}
*/
RequestManager.prototype.send = function (data) {
if (!this.provider) {
console.error(errors.InvalidProvider());
return null;
}
var payload = Jsonrpc.toPayload(data.method, data.params);
var result = this.provider.send(payload);
if (!Jsonrpc.isValidResponse(result)) {
throw errors.InvalidResponse(result);
}
return result.result;
};
/**
* Should be used to asynchronously send request
*
* @method sendAsync
* @param {Object} data
* @param {Function} callback
*/
RequestManager.prototype.sendAsync = function (data, callback) {
if (!this.provider) {
return callback(errors.InvalidProvider());
}
var payload = Jsonrpc.toPayload(data.method, data.params);
this.provider.sendAsync(payload, function (err, result) {
if (err) {
return callback(err);
}
if (!Jsonrpc.isValidResponse(result)) {
return callback(errors.InvalidResponse(result));
}
callback(null, result.result);
});
};
/**
* Should be called to asynchronously send batch request
*
* @method sendBatch
* @param {Array} batch data
* @param {Function} callback
*/
RequestManager.prototype.sendBatch = function (data, callback) {
if (!this.provider) {
return callback(errors.InvalidProvider());
}
var payload = Jsonrpc.toBatchPayload(data);
this.provider.sendAsync(payload, function (err, results) {
if (err) {
return callback(err);
}
if (!utils.isArray(results)) {
return callback(errors.InvalidResponse(results));
}
callback(err, results);
});
};
/**
* Should be used to set provider of request manager
*
* @method setProvider
* @param {Object}
*/
RequestManager.prototype.setProvider = function (p) {
this.provider = p;
};
/**
* Should be used to start polling
*
* @method startPolling
* @param {Object} data
* @param {Number} pollId
* @param {Function} callback
* @param {Function} uninstall
*
* @todo cleanup number of params
*/
RequestManager.prototype.startPolling = function (data, pollId, callback, uninstall) {
this.polls[pollId] = {data: data, id: pollId, callback: callback, uninstall: uninstall};
// start polling
if (!this.timeout) {
this.poll();
}
};
/**
* Should be used to stop polling for filter with given id
*
* @method stopPolling
* @param {Number} pollId
*/
RequestManager.prototype.stopPolling = function (pollId) {
delete this.polls[pollId];
// stop polling
if(Object.keys(this.polls).length === 0 && this.timeout) {
clearTimeout(this.timeout);
this.timeout = null;
}
};
/**
* Should be called to reset the polling mechanism of the request manager
*
* @method reset
*/
RequestManager.prototype.reset = function (keepIsSyncing) {
/*jshint maxcomplexity:5 */
for (var key in this.polls) {
// remove all polls, except sync polls,
// they need to be removed manually by calling syncing.stopWatching()
if(!keepIsSyncing || key.indexOf('syncPoll_') === -1) {
this.polls[key].uninstall();
delete this.polls[key];
}
}
// stop polling
if(Object.keys(this.polls).length === 0 && this.timeout) {
clearTimeout(this.timeout);
this.timeout = null;
}
};
/**
* Should be called to poll for changes on filter with given id
*
* @method poll
*/
RequestManager.prototype.poll = function () {
/*jshint maxcomplexity: 6 */
this.timeout = setTimeout(this.poll.bind(this), c.ETH_POLLING_TIMEOUT);
if (Object.keys(this.polls).length === 0) {
return;
}
if (!this.provider) {
console.error(errors.InvalidProvider());
return;
}
var pollsData = [];
var pollsIds = [];
for (var key in this.polls) {
pollsData.push(this.polls[key].data);
pollsIds.push(key);
}
if (pollsData.length === 0) {
return;
}
var payload = Jsonrpc.toBatchPayload(pollsData);
// map the request id to they poll id
var pollsIdMap = {};
payload.forEach(function(load, index){
pollsIdMap[load.id] = pollsIds[index];
});
var self = this;
this.provider.sendAsync(payload, function (error, results) {
// TODO: console log?
if (error) {
return;
}
if (!utils.isArray(results)) {
throw errors.InvalidResponse(results);
}
results.map(function (result) {
var id = pollsIdMap[result.id];
// make sure the filter is still installed after arrival of the request
if (self.polls[id]) {
result.callback = self.polls[id].callback;
return result;
} else
return false;
}).filter(function (result) {
return !!result;
}).filter(function (result) {
var valid = Jsonrpc.isValidResponse(result);
if (!valid) {
result.callback(errors.InvalidResponse(result));
}
return valid;
}).forEach(function (result) {
result.callback(null, result.result);
});
});
};
module.exports = RequestManager;
},{"../utils/config":18,"../utils/utils":20,"./errors":26,"./jsonrpc":35}],47:[function(require,module,exports){
var Settings = function () {
this.defaultBlock = 'latest';
this.defaultAccount = undefined;
};
module.exports = Settings;
},{}],48:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file syncing.js
* @authors:
* Fabian Vogelsteller <fabian@ethdev.com>
* @date 2015
*/
var formatters = require('./formatters');
var utils = require('../utils/utils');
var count = 1;
/**
Adds the callback and sets up the methods, to iterate over the results.
@method pollSyncing
@param {Object} self
*/
var pollSyncing = function(self) {
var onMessage = function (error, sync) {
if (error) {
return self.callbacks.forEach(function (callback) {
callback(error);
});
}
if(utils.isObject(sync) && sync.startingBlock)
sync = formatters.outputSyncingFormatter(sync);
self.callbacks.forEach(function (callback) {
if (self.lastSyncState !== sync) {
// call the callback with true first so the app can stop anything, before receiving the sync data
if(!self.lastSyncState && utils.isObject(sync))
callback(null, true);
// call on the next CPU cycle, so the actions of the sync stop can be processes first
setTimeout(function() {
callback(null, sync);
}, 0);
self.lastSyncState = sync;
}
});
};
self.requestManager.startPolling({
method: 'eth_syncing',
params: [],
}, self.pollId, onMessage, self.stopWatching.bind(self));
};
var IsSyncing = function (requestManager, callback) {
this.requestManager = requestManager;
this.pollId = 'syncPoll_'+ count++;
this.callbacks = [];
this.addCallback(callback);
this.lastSyncState = false;
pollSyncing(this);
return this;
};
IsSyncing.prototype.addCallback = function (callback) {
if(callback)
this.callbacks.push(callback);
return this;
};
IsSyncing.prototype.stopWatching = function () {
this.requestManager.stopPolling(this.pollId);
this.callbacks = [];
};
module.exports = IsSyncing;
},{"../utils/utils":20,"./formatters":30}],49:[function(require,module,exports){
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js 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 web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file transfer.js
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
var Iban = require('./iban');
var exchangeAbi = require('../contracts/SmartExchange.json');
/**
* Should be used to make Iban transfer
*
* @method transfer
* @param {String} from
* @param {String} to iban
* @param {Value} value to be tranfered
* @param {Function} callback, callback
*/
var transfer = function (eth, from, to, value, callback) {
var iban = new Iban(to);
if (!iban.isValid()) {
throw new Error('invalid iban address');
}
if (iban.isDirect()) {
return transferToAddress(eth, from, iban.address(), value, callback);
}
if (!callback) {
var address = eth.icapNamereg().addr(iban.institution());
return deposit(eth, from, address, value, iban.client());
}
eth.icapNamereg().addr(iban.institution(), function (err, address) {
return deposit(eth, from, address, value, iban.client(), callback);
});
};
/**
* Should be used to transfer funds to certain address
*
* @method transferToAddress
* @param {String} from
* @param {String} to
* @param {Value} value to be tranfered
* @param {Function} callback, callback
*/
var transferToAddress = function (eth, from, to, value, callback) {
return eth.sendTransaction({
address: to,
from: from,
value: value
}, callback);
};
/**
* Should be used to deposit funds to generic Exchange contract (must implement deposit(bytes32) method!)
*
* @method deposit
* @param {String} from
* @param {String} to
* @param {Value} value to be transfered
* @param {String} client unique identifier
* @param {Function} callback, callback
*/
var deposit = function (eth, from, to, value, client, callback) {
var abi = exchangeAbi;
return eth.contract(abi).at(to).deposit(client, {
from: from,
value: value
}, callback);
};
module.exports = transfer;
},{"../contracts/SmartExchange.json":3,"./iban":33}],50:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Lookup tables
var SBOX = [];
var INV_SBOX = [];
var SUB_MIX_0 = [];
var SUB_MIX_1 = [];
var SUB_MIX_2 = [];
var SUB_MIX_3 = [];
var INV_SUB_MIX_0 = [];
var INV_SUB_MIX_1 = [];
var INV_SUB_MIX_2 = [];
var INV_SUB_MIX_3 = [];
// Compute lookup tables
(function () {
// Compute double table
var d = [];
for (var i = 0; i < 256; i++) {
if (i < 128) {
d[i] = i << 1;
} else {
d[i] = (i << 1) ^ 0x11b;
}
}
// Walk GF(2^8)
var x = 0;
var xi = 0;
for (var i = 0; i < 256; i++) {
// Compute sbox
var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
SBOX[x] = sx;
INV_SBOX[sx] = x;
// Compute multiplication
var x2 = d[x];
var x4 = d[x2];
var x8 = d[x4];
// Compute sub bytes, mix columns tables
var t = (d[sx] * 0x101) ^ (sx * 0x1010100);
SUB_MIX_0[x] = (t << 24) | (t >>> 8);
SUB_MIX_1[x] = (t << 16) | (t >>> 16);
SUB_MIX_2[x] = (t << 8) | (t >>> 24);
SUB_MIX_3[x] = t;
// Compute inv sub bytes, inv mix columns tables
var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8);
INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16);
INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24);
INV_SUB_MIX_3[sx] = t;
// Compute next counter
if (!x) {
x = xi = 1;
} else {
x = x2 ^ d[d[d[x8 ^ x2]]];
xi ^= d[d[xi]];
}
}
}());
// Precomputed Rcon lookup
var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
/**
* AES block cipher algorithm.
*/
var AES = C_algo.AES = BlockCipher.extend({
_doReset: function () {
// Skip reset of nRounds has been set before and key did not change
if (this._nRounds && this._keyPriorReset === this._key) {
return;
}
// Shortcuts
var key = this._keyPriorReset = this._key;
var keyWords = key.words;
var keySize = key.sigBytes / 4;
// Compute number of rounds
var nRounds = this._nRounds = keySize + 6;
// Compute number of key schedule rows
var ksRows = (nRounds + 1) * 4;
// Compute key schedule
var keySchedule = this._keySchedule = [];
for (var ksRow = 0; ksRow < ksRows; ksRow++) {
if (ksRow < keySize) {
keySchedule[ksRow] = keyWords[ksRow];
} else {
var t = keySchedule[ksRow - 1];
if (!(ksRow % keySize)) {
// Rot word
t = (t << 8) | (t >>> 24);
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
// Mix Rcon
t ^= RCON[(ksRow / keySize) | 0] << 24;
} else if (keySize > 6 && ksRow % keySize == 4) {
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
}
keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t;
}
}
// Compute inv key schedule
var invKeySchedule = this._invKeySchedule = [];
for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
var ksRow = ksRows - invKsRow;
if (invKsRow % 4) {
var t = keySchedule[ksRow];
} else {
var t = keySchedule[ksRow - 4];
}
if (invKsRow < 4 || ksRow <= 4) {
invKeySchedule[invKsRow] = t;
} else {
invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^
INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]];
}
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
},
decryptBlock: function (M, offset) {
// Swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);
// Inv swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
},
_doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) {
// Shortcut
var nRounds = this._nRounds;
// Get input, add round key
var s0 = M[offset] ^ keySchedule[0];
var s1 = M[offset + 1] ^ keySchedule[1];
var s2 = M[offset + 2] ^ keySchedule[2];
var s3 = M[offset + 3] ^ keySchedule[3];
// Key schedule row counter
var ksRow = 4;
// Rounds
for (var round = 1; round < nRounds; round++) {
// Shift rows, sub bytes, mix columns, add round key
var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++];
var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++];
var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++];
var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++];
// Update state
s0 = t0;
s1 = t1;
s2 = t2;
s3 = t3;
}
// Shift rows, sub bytes, add round key
var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++];
var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++];
var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++];
var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++];
// Set output
M[offset] = t0;
M[offset + 1] = t1;
M[offset + 2] = t2;
M[offset + 3] = t3;
},
keySize: 256/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg);
*/
C.AES = BlockCipher._createHelper(AES);
}());
return CryptoJS.AES;
}));
},{"./cipher-core":51,"./core":52,"./enc-base64":53,"./evpkdf":55,"./md5":60}],51:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher core components.
*/
CryptoJS.lib.Cipher || (function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var Base64 = C_enc.Base64;
var C_algo = C.algo;
var EvpKDF = C_algo.EvpKDF;
/**
* Abstract base cipher template.
*
* @property {number} keySize This cipher's key size. Default: 4 (128 bits)
* @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)
* @property {number} _ENC_XFORM_MODE A constant representing encryption mode.
* @property {number} _DEC_XFORM_MODE A constant representing decryption mode.
*/
var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*
* @property {WordArray} iv The IV to use for this operation.
*/
cfg: Base.extend(),
/**
* Creates this cipher in encryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
*/
createEncryptor: function (key, cfg) {
return this.create(this._ENC_XFORM_MODE, key, cfg);
},
/**
* Creates this cipher in decryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
*/
createDecryptor: function (key, cfg) {
return this.create(this._DEC_XFORM_MODE, key, cfg);
},
/**
* Initializes a newly created cipher.
*
* @param {number} xformMode Either the encryption or decryption transormation mode constant.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @example
*
* var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
*/
init: function (xformMode, key, cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Store transform mode and key
this._xformMode = xformMode;
this._key = key;
// Set initial values
this.reset();
},
/**
* Resets this cipher to its initial state.
*
* @example
*
* cipher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-cipher logic
this._doReset();
},
/**
* Adds data to be encrypted or decrypted.
*
* @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
*
* @return {WordArray} The data after processing.
*
* @example
*
* var encrypted = cipher.process('data');
* var encrypted = cipher.process(wordArray);
*/
process: function (dataUpdate) {
// Append
this._append(dataUpdate);
// Process available blocks
return this._process();
},
/**
* Finalizes the encryption or decryption process.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
*
* @return {WordArray} The data after final processing.
*
* @example
*
* var encrypted = cipher.finalize();
* var encrypted = cipher.finalize('data');
* var encrypted = cipher.finalize(wordArray);
*/
finalize: function (dataUpdate) {
// Final data update
if (dataUpdate) {
this._append(dataUpdate);
}
// Perform concrete-cipher logic
var finalProcessedData = this._doFinalize();
return finalProcessedData;
},
keySize: 128/32,
ivSize: 128/32,
_ENC_XFORM_MODE: 1,
_DEC_XFORM_MODE: 2,
/**
* Creates shortcut functions to a cipher's object interface.
*
* @param {Cipher} cipher The cipher to create a helper for.
*
* @return {Object} An object with encrypt and decrypt shortcut functions.
*
* @static
*
* @example
*
* var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
*/
_createHelper: (function () {
function selectCipherStrategy(key) {
if (typeof key == 'string') {
return PasswordBasedCipher;
} else {
return SerializableCipher;
}
}
return function (cipher) {
return {
encrypt: function (message, key, cfg) {
return selectCipherStrategy(key).encrypt(cipher, message, key, cfg);
},
decrypt: function (ciphertext, key, cfg) {
return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg);
}
};
};
}())
});
/**
* Abstract base stream cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits)
*/
var StreamCipher = C_lib.StreamCipher = Cipher.extend({
_doFinalize: function () {
// Process partial blocks
var finalProcessedBlocks = this._process(!!'flush');
return finalProcessedBlocks;
},
blockSize: 1
});
/**
* Mode namespace.
*/
var C_mode = C.mode = {};
/**
* Abstract base block cipher mode template.
*/
var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({
/**
* Creates this mode for encryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
*/
createEncryptor: function (cipher, iv) {
return this.Encryptor.create(cipher, iv);
},
/**
* Creates this mode for decryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
*/
createDecryptor: function (cipher, iv) {
return this.Decryptor.create(cipher, iv);
},
/**
* Initializes a newly created mode.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @example
*
* var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
*/
init: function (cipher, iv) {
this._cipher = cipher;
this._iv = iv;
}
});
/**
* Cipher Block Chaining mode.
*/
var CBC = C_mode.CBC = (function () {
/**
* Abstract base CBC mode.
*/
var CBC = BlockCipherMode.extend();
/**
* CBC encryptor.
*/
CBC.Encryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// XOR and encrypt
xorBlock.call(this, words, offset, blockSize);
cipher.encryptBlock(words, offset);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
/**
* CBC decryptor.
*/
CBC.Decryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
// Decrypt and XOR
cipher.decryptBlock(words, offset);
xorBlock.call(this, words, offset, blockSize);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function xorBlock(words, offset, blockSize) {
// Shortcut
var iv = this._iv;
// Choose mixing block
if (iv) {
var block = iv;
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var block = this._prevBlock;
}
// XOR blocks
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= block[i];
}
}
return CBC;
}());
/**
* Padding namespace.
*/
var C_pad = C.pad = {};
/**
* PKCS #5/7 padding strategy.
*/
var Pkcs7 = C_pad.Pkcs7 = {
/**
* Pads data using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to pad.
* @param {number} blockSize The multiple that the data should be padded to.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.pad(wordArray, 4);
*/
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Create padding word
var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes;
// Create padding
var paddingWords = [];
for (var i = 0; i < nPaddingBytes; i += 4) {
paddingWords.push(paddingWord);
}
var padding = WordArray.create(paddingWords, nPaddingBytes);
// Add padding
data.concat(padding);
},
/**
* Unpads data that had been padded using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to unpad.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.unpad(wordArray);
*/
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
/**
* Abstract base block cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits)
*/
var BlockCipher = C_lib.BlockCipher = Cipher.extend({
/**
* Configuration options.
*
* @property {Mode} mode The block mode to use. Default: CBC
* @property {Padding} padding The padding strategy to use. Default: Pkcs7
*/
cfg: Cipher.cfg.extend({
mode: CBC,
padding: Pkcs7
}),
reset: function () {
// Reset cipher
Cipher.reset.call(this);
// Shortcuts
var cfg = this.cfg;
var iv = cfg.iv;
var mode = cfg.mode;
// Reset block mode
if (this._xformMode == this._ENC_XFORM_MODE) {
var modeCreator = mode.createEncryptor;
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
var modeCreator = mode.createDecryptor;
// Keep at least one block in the buffer for unpadding
this._minBufferSize = 1;
}
this._mode = modeCreator.call(mode, this, iv && iv.words);
},
_doProcessBlock: function (words, offset) {
this._mode.processBlock(words, offset);
},
_doFinalize: function () {
// Shortcut
var padding = this.cfg.padding;
// Finalize
if (this._xformMode == this._ENC_XFORM_MODE) {
// Pad data
padding.pad(this._data, this.blockSize);
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
// Unpad data
padding.unpad(finalProcessedBlocks);
}
return finalProcessedBlocks;
},
blockSize: 128/32
});
/**
* A collection of cipher parameters.
*
* @property {WordArray} ciphertext The raw ciphertext.
* @property {WordArray} key The key to this ciphertext.
* @property {WordArray} iv The IV used in the ciphering operation.
* @property {WordArray} salt The salt used with a key derivation function.
* @property {Cipher} algorithm The cipher algorithm.
* @property {Mode} mode The block mode used in the ciphering operation.
* @property {Padding} padding The padding scheme used in the ciphering operation.
* @property {number} blockSize The block size of the cipher.
* @property {Format} formatter The default formatting strategy to convert this cipher params object to a string.
*/
var CipherParams = C_lib.CipherParams = Base.extend({
/**
* Initializes a newly created cipher params object.
*
* @param {Object} cipherParams An object with any of the possible cipher parameters.
*
* @example
*
* var cipherParams = CryptoJS.lib.CipherParams.create({
* ciphertext: ciphertextWordArray,
* key: keyWordArray,
* iv: ivWordArray,
* salt: saltWordArray,
* algorithm: CryptoJS.algo.AES,
* mode: CryptoJS.mode.CBC,
* padding: CryptoJS.pad.PKCS7,
* blockSize: 4,
* formatter: CryptoJS.format.OpenSSL
* });
*/
init: function (cipherParams) {
this.mixIn(cipherParams);
},
/**
* Converts this cipher params object to a string.
*
* @param {Format} formatter (Optional) The formatting strategy to use.
*
* @return {string} The stringified cipher params.
*
* @throws Error If neither the formatter nor the default formatter is set.
*
* @example
*
* var string = cipherParams + '';
* var string = cipherParams.toString();
* var string = cipherParams.toString(CryptoJS.format.OpenSSL);
*/
toString: function (formatter) {
return (formatter || this.formatter).stringify(this);
}
});
/**
* Format namespace.
*/
var C_format = C.format = {};
/**
* OpenSSL formatting strategy.
*/
var OpenSSLFormatter = C_format.OpenSSL = {
/**
* Converts a cipher params object to an OpenSSL-compatible string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The OpenSSL-compatible string.
*
* @static
*
* @example
*
* var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
*/
stringify: function (cipherParams) {
// Shortcuts
var ciphertext = cipherParams.ciphertext;
var salt = cipherParams.salt;
// Format
if (salt) {
var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext);
} else {
var wordArray = ciphertext;
}
return wordArray.toString(Base64);
},
/**
* Converts an OpenSSL-compatible string to a cipher params object.
*
* @param {string} openSSLStr The OpenSSL-compatible string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
*/
parse: function (openSSLStr) {
// Parse base64
var ciphertext = Base64.parse(openSSLStr);
// Shortcut
var ciphertextWords = ciphertext.words;
// Test for salt
if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) {
// Extract salt
var salt = WordArray.create(ciphertextWords.slice(2, 4));
// Remove salt from ciphertext
ciphertextWords.splice(0, 4);
ciphertext.sigBytes -= 16;
}
return CipherParams.create({ ciphertext: ciphertext, salt: salt });
}
};
/**
* A cipher wrapper that returns ciphertext as a serializable cipher params object.
*/
var SerializableCipher = C_lib.SerializableCipher = Base.extend({
/**
* Configuration options.
*
* @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
*/
cfg: Base.extend({
format: OpenSSLFormatter
}),
/**
* Encrypts a message.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key);
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Encrypt
var encryptor = cipher.createEncryptor(key, cfg);
var ciphertext = encryptor.finalize(message);
// Shortcut
var cipherCfg = encryptor.cfg;
// Create and return serializable cipher params
return CipherParams.create({
ciphertext: ciphertext,
key: key,
iv: cipherCfg.iv,
algorithm: cipher,
mode: cipherCfg.mode,
padding: cipherCfg.padding,
blockSize: cipher.blockSize,
formatter: cfg.format
});
},
/**
* Decrypts serialized ciphertext.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Decrypt
var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext);
return plaintext;
},
/**
* Converts serialized ciphertext to CipherParams,
* else assumed CipherParams already and returns ciphertext unchanged.
*
* @param {CipherParams|string} ciphertext The ciphertext.
* @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
*
* @return {CipherParams} The unserialized ciphertext.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
*/
_parse: function (ciphertext, format) {
if (typeof ciphertext == 'string') {
return format.parse(ciphertext, this);
} else {
return ciphertext;
}
}
});
/**
* Key derivation function namespace.
*/
var C_kdf = C.kdf = {};
/**
* OpenSSL key derivation function.
*/
var OpenSSLKdf = C_kdf.OpenSSL = {
/**
* Derives a key and IV from a password.
*
* @param {string} password The password to derive from.
* @param {number} keySize The size in words of the key to generate.
* @param {number} ivSize The size in words of the IV to generate.
* @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
*
* @return {CipherParams} A cipher params object with the key, IV, and salt.
*
* @static
*
* @example
*
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
*/
execute: function (password, keySize, ivSize, salt) {
// Generate random salt
if (!salt) {
salt = WordArray.random(64/8);
}
// Derive key and IV
var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt);
// Separate key and IV
var iv = WordArray.create(key.words.slice(keySize), ivSize * 4);
key.sigBytes = keySize * 4;
// Return params
return CipherParams.create({ key: key, iv: iv, salt: salt });
}
};
/**
* A serializable cipher wrapper that derives the key from a password,
* and returns ciphertext as a serializable cipher params object.
*/
var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({
/**
* Configuration options.
*
* @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
*/
cfg: SerializableCipher.cfg.extend({
kdf: OpenSSLKdf
}),
/**
* Encrypts a message using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password');
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize);
// Add IV to config
cfg.iv = derivedParams.iv;
// Encrypt
var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg);
// Mix in derived params
ciphertext.mixIn(derivedParams);
return ciphertext;
},
/**
* Decrypts serialized ciphertext using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt);
// Add IV to config
cfg.iv = derivedParams.iv;
// Decrypt
var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg);
return plaintext;
}
});
}());
}));
},{"./core":52}],52:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory();
}
else if (typeof define === "function" && define.amd) {
// AMD
define([], factory);
}
else {
// Global (browser)
root.CryptoJS = factory();
}
}(this, function () {
/**
* CryptoJS core components.
*/
var CryptoJS = CryptoJS || (function (Math, undefined) {
/*
* Local polyfil of Object.create
*/
var create = Object.create || (function () {
function F() {};
return function (obj) {
var subtype;
F.prototype = obj;
subtype = new F();
F.prototype = null;
return subtype;
};
}())
/**
* CryptoJS namespace.
*/
var C = {};
/**
* Library namespace.
*/
var C_lib = C.lib = {};
/**
* Base object for prototypal inheritance.
*/
var Base = C_lib.Base = (function () {
return {
/**
* Creates a new object that inherits from this object.
*
* @param {Object} overrides Properties to copy into the new object.
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* field: 'value',
*
* method: function () {
* }
* });
*/
extend: function (overrides) {
// Spawn
var subtype = create(this);
// Augment
if (overrides) {
subtype.mixIn(overrides);
}
// Create default initializer
if (!subtype.hasOwnProperty('init') || this.init === subtype.init) {
subtype.init = function () {
subtype.$super.init.apply(this, arguments);
};
}
// Initializer's prototype is the subtype object
subtype.init.prototype = subtype;
// Reference supertype
subtype.$super = this;
return subtype;
},
/**
* Extends this object and runs the init method.
* Arguments to create() will be passed to init().
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var instance = MyType.create();
*/
create: function () {
var instance = this.extend();
instance.init.apply(instance, arguments);
return instance;
},
/**
* Initializes a newly created object.
* Override this method to add some logic when your objects are created.
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* init: function () {
* // ...
* }
* });
*/
init: function () {
},
/**
* Copies properties into this object.
*
* @param {Object} properties The properties to mix in.
*
* @example
*
* MyType.mixIn({
* field: 'value'
* });
*/
mixIn: function (properties) {
for (var propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
this[propertyName] = properties[propertyName];
}
}
// IE won't copy toString using the loop above
if (properties.hasOwnProperty('toString')) {
this.toString = properties.toString;
}
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = instance.clone();
*/
clone: function () {
return this.init.prototype.extend(this);
}
};
}());
/**
* An array of 32-bit words.
*
* @property {Array} words The array of 32-bit words.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var WordArray = C_lib.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of 32-bit words.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.create();
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 4;
}
},
/**
* Converts this word array to a string.
*
* @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
*
* @return {string} The stringified word array.
*
* @example
*
* var string = wordArray + '';
* var string = wordArray.toString();
* var string = wordArray.toString(CryptoJS.enc.Utf8);
*/
toString: function (encoder) {
return (encoder || Hex).stringify(this);
},
/**
* Concatenates a word array to this word array.
*
* @param {WordArray} wordArray The word array to append.
*
* @return {WordArray} This word array.
*
* @example
*
* wordArray1.concat(wordArray2);
*/
concat: function (wordArray) {
// Shortcuts
var thisWords = this.words;
var thatWords = wordArray.words;
var thisSigBytes = this.sigBytes;
var thatSigBytes = wordArray.sigBytes;
// Clamp excess bits
this.clamp();
// Concat
if (thisSigBytes % 4) {
// Copy one byte at a time
for (var i = 0; i < thatSigBytes; i++) {
var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
}
} else {
// Copy one word at a time
for (var i = 0; i < thatSigBytes; i += 4) {
thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
}
}
this.sigBytes += thatSigBytes;
// Chainable
return this;
},
/**
* Removes insignificant bits.
*
* @example
*
* wordArray.clamp();
*/
clamp: function () {
// Shortcuts
var words = this.words;
var sigBytes = this.sigBytes;
// Clamp
words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
words.length = Math.ceil(sigBytes / 4);
},
/**
* Creates a copy of this word array.
*
* @return {WordArray} The clone.
*
* @example
*
* var clone = wordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone.words = this.words.slice(0);
return clone;
},
/**
* Creates a word array filled with random bytes.
*
* @param {number} nBytes The number of random bytes to generate.
*
* @return {WordArray} The random word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.random(16);
*/
random: function (nBytes) {
var words = [];
var r = (function (m_w) {
var m_w = m_w;
var m_z = 0x3ade68b1;
var mask = 0xffffffff;
return function () {
m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask;
m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask;
var result = ((m_z << 0x10) + m_w) & mask;
result /= 0x100000000;
result += 0.5;
return result * (Math.random() > .5 ? 1 : -1);
}
});
for (var i = 0, rcache; i < nBytes; i += 4) {
var _r = r((rcache || Math.random()) * 0x100000000);
rcache = _r() * 0x3ade67b7;
words.push((_r() * 0x100000000) | 0);
}
return new WordArray.init(words, nBytes);
}
});
/**
* Encoder namespace.
*/
var C_enc = C.enc = {};
/**
* Hex encoding strategy.
*/
var Hex = C_enc.Hex = {
/**
* Converts a word array to a hex string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The hex string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.enc.Hex.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var hexChars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
hexChars.push((bite >>> 4).toString(16));
hexChars.push((bite & 0x0f).toString(16));
}
return hexChars.join('');
},
/**
* Converts a hex string to a word array.
*
* @param {string} hexStr The hex string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Hex.parse(hexString);
*/
parse: function (hexStr) {
// Shortcut
var hexStrLength = hexStr.length;
// Convert
var words = [];
for (var i = 0; i < hexStrLength; i += 2) {
words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
}
return new WordArray.init(words, hexStrLength / 2);
}
};
/**
* Latin1 encoding strategy.
*/
var Latin1 = C_enc.Latin1 = {
/**
* Converts a word array to a Latin1 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Latin1 string.
*
* @static
*
* @example
*
* var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var latin1Chars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
latin1Chars.push(String.fromCharCode(bite));
}
return latin1Chars.join('');
},
/**
* Converts a Latin1 string to a word array.
*
* @param {string} latin1Str The Latin1 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
*/
parse: function (latin1Str) {
// Shortcut
var latin1StrLength = latin1Str.length;
// Convert
var words = [];
for (var i = 0; i < latin1StrLength; i++) {
words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
}
return new WordArray.init(words, latin1StrLength);
}
};
/**
* UTF-8 encoding strategy.
*/
var Utf8 = C_enc.Utf8 = {
/**
* Converts a word array to a UTF-8 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-8 string.
*
* @static
*
* @example
*
* var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
*/
stringify: function (wordArray) {
try {
return decodeURIComponent(escape(Latin1.stringify(wordArray)));
} catch (e) {
throw new Error('Malformed UTF-8 data');
}
},
/**
* Converts a UTF-8 string to a word array.
*
* @param {string} utf8Str The UTF-8 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
*/
parse: function (utf8Str) {
return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
}
};
/**
* Abstract buffered block algorithm template.
*
* The property blockSize must be implemented in a concrete subtype.
*
* @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
*/
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
/**
* Resets this block algorithm's data buffer to its initial state.
*
* @example
*
* bufferedBlockAlgorithm.reset();
*/
reset: function () {
// Initial values
this._data = new WordArray.init();
this._nDataBytes = 0;
},
/**
* Adds new data to this block algorithm's buffer.
*
* @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
*
* @example
*
* bufferedBlockAlgorithm._append('data');
* bufferedBlockAlgorithm._append(wordArray);
*/
_append: function (data) {
// Convert string to WordArray, else assume WordArray already
if (typeof data == 'string') {
data = Utf8.parse(data);
}
// Append
this._data.concat(data);
this._nDataBytes += data.sigBytes;
},
/**
* Processes available data blocks.
*
* This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
*
* @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
*
* @return {WordArray} The processed data.
*
* @example
*
* var processedData = bufferedBlockAlgorithm._process();
* var processedData = bufferedBlockAlgorithm._process(!!'flush');
*/
_process: function (doFlush) {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var dataSigBytes = data.sigBytes;
var blockSize = this.blockSize;
var blockSizeBytes = blockSize * 4;
// Count blocks ready
var nBlocksReady = dataSigBytes / blockSizeBytes;
if (doFlush) {
// Round up to include partial blocks
nBlocksReady = Math.ceil(nBlocksReady);
} else {
// Round down to include only full blocks,
// less the number of blocks that must remain in the buffer
nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
}
// Count words ready
var nWordsReady = nBlocksReady * blockSize;
// Count bytes ready
var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
// Process blocks
if (nWordsReady) {
for (var offset = 0; offset < nWordsReady; offset += blockSize) {
// Perform concrete-algorithm logic
this._doProcessBlock(dataWords, offset);
}
// Remove processed words
var processedWords = dataWords.splice(0, nWordsReady);
data.sigBytes -= nBytesReady;
}
// Return processed words
return new WordArray.init(processedWords, nBytesReady);
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = bufferedBlockAlgorithm.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone._data = this._data.clone();
return clone;
},
_minBufferSize: 0
});
/**
* Abstract hasher template.
*
* @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
*/
var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*/
cfg: Base.extend(),
/**
* Initializes a newly created hasher.
*
* @param {Object} cfg (Optional) The configuration options to use for this hash computation.
*
* @example
*
* var hasher = CryptoJS.algo.SHA256.create();
*/
init: function (cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Set initial values
this.reset();
},
/**
* Resets this hasher to its initial state.
*
* @example
*
* hasher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-hasher logic
this._doReset();
},
/**
* Updates this hasher with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {Hasher} This hasher.
*
* @example
*
* hasher.update('message');
* hasher.update(wordArray);
*/
update: function (messageUpdate) {
// Append
this._append(messageUpdate);
// Update the hash
this._process();
// Chainable
return this;
},
/**
* Finalizes the hash computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The hash.
*
* @example
*
* var hash = hasher.finalize();
* var hash = hasher.finalize('message');
* var hash = hasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Final message update
if (messageUpdate) {
this._append(messageUpdate);
}
// Perform concrete-hasher logic
var hash = this._doFinalize();
return hash;
},
blockSize: 512/32,
/**
* Creates a shortcut function to a hasher's object interface.
*
* @param {Hasher} hasher The hasher to create a helper for.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
*/
_createHelper: function (hasher) {
return function (message, cfg) {
return new hasher.init(cfg).finalize(message);
};
},
/**
* Creates a shortcut function to the HMAC's object interface.
*
* @param {Hasher} hasher The hasher to use in this HMAC helper.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
*/
_createHmacHelper: function (hasher) {
return function (message, key) {
return new C_algo.HMAC.init(hasher, key).finalize(message);
};
}
});
/**
* Algorithm namespace.
*/
var C_algo = C.algo = {};
return C;
}(Math));
return CryptoJS;
}));
},{}],53:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* Base64 encoding strategy.
*/
var Base64 = C_enc.Base64 = {
/**
* Converts a word array to a Base64 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Base64 string.
*
* @static
*
* @example
*
* var base64String = CryptoJS.enc.Base64.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
var map = this._map;
// Clamp excess bits
wordArray.clamp();
// Convert
var base64Chars = [];
for (var i = 0; i < sigBytes; i += 3) {
var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
}
}
// Add padding
var paddingChar = map.charAt(64);
if (paddingChar) {
while (base64Chars.length % 4) {
base64Chars.push(paddingChar);
}
}
return base64Chars.join('');
},
/**
* Converts a Base64 string to a word array.
*
* @param {string} base64Str The Base64 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Base64.parse(base64String);
*/
parse: function (base64Str) {
// Shortcuts
var base64StrLength = base64Str.length;
var map = this._map;
var reverseMap = this._reverseMap;
if (!reverseMap) {
reverseMap = this._reverseMap = [];
for (var j = 0; j < map.length; j++) {
reverseMap[map.charCodeAt(j)] = j;
}
}
// Ignore padding
var paddingChar = map.charAt(64);
if (paddingChar) {
var paddingIndex = base64Str.indexOf(paddingChar);
if (paddingIndex !== -1) {
base64StrLength = paddingIndex;
}
}
// Convert
return parseLoop(base64Str, base64StrLength, reverseMap);
},
_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
};
function parseLoop(base64Str, base64StrLength, reverseMap) {
var words = [];
var nBytes = 0;
for (var i = 0; i < base64StrLength; i++) {
if (i % 4) {
var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2);
var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2);
words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8);
nBytes++;
}
}
return WordArray.create(words, nBytes);
}
}());
return CryptoJS.enc.Base64;
}));
},{"./core":52}],54:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* UTF-16 BE encoding strategy.
*/
var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = {
/**
* Converts a word array to a UTF-16 BE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 BE string.
*
* @static
*
* @example
*
* var utf16String = CryptoJS.enc.Utf16.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff;
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 BE string to a word array.
*
* @param {string} utf16Str The UTF-16 BE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16.parse(utf16String);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16);
}
return WordArray.create(words, utf16StrLength * 2);
}
};
/**
* UTF-16 LE encoding strategy.
*/
C_enc.Utf16LE = {
/**
* Converts a word array to a UTF-16 LE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 LE string.
*
* @static
*
* @example
*
* var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff);
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 LE string to a word array.
*
* @param {string} utf16Str The UTF-16 LE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16));
}
return WordArray.create(words, utf16StrLength * 2);
}
};
function swapEndian(word) {
return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff);
}
}());
return CryptoJS.enc.Utf16;
}));
},{"./core":52}],55:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./sha1"), require("./hmac"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha1", "./hmac"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var MD5 = C_algo.MD5;
/**
* This key derivation function is meant to conform with EVP_BytesToKey.
* www.openssl.org/docs/crypto/EVP_BytesToKey.html
*/
var EvpKDF = C_algo.EvpKDF = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hash algorithm to use. Default: MD5
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: MD5,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.EvpKDF.create();
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
// Shortcut
var cfg = this.cfg;
// Init hasher
var hasher = cfg.hasher.create();
// Initial values
var derivedKey = WordArray.create();
// Shortcuts
var derivedKeyWords = derivedKey.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
if (block) {
hasher.update(block);
}
var block = hasher.update(password).finalize(salt);
hasher.reset();
// Iterations
for (var i = 1; i < iterations; i++) {
block = hasher.finalize(block);
hasher.reset();
}
derivedKey.concat(block);
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.EvpKDF(password, salt);
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 });
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 });
*/
C.EvpKDF = function (password, salt, cfg) {
return EvpKDF.create(cfg).compute(password, salt);
};
}());
return CryptoJS.EvpKDF;
}));
},{"./core":52,"./hmac":57,"./sha1":76}],56:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var CipherParams = C_lib.CipherParams;
var C_enc = C.enc;
var Hex = C_enc.Hex;
var C_format = C.format;
var HexFormatter = C_format.Hex = {
/**
* Converts the ciphertext of a cipher params object to a hexadecimally encoded string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The hexadecimally encoded string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.format.Hex.stringify(cipherParams);
*/
stringify: function (cipherParams) {
return cipherParams.ciphertext.toString(Hex);
},
/**
* Converts a hexadecimally encoded ciphertext string to a cipher params object.
*
* @param {string} input The hexadecimally encoded string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.Hex.parse(hexString);
*/
parse: function (input) {
var ciphertext = Hex.parse(input);
return CipherParams.create({ ciphertext: ciphertext });
}
};
}());
return CryptoJS.format.Hex;
}));
},{"./cipher-core":51,"./core":52}],57:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var C_algo = C.algo;
/**
* HMAC algorithm.
*/
var HMAC = C_algo.HMAC = Base.extend({
/**
* Initializes a newly created HMAC.
*
* @param {Hasher} hasher The hash algorithm to use.
* @param {WordArray|string} key The secret key.
*
* @example
*
* var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
*/
init: function (hasher, key) {
// Init hasher
hasher = this._hasher = new hasher.init();
// Convert string to WordArray, else assume WordArray already
if (typeof key == 'string') {
key = Utf8.parse(key);
}
// Shortcuts
var hasherBlockSize = hasher.blockSize;
var hasherBlockSizeBytes = hasherBlockSize * 4;
// Allow arbitrary length keys
if (key.sigBytes > hasherBlockSizeBytes) {
key = hasher.finalize(key);
}
// Clamp excess bits
key.clamp();
// Clone key for inner and outer pads
var oKey = this._oKey = key.clone();
var iKey = this._iKey = key.clone();
// Shortcuts
var oKeyWords = oKey.words;
var iKeyWords = iKey.words;
// XOR keys with pad constants
for (var i = 0; i < hasherBlockSize; i++) {
oKeyWords[i] ^= 0x5c5c5c5c;
iKeyWords[i] ^= 0x36363636;
}
oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
// Set initial values
this.reset();
},
/**
* Resets this HMAC to its initial state.
*
* @example
*
* hmacHasher.reset();
*/
reset: function () {
// Shortcut
var hasher = this._hasher;
// Reset
hasher.reset();
hasher.update(this._iKey);
},
/**
* Updates this HMAC with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {HMAC} This HMAC instance.
*
* @example
*
* hmacHasher.update('message');
* hmacHasher.update(wordArray);
*/
update: function (messageUpdate) {
this._hasher.update(messageUpdate);
// Chainable
return this;
},
/**
* Finalizes the HMAC computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The HMAC.
*
* @example
*
* var hmac = hmacHasher.finalize();
* var hmac = hmacHasher.finalize('message');
* var hmac = hmacHasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Shortcut
var hasher = this._hasher;
// Compute HMAC
var innerHash = hasher.finalize(messageUpdate);
hasher.reset();
var hmac = hasher.finalize(this._oKey.clone().concat(innerHash));
return hmac;
}
});
}());
}));
},{"./core":52}],58:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./x64-core"), require("./lib-typedarrays"), require("./enc-utf16"), require("./enc-base64"), require("./md5"), require("./sha1"), require("./sha256"), require("./sha224"), require("./sha512"), require("./sha384"), require("./sha3"), require("./ripemd160"), require("./hmac"), require("./pbkdf2"), require("./evpkdf"), require("./cipher-core"), require("./mode-cfb"), require("./mode-ctr"), require("./mode-ctr-gladman"), require("./mode-ofb"), require("./mode-ecb"), require("./pad-ansix923"), require("./pad-iso10126"), require("./pad-iso97971"), require("./pad-zeropadding"), require("./pad-nopadding"), require("./format-hex"), require("./aes"), require("./tripledes"), require("./rc4"), require("./rabbit"), require("./rabbit-legacy"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory);
}
else {
// Global (browser)
root.CryptoJS = factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
return CryptoJS;
}));
},{"./aes":50,"./cipher-core":51,"./core":52,"./enc-base64":53,"./enc-utf16":54,"./evpkdf":55,"./format-hex":56,"./hmac":57,"./lib-typedarrays":59,"./md5":60,"./mode-cfb":61,"./mode-ctr":63,"./mode-ctr-gladman":62,"./mode-ecb":64,"./mode-ofb":65,"./pad-ansix923":66,"./pad-iso10126":67,"./pad-iso97971":68,"./pad-nopadding":69,"./pad-zeropadding":70,"./pbkdf2":71,"./rabbit":73,"./rabbit-legacy":72,"./rc4":74,"./ripemd160":75,"./sha1":76,"./sha224":77,"./sha256":78,"./sha3":79,"./sha384":80,"./sha512":81,"./tripledes":82,"./x64-core":83}],59:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Check if typed arrays are supported
if (typeof ArrayBuffer != 'function') {
return;
}
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
// Reference original init
var superInit = WordArray.init;
// Augment WordArray.init to handle typed arrays
var subInit = WordArray.init = function (typedArray) {
// Convert buffers to uint8
if (typedArray instanceof ArrayBuffer) {
typedArray = new Uint8Array(typedArray);
}
// Convert other array views to uint8
if (
typedArray instanceof Int8Array ||
(typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) ||
typedArray instanceof Int16Array ||
typedArray instanceof Uint16Array ||
typedArray instanceof Int32Array ||
typedArray instanceof Uint32Array ||
typedArray instanceof Float32Array ||
typedArray instanceof Float64Array
) {
typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
}
// Handle Uint8Array
if (typedArray instanceof Uint8Array) {
// Shortcut
var typedArrayByteLength = typedArray.byteLength;
// Extract bytes
var words = [];
for (var i = 0; i < typedArrayByteLength; i++) {
words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8);
}
// Initialize this word array
superInit.call(this, words, typedArrayByteLength);
} else {
// Else call normal init
superInit.apply(this, arguments);
}
};
subInit.prototype = WordArray;
}());
return CryptoJS.lib.WordArray;
}));
},{"./core":52}],60:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var T = [];
// Compute constants
(function () {
for (var i = 0; i < 64; i++) {
T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0;
}
}());
/**
* MD5 hash algorithm.
*/
var MD5 = C_algo.MD5 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476
]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcuts
var H = this._hash.words;
var M_offset_0 = M[offset + 0];
var M_offset_1 = M[offset + 1];
var M_offset_2 = M[offset + 2];
var M_offset_3 = M[offset + 3];
var M_offset_4 = M[offset + 4];
var M_offset_5 = M[offset + 5];
var M_offset_6 = M[offset + 6];
var M_offset_7 = M[offset + 7];
var M_offset_8 = M[offset + 8];
var M_offset_9 = M[offset + 9];
var M_offset_10 = M[offset + 10];
var M_offset_11 = M[offset + 11];
var M_offset_12 = M[offset + 12];
var M_offset_13 = M[offset + 13];
var M_offset_14 = M[offset + 14];
var M_offset_15 = M[offset + 15];
// Working varialbes
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
// Computation
a = FF(a, b, c, d, M_offset_0, 7, T[0]);
d = FF(d, a, b, c, M_offset_1, 12, T[1]);
c = FF(c, d, a, b, M_offset_2, 17, T[2]);
b = FF(b, c, d, a, M_offset_3, 22, T[3]);
a = FF(a, b, c, d, M_offset_4, 7, T[4]);
d = FF(d, a, b, c, M_offset_5, 12, T[5]);
c = FF(c, d, a, b, M_offset_6, 17, T[6]);
b = FF(b, c, d, a, M_offset_7, 22, T[7]);
a = FF(a, b, c, d, M_offset_8, 7, T[8]);
d = FF(d, a, b, c, M_offset_9, 12, T[9]);
c = FF(c, d, a, b, M_offset_10, 17, T[10]);
b = FF(b, c, d, a, M_offset_11, 22, T[11]);
a = FF(a, b, c, d, M_offset_12, 7, T[12]);
d = FF(d, a, b, c, M_offset_13, 12, T[13]);
c = FF(c, d, a, b, M_offset_14, 17, T[14]);
b = FF(b, c, d, a, M_offset_15, 22, T[15]);
a = GG(a, b, c, d, M_offset_1, 5, T[16]);
d = GG(d, a, b, c, M_offset_6, 9, T[17]);
c = GG(c, d, a, b, M_offset_11, 14, T[18]);
b = GG(b, c, d, a, M_offset_0, 20, T[19]);
a = GG(a, b, c, d, M_offset_5, 5, T[20]);
d = GG(d, a, b, c, M_offset_10, 9, T[21]);
c = GG(c, d, a, b, M_offset_15, 14, T[22]);
b = GG(b, c, d, a, M_offset_4, 20, T[23]);
a = GG(a, b, c, d, M_offset_9, 5, T[24]);
d = GG(d, a, b, c, M_offset_14, 9, T[25]);
c = GG(c, d, a, b, M_offset_3, 14, T[26]);
b = GG(b, c, d, a, M_offset_8, 20, T[27]);
a = GG(a, b, c, d, M_offset_13, 5, T[28]);
d = GG(d, a, b, c, M_offset_2, 9, T[29]);
c = GG(c, d, a, b, M_offset_7, 14, T[30]);
b = GG(b, c, d, a, M_offset_12, 20, T[31]);
a = HH(a, b, c, d, M_offset_5, 4, T[32]);
d = HH(d, a, b, c, M_offset_8, 11, T[33]);
c = HH(c, d, a, b, M_offset_11, 16, T[34]);
b = HH(b, c, d, a, M_offset_14, 23, T[35]);
a = HH(a, b, c, d, M_offset_1, 4, T[36]);
d = HH(d, a, b, c, M_offset_4, 11, T[37]);
c = HH(c, d, a, b, M_offset_7, 16, T[38]);
b = HH(b, c, d, a, M_offset_10, 23, T[39]);
a = HH(a, b, c, d, M_offset_13, 4, T[40]);
d = HH(d, a, b, c, M_offset_0, 11, T[41]);
c = HH(c, d, a, b, M_offset_3, 16, T[42]);
b = HH(b, c, d, a, M_offset_6, 23, T[43]);
a = HH(a, b, c, d, M_offset_9, 4, T[44]);
d = HH(d, a, b, c, M_offset_12, 11, T[45]);
c = HH(c, d, a, b, M_offset_15, 16, T[46]);
b = HH(b, c, d, a, M_offset_2, 23, T[47]);
a = II(a, b, c, d, M_offset_0, 6, T[48]);
d = II(d, a, b, c, M_offset_7, 10, T[49]);
c = II(c, d, a, b, M_offset_14, 15, T[50]);
b = II(b, c, d, a, M_offset_5, 21, T[51]);
a = II(a, b, c, d, M_offset_12, 6, T[52]);
d = II(d, a, b, c, M_offset_3, 10, T[53]);
c = II(c, d, a, b, M_offset_10, 15, T[54]);
b = II(b, c, d, a, M_offset_1, 21, T[55]);
a = II(a, b, c, d, M_offset_8, 6, T[56]);
d = II(d, a, b, c, M_offset_15, 10, T[57]);
c = II(c, d, a, b, M_offset_6, 15, T[58]);
b = II(b, c, d, a, M_offset_13, 21, T[59]);
a = II(a, b, c, d, M_offset_4, 6, T[60]);
d = II(d, a, b, c, M_offset_11, 10, T[61]);
c = II(c, d, a, b, M_offset_2, 15, T[62]);
b = II(b, c, d, a, M_offset_9, 21, T[63]);
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000);
var nBitsTotalL = nBitsTotal;
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = (
(((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) |
(((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00)
);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) |
(((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 4; i++) {
// Shortcut
var H_i = H[i];
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function FF(a, b, c, d, x, s, t) {
var n = a + ((b & c) | (~b & d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function GG(a, b, c, d, x, s, t) {
var n = a + ((b & d) | (c & ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function HH(a, b, c, d, x, s, t) {
var n = a + (b ^ c ^ d) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function II(a, b, c, d, x, s, t) {
var n = a + (c ^ (b | ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.MD5('message');
* var hash = CryptoJS.MD5(wordArray);
*/
C.MD5 = Hasher._createHelper(MD5);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacMD5(message, key);
*/
C.HmacMD5 = Hasher._createHmacHelper(MD5);
}(Math));
return CryptoJS.MD5;
}));
},{"./core":52}],61:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher Feedback block mode.
*/
CryptoJS.mode.CFB = (function () {
var CFB = CryptoJS.lib.BlockCipherMode.extend();
CFB.Encryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
CFB.Decryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) {
// Shortcut
var iv = this._iv;
// Generate keystream
if (iv) {
var keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var keystream = this._prevBlock;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
return CFB;
}());
return CryptoJS.mode.CFB;
}));
},{"./cipher-core":51,"./core":52}],62:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
* Counter block mode compatible with Dr Brian Gladman fileenc.c
* derived from CryptoJS.mode.CTR
* Jan Hruby jhruby.web@gmail.com
*/
CryptoJS.mode.CTRGladman = (function () {
var CTRGladman = CryptoJS.lib.BlockCipherMode.extend();
function incWord(word)
{
if (((word >> 24) & 0xff) === 0xff) { //overflow
var b1 = (word >> 16)&0xff;
var b2 = (word >> 8)&0xff;
var b3 = word & 0xff;
if (b1 === 0xff) // overflow b1
{
b1 = 0;
if (b2 === 0xff)
{
b2 = 0;
if (b3 === 0xff)
{
b3 = 0;
}
else
{
++b3;
}
}
else
{
++b2;
}
}
else
{
++b1;
}
word = 0;
word += (b1 << 16);
word += (b2 << 8);
word += b3;
}
else
{
word += (0x01 << 24);
}
return word;
}
function incCounter(counter)
{
if ((counter[0] = incWord(counter[0])) === 0)
{
// encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8
counter[1] = incWord(counter[1]);
}
return counter;
}
var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
incCounter(counter);
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTRGladman.Decryptor = Encryptor;
return CTRGladman;
}());
return CryptoJS.mode.CTRGladman;
}));
},{"./cipher-core":51,"./core":52}],63:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Counter block mode.
*/
CryptoJS.mode.CTR = (function () {
var CTR = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = CTR.Encryptor = CTR.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Increment counter
counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTR.Decryptor = Encryptor;
return CTR;
}());
return CryptoJS.mode.CTR;
}));
},{"./cipher-core":51,"./core":52}],64:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Electronic Codebook block mode.
*/
CryptoJS.mode.ECB = (function () {
var ECB = CryptoJS.lib.BlockCipherMode.extend();
ECB.Encryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.encryptBlock(words, offset);
}
});
ECB.Decryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.decryptBlock(words, offset);
}
});
return ECB;
}());
return CryptoJS.mode.ECB;
}));
},{"./cipher-core":51,"./core":52}],65:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Output Feedback block mode.
*/
CryptoJS.mode.OFB = (function () {
var OFB = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = OFB.Encryptor = OFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var keystream = this._keystream;
// Generate keystream
if (iv) {
keystream = this._keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
OFB.Decryptor = Encryptor;
return OFB;
}());
return CryptoJS.mode.OFB;
}));
},{"./cipher-core":51,"./core":52}],66:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ANSI X.923 padding strategy.
*/
CryptoJS.pad.AnsiX923 = {
pad: function (data, blockSize) {
// Shortcuts
var dataSigBytes = data.sigBytes;
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes;
// Compute last byte position
var lastBytePos = dataSigBytes + nPaddingBytes - 1;
// Pad
data.clamp();
data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8);
data.sigBytes += nPaddingBytes;
},
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
return CryptoJS.pad.Ansix923;
}));
},{"./cipher-core":51,"./core":52}],67:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO 10126 padding strategy.
*/
CryptoJS.pad.Iso10126 = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Pad
data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)).
concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1));
},
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
return CryptoJS.pad.Iso10126;
}));
},{"./cipher-core":51,"./core":52}],68:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO/IEC 9797-1 Padding Method 2.
*/
CryptoJS.pad.Iso97971 = {
pad: function (data, blockSize) {
// Add 0x80 byte
data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1));
// Zero pad the rest
CryptoJS.pad.ZeroPadding.pad(data, blockSize);
},
unpad: function (data) {
// Remove zero padding
CryptoJS.pad.ZeroPadding.unpad(data);
// Remove one more byte -- the 0x80 byte
data.sigBytes--;
}
};
return CryptoJS.pad.Iso97971;
}));
},{"./cipher-core":51,"./core":52}],69:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* A noop padding strategy.
*/
CryptoJS.pad.NoPadding = {
pad: function () {
},
unpad: function () {
}
};
return CryptoJS.pad.NoPadding;
}));
},{"./cipher-core":51,"./core":52}],70:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Zero padding strategy.
*/
CryptoJS.pad.ZeroPadding = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Pad
data.clamp();
data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes);
},
unpad: function (data) {
// Shortcut
var dataWords = data.words;
// Unpad
var i = data.sigBytes - 1;
while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) {
i--;
}
data.sigBytes = i + 1;
}
};
return CryptoJS.pad.ZeroPadding;
}));
},{"./cipher-core":51,"./core":52}],71:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./sha1"), require("./hmac"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha1", "./hmac"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var SHA1 = C_algo.SHA1;
var HMAC = C_algo.HMAC;
/**
* Password-Based Key Derivation Function 2 algorithm.
*/
var PBKDF2 = C_algo.PBKDF2 = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hasher to use. Default: SHA1
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: SHA1,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.PBKDF2.create();
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 });
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
// Shortcut
var cfg = this.cfg;
// Init HMAC
var hmac = HMAC.create(cfg.hasher, password);
// Initial values
var derivedKey = WordArray.create();
var blockIndex = WordArray.create([0x00000001]);
// Shortcuts
var derivedKeyWords = derivedKey.words;
var blockIndexWords = blockIndex.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
var block = hmac.update(salt).finalize(blockIndex);
hmac.reset();
// Shortcuts
var blockWords = block.words;
var blockWordsLength = blockWords.length;
// Iterations
var intermediate = block;
for (var i = 1; i < iterations; i++) {
intermediate = hmac.finalize(intermediate);
hmac.reset();
// Shortcut
var intermediateWords = intermediate.words;
// XOR intermediate with block
for (var j = 0; j < blockWordsLength; j++) {
blockWords[j] ^= intermediateWords[j];
}
}
derivedKey.concat(block);
blockIndexWords[0]++;
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.PBKDF2(password, salt);
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 });
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 });
*/
C.PBKDF2 = function (password, salt, cfg) {
return PBKDF2.create(cfg).compute(password, salt);
};
}());
return CryptoJS.PBKDF2;
}));
},{"./core":52,"./hmac":57,"./sha1":76}],72:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm.
*
* This is a legacy version that neglected to convert the key to little-endian.
* This error doesn't affect the cipher's security,
* but it does affect its compatibility with other implementations.
*/
var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg);
*/
C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy);
}());
return CryptoJS.RabbitLegacy;
}));
},{"./cipher-core":51,"./core":52,"./enc-base64":53,"./evpkdf":55,"./md5":60}],73:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm
*/
var Rabbit = C_algo.Rabbit = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Swap endian
for (var i = 0; i < 4; i++) {
K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) |
(((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00);
}
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg);
* var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg);
*/
C.Rabbit = StreamCipher._createHelper(Rabbit);
}());
return CryptoJS.Rabbit;
}));
},{"./cipher-core":51,"./core":52,"./enc-base64":53,"./evpkdf":55,"./md5":60}],74:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
/**
* RC4 stream cipher algorithm.
*/
var RC4 = C_algo.RC4 = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
var keySigBytes = key.sigBytes;
// Init sbox
var S = this._S = [];
for (var i = 0; i < 256; i++) {
S[i] = i;
}
// Key setup
for (var i = 0, j = 0; i < 256; i++) {
var keyByteIndex = i % keySigBytes;
var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff;
j = (j + S[i] + keyByte) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
}
// Counters
this._i = this._j = 0;
},
_doProcessBlock: function (M, offset) {
M[offset] ^= generateKeystreamWord.call(this);
},
keySize: 256/32,
ivSize: 0
});
function generateKeystreamWord() {
// Shortcuts
var S = this._S;
var i = this._i;
var j = this._j;
// Generate keystream word
var keystreamWord = 0;
for (var n = 0; n < 4; n++) {
i = (i + 1) % 256;
j = (j + S[i]) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8);
}
// Update counters
this._i = i;
this._j = j;
return keystreamWord;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg);
*/
C.RC4 = StreamCipher._createHelper(RC4);
/**
* Modified RC4 stream cipher algorithm.
*/
var RC4Drop = C_algo.RC4Drop = RC4.extend({
/**
* Configuration options.
*
* @property {number} drop The number of keystream words to drop. Default 192
*/
cfg: RC4.cfg.extend({
drop: 192
}),
_doReset: function () {
RC4._doReset.call(this);
// Drop
for (var i = this.cfg.drop; i > 0; i--) {
generateKeystreamWord.call(this);
}
}
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg);
*/
C.RC4Drop = StreamCipher._createHelper(RC4Drop);
}());
return CryptoJS.RC4;
}));
},{"./cipher-core":51,"./core":52,"./enc-base64":53,"./evpkdf":55,"./md5":60}],75:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
(c) 2012 by Cédric Mesnil. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var _zl = WordArray.create([
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]);
var _zr = WordArray.create([
5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]);
var _sl = WordArray.create([
11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]);
var _sr = WordArray.create([
8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]);
var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]);
var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]);
/**
* RIPEMD160 hash algorithm.
*/
var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({
_doReset: function () {
this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
// Swap
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcut
var H = this._hash.words;
var hl = _hl.words;
var hr = _hr.words;
var zl = _zl.words;
var zr = _zr.words;
var sl = _sl.words;
var sr = _sr.words;
// Working variables
var al, bl, cl, dl, el;
var ar, br, cr, dr, er;
ar = al = H[0];
br = bl = H[1];
cr = cl = H[2];
dr = dl = H[3];
er = el = H[4];
// Computation
var t;
for (var i = 0; i < 80; i += 1) {
t = (al + M[offset+zl[i]])|0;
if (i<16){
t += f1(bl,cl,dl) + hl[0];
} else if (i<32) {
t += f2(bl,cl,dl) + hl[1];
} else if (i<48) {
t += f3(bl,cl,dl) + hl[2];
} else if (i<64) {
t += f4(bl,cl,dl) + hl[3];
} else {// if (i<80) {
t += f5(bl,cl,dl) + hl[4];
}
t = t|0;
t = rotl(t,sl[i]);
t = (t+el)|0;
al = el;
el = dl;
dl = rotl(cl, 10);
cl = bl;
bl = t;
t = (ar + M[offset+zr[i]])|0;
if (i<16){
t += f5(br,cr,dr) + hr[0];
} else if (i<32) {
t += f4(br,cr,dr) + hr[1];
} else if (i<48) {
t += f3(br,cr,dr) + hr[2];
} else if (i<64) {
t += f2(br,cr,dr) + hr[3];
} else {// if (i<80) {
t += f1(br,cr,dr) + hr[4];
}
t = t|0;
t = rotl(t,sr[i]) ;
t = (t+er)|0;
ar = er;
er = dr;
dr = rotl(cr, 10);
cr = br;
br = t;
}
// Intermediate hash value
t = (H[1] + cl + dr)|0;
H[1] = (H[2] + dl + er)|0;
H[2] = (H[3] + el + ar)|0;
H[3] = (H[4] + al + br)|0;
H[4] = (H[0] + bl + cr)|0;
H[0] = t;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
(((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 5; i++) {
// Shortcut
var H_i = H[i];
// Swap
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function f1(x, y, z) {
return ((x) ^ (y) ^ (z));
}
function f2(x, y, z) {
return (((x)&(y)) | ((~x)&(z)));
}
function f3(x, y, z) {
return (((x) | (~(y))) ^ (z));
}
function f4(x, y, z) {
return (((x) & (z)) | ((y)&(~(z))));
}
function f5(x, y, z) {
return ((x) ^ ((y) |(~(z))));
}
function rotl(x,n) {
return (x<<n) | (x>>>(32-n));
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.RIPEMD160('message');
* var hash = CryptoJS.RIPEMD160(wordArray);
*/
C.RIPEMD160 = Hasher._createHelper(RIPEMD160);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacRIPEMD160(message, key);
*/
C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160);
}(Math));
return CryptoJS.RIPEMD160;
}));
},{"./core":52}],76:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Reusable object
var W = [];
/**
* SHA-1 hash algorithm.
*/
var SHA1 = C_algo.SHA1 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476,
0xc3d2e1f0
]);
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
// Computation
for (var i = 0; i < 80; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
W[i] = (n << 1) | (n >>> 31);
}
var t = ((a << 5) | (a >>> 27)) + e + W[i];
if (i < 20) {
t += ((b & c) | (~b & d)) + 0x5a827999;
} else if (i < 40) {
t += (b ^ c ^ d) + 0x6ed9eba1;
} else if (i < 60) {
t += ((b & c) | (b & d) | (c & d)) - 0x70e44324;
} else /* if (i < 80) */ {
t += (b ^ c ^ d) - 0x359d3e2a;
}
e = d;
d = c;
c = (b << 30) | (b >>> 2);
b = a;
a = t;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA1('message');
* var hash = CryptoJS.SHA1(wordArray);
*/
C.SHA1 = Hasher._createHelper(SHA1);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA1(message, key);
*/
C.HmacSHA1 = Hasher._createHmacHelper(SHA1);
}());
return CryptoJS.SHA1;
}));
},{"./core":52}],77:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./sha256"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha256"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var SHA256 = C_algo.SHA256;
/**
* SHA-224 hash algorithm.
*/
var SHA224 = C_algo.SHA224 = SHA256.extend({
_doReset: function () {
this._hash = new WordArray.init([
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4
]);
},
_doFinalize: function () {
var hash = SHA256._doFinalize.call(this);
hash.sigBytes -= 4;
return hash;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA224('message');
* var hash = CryptoJS.SHA224(wordArray);
*/
C.SHA224 = SHA256._createHelper(SHA224);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA224(message, key);
*/
C.HmacSHA224 = SHA256._createHmacHelper(SHA224);
}());
return CryptoJS.SHA224;
}));
},{"./core":52,"./sha256":78}],78:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Initialization and round constants tables
var H = [];
var K = [];
// Compute constants
(function () {
function isPrime(n) {
var sqrtN = Math.sqrt(n);
for (var factor = 2; factor <= sqrtN; factor++) {
if (!(n % factor)) {
return false;
}
}
return true;
}
function getFractionalBits(n) {
return ((n - (n | 0)) * 0x100000000) | 0;
}
var n = 2;
var nPrime = 0;
while (nPrime < 64) {
if (isPrime(n)) {
if (nPrime < 8) {
H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
}
K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
nPrime++;
}
n++;
}
}());
// Reusable object
var W = [];
/**
* SHA-256 hash algorithm.
*/
var SHA256 = C_algo.SHA256 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init(H.slice(0));
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
var f = H[5];
var g = H[6];
var h = H[7];
// Computation
for (var i = 0; i < 64; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var gamma0x = W[i - 15];
var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
((gamma0x << 14) | (gamma0x >>> 18)) ^
(gamma0x >>> 3);
var gamma1x = W[i - 2];
var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
((gamma1x << 13) | (gamma1x >>> 19)) ^
(gamma1x >>> 10);
W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
}
var ch = (e & f) ^ (~e & g);
var maj = (a & b) ^ (a & c) ^ (b & c);
var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
var t1 = h + sigma1 + ch + K[i] + W[i];
var t2 = sigma0 + maj;
h = g;
g = f;
f = e;
e = (d + t1) | 0;
d = c;
c = b;
b = a;
a = (t1 + t2) | 0;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
H[5] = (H[5] + f) | 0;
H[6] = (H[6] + g) | 0;
H[7] = (H[7] + h) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA256('message');
* var hash = CryptoJS.SHA256(wordArray);
*/
C.SHA256 = Hasher._createHelper(SHA256);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA256(message, key);
*/
C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
}(Math));
return CryptoJS.SHA256;
}));
},{"./core":52}],79:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var C_algo = C.algo;
// Constants tables
var RHO_OFFSETS = [];
var PI_INDEXES = [];
var ROUND_CONSTANTS = [];
// Compute Constants
(function () {
// Compute rho offset constants
var x = 1, y = 0;
for (var t = 0; t < 24; t++) {
RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64;
var newX = y % 5;
var newY = (2 * x + 3 * y) % 5;
x = newX;
y = newY;
}
// Compute pi index constants
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5;
}
}
// Compute round constants
var LFSR = 0x01;
for (var i = 0; i < 24; i++) {
var roundConstantMsw = 0;
var roundConstantLsw = 0;
for (var j = 0; j < 7; j++) {
if (LFSR & 0x01) {
var bitPosition = (1 << j) - 1;
if (bitPosition < 32) {
roundConstantLsw ^= 1 << bitPosition;
} else /* if (bitPosition >= 32) */ {
roundConstantMsw ^= 1 << (bitPosition - 32);
}
}
// Compute next LFSR
if (LFSR & 0x80) {
// Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1
LFSR = (LFSR << 1) ^ 0x71;
} else {
LFSR <<= 1;
}
}
ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw);
}
}());
// Reusable objects for temporary values
var T = [];
(function () {
for (var i = 0; i < 25; i++) {
T[i] = X64Word.create();
}
}());
/**
* SHA-3 hash algorithm.
*/
var SHA3 = C_algo.SHA3 = Hasher.extend({
/**
* Configuration options.
*
* @property {number} outputLength
* The desired number of bits in the output hash.
* Only values permitted are: 224, 256, 384, 512.
* Default: 512
*/
cfg: Hasher.cfg.extend({
outputLength: 512
}),
_doReset: function () {
var state = this._state = []
for (var i = 0; i < 25; i++) {
state[i] = new X64Word.init();
}
this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32;
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var state = this._state;
var nBlockSizeLanes = this.blockSize / 2;
// Absorb
for (var i = 0; i < nBlockSizeLanes; i++) {
// Shortcuts
var M2i = M[offset + 2 * i];
var M2i1 = M[offset + 2 * i + 1];
// Swap endian
M2i = (
(((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) |
(((M2i << 24) | (M2i >>> 8)) & 0xff00ff00)
);
M2i1 = (
(((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) |
(((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00)
);
// Absorb message into state
var lane = state[i];
lane.high ^= M2i1;
lane.low ^= M2i;
}
// Rounds
for (var round = 0; round < 24; round++) {
// Theta
for (var x = 0; x < 5; x++) {
// Mix column lanes
var tMsw = 0, tLsw = 0;
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
tMsw ^= lane.high;
tLsw ^= lane.low;
}
// Temporary values
var Tx = T[x];
Tx.high = tMsw;
Tx.low = tLsw;
}
for (var x = 0; x < 5; x++) {
// Shortcuts
var Tx4 = T[(x + 4) % 5];
var Tx1 = T[(x + 1) % 5];
var Tx1Msw = Tx1.high;
var Tx1Lsw = Tx1.low;
// Mix surrounding columns
var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31));
var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31));
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
lane.high ^= tMsw;
lane.low ^= tLsw;
}
}
// Rho Pi
for (var laneIndex = 1; laneIndex < 25; laneIndex++) {
// Shortcuts
var lane = state[laneIndex];
var laneMsw = lane.high;
var laneLsw = lane.low;
var rhoOffset = RHO_OFFSETS[laneIndex];
// Rotate lanes
if (rhoOffset < 32) {
var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset));
var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset));
} else /* if (rhoOffset >= 32) */ {
var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset));
var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset));
}
// Transpose lanes
var TPiLane = T[PI_INDEXES[laneIndex]];
TPiLane.high = tMsw;
TPiLane.low = tLsw;
}
// Rho pi at x = y = 0
var T0 = T[0];
var state0 = state[0];
T0.high = state0.high;
T0.low = state0.low;
// Chi
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
// Shortcuts
var laneIndex = x + 5 * y;
var lane = state[laneIndex];
var TLane = T[laneIndex];
var Tx1Lane = T[((x + 1) % 5) + 5 * y];
var Tx2Lane = T[((x + 2) % 5) + 5 * y];
// Mix rows
lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high);
lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low);
}
}
// Iota
var lane = state[0];
var roundConstant = ROUND_CONSTANTS[round];
lane.high ^= roundConstant.high;
lane.low ^= roundConstant.low;;
}
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
var blockSizeBits = this.blockSize * 32;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32);
dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Shortcuts
var state = this._state;
var outputLengthBytes = this.cfg.outputLength / 8;
var outputLengthLanes = outputLengthBytes / 8;
// Squeeze
var hashWords = [];
for (var i = 0; i < outputLengthLanes; i++) {
// Shortcuts
var lane = state[i];
var laneMsw = lane.high;
var laneLsw = lane.low;
// Swap endian
laneMsw = (
(((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) |
(((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00)
);
laneLsw = (
(((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) |
(((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00)
);
// Squeeze state to retrieve hash
hashWords.push(laneLsw);
hashWords.push(laneMsw);
}
// Return final computed hash
return new WordArray.init(hashWords, outputLengthBytes);
},
clone: function () {
var clone = Hasher.clone.call(this);
var state = clone._state = this._state.slice(0);
for (var i = 0; i < 25; i++) {
state[i] = state[i].clone();
}
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA3('message');
* var hash = CryptoJS.SHA3(wordArray);
*/
C.SHA3 = Hasher._createHelper(SHA3);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA3(message, key);
*/
C.HmacSHA3 = Hasher._createHmacHelper(SHA3);
}(Math));
return CryptoJS.SHA3;
}));
},{"./core":52,"./x64-core":83}],80:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./x64-core"), require("./sha512"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core", "./sha512"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
var SHA512 = C_algo.SHA512;
/**
* SHA-384 hash algorithm.
*/
var SHA384 = C_algo.SHA384 = SHA512.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507),
new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939),
new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511),
new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4)
]);
},
_doFinalize: function () {
var hash = SHA512._doFinalize.call(this);
hash.sigBytes -= 16;
return hash;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA384('message');
* var hash = CryptoJS.SHA384(wordArray);
*/
C.SHA384 = SHA512._createHelper(SHA384);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA384(message, key);
*/
C.HmacSHA384 = SHA512._createHmacHelper(SHA384);
}());
return CryptoJS.SHA384;
}));
},{"./core":52,"./sha512":81,"./x64-core":83}],81:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
function X64Word_create() {
return X64Word.create.apply(X64Word, arguments);
}
// Constants
var K = [
X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd),
X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc),
X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019),
X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118),
X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe),
X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2),
X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1),
X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694),
X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3),
X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65),
X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483),
X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5),
X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210),
X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4),
X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725),
X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70),
X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926),
X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df),
X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8),
X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b),
X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001),
X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30),
X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910),
X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8),
X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53),
X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8),
X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb),
X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3),
X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60),
X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec),
X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9),
X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b),
X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207),
X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178),
X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6),
X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b),
X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493),
X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c),
X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a),
X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817)
];
// Reusable objects
var W = [];
(function () {
for (var i = 0; i < 80; i++) {
W[i] = X64Word_create();
}
}());
/**
* SHA-512 hash algorithm.
*/
var SHA512 = C_algo.SHA512 = Hasher.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b),
new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1),
new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f),
new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179)
]);
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var H = this._hash.words;
var H0 = H[0];
var H1 = H[1];
var H2 = H[2];
var H3 = H[3];
var H4 = H[4];
var H5 = H[5];
var H6 = H[6];
var H7 = H[7];
var H0h = H0.high;
var H0l = H0.low;
var H1h = H1.high;
var H1l = H1.low;
var H2h = H2.high;
var H2l = H2.low;
var H3h = H3.high;
var H3l = H3.low;
var H4h = H4.high;
var H4l = H4.low;
var H5h = H5.high;
var H5l = H5.low;
var H6h = H6.high;
var H6l = H6.low;
var H7h = H7.high;
var H7l = H7.low;
// Working variables
var ah = H0h;
var al = H0l;
var bh = H1h;
var bl = H1l;
var ch = H2h;
var cl = H2l;
var dh = H3h;
var dl = H3l;
var eh = H4h;
var el = H4l;
var fh = H5h;
var fl = H5l;
var gh = H6h;
var gl = H6l;
var hh = H7h;
var hl = H7l;
// Rounds
for (var i = 0; i < 80; i++) {
// Shortcut
var Wi = W[i];
// Extend message
if (i < 16) {
var Wih = Wi.high = M[offset + i * 2] | 0;
var Wil = Wi.low = M[offset + i * 2 + 1] | 0;
} else {
// Gamma0
var gamma0x = W[i - 15];
var gamma0xh = gamma0x.high;
var gamma0xl = gamma0x.low;
var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7);
var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25));
// Gamma1
var gamma1x = W[i - 2];
var gamma1xh = gamma1x.high;
var gamma1xl = gamma1x.low;
var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6);
var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26));
// W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
var Wi7 = W[i - 7];
var Wi7h = Wi7.high;
var Wi7l = Wi7.low;
var Wi16 = W[i - 16];
var Wi16h = Wi16.high;
var Wi16l = Wi16.low;
var Wil = gamma0l + Wi7l;
var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0);
var Wil = Wil + gamma1l;
var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0);
var Wil = Wil + Wi16l;
var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0);
Wi.high = Wih;
Wi.low = Wil;
}
var chh = (eh & fh) ^ (~eh & gh);
var chl = (el & fl) ^ (~el & gl);
var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch);
var majl = (al & bl) ^ (al & cl) ^ (bl & cl);
var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7));
var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7));
var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9));
var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9));
// t1 = h + sigma1 + ch + K[i] + W[i]
var Ki = K[i];
var Kih = Ki.high;
var Kil = Ki.low;
var t1l = hl + sigma1l;
var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0);
var t1l = t1l + chl;
var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0);
var t1l = t1l + Kil;
var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0);
var t1l = t1l + Wil;
var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0);
// t2 = sigma0 + maj
var t2l = sigma0l + majl;
var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0);
// Update working variables
hh = gh;
hl = gl;
gh = fh;
gl = fl;
fh = eh;
fl = el;
el = (dl + t1l) | 0;
eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0;
dh = ch;
dl = cl;
ch = bh;
cl = bl;
bh = ah;
bl = al;
al = (t1l + t2l) | 0;
ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0;
}
// Intermediate hash value
H0l = H0.low = (H0l + al);
H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0));
H1l = H1.low = (H1l + bl);
H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0));
H2l = H2.low = (H2l + cl);
H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0));
H3l = H3.low = (H3l + dl);
H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0));
H4l = H4.low = (H4l + el);
H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0));
H5l = H5.low = (H5l + fl);
H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0));
H6l = H6.low = (H6l + gl);
H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0));
H7l = H7.low = (H7l + hl);
H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0));
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Convert hash to 32-bit word array before returning
var hash = this._hash.toX32();
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
},
blockSize: 1024/32
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA512('message');
* var hash = CryptoJS.SHA512(wordArray);
*/
C.SHA512 = Hasher._createHelper(SHA512);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA512(message, key);
*/
C.HmacSHA512 = Hasher._createHmacHelper(SHA512);
}());
return CryptoJS.SHA512;
}));
},{"./core":52,"./x64-core":83}],82:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Permuted Choice 1 constants
var PC1 = [
57, 49, 41, 33, 25, 17, 9, 1,
58, 50, 42, 34, 26, 18, 10, 2,
59, 51, 43, 35, 27, 19, 11, 3,
60, 52, 44, 36, 63, 55, 47, 39,
31, 23, 15, 7, 62, 54, 46, 38,
30, 22, 14, 6, 61, 53, 45, 37,
29, 21, 13, 5, 28, 20, 12, 4
];
// Permuted Choice 2 constants
var PC2 = [
14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55,
30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53,
46, 42, 50, 36, 29, 32
];
// Cumulative bit shift constants
var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28];
// SBOXes and round permutation constants
var SBOX_P = [
{
0x0: 0x808200,
0x10000000: 0x8000,
0x20000000: 0x808002,
0x30000000: 0x2,
0x40000000: 0x200,
0x50000000: 0x808202,
0x60000000: 0x800202,
0x70000000: 0x800000,
0x80000000: 0x202,
0x90000000: 0x800200,
0xa0000000: 0x8200,
0xb0000000: 0x808000,
0xc0000000: 0x8002,
0xd0000000: 0x800002,
0xe0000000: 0x0,
0xf0000000: 0x8202,
0x8000000: 0x0,
0x18000000: 0x808202,
0x28000000: 0x8202,
0x38000000: 0x8000,
0x48000000: 0x808200,
0x58000000: 0x200,
0x68000000: 0x808002,
0x78000000: 0x2,
0x88000000: 0x800200,
0x98000000: 0x8200,
0xa8000000: 0x808000,
0xb8000000: 0x800202,
0xc8000000: 0x800002,
0xd8000000: 0x8002,
0xe8000000: 0x202,
0xf8000000: 0x800000,
0x1: 0x8000,
0x10000001: 0x2,
0x20000001: 0x808200,
0x30000001: 0x800000,
0x40000001: 0x808002,
0x50000001: 0x8200,
0x60000001: 0x200,
0x70000001: 0x800202,
0x80000001: 0x808202,
0x90000001: 0x808000,
0xa0000001: 0x800002,
0xb0000001: 0x8202,
0xc0000001: 0x202,
0xd0000001: 0x800200,
0xe0000001: 0x8002,
0xf0000001: 0x0,
0x8000001: 0x808202,
0x18000001: 0x808000,
0x28000001: 0x800000,
0x38000001: 0x200,
0x48000001: 0x8000,
0x58000001: 0x800002,
0x68000001: 0x2,
0x78000001: 0x8202,
0x88000001: 0x8002,
0x98000001: 0x800202,
0xa8000001: 0x202,
0xb8000001: 0x808200,
0xc8000001: 0x800200,
0xd8000001: 0x0,
0xe8000001: 0x8200,
0xf8000001: 0x808002
},
{
0x0: 0x40084010,
0x1000000: 0x4000,
0x2000000: 0x80000,
0x3000000: 0x40080010,
0x4000000: 0x40000010,
0x5000000: 0x40084000,
0x6000000: 0x40004000,
0x7000000: 0x10,
0x8000000: 0x84000,
0x9000000: 0x40004010,
0xa000000: 0x40000000,
0xb000000: 0x84010,
0xc000000: 0x80010,
0xd000000: 0x0,
0xe000000: 0x4010,
0xf000000: 0x40080000,
0x800000: 0x40004000,
0x1800000: 0x84010,
0x2800000: 0x10,
0x3800000: 0x40004010,
0x4800000: 0x40084010,
0x5800000: 0x40000000,
0x6800000: 0x80000,
0x7800000: 0x40080010,
0x8800000: 0x80010,
0x9800000: 0x0,
0xa800000: 0x4000,
0xb800000: 0x40080000,
0xc800000: 0x40000010,
0xd800000: 0x84000,
0xe800000: 0x40084000,
0xf800000: 0x4010,
0x10000000: 0x0,
0x11000000: 0x40080010,
0x12000000: 0x40004010,
0x13000000: 0x40084000,
0x14000000: 0x40080000,
0x15000000: 0x10,
0x16000000: 0x84010,
0x17000000: 0x4000,
0x18000000: 0x4010,
0x19000000: 0x80000,
0x1a000000: 0x80010,
0x1b000000: 0x40000010,
0x1c000000: 0x84000,
0x1d000000: 0x40004000,
0x1e000000: 0x40000000,
0x1f000000: 0x40084010,
0x10800000: 0x84010,
0x11800000: 0x80000,
0x12800000: 0x40080000,
0x13800000: 0x4000,
0x14800000: 0x40004000,
0x15800000: 0x40084010,
0x16800000: 0x10,
0x17800000: 0x40000000,
0x18800000: 0x40084000,
0x19800000: 0x40000010,
0x1a800000: 0x40004010,
0x1b800000: 0x80010,
0x1c800000: 0x0,
0x1d800000: 0x4010,
0x1e800000: 0x40080010,
0x1f800000: 0x84000
},
{
0x0: 0x104,
0x100000: 0x0,
0x200000: 0x4000100,
0x300000: 0x10104,
0x400000: 0x10004,
0x500000: 0x4000004,
0x600000: 0x4010104,
0x700000: 0x4010000,
0x800000: 0x4000000,
0x900000: 0x4010100,
0xa00000: 0x10100,
0xb00000: 0x4010004,
0xc00000: 0x4000104,
0xd00000: 0x10000,
0xe00000: 0x4,
0xf00000: 0x100,
0x80000: 0x4010100,
0x180000: 0x4010004,
0x280000: 0x0,
0x380000: 0x4000100,
0x480000: 0x4000004,
0x580000: 0x10000,
0x680000: 0x10004,
0x780000: 0x104,
0x880000: 0x4,
0x980000: 0x100,
0xa80000: 0x4010000,
0xb80000: 0x10104,
0xc80000: 0x10100,
0xd80000: 0x4000104,
0xe80000: 0x4010104,
0xf80000: 0x4000000,
0x1000000: 0x4010100,
0x1100000: 0x10004,
0x1200000: 0x10000,
0x1300000: 0x4000100,
0x1400000: 0x100,
0x1500000: 0x4010104,
0x1600000: 0x4000004,
0x1700000: 0x0,
0x1800000: 0x4000104,
0x1900000: 0x4000000,
0x1a00000: 0x4,
0x1b00000: 0x10100,
0x1c00000: 0x4010000,
0x1d00000: 0x104,
0x1e00000: 0x10104,
0x1f00000: 0x4010004,
0x1080000: 0x4000000,
0x1180000: 0x104,
0x1280000: 0x4010100,
0x1380000: 0x0,
0x1480000: 0x10004,
0x1580000: 0x4000100,
0x1680000: 0x100,
0x1780000: 0x4010004,
0x1880000: 0x10000,
0x1980000: 0x4010104,
0x1a80000: 0x10104,
0x1b80000: 0x4000004,
0x1c80000: 0x4000104,
0x1d80000: 0x4010000,
0x1e80000: 0x4,
0x1f80000: 0x10100
},
{
0x0: 0x80401000,
0x10000: 0x80001040,
0x20000: 0x401040,
0x30000: 0x80400000,
0x40000: 0x0,
0x50000: 0x401000,
0x60000: 0x80000040,
0x70000: 0x400040,
0x80000: 0x80000000,
0x90000: 0x400000,
0xa0000: 0x40,
0xb0000: 0x80001000,
0xc0000: 0x80400040,
0xd0000: 0x1040,
0xe0000: 0x1000,
0xf0000: 0x80401040,
0x8000: 0x80001040,
0x18000: 0x40,
0x28000: 0x80400040,
0x38000: 0x80001000,
0x48000: 0x401000,
0x58000: 0x80401040,
0x68000: 0x0,
0x78000: 0x80400000,
0x88000: 0x1000,
0x98000: 0x80401000,
0xa8000: 0x400000,
0xb8000: 0x1040,
0xc8000: 0x80000000,
0xd8000: 0x400040,
0xe8000: 0x401040,
0xf8000: 0x80000040,
0x100000: 0x400040,
0x110000: 0x401000,
0x120000: 0x80000040,
0x130000: 0x0,
0x140000: 0x1040,
0x150000: 0x80400040,
0x160000: 0x80401000,
0x170000: 0x80001040,
0x180000: 0x80401040,
0x190000: 0x80000000,
0x1a0000: 0x80400000,
0x1b0000: 0x401040,
0x1c0000: 0x80001000,
0x1d0000: 0x400000,
0x1e0000: 0x40,
0x1f0000: 0x1000,
0x108000: 0x80400000,
0x118000: 0x80401040,
0x128000: 0x0,
0x138000: 0x401000,
0x148000: 0x400040,
0x158000: 0x80000000,
0x168000: 0x80001040,
0x178000: 0x40,
0x188000: 0x80000040,
0x198000: 0x1000,
0x1a8000: 0x80001000,
0x1b8000: 0x80400040,
0x1c8000: 0x1040,
0x1d8000: 0x80401000,
0x1e8000: 0x400000,
0x1f8000: 0x401040
},
{
0x0: 0x80,
0x1000: 0x1040000,
0x2000: 0x40000,
0x3000: 0x20000000,
0x4000: 0x20040080,
0x5000: 0x1000080,
0x6000: 0x21000080,
0x7000: 0x40080,
0x8000: 0x1000000,
0x9000: 0x20040000,
0xa000: 0x20000080,
0xb000: 0x21040080,
0xc000: 0x21040000,
0xd000: 0x0,
0xe000: 0x1040080,
0xf000: 0x21000000,
0x800: 0x1040080,
0x1800: 0x21000080,
0x2800: 0x80,
0x3800: 0x1040000,
0x4800: 0x40000,
0x5800: 0x20040080,
0x6800: 0x21040000,
0x7800: 0x20000000,
0x8800: 0x20040000,
0x9800: 0x0,
0xa800: 0x21040080,
0xb800: 0x1000080,
0xc800: 0x20000080,
0xd800: 0x21000000,
0xe800: 0x1000000,
0xf800: 0x40080,
0x10000: 0x40000,
0x11000: 0x80,
0x12000: 0x20000000,
0x13000: 0x21000080,
0x14000: 0x1000080,
0x15000: 0x21040000,
0x16000: 0x20040080,
0x17000: 0x1000000,
0x18000: 0x21040080,
0x19000: 0x21000000,
0x1a000: 0x1040000,
0x1b000: 0x20040000,
0x1c000: 0x40080,
0x1d000: 0x20000080,
0x1e000: 0x0,
0x1f000: 0x1040080,
0x10800: 0x21000080,
0x11800: 0x1000000,
0x12800: 0x1040000,
0x13800: 0x20040080,
0x14800: 0x20000000,
0x15800: 0x1040080,
0x16800: 0x80,
0x17800: 0x21040000,
0x18800: 0x40080,
0x19800: 0x21040080,
0x1a800: 0x0,
0x1b800: 0x21000000,
0x1c800: 0x1000080,
0x1d800: 0x40000,
0x1e800: 0x20040000,
0x1f800: 0x20000080
},
{
0x0: 0x10000008,
0x100: 0x2000,
0x200: 0x10200000,
0x300: 0x10202008,
0x400: 0x10002000,
0x500: 0x200000,
0x600: 0x200008,
0x700: 0x10000000,
0x800: 0x0,
0x900: 0x10002008,
0xa00: 0x202000,
0xb00: 0x8,
0xc00: 0x10200008,
0xd00: 0x202008,
0xe00: 0x2008,
0xf00: 0x10202000,
0x80: 0x10200000,
0x180: 0x10202008,
0x280: 0x8,
0x380: 0x200000,
0x480: 0x202008,
0x580: 0x10000008,
0x680: 0x10002000,
0x780: 0x2008,
0x880: 0x200008,
0x980: 0x2000,
0xa80: 0x10002008,
0xb80: 0x10200008,
0xc80: 0x0,
0xd80: 0x10202000,
0xe80: 0x202000,
0xf80: 0x10000000,
0x1000: 0x10002000,
0x1100: 0x10200008,
0x1200: 0x10202008,
0x1300: 0x2008,
0x1400: 0x200000,
0x1500: 0x10000000,
0x1600: 0x10000008,
0x1700: 0x202000,
0x1800: 0x202008,
0x1900: 0x0,
0x1a00: 0x8,
0x1b00: 0x10200000,
0x1c00: 0x2000,
0x1d00: 0x10002008,
0x1e00: 0x10202000,
0x1f00: 0x200008,
0x1080: 0x8,
0x1180: 0x202000,
0x1280: 0x200000,
0x1380: 0x10000008,
0x1480: 0x10002000,
0x1580: 0x2008,
0x1680: 0x10202008,
0x1780: 0x10200000,
0x1880: 0x10202000,
0x1980: 0x10200008,
0x1a80: 0x2000,
0x1b80: 0x202008,
0x1c80: 0x200008,
0x1d80: 0x0,
0x1e80: 0x10000000,
0x1f80: 0x10002008
},
{
0x0: 0x100000,
0x10: 0x2000401,
0x20: 0x400,
0x30: 0x100401,
0x40: 0x2100401,
0x50: 0x0,
0x60: 0x1,
0x70: 0x2100001,
0x80: 0x2000400,
0x90: 0x100001,
0xa0: 0x2000001,
0xb0: 0x2100400,
0xc0: 0x2100000,
0xd0: 0x401,
0xe0: 0x100400,
0xf0: 0x2000000,
0x8: 0x2100001,
0x18: 0x0,
0x28: 0x2000401,
0x38: 0x2100400,
0x48: 0x100000,
0x58: 0x2000001,
0x68: 0x2000000,
0x78: 0x401,
0x88: 0x100401,
0x98: 0x2000400,
0xa8: 0x2100000,
0xb8: 0x100001,
0xc8: 0x400,
0xd8: 0x2100401,
0xe8: 0x1,
0xf8: 0x100400,
0x100: 0x2000000,
0x110: 0x100000,
0x120: 0x2000401,
0x130: 0x2100001,
0x140: 0x100001,
0x150: 0x2000400,
0x160: 0x2100400,
0x170: 0x100401,
0x180: 0x401,
0x190: 0x2100401,
0x1a0: 0x100400,
0x1b0: 0x1,
0x1c0: 0x0,
0x1d0: 0x2100000,
0x1e0: 0x2000001,
0x1f0: 0x400,
0x108: 0x100400,
0x118: 0x2000401,
0x128: 0x2100001,
0x138: 0x1,
0x148: 0x2000000,
0x158: 0x100000,
0x168: 0x401,
0x178: 0x2100400,
0x188: 0x2000001,
0x198: 0x2100000,
0x1a8: 0x0,
0x1b8: 0x2100401,
0x1c8: 0x100401,
0x1d8: 0x400,
0x1e8: 0x2000400,
0x1f8: 0x100001
},
{
0x0: 0x8000820,
0x1: 0x20000,
0x2: 0x8000000,
0x3: 0x20,
0x4: 0x20020,
0x5: 0x8020820,
0x6: 0x8020800,
0x7: 0x800,
0x8: 0x8020000,
0x9: 0x8000800,
0xa: 0x20800,
0xb: 0x8020020,
0xc: 0x820,
0xd: 0x0,
0xe: 0x8000020,
0xf: 0x20820,
0x80000000: 0x800,
0x80000001: 0x8020820,
0x80000002: 0x8000820,
0x80000003: 0x8000000,
0x80000004: 0x8020000,
0x80000005: 0x20800,
0x80000006: 0x20820,
0x80000007: 0x20,
0x80000008: 0x8000020,
0x80000009: 0x820,
0x8000000a: 0x20020,
0x8000000b: 0x8020800,
0x8000000c: 0x0,
0x8000000d: 0x8020020,
0x8000000e: 0x8000800,
0x8000000f: 0x20000,
0x10: 0x20820,
0x11: 0x8020800,
0x12: 0x20,
0x13: 0x800,
0x14: 0x8000800,
0x15: 0x8000020,
0x16: 0x8020020,
0x17: 0x20000,
0x18: 0x0,
0x19: 0x20020,
0x1a: 0x8020000,
0x1b: 0x8000820,
0x1c: 0x8020820,
0x1d: 0x20800,
0x1e: 0x820,
0x1f: 0x8000000,
0x80000010: 0x20000,
0x80000011: 0x800,
0x80000012: 0x8020020,
0x80000013: 0x20820,
0x80000014: 0x20,
0x80000015: 0x8020000,
0x80000016: 0x8000000,
0x80000017: 0x8000820,
0x80000018: 0x8020820,
0x80000019: 0x8000020,
0x8000001a: 0x8000800,
0x8000001b: 0x0,
0x8000001c: 0x20800,
0x8000001d: 0x820,
0x8000001e: 0x20020,
0x8000001f: 0x8020800
}
];
// Masks that select the SBOX input
var SBOX_MASK = [
0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000,
0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f
];
/**
* DES block cipher algorithm.
*/
var DES = C_algo.DES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Select 56 bits according to PC1
var keyBits = [];
for (var i = 0; i < 56; i++) {
var keyBitPos = PC1[i] - 1;
keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1;
}
// Assemble 16 subkeys
var subKeys = this._subKeys = [];
for (var nSubKey = 0; nSubKey < 16; nSubKey++) {
// Create subkey
var subKey = subKeys[nSubKey] = [];
// Shortcut
var bitShift = BIT_SHIFTS[nSubKey];
// Select 48 bits according to PC2
for (var i = 0; i < 24; i++) {
// Select from the left 28 key bits
subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6);
// Select from the right 28 key bits
subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6);
}
// Since each subkey is applied to an expanded 32-bit input,
// the subkey can be broken into 8 values scaled to 32-bits,
// which allows the key to be used without expansion
subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31);
for (var i = 1; i < 7; i++) {
subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3);
}
subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27);
}
// Compute inverse subkeys
var invSubKeys = this._invSubKeys = [];
for (var i = 0; i < 16; i++) {
invSubKeys[i] = subKeys[15 - i];
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._subKeys);
},
decryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._invSubKeys);
},
_doCryptBlock: function (M, offset, subKeys) {
// Get input
this._lBlock = M[offset];
this._rBlock = M[offset + 1];
// Initial permutation
exchangeLR.call(this, 4, 0x0f0f0f0f);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeRL.call(this, 2, 0x33333333);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeLR.call(this, 1, 0x55555555);
// Rounds
for (var round = 0; round < 16; round++) {
// Shortcuts
var subKey = subKeys[round];
var lBlock = this._lBlock;
var rBlock = this._rBlock;
// Feistel function
var f = 0;
for (var i = 0; i < 8; i++) {
f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0];
}
this._lBlock = rBlock;
this._rBlock = lBlock ^ f;
}
// Undo swap from last round
var t = this._lBlock;
this._lBlock = this._rBlock;
this._rBlock = t;
// Final permutation
exchangeLR.call(this, 1, 0x55555555);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeRL.call(this, 2, 0x33333333);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeLR.call(this, 4, 0x0f0f0f0f);
// Set output
M[offset] = this._lBlock;
M[offset + 1] = this._rBlock;
},
keySize: 64/32,
ivSize: 64/32,
blockSize: 64/32
});
// Swap bits across the left and right words
function exchangeLR(offset, mask) {
var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask;
this._rBlock ^= t;
this._lBlock ^= t << offset;
}
function exchangeRL(offset, mask) {
var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask;
this._lBlock ^= t;
this._rBlock ^= t << offset;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.DES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg);
*/
C.DES = BlockCipher._createHelper(DES);
/**
* Triple-DES block cipher algorithm.
*/
var TripleDES = C_algo.TripleDES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Create DES instances
this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2)));
this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4)));
this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6)));
},
encryptBlock: function (M, offset) {
this._des1.encryptBlock(M, offset);
this._des2.decryptBlock(M, offset);
this._des3.encryptBlock(M, offset);
},
decryptBlock: function (M, offset) {
this._des3.decryptBlock(M, offset);
this._des2.encryptBlock(M, offset);
this._des1.decryptBlock(M, offset);
},
keySize: 192/32,
ivSize: 64/32,
blockSize: 64/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg);
*/
C.TripleDES = BlockCipher._createHelper(TripleDES);
}());
return CryptoJS.TripleDES;
}));
},{"./cipher-core":51,"./core":52,"./enc-base64":53,"./evpkdf":55,"./md5":60}],83:[function(require,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var X32WordArray = C_lib.WordArray;
/**
* x64 namespace.
*/
var C_x64 = C.x64 = {};
/**
* A 64-bit word.
*/
var X64Word = C_x64.Word = Base.extend({
/**
* Initializes a newly created 64-bit word.
*
* @param {number} high The high 32 bits.
* @param {number} low The low 32 bits.
*
* @example
*
* var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
*/
init: function (high, low) {
this.high = high;
this.low = low;
}
/**
* Bitwise NOTs this word.
*
* @return {X64Word} A new x64-Word object after negating.
*
* @example
*
* var negated = x64Word.not();
*/
// not: function () {
// var high = ~this.high;
// var low = ~this.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ANDs this word with the passed word.
*
* @param {X64Word} word The x64-Word to AND with this word.
*
* @return {X64Word} A new x64-Word object after ANDing.
*
* @example
*
* var anded = x64Word.and(anotherX64Word);
*/
// and: function (word) {
// var high = this.high & word.high;
// var low = this.low & word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to OR with this word.
*
* @return {X64Word} A new x64-Word object after ORing.
*
* @example
*
* var ored = x64Word.or(anotherX64Word);
*/
// or: function (word) {
// var high = this.high | word.high;
// var low = this.low | word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise XORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to XOR with this word.
*
* @return {X64Word} A new x64-Word object after XORing.
*
* @example
*
* var xored = x64Word.xor(anotherX64Word);
*/
// xor: function (word) {
// var high = this.high ^ word.high;
// var low = this.low ^ word.low;
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the left.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftL(25);
*/
// shiftL: function (n) {
// if (n < 32) {
// var high = (this.high << n) | (this.low >>> (32 - n));
// var low = this.low << n;
// } else {
// var high = this.low << (n - 32);
// var low = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the right.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftR(7);
*/
// shiftR: function (n) {
// if (n < 32) {
// var low = (this.low >>> n) | (this.high << (32 - n));
// var high = this.high >>> n;
// } else {
// var low = this.high >>> (n - 32);
// var high = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Rotates this word n bits to the left.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotL(25);
*/
// rotL: function (n) {
// return this.shiftL(n).or(this.shiftR(64 - n));
// },
/**
* Rotates this word n bits to the right.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotR(7);
*/
// rotR: function (n) {
// return this.shiftR(n).or(this.shiftL(64 - n));
// },
/**
* Adds this word with the passed word.
*
* @param {X64Word} word The x64-Word to add with this word.
*
* @return {X64Word} A new x64-Word object after adding.
*
* @example
*
* var added = x64Word.add(anotherX64Word);
*/
// add: function (word) {
// var low = (this.low + word.low) | 0;
// var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0;
// var high = (this.high + word.high + carry) | 0;
// return X64Word.create(high, low);
// }
});
/**
* An array of 64-bit words.
*
* @property {Array} words The array of CryptoJS.x64.Word objects.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var X64WordArray = C_x64.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of CryptoJS.x64.Word objects.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.x64.WordArray.create();
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ]);
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ], 10);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 8;
}
},
/**
* Converts this 64-bit word array to a 32-bit word array.
*
* @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array.
*
* @example
*
* var x32WordArray = x64WordArray.toX32();
*/
toX32: function () {
// Shortcuts
var x64Words = this.words;
var x64WordsLength = x64Words.length;
// Convert
var x32Words = [];
for (var i = 0; i < x64WordsLength; i++) {
var x64Word = x64Words[i];
x32Words.push(x64Word.high);
x32Words.push(x64Word.low);
}
return X32WordArray.create(x32Words, this.sigBytes);
},
/**
* Creates a copy of this word array.
*
* @return {X64WordArray} The clone.
*
* @example
*
* var clone = x64WordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
// Clone "words" array
var words = clone.words = this.words.slice(0);
// Clone each X64Word object
var wordsLength = words.length;
for (var i = 0; i < wordsLength; i++) {
words[i] = words[i].clone();
}
return clone;
}
});
}());
return CryptoJS;
}));
},{"./core":52}],84:[function(require,module,exports){
/*! https://mths.be/utf8js v2.1.2 by @mathias */
;(function(root) {
// Detect free variables `exports`
var freeExports = typeof exports == 'object' && exports;
// Detect free variable `module`
var freeModule = typeof module == 'object' && module &&
module.exports == freeExports && module;
// Detect free variable `global`, from Node.js or Browserified code,
// and use it as `root`
var freeGlobal = typeof global == 'object' && global;
if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
root = freeGlobal;
}
/*--------------------------------------------------------------------------*/
var stringFromCharCode = String.fromCharCode;
// Taken from https://mths.be/punycode
function ucs2decode(string) {
var output = [];
var counter = 0;
var length = string.length;
var value;
var extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
// Taken from https://mths.be/punycode
function ucs2encode(array) {
var length = array.length;
var index = -1;
var value;
var output = '';
while (++index < length) {
value = array[index];
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
}
return output;
}
function checkScalarValue(codePoint) {
if (codePoint >= 0xD800 && codePoint <= 0xDFFF) {
throw Error(
'Lone surrogate U+' + codePoint.toString(16).toUpperCase() +
' is not a scalar value'
);
}
}
/*--------------------------------------------------------------------------*/
function createByte(codePoint, shift) {
return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
}
function encodeCodePoint(codePoint) {
if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
return stringFromCharCode(codePoint);
}
var symbol = '';
if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
}
else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
checkScalarValue(codePoint);
symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
symbol += createByte(codePoint, 6);
}
else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
symbol += createByte(codePoint, 12);
symbol += createByte(codePoint, 6);
}
symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
return symbol;
}
function utf8encode(string) {
var codePoints = ucs2decode(string);
var length = codePoints.length;
var index = -1;
var codePoint;
var byteString = '';
while (++index < length) {
codePoint = codePoints[index];
byteString += encodeCodePoint(codePoint);
}
return byteString;
}
/*--------------------------------------------------------------------------*/
function readContinuationByte() {
if (byteIndex >= byteCount) {
throw Error('Invalid byte index');
}
var continuationByte = byteArray[byteIndex] & 0xFF;
byteIndex++;
if ((continuationByte & 0xC0) == 0x80) {
return continuationByte & 0x3F;
}
// If we end up here, it’s not a continuation byte
throw Error('Invalid continuation byte');
}
function decodeSymbol() {
var byte1;
var byte2;
var byte3;
var byte4;
var codePoint;
if (byteIndex > byteCount) {
throw Error('Invalid byte index');
}
if (byteIndex == byteCount) {
return false;
}
// Read first byte
byte1 = byteArray[byteIndex] & 0xFF;
byteIndex++;
// 1-byte sequence (no continuation bytes)
if ((byte1 & 0x80) == 0) {
return byte1;
}
// 2-byte sequence
if ((byte1 & 0xE0) == 0xC0) {
byte2 = readContinuationByte();
codePoint = ((byte1 & 0x1F) << 6) | byte2;
if (codePoint >= 0x80) {
return codePoint;
} else {
throw Error('Invalid continuation byte');
}
}
// 3-byte sequence (may include unpaired surrogates)
if ((byte1 & 0xF0) == 0xE0) {
byte2 = readContinuationByte();
byte3 = readContinuationByte();
codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
if (codePoint >= 0x0800) {
checkScalarValue(codePoint);
return codePoint;
} else {
throw Error('Invalid continuation byte');
}
}
// 4-byte sequence
if ((byte1 & 0xF8) == 0xF0) {
byte2 = readContinuationByte();
byte3 = readContinuationByte();
byte4 = readContinuationByte();
codePoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0C) |
(byte3 << 0x06) | byte4;
if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
return codePoint;
}
}
throw Error('Invalid UTF-8 detected');
}
var byteArray;
var byteCount;
var byteIndex;
function utf8decode(byteString) {
byteArray = ucs2decode(byteString);
byteCount = byteArray.length;
byteIndex = 0;
var codePoints = [];
var tmp;
while ((tmp = decodeSymbol()) !== false) {
codePoints.push(tmp);
}
return ucs2encode(codePoints);
}
/*--------------------------------------------------------------------------*/
var utf8 = {
'version': '2.1.2',
'encode': utf8encode,
'decode': utf8decode
};
// Some AMD build optimizers, like r.js, check for specific condition patterns
// like the following:
if (
typeof define == 'function' &&
typeof define.amd == 'object' &&
define.amd
) {
define(function() {
return utf8;
});
} else if (freeExports && !freeExports.nodeType) {
if (freeModule) { // in Node.js or RingoJS v0.8.0+
freeModule.exports = utf8;
} else { // in Narwhal or RingoJS v0.7.0-
var object = {};
var hasOwnProperty = object.hasOwnProperty;
for (var key in utf8) {
hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
}
}
} else { // in Rhino or a web browser
root.utf8 = utf8;
}
}(this));
},{}],85:[function(require,module,exports){
module.exports = XMLHttpRequest;
},{}],"bignumber.js":[function(require,module,exports){
/*! bignumber.js v4.0.0 https://github.com/MikeMcl/bignumber.js/LICENCE */
;(function (globalObj) {
'use strict';
/*
bignumber.js v4.0.0
A JavaScript library for arbitrary-precision arithmetic.
https://github.com/MikeMcl/bignumber.js
Copyright (c) 2017 Michael Mclaughlin <M8ch88l@gmail.com>
MIT Expat Licence
*/
var BigNumber,
isNumeric = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
mathceil = Math.ceil,
mathfloor = Math.floor,
notBool = ' not a boolean or binary digit',
roundingMode = 'rounding mode',
tooManyDigits = 'number type has more than 15 significant digits',
ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_',
BASE = 1e14,
LOG_BASE = 14,
MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1
// MAX_INT32 = 0x7fffffff, // 2^31 - 1
POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],
SQRT_BASE = 1e7,
/*
* The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and
* the arguments to toExponential, toFixed, toFormat, and toPrecision, beyond which an
* exception is thrown (if ERRORS is true).
*/
MAX = 1E9; // 0 to MAX_INT32
/*
* Create and return a BigNumber constructor.
*/
function constructorFactory(config) {
var div, parseNumeric,
// id tracks the caller function, so its name can be included in error messages.
id = 0,
P = BigNumber.prototype,
ONE = new BigNumber(1),
/********************************* EDITABLE DEFAULTS **********************************/
/*
* The default values below must be integers within the inclusive ranges stated.
* The values can also be changed at run-time using BigNumber.config.
*/
// The maximum number of decimal places for operations involving division.
DECIMAL_PLACES = 20, // 0 to MAX
/*
* The rounding mode used when rounding to the above decimal places, and when using
* toExponential, toFixed, toFormat and toPrecision, and round (default value).
* UP 0 Away from zero.
* DOWN 1 Towards zero.
* CEIL 2 Towards +Infinity.
* FLOOR 3 Towards -Infinity.
* HALF_UP 4 Towards nearest neighbour. If equidistant, up.
* HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
* HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
* HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
* HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
*/
ROUNDING_MODE = 4, // 0 to 8
// EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]
// The exponent value at and beneath which toString returns exponential notation.
// Number type: -7
TO_EXP_NEG = -7, // 0 to -MAX
// The exponent value at and above which toString returns exponential notation.
// Number type: 21
TO_EXP_POS = 21, // 0 to MAX
// RANGE : [MIN_EXP, MAX_EXP]
// The minimum exponent value, beneath which underflow to zero occurs.
// Number type: -324 (5e-324)
MIN_EXP = -1e7, // -1 to -MAX
// The maximum exponent value, above which overflow to Infinity occurs.
// Number type: 308 (1.7976931348623157e+308)
// For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.
MAX_EXP = 1e7, // 1 to MAX
// Whether BigNumber Errors are ever thrown.
ERRORS = true, // true or false
// Change to intValidatorNoErrors if ERRORS is false.
isValidInt = intValidatorWithErrors, // intValidatorWithErrors/intValidatorNoErrors
// Whether to use cryptographically-secure random number generation, if available.
CRYPTO = false, // true or false
/*
* The modulo mode used when calculating the modulus: a mod n.
* The quotient (q = a / n) is calculated according to the corresponding rounding mode.
* The remainder (r) is calculated as: r = a - n * q.
*
* UP 0 The remainder is positive if the dividend is negative, else is negative.
* DOWN 1 The remainder has the same sign as the dividend.
* This modulo mode is commonly known as 'truncated division' and is
* equivalent to (a % n) in JavaScript.
* FLOOR 3 The remainder has the same sign as the divisor (Python %).
* HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.
* EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).
* The remainder is always positive.
*
* The truncated division, floored division, Euclidian division and IEEE 754 remainder
* modes are commonly used for the modulus operation.
* Although the other rounding modes can also be used, they may not give useful results.
*/
MODULO_MODE = 1, // 0 to 9
// The maximum number of significant digits of the result of the toPower operation.
// If POW_PRECISION is 0, there will be unlimited significant digits.
POW_PRECISION = 0, // 0 to MAX
// The format specification used by the BigNumber.prototype.toFormat method.
FORMAT = {
decimalSeparator: '.',
groupSeparator: ',',
groupSize: 3,
secondaryGroupSize: 0,
fractionGroupSeparator: '\xA0', // non-breaking space
fractionGroupSize: 0
};
/******************************************************************************************/
// CONSTRUCTOR
/*
* The BigNumber constructor and exported function.
* Create and return a new instance of a BigNumber object.
*
* n {number|string|BigNumber} A numeric value.
* [b] {number} The base of n. Integer, 2 to 64 inclusive.
*/
function BigNumber( n, b ) {
var c, e, i, num, len, str,
x = this;
// Enable constructor usage without new.
if ( !( x instanceof BigNumber ) ) {
// 'BigNumber() constructor call without new: {n}'
if (ERRORS) raise( 26, 'constructor call without new', n );
return new BigNumber( n, b );
}
// 'new BigNumber() base not an integer: {b}'
// 'new BigNumber() base out of range: {b}'
if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) {
// Duplicate.
if ( n instanceof BigNumber ) {
x.s = n.s;
x.e = n.e;
x.c = ( n = n.c ) ? n.slice() : n;
id = 0;
return;
}
if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) {
x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1;
// Fast path for integers.
if ( n === ~~n ) {
for ( e = 0, i = n; i >= 10; i /= 10, e++ );
x.e = e;
x.c = [n];
id = 0;
return;
}
str = n + '';
} else {
if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num );
x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
}
} else {
b = b | 0;
str = n + '';
// Ensure return value is rounded to DECIMAL_PLACES as with other bases.
// Allow exponential notation to be used with base 10 argument.
if ( b == 10 ) {
x = new BigNumber( n instanceof BigNumber ? n : str );
return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE );
}
// Avoid potential interpretation of Infinity and NaN as base 44+ values.
// Any number in exponential form will fail due to the [Ee][+-].
if ( ( num = typeof n == 'number' ) && n * 0 != 0 ||
!( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) +
'(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) {
return parseNumeric( x, str, num, b );
}
if (num) {
x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1;
if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) {
// 'new BigNumber() number type has more than 15 significant digits: {n}'
raise( id, tooManyDigits, n );
}
// Prevent later check for length on converted number.
num = false;
} else {
x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
}
str = convertBase( str, 10, b, x.s );
}
// Decimal point?
if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' );
// Exponential form?
if ( ( i = str.search( /e/i ) ) > 0 ) {
// Determine exponent.
if ( e < 0 ) e = i;
e += +str.slice( i + 1 );
str = str.substring( 0, i );
} else if ( e < 0 ) {
// Integer.
e = str.length;
}
// Determine leading zeros.
for ( i = 0; str.charCodeAt(i) === 48; i++ );
// Determine trailing zeros.
for ( len = str.length; str.charCodeAt(--len) === 48; );
str = str.slice( i, len + 1 );
if (str) {
len = str.length;
// Disallow numbers with over 15 significant digits if number type.
// 'new BigNumber() number type has more than 15 significant digits: {n}'
if ( num && ERRORS && len > 15 && ( n > MAX_SAFE_INTEGER || n !== mathfloor(n) ) ) {
raise( id, tooManyDigits, x.s * n );
}
e = e - i - 1;
// Overflow?
if ( e > MAX_EXP ) {
// Infinity.
x.c = x.e = null;
// Underflow?
} else if ( e < MIN_EXP ) {
// Zero.
x.c = [ x.e = 0 ];
} else {
x.e = e;
x.c = [];
// Transform base
// e is the base 10 exponent.
// i is where to slice str to get the first element of the coefficient array.
i = ( e + 1 ) % LOG_BASE;
if ( e < 0 ) i += LOG_BASE;
if ( i < len ) {
if (i) x.c.push( +str.slice( 0, i ) );
for ( len -= LOG_BASE; i < len; ) {
x.c.push( +str.slice( i, i += LOG_BASE ) );
}
str = str.slice(i);
i = LOG_BASE - str.length;
} else {
i -= len;
}
for ( ; i--; str += '0' );
x.c.push( +str );
}
} else {
// Zero.
x.c = [ x.e = 0 ];
}
id = 0;
}
// CONSTRUCTOR PROPERTIES
BigNumber.another = constructorFactory;
BigNumber.ROUND_UP = 0;
BigNumber.ROUND_DOWN = 1;
BigNumber.ROUND_CEIL = 2;
BigNumber.ROUND_FLOOR = 3;
BigNumber.ROUND_HALF_UP = 4;
BigNumber.ROUND_HALF_DOWN = 5;
BigNumber.ROUND_HALF_EVEN = 6;
BigNumber.ROUND_HALF_CEIL = 7;
BigNumber.ROUND_HALF_FLOOR = 8;
BigNumber.EUCLID = 9;
/*
* Configure infrequently-changing library-wide settings.
*
* Accept an object or an argument list, with one or many of the following properties or
* parameters respectively:
*
* DECIMAL_PLACES {number} Integer, 0 to MAX inclusive
* ROUNDING_MODE {number} Integer, 0 to 8 inclusive
* EXPONENTIAL_AT {number|number[]} Integer, -MAX to MAX inclusive or
* [integer -MAX to 0 incl., 0 to MAX incl.]
* RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
* [integer -MAX to -1 incl., integer 1 to MAX incl.]
* ERRORS {boolean|number} true, false, 1 or 0
* CRYPTO {boolean|number} true, false, 1 or 0
* MODULO_MODE {number} 0 to 9 inclusive
* POW_PRECISION {number} 0 to MAX inclusive
* FORMAT {object} See BigNumber.prototype.toFormat
* decimalSeparator {string}
* groupSeparator {string}
* groupSize {number}
* secondaryGroupSize {number}
* fractionGroupSeparator {string}
* fractionGroupSize {number}
*
* (The values assigned to the above FORMAT object properties are not checked for validity.)
*
* E.g.
* BigNumber.config(20, 4) is equivalent to
* BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })
*
* Ignore properties/parameters set to null or undefined.
* Return an object with the properties current values.
*/
BigNumber.config = BigNumber.set = function () {
var v, p,
i = 0,
r = {},
a = arguments,
o = a[0],
has = o && typeof o == 'object'
? function () { if ( o.hasOwnProperty(p) ) return ( v = o[p] ) != null; }
: function () { if ( a.length > i ) return ( v = a[i++] ) != null; };
// DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.
// 'config() DECIMAL_PLACES not an integer: {v}'
// 'config() DECIMAL_PLACES out of range: {v}'
if ( has( p = 'DECIMAL_PLACES' ) && isValidInt( v, 0, MAX, 2, p ) ) {
DECIMAL_PLACES = v | 0;
}
r[p] = DECIMAL_PLACES;
// ROUNDING_MODE {number} Integer, 0 to 8 inclusive.
// 'config() ROUNDING_MODE not an integer: {v}'
// 'config() ROUNDING_MODE out of range: {v}'
if ( has( p = 'ROUNDING_MODE' ) && isValidInt( v, 0, 8, 2, p ) ) {
ROUNDING_MODE = v | 0;
}
r[p] = ROUNDING_MODE;
// EXPONENTIAL_AT {number|number[]}
// Integer, -MAX to MAX inclusive or [integer -MAX to 0 inclusive, 0 to MAX inclusive].
// 'config() EXPONENTIAL_AT not an integer: {v}'
// 'config() EXPONENTIAL_AT out of range: {v}'
if ( has( p = 'EXPONENTIAL_AT' ) ) {
if ( isArray(v) ) {
if ( isValidInt( v[0], -MAX, 0, 2, p ) && isValidInt( v[1], 0, MAX, 2, p ) ) {
TO_EXP_NEG = v[0] | 0;
TO_EXP_POS = v[1] | 0;
}
} else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
TO_EXP_NEG = -( TO_EXP_POS = ( v < 0 ? -v : v ) | 0 );
}
}
r[p] = [ TO_EXP_NEG, TO_EXP_POS ];
// RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
// [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].
// 'config() RANGE not an integer: {v}'
// 'config() RANGE cannot be zero: {v}'
// 'config() RANGE out of range: {v}'
if ( has( p = 'RANGE' ) ) {
if ( isArray(v) ) {
if ( isValidInt( v[0], -MAX, -1, 2, p ) && isValidInt( v[1], 1, MAX, 2, p ) ) {
MIN_EXP = v[0] | 0;
MAX_EXP = v[1] | 0;
}
} else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
if ( v | 0 ) MIN_EXP = -( MAX_EXP = ( v < 0 ? -v : v ) | 0 );
else if (ERRORS) raise( 2, p + ' cannot be zero', v );
}
}
r[p] = [ MIN_EXP, MAX_EXP ];
// ERRORS {boolean|number} true, false, 1 or 0.
// 'config() ERRORS not a boolean or binary digit: {v}'
if ( has( p = 'ERRORS' ) ) {
if ( v === !!v || v === 1 || v === 0 ) {
id = 0;
isValidInt = ( ERRORS = !!v ) ? intValidatorWithErrors : intValidatorNoErrors;
} else if (ERRORS) {
raise( 2, p + notBool, v );
}
}
r[p] = ERRORS;
// CRYPTO {boolean|number} true, false, 1 or 0.
// 'config() CRYPTO not a boolean or binary digit: {v}'
// 'config() crypto unavailable: {crypto}'
if ( has( p = 'CRYPTO' ) ) {
if ( v === true || v === false || v === 1 || v === 0 ) {
if (v) {
v = typeof crypto == 'undefined';
if ( !v && crypto && (crypto.getRandomValues || crypto.randomBytes)) {
CRYPTO = true;
} else if (ERRORS) {
raise( 2, 'crypto unavailable', v ? void 0 : crypto );
} else {
CRYPTO = false;
}
} else {
CRYPTO = false;
}
} else if (ERRORS) {
raise( 2, p + notBool, v );
}
}
r[p] = CRYPTO;
// MODULO_MODE {number} Integer, 0 to 9 inclusive.
// 'config() MODULO_MODE not an integer: {v}'
// 'config() MODULO_MODE out of range: {v}'
if ( has( p = 'MODULO_MODE' ) && isValidInt( v, 0, 9, 2, p ) ) {
MODULO_MODE = v | 0;
}
r[p] = MODULO_MODE;
// POW_PRECISION {number} Integer, 0 to MAX inclusive.
// 'config() POW_PRECISION not an integer: {v}'
// 'config() POW_PRECISION out of range: {v}'
if ( has( p = 'POW_PRECISION' ) && isValidInt( v, 0, MAX, 2, p ) ) {
POW_PRECISION = v | 0;
}
r[p] = POW_PRECISION;
// FORMAT {object}
// 'config() FORMAT not an object: {v}'
if ( has( p = 'FORMAT' ) ) {
if ( typeof v == 'object' ) {
FORMAT = v;
} else if (ERRORS) {
raise( 2, p + ' not an object', v );
}
}
r[p] = FORMAT;
return r;
};
/*
* Return a new BigNumber whose value is the maximum of the arguments.
*
* arguments {number|string|BigNumber}
*/
BigNumber.max = function () { return maxOrMin( arguments, P.lt ); };
/*
* Return a new BigNumber whose value is the minimum of the arguments.
*
* arguments {number|string|BigNumber}
*/
BigNumber.min = function () { return maxOrMin( arguments, P.gt ); };
/*
* Return a new BigNumber with a random value equal to or greater than 0 and less than 1,
* and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing
* zeros are produced).
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
*
* 'random() decimal places not an integer: {dp}'
* 'random() decimal places out of range: {dp}'
* 'random() crypto unavailable: {crypto}'
*/
BigNumber.random = (function () {
var pow2_53 = 0x20000000000000;
// Return a 53 bit integer n, where 0 <= n < 9007199254740992.
// Check if Math.random() produces more than 32 bits of randomness.
// If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.
// 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.
var random53bitInt = (Math.random() * pow2_53) & 0x1fffff
? function () { return mathfloor( Math.random() * pow2_53 ); }
: function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +
(Math.random() * 0x800000 | 0); };
return function (dp) {
var a, b, e, k, v,
i = 0,
c = [],
rand = new BigNumber(ONE);
dp = dp == null || !isValidInt( dp, 0, MAX, 14 ) ? DECIMAL_PLACES : dp | 0;
k = mathceil( dp / LOG_BASE );
if (CRYPTO) {
// Browsers supporting crypto.getRandomValues.
if (crypto.getRandomValues) {
a = crypto.getRandomValues( new Uint32Array( k *= 2 ) );
for ( ; i < k; ) {
// 53 bits:
// ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)
// 11111 11111111 11111111 11111111 11100000 00000000 00000000
// ((Math.pow(2, 32) - 1) >>> 11).toString(2)
// 11111 11111111 11111111
// 0x20000 is 2^21.
v = a[i] * 0x20000 + (a[i + 1] >>> 11);
// Rejection sampling:
// 0 <= v < 9007199254740992
// Probability that v >= 9e15, is
// 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251
if ( v >= 9e15 ) {
b = crypto.getRandomValues( new Uint32Array(2) );
a[i] = b[0];
a[i + 1] = b[1];
} else {
// 0 <= v <= 8999999999999999
// 0 <= (v % 1e14) <= 99999999999999
c.push( v % 1e14 );
i += 2;
}
}
i = k / 2;
// Node.js supporting crypto.randomBytes.
} else if (crypto.randomBytes) {
// buffer
a = crypto.randomBytes( k *= 7 );
for ( ; i < k; ) {
// 0x1000000000000 is 2^48, 0x10000000000 is 2^40
// 0x100000000 is 2^32, 0x1000000 is 2^24
// 11111 11111111 11111111 11111111 11111111 11111111 11111111
// 0 <= v < 9007199254740992
v = ( ( a[i] & 31 ) * 0x1000000000000 ) + ( a[i + 1] * 0x10000000000 ) +
( a[i + 2] * 0x100000000 ) + ( a[i + 3] * 0x1000000 ) +
( a[i + 4] << 16 ) + ( a[i + 5] << 8 ) + a[i + 6];
if ( v >= 9e15 ) {
crypto.randomBytes(7).copy( a, i );
} else {
// 0 <= (v % 1e14) <= 99999999999999
c.push( v % 1e14 );
i += 7;
}
}
i = k / 7;
} else {
CRYPTO = false;
if (ERRORS) raise( 14, 'crypto unavailable', crypto );
}
}
// Use Math.random.
if (!CRYPTO) {
for ( ; i < k; ) {
v = random53bitInt();
if ( v < 9e15 ) c[i++] = v % 1e14;
}
}
k = c[--i];
dp %= LOG_BASE;
// Convert trailing digits to zeros according to dp.
if ( k && dp ) {
v = POWS_TEN[LOG_BASE - dp];
c[i] = mathfloor( k / v ) * v;
}
// Remove trailing elements which are zero.
for ( ; c[i] === 0; c.pop(), i-- );
// Zero?
if ( i < 0 ) {
c = [ e = 0 ];
} else {
// Remove leading elements which are zero and adjust exponent accordingly.
for ( e = -1 ; c[0] === 0; c.shift(), e -= LOG_BASE);
// Count the digits of the first element of c to determine leading zeros, and...
for ( i = 1, v = c[0]; v >= 10; v /= 10, i++);
// adjust the exponent accordingly.
if ( i < LOG_BASE ) e -= LOG_BASE - i;
}
rand.e = e;
rand.c = c;
return rand;
};
})();
// PRIVATE FUNCTIONS
// Convert a numeric string of baseIn to a numeric string of baseOut.
function convertBase( str, baseOut, baseIn, sign ) {
var d, e, k, r, x, xc, y,
i = str.indexOf( '.' ),
dp = DECIMAL_PLACES,
rm = ROUNDING_MODE;
if ( baseIn < 37 ) str = str.toLowerCase();
// Non-integer.
if ( i >= 0 ) {
k = POW_PRECISION;
// Unlimited precision.
POW_PRECISION = 0;
str = str.replace( '.', '' );
y = new BigNumber(baseIn);
x = y.pow( str.length - i );
POW_PRECISION = k;
// Convert str as if an integer, then restore the fraction part by dividing the
// result by its base raised to a power.
y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut );
y.e = y.c.length;
}
// Convert the number as integer.
xc = toBaseOut( str, baseIn, baseOut );
e = k = xc.length;
// Remove trailing zeros.
for ( ; xc[--k] == 0; xc.pop() );
if ( !xc[0] ) return '0';
if ( i < 0 ) {
--e;
} else {
x.c = xc;
x.e = e;
// sign is needed for correct rounding.
x.s = sign;
x = div( x, y, dp, rm, baseOut );
xc = x.c;
r = x.r;
e = x.e;
}
d = e + dp + 1;
// The rounding digit, i.e. the digit to the right of the digit that may be rounded up.
i = xc[d];
k = baseOut / 2;
r = r || d < 0 || xc[d + 1] != null;
r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
: i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||
rm == ( x.s < 0 ? 8 : 7 ) );
if ( d < 1 || !xc[0] ) {
// 1^-dp or 0.
str = r ? toFixedPoint( '1', -dp ) : '0';
} else {
xc.length = d;
if (r) {
// Rounding up may mean the previous digit has to be rounded up and so on.
for ( --baseOut; ++xc[--d] > baseOut; ) {
xc[d] = 0;
if ( !d ) {
++e;
xc.unshift(1);
}
}
}
// Determine trailing zeros.
for ( k = xc.length; !xc[--k]; );
// E.g. [4, 11, 15] becomes 4bf.
for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) );
str = toFixedPoint( str, e );
}
// The caller will add the sign.
return str;
}
// Perform division in the specified base. Called by div and convertBase.
div = (function () {
// Assume non-zero x and k.
function multiply( x, k, base ) {
var m, temp, xlo, xhi,
carry = 0,
i = x.length,
klo = k % SQRT_BASE,
khi = k / SQRT_BASE | 0;
for ( x = x.slice(); i--; ) {
xlo = x[i] % SQRT_BASE;
xhi = x[i] / SQRT_BASE | 0;
m = khi * xlo + xhi * klo;
temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;
carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;
x[i] = temp % base;
}
if (carry) x.unshift(carry);
return x;
}
function compare( a, b, aL, bL ) {
var i, cmp;
if ( aL != bL ) {
cmp = aL > bL ? 1 : -1;
} else {
for ( i = cmp = 0; i < aL; i++ ) {
if ( a[i] != b[i] ) {
cmp = a[i] > b[i] ? 1 : -1;
break;
}
}
}
return cmp;
}
function subtract( a, b, aL, base ) {
var i = 0;
// Subtract b from a.
for ( ; aL--; ) {
a[aL] -= i;
i = a[aL] < b[aL] ? 1 : 0;
a[aL] = i * base + a[aL] - b[aL];
}
// Remove leading zeros.
for ( ; !a[0] && a.length > 1; a.shift() );
}
// x: dividend, y: divisor.
return function ( x, y, dp, rm, base ) {
var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,
yL, yz,
s = x.s == y.s ? 1 : -1,
xc = x.c,
yc = y.c;
// Either NaN, Infinity or 0?
if ( !xc || !xc[0] || !yc || !yc[0] ) {
return new BigNumber(
// Return NaN if either NaN, or both Infinity or 0.
!x.s || !y.s || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN :
// Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.
xc && xc[0] == 0 || !yc ? s * 0 : s / 0
);
}
q = new BigNumber(s);
qc = q.c = [];
e = x.e - y.e;
s = dp + e + 1;
if ( !base ) {
base = BASE;
e = bitFloor( x.e / LOG_BASE ) - bitFloor( y.e / LOG_BASE );
s = s / LOG_BASE | 0;
}
// Result exponent may be one less then the current value of e.
// The coefficients of the BigNumbers from convertBase may have trailing zeros.
for ( i = 0; yc[i] == ( xc[i] || 0 ); i++ );
if ( yc[i] > ( xc[i] || 0 ) ) e--;
if ( s < 0 ) {
qc.push(1);
more = true;
} else {
xL = xc.length;
yL = yc.length;
i = 0;
s += 2;
// Normalise xc and yc so highest order digit of yc is >= base / 2.
n = mathfloor( base / ( yc[0] + 1 ) );
// Not necessary, but to handle odd bases where yc[0] == ( base / 2 ) - 1.
// if ( n > 1 || n++ == 1 && yc[0] < base / 2 ) {
if ( n > 1 ) {
yc = multiply( yc, n, base );
xc = multiply( xc, n, base );
yL = yc.length;
xL = xc.length;
}
xi = yL;
rem = xc.slice( 0, yL );
remL = rem.length;
// Add zeros to make remainder as long as divisor.
for ( ; remL < yL; rem[remL++] = 0 );
yz = yc.slice();
yz.unshift(0);
yc0 = yc[0];
if ( yc[1] >= base / 2 ) yc0++;
// Not necessary, but to prevent trial digit n > base, when using base 3.
// else if ( base == 3 && yc0 == 1 ) yc0 = 1 + 1e-15;
do {
n = 0;
// Compare divisor and remainder.
cmp = compare( yc, rem, yL, remL );
// If divisor < remainder.
if ( cmp < 0 ) {
// Calculate trial digit, n.
rem0 = rem[0];
if ( yL != remL ) rem0 = rem0 * base + ( rem[1] || 0 );
// n is how many times the divisor goes into the current remainder.
n = mathfloor( rem0 / yc0 );
// Algorithm:
// 1. product = divisor * trial digit (n)
// 2. if product > remainder: product -= divisor, n--
// 3. remainder -= product
// 4. if product was < remainder at 2:
// 5. compare new remainder and divisor
// 6. If remainder > divisor: remainder -= divisor, n++
if ( n > 1 ) {
// n may be > base only when base is 3.
if (n >= base) n = base - 1;
// product = divisor * trial digit.
prod = multiply( yc, n, base );
prodL = prod.length;
remL = rem.length;
// Compare product and remainder.
// If product > remainder.
// Trial digit n too high.
// n is 1 too high about 5% of the time, and is not known to have
// ever been more than 1 too high.
while ( compare( prod, rem, prodL, remL ) == 1 ) {
n--;
// Subtract divisor from product.
subtract( prod, yL < prodL ? yz : yc, prodL, base );
prodL = prod.length;
cmp = 1;
}
} else {
// n is 0 or 1, cmp is -1.
// If n is 0, there is no need to compare yc and rem again below,
// so change cmp to 1 to avoid it.
// If n is 1, leave cmp as -1, so yc and rem are compared again.
if ( n == 0 ) {
// divisor < remainder, so n must be at least 1.
cmp = n = 1;
}
// product = divisor
prod = yc.slice();
prodL = prod.length;
}
if ( prodL < remL ) prod.unshift(0);
// Subtract product from remainder.
subtract( rem, prod, remL, base );
remL = rem.length;
// If product was < remainder.
if ( cmp == -1 ) {
// Compare divisor and new remainder.
// If divisor < new remainder, subtract divisor from remainder.
// Trial digit n too low.
// n is 1 too low about 5% of the time, and very rarely 2 too low.
while ( compare( yc, rem, yL, remL ) < 1 ) {
n++;
// Subtract divisor from remainder.
subtract( rem, yL < remL ? yz : yc, remL, base );
remL = rem.length;
}
}
} else if ( cmp === 0 ) {
n++;
rem = [0];
} // else cmp === 1 and n will be 0
// Add the next digit, n, to the result array.
qc[i++] = n;
// Update the remainder.
if ( rem[0] ) {
rem[remL++] = xc[xi] || 0;
} else {
rem = [ xc[xi] ];
remL = 1;
}
} while ( ( xi++ < xL || rem[0] != null ) && s-- );
more = rem[0] != null;
// Leading zero?
if ( !qc[0] ) qc.shift();
}
if ( base == BASE ) {
// To calculate q.e, first get the number of digits of qc[0].
for ( i = 1, s = qc[0]; s >= 10; s /= 10, i++ );
round( q, dp + ( q.e = i + e * LOG_BASE - 1 ) + 1, rm, more );
// Caller is convertBase.
} else {
q.e = e;
q.r = +more;
}
return q;
};
})();
/*
* Return a string representing the value of BigNumber n in fixed-point or exponential
* notation rounded to the specified decimal places or significant digits.
*
* n is a BigNumber.
* i is the index of the last digit required (i.e. the digit that may be rounded up).
* rm is the rounding mode.
* caller is caller id: toExponential 19, toFixed 20, toFormat 21, toPrecision 24.
*/
function format( n, i, rm, caller ) {
var c0, e, ne, len, str;
rm = rm != null && isValidInt( rm, 0, 8, caller, roundingMode )
? rm | 0 : ROUNDING_MODE;
if ( !n.c ) return n.toString();
c0 = n.c[0];
ne = n.e;
if ( i == null ) {
str = coeffToString( n.c );
str = caller == 19 || caller == 24 && ne <= TO_EXP_NEG
? toExponential( str, ne )
: toFixedPoint( str, ne );
} else {
n = round( new BigNumber(n), i, rm );
// n.e may have changed if the value was rounded up.
e = n.e;
str = coeffToString( n.c );
len = str.length;
// toPrecision returns exponential notation if the number of significant digits
// specified is less than the number of digits necessary to represent the integer
// part of the value in fixed-point notation.
// Exponential notation.
if ( caller == 19 || caller == 24 && ( i <= e || e <= TO_EXP_NEG ) ) {
// Append zeros?
for ( ; len < i; str += '0', len++ );
str = toExponential( str, e );
// Fixed-point notation.
} else {
i -= ne;
str = toFixedPoint( str, e );
// Append zeros?
if ( e + 1 > len ) {
if ( --i > 0 ) for ( str += '.'; i--; str += '0' );
} else {
i += e - len;
if ( i > 0 ) {
if ( e + 1 == len ) str += '.';
for ( ; i--; str += '0' );
}
}
}
}
return n.s < 0 && c0 ? '-' + str : str;
}
// Handle BigNumber.max and BigNumber.min.
function maxOrMin( args, method ) {
var m, n,
i = 0;
if ( isArray( args[0] ) ) args = args[0];
m = new BigNumber( args[0] );
for ( ; ++i < args.length; ) {
n = new BigNumber( args[i] );
// If any number is NaN, return NaN.
if ( !n.s ) {
m = n;
break;
} else if ( method.call( m, n ) ) {
m = n;
}
}
return m;
}
/*
* Return true if n is an integer in range, otherwise throw.
* Use for argument validation when ERRORS is true.
*/
function intValidatorWithErrors( n, min, max, caller, name ) {
if ( n < min || n > max || n != truncate(n) ) {
raise( caller, ( name || 'decimal places' ) +
( n < min || n > max ? ' out of range' : ' not an integer' ), n );
}
return true;
}
/*
* Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.
* Called by minus, plus and times.
*/
function normalise( n, c, e ) {
var i = 1,
j = c.length;
// Remove trailing zeros.
for ( ; !c[--j]; c.pop() );
// Calculate the base 10 exponent. First get the number of digits of c[0].
for ( j = c[0]; j >= 10; j /= 10, i++ );
// Overflow?
if ( ( e = i + e * LOG_BASE - 1 ) > MAX_EXP ) {
// Infinity.
n.c = n.e = null;
// Underflow?
} else if ( e < MIN_EXP ) {
// Zero.
n.c = [ n.e = 0 ];
} else {
n.e = e;
n.c = c;
}
return n;
}
// Handle values that fail the validity test in BigNumber.
parseNumeric = (function () {
var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i,
dotAfter = /^([^.]+)\.$/,
dotBefore = /^\.([^.]+)$/,
isInfinityOrNaN = /^-?(Infinity|NaN)$/,
whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g;
return function ( x, str, num, b ) {
var base,
s = num ? str : str.replace( whitespaceOrPlus, '' );
// No exception on ±Infinity or NaN.
if ( isInfinityOrNaN.test(s) ) {
x.s = isNaN(s) ? null : s < 0 ? -1 : 1;
} else {
if ( !num ) {
// basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i
s = s.replace( basePrefix, function ( m, p1, p2 ) {
base = ( p2 = p2.toLowerCase() ) == 'x' ? 16 : p2 == 'b' ? 2 : 8;
return !b || b == base ? p1 : m;
});
if (b) {
base = b;
// E.g. '1.' to '1', '.1' to '0.1'
s = s.replace( dotAfter, '$1' ).replace( dotBefore, '0.$1' );
}
if ( str != s ) return new BigNumber( s, base );
}
// 'new BigNumber() not a number: {n}'
// 'new BigNumber() not a base {b} number: {n}'
if (ERRORS) raise( id, 'not a' + ( b ? ' base ' + b : '' ) + ' number', str );
x.s = null;
}
x.c = x.e = null;
id = 0;
}
})();
// Throw a BigNumber Error.
function raise( caller, msg, val ) {
var error = new Error( [
'new BigNumber', // 0
'cmp', // 1
'config', // 2
'div', // 3
'divToInt', // 4
'eq', // 5
'gt', // 6
'gte', // 7
'lt', // 8
'lte', // 9
'minus', // 10
'mod', // 11
'plus', // 12
'precision', // 13
'random', // 14
'round', // 15
'shift', // 16
'times', // 17
'toDigits', // 18
'toExponential', // 19
'toFixed', // 20
'toFormat', // 21
'toFraction', // 22
'pow', // 23
'toPrecision', // 24
'toString', // 25
'BigNumber' // 26
][caller] + '() ' + msg + ': ' + val );
error.name = 'BigNumber Error';
id = 0;
throw error;
}
/*
* Round x to sd significant digits using rounding mode rm. Check for over/under-flow.
* If r is truthy, it is known that there are more digits after the rounding digit.
*/
function round( x, sd, rm, r ) {
var d, i, j, k, n, ni, rd,
xc = x.c,
pows10 = POWS_TEN;
// if x is not Infinity or NaN...
if (xc) {
// rd is the rounding digit, i.e. the digit after the digit that may be rounded up.
// n is a base 1e14 number, the value of the element of array x.c containing rd.
// ni is the index of n within x.c.
// d is the number of digits of n.
// i is the index of rd within n including leading zeros.
// j is the actual index of rd within n (if < 0, rd is a leading zero).
out: {
// Get the number of digits of the first element of xc.
for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ );
i = sd - d;
// If the rounding digit is in the first element of xc...
if ( i < 0 ) {
i += LOG_BASE;
j = sd;
n = xc[ ni = 0 ];
// Get the rounding digit at index j of n.
rd = n / pows10[ d - j - 1 ] % 10 | 0;
} else {
ni = mathceil( ( i + 1 ) / LOG_BASE );
if ( ni >= xc.length ) {
if (r) {
// Needed by sqrt.
for ( ; xc.length <= ni; xc.push(0) );
n = rd = 0;
d = 1;
i %= LOG_BASE;
j = i - LOG_BASE + 1;
} else {
break out;
}
} else {
n = k = xc[ni];
// Get the number of digits of n.
for ( d = 1; k >= 10; k /= 10, d++ );
// Get the index of rd within n.
i %= LOG_BASE;
// Get the index of rd within n, adjusted for leading zeros.
// The number of leading zeros of n is given by LOG_BASE - d.
j = i - LOG_BASE + d;
// Get the rounding digit at index j of n.
rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0;
}
}
r = r || sd < 0 ||
// Are there any non-zero digits after the rounding digit?
// The expression n % pows10[ d - j - 1 ] returns all digits of n to the right
// of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.
xc[ni + 1] != null || ( j < 0 ? n : n % pows10[ d - j - 1 ] );
r = rm < 4
? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
: rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 &&
// Check whether the digit to the left of the rounding digit is odd.
( ( i > 0 ? j > 0 ? n / pows10[ d - j ] : 0 : xc[ni - 1] ) % 10 ) & 1 ||
rm == ( x.s < 0 ? 8 : 7 ) );
if ( sd < 1 || !xc[0] ) {
xc.length = 0;
if (r) {
// Convert sd to decimal places.
sd -= x.e + 1;
// 1, 0.1, 0.01, 0.001, 0.0001 etc.
xc[0] = pows10[ ( LOG_BASE - sd % LOG_BASE ) % LOG_BASE ];
x.e = -sd || 0;
} else {
// Zero.
xc[0] = x.e = 0;
}
return x;
}
// Remove excess digits.
if ( i == 0 ) {
xc.length = ni;
k = 1;
ni--;
} else {
xc.length = ni + 1;
k = pows10[ LOG_BASE - i ];
// E.g. 56700 becomes 56000 if 7 is the rounding digit.
// j > 0 means i > number of leading zeros of n.
xc[ni] = j > 0 ? mathfloor( n / pows10[ d - j ] % pows10[j] ) * k : 0;
}
// Round up?
if (r) {
for ( ; ; ) {
// If the digit to be rounded up is in the first element of xc...
if ( ni == 0 ) {
// i will be the length of xc[0] before k is added.
for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ );
j = xc[0] += k;
for ( k = 1; j >= 10; j /= 10, k++ );
// if i != k the length has increased.
if ( i != k ) {
x.e++;
if ( xc[0] == BASE ) xc[0] = 1;
}
break;
} else {
xc[ni] += k;
if ( xc[ni] != BASE ) break;
xc[ni--] = 0;
k = 1;
}
}
}
// Remove trailing zeros.
for ( i = xc.length; xc[--i] === 0; xc.pop() );
}
// Overflow? Infinity.
if ( x.e > MAX_EXP ) {
x.c = x.e = null;
// Underflow? Zero.
} else if ( x.e < MIN_EXP ) {
x.c = [ x.e = 0 ];
}
}
return x;
}
// PROTOTYPE/INSTANCE METHODS
/*
* Return a new BigNumber whose value is the absolute value of this BigNumber.
*/
P.absoluteValue = P.abs = function () {
var x = new BigNumber(this);
if ( x.s < 0 ) x.s = 1;
return x;
};
/*
* Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
* number in the direction of Infinity.
*/
P.ceil = function () {
return round( new BigNumber(this), this.e + 1, 2 );
};
/*
* Return
* 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),
* -1 if the value of this BigNumber is less than the value of BigNumber(y, b),
* 0 if they have the same value,
* or null if the value of either is NaN.
*/
P.comparedTo = P.cmp = function ( y, b ) {
id = 1;
return compare( this, new BigNumber( y, b ) );
};
/*
* Return the number of decimal places of the value of this BigNumber, or null if the value
* of this BigNumber is ±Infinity or NaN.
*/
P.decimalPlaces = P.dp = function () {
var n, v,
c = this.c;
if ( !c ) return null;
n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE;
// Subtract the number of trailing zeros of the last number.
if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- );
if ( n < 0 ) n = 0;
return n;
};
/*
* n / 0 = I
* n / N = N
* n / I = 0
* 0 / n = 0
* 0 / 0 = N
* 0 / N = N
* 0 / I = 0
* N / n = N
* N / 0 = N
* N / N = N
* N / I = N
* I / n = I
* I / 0 = I
* I / N = N
* I / I = N
*
* Return a new BigNumber whose value is the value of this BigNumber divided by the value of
* BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.
*/
P.dividedBy = P.div = function ( y, b ) {
id = 3;
return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE );
};
/*
* Return a new BigNumber whose value is the integer part of dividing the value of this
* BigNumber by the value of BigNumber(y, b).
*/
P.dividedToIntegerBy = P.divToInt = function ( y, b ) {
id = 4;
return div( this, new BigNumber( y, b ), 0, 1 );
};
/*
* Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),
* otherwise returns false.
*/
P.equals = P.eq = function ( y, b ) {
id = 5;
return compare( this, new BigNumber( y, b ) ) === 0;
};
/*
* Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
* number in the direction of -Infinity.
*/
P.floor = function () {
return round( new BigNumber(this), this.e + 1, 3 );
};
/*
* Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),
* otherwise returns false.
*/
P.greaterThan = P.gt = function ( y, b ) {
id = 6;
return compare( this, new BigNumber( y, b ) ) > 0;
};
/*
* Return true if the value of this BigNumber is greater than or equal to the value of
* BigNumber(y, b), otherwise returns false.
*/
P.greaterThanOrEqualTo = P.gte = function ( y, b ) {
id = 7;
return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0;
};
/*
* Return true if the value of this BigNumber is a finite number, otherwise returns false.
*/
P.isFinite = function () {
return !!this.c;
};
/*
* Return true if the value of this BigNumber is an integer, otherwise return false.
*/
P.isInteger = P.isInt = function () {
return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2;
};
/*
* Return true if the value of this BigNumber is NaN, otherwise returns false.
*/
P.isNaN = function () {
return !this.s;
};
/*
* Return true if the value of this BigNumber is negative, otherwise returns false.
*/
P.isNegative = P.isNeg = function () {
return this.s < 0;
};
/*
* Return true if the value of this BigNumber is 0 or -0, otherwise returns false.
*/
P.isZero = function () {
return !!this.c && this.c[0] == 0;
};
/*
* Return true if the value of this BigNumber is less than the value of BigNumber(y, b),
* otherwise returns false.
*/
P.lessThan = P.lt = function ( y, b ) {
id = 8;
return compare( this, new BigNumber( y, b ) ) < 0;
};
/*
* Return true if the value of this BigNumber is less than or equal to the value of
* BigNumber(y, b), otherwise returns false.
*/
P.lessThanOrEqualTo = P.lte = function ( y, b ) {
id = 9;
return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0;
};
/*
* n - 0 = n
* n - N = N
* n - I = -I
* 0 - n = -n
* 0 - 0 = 0
* 0 - N = N
* 0 - I = -I
* N - n = N
* N - 0 = N
* N - N = N
* N - I = N
* I - n = I
* I - 0 = I
* I - N = N
* I - I = N
*
* Return a new BigNumber whose value is the value of this BigNumber minus the value of
* BigNumber(y, b).
*/
P.minus = P.sub = function ( y, b ) {
var i, j, t, xLTy,
x = this,
a = x.s;
id = 10;
y = new BigNumber( y, b );
b = y.s;
// Either NaN?
if ( !a || !b ) return new BigNumber(NaN);
// Signs differ?
if ( a != b ) {
y.s = -b;
return x.plus(y);
}
var xe = x.e / LOG_BASE,
ye = y.e / LOG_BASE,
xc = x.c,
yc = y.c;
if ( !xe || !ye ) {
// Either Infinity?
if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN );
// Either zero?
if ( !xc[0] || !yc[0] ) {
// Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x :
// IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
ROUNDING_MODE == 3 ? -0 : 0 );
}
}
xe = bitFloor(xe);
ye = bitFloor(ye);
xc = xc.slice();
// Determine which is the bigger number.
if ( a = xe - ye ) {
if ( xLTy = a < 0 ) {
a = -a;
t = xc;
} else {
ye = xe;
t = yc;
}
t.reverse();
// Prepend zeros to equalise exponents.
for ( b = a; b--; t.push(0) );
t.reverse();
} else {
// Exponents equal. Check digit by digit.
j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b;
for ( a = b = 0; b < j; b++ ) {
if ( xc[b] != yc[b] ) {
xLTy = xc[b] < yc[b];
break;
}
}
}
// x < y? Point xc to the array of the bigger number.
if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s;
b = ( j = yc.length ) - ( i = xc.length );
// Append zeros to xc if shorter.
// No need to add zeros to yc if shorter as subtract only needs to start at yc.length.
if ( b > 0 ) for ( ; b--; xc[i++] = 0 );
b = BASE - 1;
// Subtract yc from xc.
for ( ; j > a; ) {
if ( xc[--j] < yc[j] ) {
for ( i = j; i && !xc[--i]; xc[i] = b );
--xc[i];
xc[j] += BASE;
}
xc[j] -= yc[j];
}
// Remove leading zeros and adjust exponent accordingly.
for ( ; xc[0] == 0; xc.shift(), --ye );
// Zero?
if ( !xc[0] ) {
// Following IEEE 754 (2008) 6.3,
// n - n = +0 but n - n = -0 when rounding towards -Infinity.
y.s = ROUNDING_MODE == 3 ? -1 : 1;
y.c = [ y.e = 0 ];
return y;
}
// No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity
// for finite x and y.
return normalise( y, xc, ye );
};
/*
* n % 0 = N
* n % N = N
* n % I = n
* 0 % n = 0
* -0 % n = -0
* 0 % 0 = N
* 0 % N = N
* 0 % I = 0
* N % n = N
* N % 0 = N
* N % N = N
* N % I = N
* I % n = N
* I % 0 = N
* I % N = N
* I % I = N
*
* Return a new BigNumber whose value is the value of this BigNumber modulo the value of
* BigNumber(y, b). The result depends on the value of MODULO_MODE.
*/
P.modulo = P.mod = function ( y, b ) {
var q, s,
x = this;
id = 11;
y = new BigNumber( y, b );
// Return NaN if x is Infinity or NaN, or y is NaN or zero.
if ( !x.c || !y.s || y.c && !y.c[0] ) {
return new BigNumber(NaN);
// Return x if y is Infinity or x is zero.
} else if ( !y.c || x.c && !x.c[0] ) {
return new BigNumber(x);
}
if ( MODULO_MODE == 9 ) {
// Euclidian division: q = sign(y) * floor(x / abs(y))
// r = x - qy where 0 <= r < abs(y)
s = y.s;
y.s = 1;
q = div( x, y, 0, 3 );
y.s = s;
q.s *= s;
} else {
q = div( x, y, 0, MODULO_MODE );
}
return x.minus( q.times(y) );
};
/*
* Return a new BigNumber whose value is the value of this BigNumber negated,
* i.e. multiplied by -1.
*/
P.negated = P.neg = function () {
var x = new BigNumber(this);
x.s = -x.s || null;
return x;
};
/*
* n + 0 = n
* n + N = N
* n + I = I
* 0 + n = n
* 0 + 0 = 0
* 0 + N = N
* 0 + I = I
* N + n = N
* N + 0 = N
* N + N = N
* N + I = N
* I + n = I
* I + 0 = I
* I + N = N
* I + I = I
*
* Return a new BigNumber whose value is the value of this BigNumber plus the value of
* BigNumber(y, b).
*/
P.plus = P.add = function ( y, b ) {
var t,
x = this,
a = x.s;
id = 12;
y = new BigNumber( y, b );
b = y.s;
// Either NaN?
if ( !a || !b ) return new BigNumber(NaN);
// Signs differ?
if ( a != b ) {
y.s = -b;
return x.minus(y);
}
var xe = x.e / LOG_BASE,
ye = y.e / LOG_BASE,
xc = x.c,
yc = y.c;
if ( !xe || !ye ) {
// Return ±Infinity if either ±Infinity.
if ( !xc || !yc ) return new BigNumber( a / 0 );
// Either zero?
// Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 );
}
xe = bitFloor(xe);
ye = bitFloor(ye);
xc = xc.slice();
// Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.
if ( a = xe - ye ) {
if ( a > 0 ) {
ye = xe;
t = yc;
} else {
a = -a;
t = xc;
}
t.reverse();
for ( ; a--; t.push(0) );
t.reverse();
}
a = xc.length;
b = yc.length;
// Point xc to the longer array, and b to the shorter length.
if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a;
// Only start adding at yc.length - 1 as the further digits of xc can be ignored.
for ( a = 0; b; ) {
a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0;
xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;
}
if (a) {
xc.unshift(a);
++ye;
}
// No need to check for zero, as +x + +y != 0 && -x + -y != 0
// ye = MAX_EXP + 1 possible
return normalise( y, xc, ye );
};
/*
* Return the number of significant digits of the value of this BigNumber.
*
* [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
*/
P.precision = P.sd = function (z) {
var n, v,
x = this,
c = x.c;
// 'precision() argument not a boolean or binary digit: {z}'
if ( z != null && z !== !!z && z !== 1 && z !== 0 ) {
if (ERRORS) raise( 13, 'argument' + notBool, z );
if ( z != !!z ) z = null;
}
if ( !c ) return null;
v = c.length - 1;
n = v * LOG_BASE + 1;
if ( v = c[v] ) {
// Subtract the number of trailing zeros of the last element.
for ( ; v % 10 == 0; v /= 10, n-- );
// Add the number of digits of the first element.
for ( v = c[0]; v >= 10; v /= 10, n++ );
}
if ( z && x.e + 1 > n ) n = x.e + 1;
return n;
};
/*
* Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
* dp decimal places using rounding mode rm, or to 0 and ROUNDING_MODE respectively if
* omitted.
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'round() decimal places out of range: {dp}'
* 'round() decimal places not an integer: {dp}'
* 'round() rounding mode not an integer: {rm}'
* 'round() rounding mode out of range: {rm}'
*/
P.round = function ( dp, rm ) {
var n = new BigNumber(this);
if ( dp == null || isValidInt( dp, 0, MAX, 15 ) ) {
round( n, ~~dp + this.e + 1, rm == null ||
!isValidInt( rm, 0, 8, 15, roundingMode ) ? ROUNDING_MODE : rm | 0 );
}
return n;
};
/*
* Return a new BigNumber whose value is the value of this BigNumber shifted by k places
* (powers of 10). Shift to the right if n > 0, and to the left if n < 0.
*
* k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
*
* If k is out of range and ERRORS is false, the result will be ±0 if k < 0, or ±Infinity
* otherwise.
*
* 'shift() argument not an integer: {k}'
* 'shift() argument out of range: {k}'
*/
P.shift = function (k) {
var n = this;
return isValidInt( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, 'argument' )
// k < 1e+21, or truncate(k) will produce exponential notation.
? n.times( '1e' + truncate(k) )
: new BigNumber( n.c && n.c[0] && ( k < -MAX_SAFE_INTEGER || k > MAX_SAFE_INTEGER )
? n.s * ( k < 0 ? 0 : 1 / 0 )
: n );
};
/*
* sqrt(-n) = N
* sqrt( N) = N
* sqrt(-I) = N
* sqrt( I) = I
* sqrt( 0) = 0
* sqrt(-0) = -0
*
* Return a new BigNumber whose value is the square root of the value of this BigNumber,
* rounded according to DECIMAL_PLACES and ROUNDING_MODE.
*/
P.squareRoot = P.sqrt = function () {
var m, n, r, rep, t,
x = this,
c = x.c,
s = x.s,
e = x.e,
dp = DECIMAL_PLACES + 4,
half = new BigNumber('0.5');
// Negative/NaN/Infinity/zero?
if ( s !== 1 || !c || !c[0] ) {
return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 );
}
// Initial estimate.
s = Math.sqrt( +x );
// Math.sqrt underflow/overflow?
// Pass x to Math.sqrt as integer, then adjust the exponent of the result.
if ( s == 0 || s == 1 / 0 ) {
n = coeffToString(c);
if ( ( n.length + e ) % 2 == 0 ) n += '0';
s = Math.sqrt(n);
e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 );
if ( s == 1 / 0 ) {
n = '1e' + e;
} else {
n = s.toExponential();
n = n.slice( 0, n.indexOf('e') + 1 ) + e;
}
r = new BigNumber(n);
} else {
r = new BigNumber( s + '' );
}
// Check for zero.
// r could be zero if MIN_EXP is changed after the this value was created.
// This would cause a division by zero (x/t) and hence Infinity below, which would cause
// coeffToString to throw.
if ( r.c[0] ) {
e = r.e;
s = e + dp;
if ( s < 3 ) s = 0;
// Newton-Raphson iteration.
for ( ; ; ) {
t = r;
r = half.times( t.plus( div( x, t, dp, 1 ) ) );
if ( coeffToString( t.c ).slice( 0, s ) === ( n =
coeffToString( r.c ) ).slice( 0, s ) ) {
// The exponent of r may here be one less than the final result exponent,
// e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits
// are indexed correctly.
if ( r.e < e ) --s;
n = n.slice( s - 3, s + 1 );
// The 4th rounding digit may be in error by -1 so if the 4 rounding digits
// are 9999 or 4999 (i.e. approaching a rounding boundary) continue the
// iteration.
if ( n == '9999' || !rep && n == '4999' ) {
// On the first iteration only, check to see if rounding up gives the
// exact result as the nines may infinitely repeat.
if ( !rep ) {
round( t, t.e + DECIMAL_PLACES + 2, 0 );
if ( t.times(t).eq(x) ) {
r = t;
break;
}
}
dp += 4;
s += 4;
rep = 1;
} else {
// If rounding digits are null, 0{0,4} or 50{0,3}, check for exact
// result. If not, then there are further digits and m will be truthy.
if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) {
// Truncate to the first rounding digit.
round( r, r.e + DECIMAL_PLACES + 2, 1 );
m = !r.times(r).eq(x);
}
break;
}
}
}
}
return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m );
};
/*
* n * 0 = 0
* n * N = N
* n * I = I
* 0 * n = 0
* 0 * 0 = 0
* 0 * N = N
* 0 * I = N
* N * n = N
* N * 0 = N
* N * N = N
* N * I = N
* I * n = I
* I * 0 = N
* I * N = N
* I * I = I
*
* Return a new BigNumber whose value is the value of this BigNumber times the value of
* BigNumber(y, b).
*/
P.times = P.mul = function ( y, b ) {
var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,
base, sqrtBase,
x = this,
xc = x.c,
yc = ( id = 17, y = new BigNumber( y, b ) ).c;
// Either NaN, ±Infinity or ±0?
if ( !xc || !yc || !xc[0] || !yc[0] ) {
// Return NaN if either is NaN, or one is 0 and the other is Infinity.
if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) {
y.c = y.e = y.s = null;
} else {
y.s *= x.s;
// Return ±Infinity if either is ±Infinity.
if ( !xc || !yc ) {
y.c = y.e = null;
// Return ±0 if either is ±0.
} else {
y.c = [0];
y.e = 0;
}
}
return y;
}
e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE );
y.s *= x.s;
xcL = xc.length;
ycL = yc.length;
// Ensure xc points to longer array and xcL to its length.
if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i;
// Initialise the result array with zeros.
for ( i = xcL + ycL, zc = []; i--; zc.push(0) );
base = BASE;
sqrtBase = SQRT_BASE;
for ( i = ycL; --i >= 0; ) {
c = 0;
ylo = yc[i] % sqrtBase;
yhi = yc[i] / sqrtBase | 0;
for ( k = xcL, j = i + k; j > i; ) {
xlo = xc[--k] % sqrtBase;
xhi = xc[k] / sqrtBase | 0;
m = yhi * xlo + xhi * ylo;
xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c;
c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi;
zc[j--] = xlo % base;
}
zc[j] = c;
}
if (c) {
++e;
} else {
zc.shift();
}
return normalise( y, zc, e );
};
/*
* Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
* sd significant digits using rounding mode rm, or ROUNDING_MODE if rm is omitted.
*
* [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'toDigits() precision out of range: {sd}'
* 'toDigits() precision not an integer: {sd}'
* 'toDigits() rounding mode not an integer: {rm}'
* 'toDigits() rounding mode out of range: {rm}'
*/
P.toDigits = function ( sd, rm ) {
var n = new BigNumber(this);
sd = sd == null || !isValidInt( sd, 1, MAX, 18, 'precision' ) ? null : sd | 0;
rm = rm == null || !isValidInt( rm, 0, 8, 18, roundingMode ) ? ROUNDING_MODE : rm | 0;
return sd ? round( n, sd, rm ) : n;
};
/*
* Return a string representing the value of this BigNumber in exponential notation and
* rounded using ROUNDING_MODE to dp fixed decimal places.
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'toExponential() decimal places not an integer: {dp}'
* 'toExponential() decimal places out of range: {dp}'
* 'toExponential() rounding mode not an integer: {rm}'
* 'toExponential() rounding mode out of range: {rm}'
*/
P.toExponential = function ( dp, rm ) {
return format( this,
dp != null && isValidInt( dp, 0, MAX, 19 ) ? ~~dp + 1 : null, rm, 19 );
};
/*
* Return a string representing the value of this BigNumber in fixed-point notation rounding
* to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.
*
* Note: as with JavaScript's number type, (-0).toFixed(0) is '0',
* but e.g. (-0.00001).toFixed(0) is '-0'.
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'toFixed() decimal places not an integer: {dp}'
* 'toFixed() decimal places out of range: {dp}'
* 'toFixed() rounding mode not an integer: {rm}'
* 'toFixed() rounding mode out of range: {rm}'
*/
P.toFixed = function ( dp, rm ) {
return format( this, dp != null && isValidInt( dp, 0, MAX, 20 )
? ~~dp + this.e + 1 : null, rm, 20 );
};
/*
* Return a string representing the value of this BigNumber in fixed-point notation rounded
* using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties
* of the FORMAT object (see BigNumber.config).
*
* FORMAT = {
* decimalSeparator : '.',
* groupSeparator : ',',
* groupSize : 3,
* secondaryGroupSize : 0,
* fractionGroupSeparator : '\xA0', // non-breaking space
* fractionGroupSize : 0
* };
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'toFormat() decimal places not an integer: {dp}'
* 'toFormat() decimal places out of range: {dp}'
* 'toFormat() rounding mode not an integer: {rm}'
* 'toFormat() rounding mode out of range: {rm}'
*/
P.toFormat = function ( dp, rm ) {
var str = format( this, dp != null && isValidInt( dp, 0, MAX, 21 )
? ~~dp + this.e + 1 : null, rm, 21 );
if ( this.c ) {
var i,
arr = str.split('.'),
g1 = +FORMAT.groupSize,
g2 = +FORMAT.secondaryGroupSize,
groupSeparator = FORMAT.groupSeparator,
intPart = arr[0],
fractionPart = arr[1],
isNeg = this.s < 0,
intDigits = isNeg ? intPart.slice(1) : intPart,
len = intDigits.length;
if (g2) i = g1, g1 = g2, g2 = i, len -= i;
if ( g1 > 0 && len > 0 ) {
i = len % g1 || g1;
intPart = intDigits.substr( 0, i );
for ( ; i < len; i += g1 ) {
intPart += groupSeparator + intDigits.substr( i, g1 );
}
if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i);
if (isNeg) intPart = '-' + intPart;
}
str = fractionPart
? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize )
? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ),
'$&' + FORMAT.fractionGroupSeparator )
: fractionPart )
: intPart;
}
return str;
};
/*
* Return a string array representing the value of this BigNumber as a simple fraction with
* an integer numerator and an integer denominator. The denominator will be a positive
* non-zero value less than or equal to the specified maximum denominator. If a maximum
* denominator is not specified, the denominator will be the lowest value necessary to
* represent the number exactly.
*
* [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator.
*
* 'toFraction() max denominator not an integer: {md}'
* 'toFraction() max denominator out of range: {md}'
*/
P.toFraction = function (md) {
var arr, d0, d2, e, exp, n, n0, q, s,
k = ERRORS,
x = this,
xc = x.c,
d = new BigNumber(ONE),
n1 = d0 = new BigNumber(ONE),
d1 = n0 = new BigNumber(ONE);
if ( md != null ) {
ERRORS = false;
n = new BigNumber(md);
ERRORS = k;
if ( !( k = n.isInt() ) || n.lt(ONE) ) {
if (ERRORS) {
raise( 22,
'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md );
}
// ERRORS is false:
// If md is a finite non-integer >= 1, round it to an integer and use it.
md = !k && n.c && round( n, n.e + 1, 1 ).gte(ONE) ? n : null;
}
}
if ( !xc ) return x.toString();
s = coeffToString(xc);
// Determine initial denominator.
// d is a power of 10 and the minimum max denominator that specifies the value exactly.
e = d.e = s.length - x.e - 1;
d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ];
md = !md || n.cmp(d) > 0 ? ( e > 0 ? d : n1 ) : n;
exp = MAX_EXP;
MAX_EXP = 1 / 0;
n = new BigNumber(s);
// n0 = d1 = 0
n0.c[0] = 0;
for ( ; ; ) {
q = div( n, d, 0, 1 );
d2 = d0.plus( q.times(d1) );
if ( d2.cmp(md) == 1 ) break;
d0 = d1;
d1 = d2;
n1 = n0.plus( q.times( d2 = n1 ) );
n0 = d2;
d = n.minus( q.times( d2 = d ) );
n = d2;
}
d2 = div( md.minus(d0), d1, 0, 1 );
n0 = n0.plus( d2.times(n1) );
d0 = d0.plus( d2.times(d1) );
n0.s = n1.s = x.s;
e *= 2;
// Determine which fraction is closer to x, n0/d0 or n1/d1
arr = div( n1, d1, e, ROUNDING_MODE ).minus(x).abs().cmp(
div( n0, d0, e, ROUNDING_MODE ).minus(x).abs() ) < 1
? [ n1.toString(), d1.toString() ]
: [ n0.toString(), d0.toString() ];
MAX_EXP = exp;
return arr;
};
/*
* Return the value of this BigNumber converted to a number primitive.
*/
P.toNumber = function () {
return +this;
};
/*
* Return a BigNumber whose value is the value of this BigNumber raised to the power n.
* If m is present, return the result modulo m.
* If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.
* If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using
* ROUNDING_MODE.
*
* The modular power operation works efficiently when x, n, and m are positive integers,
* otherwise it is equivalent to calculating x.toPower(n).modulo(m) (with POW_PRECISION 0).
*
* n {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
* [m] {number|string|BigNumber} The modulus.
*
* 'pow() exponent not an integer: {n}'
* 'pow() exponent out of range: {n}'
*
* Performs 54 loop iterations for n of 9007199254740991.
*/
P.toPower = P.pow = function ( n, m ) {
var k, y, z,
i = mathfloor( n < 0 ? -n : +n ),
x = this;
if ( m != null ) {
id = 23;
m = new BigNumber(m);
}
// Pass ±Infinity to Math.pow if exponent is out of range.
if ( !isValidInt( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 23, 'exponent' ) &&
( !isFinite(n) || i > MAX_SAFE_INTEGER && ( n /= 0 ) ||
parseFloat(n) != n && !( n = NaN ) ) || n == 0 ) {
k = Math.pow( +x, n );
return new BigNumber( m ? k % m : k );
}
if (m) {
if ( n > 1 && x.gt(ONE) && x.isInt() && m.gt(ONE) && m.isInt() ) {
x = x.mod(m);
} else {
z = m;
// Nullify m so only a single mod operation is performed at the end.
m = null;
}
} else if (POW_PRECISION) {
// Truncating each coefficient array to a length of k after each multiplication
// equates to truncating significant digits to POW_PRECISION + [28, 41],
// i.e. there will be a minimum of 28 guard digits retained.
// (Using + 1.5 would give [9, 21] guard digits.)
k = mathceil( POW_PRECISION / LOG_BASE + 2 );
}
y = new BigNumber(ONE);
for ( ; ; ) {
if ( i % 2 ) {
y = y.times(x);
if ( !y.c ) break;
if (k) {
if ( y.c.length > k ) y.c.length = k;
} else if (m) {
y = y.mod(m);
}
}
i = mathfloor( i / 2 );
if ( !i ) break;
x = x.times(x);
if (k) {
if ( x.c && x.c.length > k ) x.c.length = k;
} else if (m) {
x = x.mod(m);
}
}
if (m) return y;
if ( n < 0 ) y = ONE.div(y);
return z ? y.mod(z) : k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y;
};
/*
* Return a string representing the value of this BigNumber rounded to sd significant digits
* using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits
* necessary to represent the integer part of the value in fixed-point notation, then use
* exponential notation.
*
* [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'toPrecision() precision not an integer: {sd}'
* 'toPrecision() precision out of range: {sd}'
* 'toPrecision() rounding mode not an integer: {rm}'
* 'toPrecision() rounding mode out of range: {rm}'
*/
P.toPrecision = function ( sd, rm ) {
return format( this, sd != null && isValidInt( sd, 1, MAX, 24, 'precision' )
? sd | 0 : null, rm, 24 );
};
/*
* Return a string representing the value of this BigNumber in base b, or base 10 if b is
* omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and
* ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent
* that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than
* TO_EXP_NEG, return exponential notation.
*
* [b] {number} Integer, 2 to 64 inclusive.
*
* 'toString() base not an integer: {b}'
* 'toString() base out of range: {b}'
*/
P.toString = function (b) {
var str,
n = this,
s = n.s,
e = n.e;
// Infinity or NaN?
if ( e === null ) {
if (s) {
str = 'Infinity';
if ( s < 0 ) str = '-' + str;
} else {
str = 'NaN';
}
} else {
str = coeffToString( n.c );
if ( b == null || !isValidInt( b, 2, 64, 25, 'base' ) ) {
str = e <= TO_EXP_NEG || e >= TO_EXP_POS
? toExponential( str, e )
: toFixedPoint( str, e );
} else {
str = convertBase( toFixedPoint( str, e ), b | 0, 10, s );
}
if ( s < 0 && n.c[0] ) str = '-' + str;
}
return str;
};
/*
* Return a new BigNumber whose value is the value of this BigNumber truncated to a whole
* number.
*/
P.truncated = P.trunc = function () {
return round( new BigNumber(this), this.e + 1, 1 );
};
/*
* Return as toString, but do not accept a base argument, and include the minus sign for
* negative zero.
*/
P.valueOf = P.toJSON = function () {
var str,
n = this,
e = n.e;
if ( e === null ) return n.toString();
str = coeffToString( n.c );
str = e <= TO_EXP_NEG || e >= TO_EXP_POS
? toExponential( str, e )
: toFixedPoint( str, e );
return n.s < 0 ? '-' + str : str;
};
P.isBigNumber = true;
if ( config != null ) BigNumber.config(config);
return BigNumber;
}
// PRIVATE HELPER FUNCTIONS
function bitFloor(n) {
var i = n | 0;
return n > 0 || n === i ? i : i - 1;
}
// Return a coefficient array as a string of base 10 digits.
function coeffToString(a) {
var s, z,
i = 1,
j = a.length,
r = a[0] + '';
for ( ; i < j; ) {
s = a[i++] + '';
z = LOG_BASE - s.length;
for ( ; z--; s = '0' + s );
r += s;
}
// Determine trailing zeros.
for ( j = r.length; r.charCodeAt(--j) === 48; );
return r.slice( 0, j + 1 || 1 );
}
// Compare the value of BigNumbers x and y.
function compare( x, y ) {
var a, b,
xc = x.c,
yc = y.c,
i = x.s,
j = y.s,
k = x.e,
l = y.e;
// Either NaN?
if ( !i || !j ) return null;
a = xc && !xc[0];
b = yc && !yc[0];
// Either zero?
if ( a || b ) return a ? b ? 0 : -j : i;
// Signs differ?
if ( i != j ) return i;
a = i < 0;
b = k == l;
// Either Infinity?
if ( !xc || !yc ) return b ? 0 : !xc ^ a ? 1 : -1;
// Compare exponents.
if ( !b ) return k > l ^ a ? 1 : -1;
j = ( k = xc.length ) < ( l = yc.length ) ? k : l;
// Compare digit by digit.
for ( i = 0; i < j; i++ ) if ( xc[i] != yc[i] ) return xc[i] > yc[i] ^ a ? 1 : -1;
// Compare lengths.
return k == l ? 0 : k > l ^ a ? 1 : -1;
}
/*
* Return true if n is a valid number in range, otherwise false.
* Use for argument validation when ERRORS is false.
* Note: parseInt('1e+1') == 1 but parseFloat('1e+1') == 10.
*/
function intValidatorNoErrors( n, min, max ) {
return ( n = truncate(n) ) >= min && n <= max;
}
function isArray(obj) {
return Object.prototype.toString.call(obj) == '[object Array]';
}
/*
* Convert string of baseIn to an array of numbers of baseOut.
* Eg. convertBase('255', 10, 16) returns [15, 15].
* Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
*/
function toBaseOut( str, baseIn, baseOut ) {
var j,
arr = [0],
arrL,
i = 0,
len = str.length;
for ( ; i < len; ) {
for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn );
arr[ j = 0 ] += ALPHABET.indexOf( str.charAt( i++ ) );
for ( ; j < arr.length; j++ ) {
if ( arr[j] > baseOut - 1 ) {
if ( arr[j + 1] == null ) arr[j + 1] = 0;
arr[j + 1] += arr[j] / baseOut | 0;
arr[j] %= baseOut;
}
}
}
return arr.reverse();
}
function toExponential( str, e ) {
return ( str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str ) +
( e < 0 ? 'e' : 'e+' ) + e;
}
function toFixedPoint( str, e ) {
var len, z;
// Negative exponent?
if ( e < 0 ) {
// Prepend zeros.
for ( z = '0.'; ++e; z += '0' );
str = z + str;
// Positive exponent
} else {
len = str.length;
// Append zeros.
if ( ++e > len ) {
for ( z = '0', e -= len; --e; z += '0' );
str += z;
} else if ( e < len ) {
str = str.slice( 0, e ) + '.' + str.slice(e);
}
}
return str;
}
function truncate(n) {
n = parseFloat(n);
return n < 0 ? mathceil(n) : mathfloor(n);
}
// EXPORT
BigNumber = constructorFactory();
BigNumber.default = BigNumber.BigNumber = BigNumber;
// AMD.
if ( typeof define == 'function' && define.amd ) {
define( function () { return BigNumber; } );
// Node.js and other environments that support module.exports.
} else if ( typeof module != 'undefined' && module.exports ) {
module.exports = BigNumber;
// Browser.
} else {
if ( !globalObj ) globalObj = typeof self != 'undefined' ? self : Function('return this')();
globalObj.BigNumber = BigNumber;
}
})(this);
},{}],"web3":[function(require,module,exports){
var Web3 = require('./lib/web3');
// dont override global variable
if (typeof window !== 'undefined' && typeof window.Web3 === 'undefined') {
window.Web3 = Web3;
}
module.exports = Web3;
},{"./lib/web3":22}]},{},["web3"])
//# sourceMappingURL=web3.js.map
| fengkiej/chainsign | node_modules/web3/dist/web3.js | JavaScript | agpl-3.0 | 500,237 |
<?php
/**
* BaseDRMDroits
*
* Base model for DRMDroits
*/
abstract class BaseDRMDroits extends acCouchdbDocumentTree {
public function configureTree() {
$this->_root_class_name = 'DRM';
$this->_tree_class_name = 'DRMDroits';
}
} | 24eme/vinsdeloire | project/plugins/acVinDRMPlugin/lib/model/DRM/base/BaseDRMDroits.class.php | PHP | agpl-3.0 | 294 |
package org.timepedia.chronoscope.client.event;
import org.timepedia.chronoscope.client.XYPlot;
import org.timepedia.exporter.client.Export;
import org.timepedia.exporter.client.ExportPackage;
import org.timepedia.exporter.client.Exportable;
/**
* Fired by plot implementations when click occurs on chart which is not handled
* by a marker or by a focus-on-point click event.
*/
@ExportPackage("chronoscope")
public class ChartClickEvent extends PlotEvent<ChartClickHandler> implements Exportable {
public static Type<ChartClickHandler> TYPE
= new Type<ChartClickHandler>();
private int x;
@Export
/**
* X coordinate of click event relative to left border of plot area.
*/
public double getX() {
return x - getPlot().getBounds().x;
}
/**
* Y coordinate of click event relative to top border of plot area.
*/
@Export
public double getY() {
return y - getPlot().getBounds().y;
}
private int y;
public ChartClickEvent(XYPlot plot, int x, int y) {
super(plot);
this.x = x;
this.y = y;
}
public Type getAssociatedType() {
return TYPE;
}
protected void dispatch(ChartClickHandler chartClickHandler) {
chartClickHandler.onChartClick(this);
}
} | KunjanSharma/gwt-chronoscope | chronoscope-api/src/main/java/org/timepedia/chronoscope/client/event/ChartClickEvent.java | Java | lgpl-2.1 | 1,231 |
/**********
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-2015 Live Networks, Inc. All rights reserved.
// A class used for digest authentication.
// Implementation
#include "DigestAuthentication.hh"
#include "ourMD5.hh"
#include <strDup.hh>
#include <GroupsockHelper.hh> // for gettimeofday()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Authenticator::Authenticator() {
assign(NULL, NULL, NULL, NULL, False);
}
Authenticator::Authenticator(char const* username, char const* password, Boolean passwordIsMD5) {
assign(NULL, NULL, username, password, passwordIsMD5);
}
Authenticator::Authenticator(const Authenticator& orig) {
assign(orig.realm(), orig.nonce(), orig.username(), orig.password(), orig.fPasswordIsMD5);
}
Authenticator& Authenticator::operator=(const Authenticator& rightSide) {
if (&rightSide != this) {
reset();
assign(rightSide.realm(), rightSide.nonce(),
rightSide.username(), rightSide.password(), rightSide.fPasswordIsMD5);
}
return *this;
}
Boolean Authenticator::operator<(const Authenticator* rightSide) {
if (rightSide != NULL && rightSide != this &&
(rightSide->realm() != NULL || rightSide->nonce() != NULL ||
strcmp(rightSide->username(), username()) != 0 ||
strcmp(rightSide->password(), password()) != 0)) {
return True;
}
return False;
}
Authenticator::~Authenticator() {
reset();
}
void Authenticator::reset() {
resetRealmAndNonce();
resetUsernameAndPassword();
}
void Authenticator::setRealmAndNonce(char const* realm, char const* nonce) {
resetRealmAndNonce();
assignRealmAndNonce(realm, nonce);
}
void Authenticator::setRealmAndRandomNonce(char const* realm) {
resetRealmAndNonce();
// Construct data to seed the random nonce:
struct {
struct timeval timestamp;
unsigned counter;
} seedData;
gettimeofday(&seedData.timestamp, NULL);
static unsigned counter = 0;
seedData.counter = ++counter;
// Use MD5 to compute a 'random' nonce from this seed data:
char nonceBuf[33];
our_MD5Data((unsigned char*)(&seedData), sizeof seedData, nonceBuf);
assignRealmAndNonce(realm, nonceBuf);
}
void Authenticator::setUsernameAndPassword(char const* username,
char const* password,
Boolean passwordIsMD5) {
resetUsernameAndPassword();
assignUsernameAndPassword(username, password, passwordIsMD5);
}
char const* Authenticator::computeDigestResponse(char const* cmd,
char const* url) const {
// The "response" field is computed as:
// md5(md5(<username>:<realm>:<password>):<nonce>:md5(<cmd>:<url>))
// or, if "fPasswordIsMD5" is True:
// md5(<password>:<nonce>:md5(<cmd>:<url>))
char ha1Buf[33];
if (fPasswordIsMD5) {
strncpy(ha1Buf, password(), 32);
ha1Buf[32] = '\0'; // just in case
} else {
unsigned const ha1DataLen = strlen(username()) + 1
+ strlen(realm()) + 1 + strlen(password());
unsigned char* ha1Data = new unsigned char[ha1DataLen+1];
sprintf((char*)ha1Data, "%s:%s:%s", username(), realm(), password());
our_MD5Data(ha1Data, ha1DataLen, ha1Buf);
delete[] ha1Data;
}
unsigned const ha2DataLen = strlen(cmd) + 1 + strlen(url);
unsigned char* ha2Data = new unsigned char[ha2DataLen+1];
sprintf((char*)ha2Data, "%s:%s", cmd, url);
char ha2Buf[33];
our_MD5Data(ha2Data, ha2DataLen, ha2Buf);
delete[] ha2Data;
unsigned const digestDataLen
= 32 + 1 + strlen(nonce()) + 1 + 32;
unsigned char* digestData = new unsigned char[digestDataLen+1];
sprintf((char*)digestData, "%s:%s:%s",
ha1Buf, nonce(), ha2Buf);
char const* result = our_MD5Data(digestData, digestDataLen, NULL);
delete[] digestData;
return result;
}
void Authenticator::reclaimDigestResponse(char const* responseStr) const {
delete[](char*)responseStr;
}
void Authenticator::resetRealmAndNonce() {
delete[] fRealm; fRealm = NULL;
delete[] fNonce; fNonce = NULL;
}
void Authenticator::resetUsernameAndPassword() {
delete[] fUsername; fUsername = NULL;
delete[] fPassword; fPassword = NULL;
fPasswordIsMD5 = False;
}
void Authenticator::assignRealmAndNonce(char const* realm, char const* nonce) {
fRealm = strDup(realm);
fNonce = strDup(nonce);
}
void Authenticator::assignUsernameAndPassword(char const* username, char const* password, Boolean passwordIsMD5) {
if (username == NULL) username = "";
if (password == NULL) password = "";
fUsername = strDup(username);
fPassword = strDup(password);
fPasswordIsMD5 = passwordIsMD5;
}
void Authenticator::assign(char const* realm, char const* nonce,
char const* username, char const* password, Boolean passwordIsMD5) {
assignRealmAndNonce(realm, nonce);
assignUsernameAndPassword(username, password, passwordIsMD5);
}
| wangdm/live555 | liveMedia/DigestAuthentication.cpp | C++ | lgpl-2.1 | 5,494 |
/*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH (http://www.alkacon.com)
*
* 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.
*
* 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.
*
* For further information about Alkacon Software GmbH, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.db.postgresql;
import org.opencms.db.CmsDbContext;
import org.opencms.db.CmsDbSqlException;
import org.opencms.db.I_CmsHistoryDriver;
import org.opencms.db.generic.CmsSqlManager;
import org.opencms.file.CmsDataAccessException;
import org.opencms.file.history.CmsHistoryProject;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* PostgreSql implementation of the history driver methods.<p>
*
* @since 6.9.1
*/
public class CmsHistoryDriver extends org.opencms.db.generic.CmsHistoryDriver {
/**
* @see org.opencms.db.I_CmsHistoryDriver#initSqlManager(String)
*/
@Override
public org.opencms.db.generic.CmsSqlManager initSqlManager(String classname) {
return CmsSqlManager.getInstance(classname);
}
/**
* @see org.opencms.db.I_CmsHistoryDriver#readProjects(org.opencms.db.CmsDbContext)
*/
@Override
public List<CmsHistoryProject> readProjects(CmsDbContext dbc) throws CmsDataAccessException {
List<CmsHistoryProject> projects = new ArrayList<CmsHistoryProject>();
ResultSet res = null;
PreparedStatement stmt = null;
Connection conn = null;
Map<Integer, CmsHistoryProject> tmpProjects = new HashMap<Integer, CmsHistoryProject>();
try {
// create the statement
conn = m_sqlManager.getConnection(dbc);
stmt = m_sqlManager.getPreparedStatement(conn, "C_POSTGRE_PROJECTS_READLAST_HISTORY");
stmt.setInt(1, 300);
res = stmt.executeQuery();
while (res.next()) {
tmpProjects.put(Integer.valueOf(res.getInt("PUBLISH_TAG")), internalCreateProject(res, null));
}
} catch (SQLException e) {
throw new CmsDbSqlException(org.opencms.db.generic.Messages.get().container(
org.opencms.db.generic.Messages.ERR_GENERIC_SQL_1,
CmsDbSqlException.getErrorQuery(stmt)), e);
} finally {
m_sqlManager.closeAll(dbc, conn, stmt, res);
}
I_CmsHistoryDriver historyDriver = m_driverManager.getHistoryDriver(dbc);
for (Map.Entry<Integer, CmsHistoryProject> entry : tmpProjects.entrySet()) {
List<String> resources = historyDriver.readProjectResources(dbc, entry.getKey().intValue());
entry.getValue().setProjectResources(resources);
projects.add(entry.getValue());
}
return projects;
}
} | it-tavis/opencms-core | src/org/opencms/db/postgresql/CmsHistoryDriver.java | Java | lgpl-2.1 | 3,735 |
/*!
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* 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 Lesser General Public License for more details.
*
* Copyright (c) 2002-2017 Hitachi Vantara.. All rights reserved.
*/
package org.pentaho.agilebi.modeler.geo;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by IntelliJ IDEA. User: rfellows Date: 9/26/11 Time: 2:09 PM To change this template use File | Settings |
* File Templates.
*/
public class LatLngRole extends GeoRole implements Serializable {
private static final long serialVersionUID = 3443044732976689019L;
private String prefix = "";
public LatLngRole() {
super();
}
public LatLngRole( String name, List<String> commonAliases ) {
super( name, commonAliases );
}
public LatLngRole( String name, String commonAliases ) {
super( name, commonAliases );
}
@Override
protected boolean eval( String fieldName, String alias ) {
if ( super.eval( fieldName, alias ) ) {
return true;
} else if ( fieldName.endsWith( getMatchSeparator() + alias ) ) {
prefix = fieldName.substring( 0, fieldName.indexOf( getMatchSeparator() + alias ) );
return true;
}
return false;
}
public String getPrefix() {
return prefix;
}
public LatLngRole clone() {
List<String> clonedAliases = (ArrayList<String>) ( (ArrayList<String>) getCommonAliases() ).clone();
LatLngRole clone = new LatLngRole( getName(), clonedAliases );
clone.prefix = getPrefix();
return clone;
}
}
| kurtwalker/modeler | core/src/main/java/org/pentaho/agilebi/modeler/geo/LatLngRole.java | Java | lgpl-2.1 | 2,170 |
define([
'dojo/_base/declare',
'dojo/dom-construct',
'JBrowse/View/Track/BlockBased',
'JBrowse/Util'],
function(
declare,
dom,
BlockBased,
Util
) {
return declare(BlockBased,
/**
* @lends JBrowse.View.Track.LocationScale.prototype
*/
{
/**
* This track is for (e.g.) position and sequence information that should
* always stay visible at the top of the view.
* @constructs
*/
constructor: function( args ) {//name, labelClass, posHeight) {
this.loaded = true;
this.labelClass = args.labelClass;
this.posHeight = args.posHeight;
this.height = Math.round( args.posHeight * 1.2 );
},
// this track has no track label or track menu, stub them out
makeTrackLabel: function() {},
makeTrackMenu: function() {},
fillBlock: function( args ) {
var blockIndex = args.blockIndex;
var block = args.block;
var leftBase = args.leftBase;
var scale = args.scale;
var thisB = this;
// find the number that is within 2 px of the left boundary of
// the block that ends with the most zeroes, or a 5 if no
// zeroes
var labelNumber = this.chooseLabel( args );
var labelOffset = (leftBase+1-labelNumber)*scale/10;
// console.log( leftBase+1, labelNumber, labelOffset );
var posLabel = document.createElement("div");
var numtext = Util.addCommas( labelNumber );
posLabel.className = this.labelClass;
// give the position label a negative left offset in ex's to
// more-or-less center it over the left boundary of the block
posLabel.style.left = "-" + Number(numtext.length)/1.7 + labelOffset + "ex";
posLabel.appendChild( document.createTextNode( numtext ) );
block.domNode.appendChild(posLabel);
var highlight = this.browser.getHighlight();
if( highlight && highlight.ref == this.refSeq.name ) {
this.renderRegionHighlight( args, highlight );
}
var bookmarks = this.browser.getBookmarks();
if( bookmarks ) {
this.renderRegionBookmark( args, bookmarks, this.refSeq.name, true );
}
this.heightUpdate( Math.round( this.posHeight*1.2 ), blockIndex);
args.finishCallback();
},
chooseLabel: function( viewArgs ) {
var left = viewArgs.leftBase + 1;
var width = viewArgs.rightBase - left + 1;
var scale = viewArgs.scale;
for( var mod = 1000000; mod > 0; mod /= 10 ) {
if( left % mod * scale <= 3 )
return left - left%mod;
}
return left;
}
});
});
| Arabidopsis-Information-Portal/jbrowse | src/JBrowse/View/Track/LocationScale.js | JavaScript | lgpl-2.1 | 2,746 |
/* Copyright (c) 2000 The Legion Of The Bouncy Castle
* (http://www.bouncycastle.org)
*
* 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 jcifs.spnego.asn1;
import java.io.IOException;
import java.util.Enumeration;
public class BERConstructedSequence
extends DERConstructedSequence
{
/*
*/
void encode(
DEROutputStream out)
throws IOException
{
if (out instanceof ASN1OutputStream || out instanceof BEROutputStream)
{
out.write(SEQUENCE | CONSTRUCTED);
out.write(0x80);
Enumeration e = getObjects();
while (e.hasMoreElements())
{
out.writeObject(e.nextElement());
}
out.write(0x00);
out.write(0x00);
}
else
{
super.encode(out);
}
}
}
| emmanuel-keller/jcifs-krb5 | src/jcifs/spnego/asn1/BERConstructedSequence.java | Java | lgpl-2.1 | 1,967 |
/**
* @license Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Spell checker.
*/
// Register a plugin named "wsc".
CKEDITOR.plugins.add( 'wsc', {
requires: 'dialog',
lang: 'af,ar,bg,bn,bs,ca,cs,cy,da,de,el,en-au,en-ca,en-gb,en,eo,es,et,eu,fa,fi,fo,fr-ca,fr,gl,gu,he,hi,hr,hu,is,it,ja,ka,km,ko,lt,lv,mk,mn,ms,nb,nl,no,pl,pt-br,pt,ro,ru,sk,sl,sr-latn,sr,sv,th,tr,ug,uk,vi,zh-cn,zh', // %REMOVE_LINE_CORE%
icons: 'spellchecker', // %REMOVE_LINE_CORE%
init: function( editor ) {
var commandName = 'checkspell';
var command = editor.addCommand( commandName, new CKEDITOR.dialogCommand( commandName ) );
// SpellChecker doesn't work in Opera and with custom domain
command.modes = { wysiwyg: ( !CKEDITOR.env.opera && !CKEDITOR.env.air && document.domain == window.location.hostname ) };
if(typeof editor.plugins.scayt == 'undefined'){
editor.ui.addButton && editor.ui.addButton( 'SpellChecker', {
label: editor.lang.wsc.toolbar,
command: commandName,
toolbar: 'spellchecker,10'
});
}
CKEDITOR.dialog.add( commandName, this.path + 'dialogs/wsc.js' );
}
});
CKEDITOR.config.wsc_customerId = CKEDITOR.config.wsc_customerId || '1:ua3xw1-2XyGJ3-GWruD3-6OFNT1-oXcuB1-nR6Bp4-hgQHc-EcYng3-sdRXG3-NOfFk';
CKEDITOR.config.wsc_customLoaderScript = CKEDITOR.config.wsc_customLoaderScript || null;
| FuadEfendi/lpotal | tomcat-7.0.57/webapps/ROOT/html/js/editor/ckeditor/plugins/wsc/plugin.js | JavaScript | lgpl-2.1 | 1,446 |
/*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH (http://www.alkacon.com)
*
* 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.
*
* 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.
*
* For further information about Alkacon Software GmbH, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.search;
import org.opencms.main.CmsIllegalArgumentException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.util.CmsStringUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
/**
* A search index source is a description of a list of Cms resources
* to be indexed.<p>
*
* @since 6.0.0
*/
public class CmsSearchIndexSource implements Comparable<CmsSearchIndexSource> {
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsSearchIndexSource.class);
/** A list of Cms resource types to be indexed. */
private List<String> m_documentTypes;
/** The indexer. */
private I_CmsIndexer m_indexer;
/** The class name of the indexer. */
private String m_indexerClassName;
/** The logical key/name of this index. */
private String m_name;
/** A map of optional key/value parameters. */
private Map<String, String> m_params;
/** A list of Cms resources to be indexed. */
private List<String> m_resourcesNames;
/**
* Creates a new CmsSearchIndexSource.<p>
*/
public CmsSearchIndexSource() {
m_params = new HashMap<String, String>();
m_resourcesNames = new ArrayList<String>();
m_documentTypes = new ArrayList<String>();
}
/**
* Adds a parameter.<p>
*
* @param key the key/name of the parameter
* @param value the value of the parameter
*/
public void addConfigurationParameter(String key, String value) {
m_params.put(key, value);
}
/**
* Adds the name of a document type.<p>
*
* @param key the name of a document type to add
*/
public void addDocumentType(String key) {
m_documentTypes.add(key);
}
/**
* Adds the path of a Cms resource.<p>
*
* @param resourceName the path of a Cms resource
*/
public void addResourceName(String resourceName) {
m_resourcesNames.add(resourceName);
}
/**
* Returns <code>0</code> if the given object is an index source with the same name. <p>
*
* Note that the name of an index source has to be unique within OpenCms.<p>
*
* @param obj another index source
*
* @return <code>0</code> if the given object is an index source with the same name
*
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(CmsSearchIndexSource obj) {
if (obj == this) {
return 0;
}
return m_name.compareTo(obj.m_name);
}
/**
* Two index sources are considered equal if their names as returned by {@link #getName()} is equal.<p>
*
* Note that the name of an index source has to be unique within OpenCms.<p>
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof CmsSearchIndexSource) {
return m_name.equals(((CmsSearchIndexSource)obj).m_name);
}
return false;
}
/**
* Returns the list of names (Strings) of the document types to be indexed.<p>
*
* @return the list of names (Strings) of the document types to be indexed
*/
public List<String> getDocumentTypes() {
return m_documentTypes;
}
/**
* Returns the indexer.<p>
*
* @return the indexer
*/
public I_CmsIndexer getIndexer() {
return m_indexer;
}
/**
* Returns the class name of the indexer.<p>
*
* @return the class name of the indexer
*/
public String getIndexerClassName() {
return m_indexerClassName;
}
/**
* Returns the logical key/name of this search index source.<p>
*
* @return the logical key/name of this search index source
*/
public String getName() {
return m_name;
}
/**
* Returns the value for a specified parameter key.<p>
*
* @param key the parameter key/name
* @return the value for the specified parameter key
*/
public String getParam(String key) {
return m_params.get(key);
}
/**
* Returns the map of optional key/value parameters.<p>
*
* @return the map of optional key/value parameters
*/
public Map<String, String> getParams() {
return m_params;
}
/**
* Returns the list of VFS resources to be indexed.<p>
*
* @return the list of VFS resources to be indexed
*/
public List<String> getResourcesNames() {
return m_resourcesNames;
}
/**
* Overriden to be consistents with overridden method
* <code>{@link #equals(Object)}</code>.
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return m_name.hashCode();
}
/**
* Returns <code>true</code> in case the given resource root path is contained in the list of
* configured resource names of this index source.<p>
*
* @param rootPath the resource root path to check
*
* @return <code>true</code> in case the given resource root path is contained in the list of
* configured resource names of this index source
*
* @see #getResourcesNames()
*/
public boolean isContaining(String rootPath) {
if ((rootPath != null) && (m_resourcesNames != null)) {
Iterator<String> i = m_resourcesNames.iterator();
while (i.hasNext()) {
String path = i.next();
if (rootPath.startsWith(path)) {
return true;
}
}
}
return false;
}
/**
* Returns <code>true</code> in case the given resource root path is contained in the list of
* configured resource names, and the given document type name is contained in the
* list if configured document type names of this index source.<p>
*
* @param rootPath the resource root path to check
* @param documentType the document type factory name to check
*
* @return <code>true</code> in case the given resource root path is contained in the list of
* configured resource names, and the given document type name is contained in the
* list if configured document type names of this index source
*
* @see #isContaining(String)
* @see #getDocumentTypes()
*/
public boolean isIndexing(String rootPath, String documentType) {
return m_documentTypes.contains(documentType) && isContaining(rootPath);
}
/**
* Removes the name of a document type from the list of configured types of this index source.<p>
*
* @param key the name of the document type to remove
*
* @return true if the given document type name was contained before thus could be removed successfully, false otherwise
*/
public boolean removeDocumentType(String key) {
return m_documentTypes.remove(key);
}
/**
* Sets the list of document type names (Strings) to be indexed.<p>
*
* @param documentTypes the list of document type names (Strings) to be indexed
*/
public void setDocumentTypes(List<String> documentTypes) {
m_documentTypes = documentTypes;
}
/**
* Sets the class name of the indexer.<p>
*
* An Exception is thrown to allow GUI-display of wrong input.<p>
*
* @param indexerClassName the class name of the indexer
*
* @throws CmsIllegalArgumentException if the given String is not a fully qualified classname (within this Java VM)
*/
public void setIndexerClassName(String indexerClassName) throws CmsIllegalArgumentException {
try {
m_indexer = (I_CmsIndexer)Class.forName(indexerClassName).newInstance();
m_indexerClassName = indexerClassName;
} catch (Exception exc) {
if (LOG.isWarnEnabled()) {
LOG.warn(
Messages.get().getBundle().key(Messages.LOG_INDEXER_CREATION_FAILED_1, m_indexerClassName),
exc);
}
throw new CmsIllegalArgumentException(Messages.get().container(
Messages.ERR_INDEXSOURCE_INDEXER_CLASS_NAME_2,
indexerClassName,
I_CmsIndexer.class.getName()));
}
}
/**
* Sets the logical key/name of this search index source.<p>
*
* @param name the logical key/name of this search index source
*
* @throws CmsIllegalArgumentException if argument name is null, an empty or whitespace-only Strings
* or already used for another indexsource's name.
*/
public void setName(String name) throws CmsIllegalArgumentException {
if (CmsStringUtil.isEmptyOrWhitespaceOnly(name)) {
throw new CmsIllegalArgumentException(Messages.get().container(
Messages.ERR_INDEXSOURCE_CREATE_MISSING_NAME_0));
}
// already used? Don't test this at xml-configuration time (no manager)
if (OpenCms.getRunLevel() > OpenCms.RUNLEVEL_2_INITIALIZING) {
CmsSearchManager mngr = OpenCms.getSearchManager();
// don't test this if the indexsource is not new (widget invokes setName even if it was not changed)
if (mngr.getIndexSource(name) != this) {
if (mngr.getSearchIndexSources().keySet().contains(name)) {
throw new CmsIllegalArgumentException(Messages.get().container(
Messages.ERR_INDEXSOURCE_CREATE_INVALID_NAME_1,
name));
}
}
}
m_name = name;
}
/**
* Sets the map of optional key/value parameters.<p>
*
* @param params the map of optional key/value parameters
*/
public void setParams(Map<String, String> params) {
m_params = params;
}
/**
* Sets the list of Cms resources to be indexed.<p>
*
* @param resources the list of Cms resources (Strings) to be indexed
*/
public void setResourcesNames(List<String> resources) {
m_resourcesNames = resources;
}
} | serrapos/opencms-core | src/org/opencms/search/CmsSearchIndexSource.java | Java | lgpl-2.1 | 11,557 |
/***************************************************************************
* Copyright (C) 2007, Sly Technologies, Inc *
* Distributed under the Lesser GNU Public License (LGPL) *
***************************************************************************/
/*
* Utility file that provides various conversion methods for chaging objects
* back and forth between C and Java JNI.
*/
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <pcap.h>
#include <jni.h>
#ifndef WIN32
#include <errno.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <unistd.h>
#endif /*WIN32*/
#include "packet_jscanner.h"
#include "packet_protocol.h"
#include "jnetpcap_utils.h"
#include "nio_jmemory.h"
#include "nio_jbuffer.h"
#include "org_jnetpcap_protocol_JProtocol.h"
#include "org_jnetpcap_nio_JMemoryReference.h"
#include "org_jnetpcap_packet_JScanner.h"
#include "org_jnetpcap_packet_JScannerReference.h"
#include "export.h"
#include "util_debug.h"
//#define DEBUG
/****************************************************************
* **************************************************************
*
* NON Java declared native functions. Private scan function
*
* **************************************************************
****************************************************************/
char str_buf[1024];
char id_str_buf[256];
/*****
* Temporarily backout of C++ Debug class and g++ compiler
*
Debug scanner_logger("jscanner");
Debug protocol_logger("jprotocol", &scanner_logger);
************/
/* scanner specific debug_ trace functions */
void debug_header(char *msg, header_t *header) {
debug_trace(msg,
"id=%s prefix=%-3d header=%-3d gap=%-3d payload=%-3d post=%-3d",
id2str(header->hdr_id), header->hdr_prefix, header->hdr_length,
header->hdr_gap, header->hdr_payload, header->hdr_postfix);
}
void debug_scan(char *msg, scan_t *scan) {
debug_trace(msg,
"id=%s off=%d prefix=%-3d header=%-3d gap=%-3d payload=%-3d post=%-3d "
"nid=%s buf_len=%-3d wire_len=%-3d flags=%0x",
id2str(scan->id), scan->offset, scan->hdr_prefix, scan->length,
scan->hdr_gap, scan->hdr_payload, scan->hdr_postfix, id2str(
scan->next_id), scan->buf_len, scan->wire_len,
scan->scanner->sc_flags[scan->id]);
}
/**
* Checks if the data at specified offset is accessible or has it possibly
* been truncated.
*/
int is_accessible(scan_t *scan, int offset) {
return (scan->offset + offset) <= scan->buf_len;
}
/*
* Converts our numerical header ID to a string, which is better suited for
* debugging.
*/
const char *id2str(int id) {
if (id == END_OF_HEADERS) {
return "END_OF_HEADERS";
} else if (native_protocol_names[id] != NULL) {
return native_protocol_names[id];
} else {
sprintf(id_str_buf, "%d", id);
return id_str_buf;
}
}
/**
* Scan packet buffer
*/
int scan(JNIEnv *env, jobject obj, jobject jpacket, scanner_t *scanner,
packet_state_t *p_packet, int first_id, char *buf, int buf_len,
uint32_t wirelen) {
scan_t scan; // Our current in progress scan's state information
scan_t *pscan = &scan;
scan.env = env;
scan.jscanner = obj;
scan.jpacket = jpacket;
scan.scanner = scanner;
scan.packet = p_packet;
scan.header = &p_packet->pkt_headers[0];
scan.buf = buf;
scan.buf_len = buf_len; // Changing buffer length, reduced by 'postfix'
scan.mem_len = buf_len; // Constant in memory buffer length
scan.wire_len = wirelen;
scan.offset = 0;
scan.length = 0;
scan.id = first_id;
scan.next_id = PAYLOAD_ID;
scan.flags = 0;
scan.hdr_flags = 0;
scan.hdr_prefix = 0;
scan.hdr_gap = 0;
scan.hdr_payload = 0;
scan.hdr_postfix = 0;
memset(scan.header, 0, sizeof(header_t));
// Point jscan
setJMemoryPhysical(env, scanner->sc_jscan, toLong(&scan));
// Local temp variables
register uint64_t mask;
#ifdef DEBUG
debug_enter("scan");
debug_trace("processing packet", "#%d", p_packet->pkt_frame_num);
#endif
/*
* Main scanner loop, 1st scans for builtin header types then
* reverts to calling on JBinding objects to provide the binding chain
*/
while (scan.id != END_OF_HEADERS) {
#ifdef DEBUG
debug_trace("", "");
debug_trace("processing header", id2str(scan.id));
debug_scan("loop-top", &scan);
#endif
/* A flag that keeps track of header recording. Set in record_header()*/
scan.is_recorded = 0;
/*
* If debugging is compiled in, we can also call on each protocols
* debug_* function to print out details about the protocol header
* structure.
*/
#ifdef DEBUG
if (native_debug[scan.id]) {
native_debug[scan.id](scan.buf + scan.offset);
}
#endif
/*
* Scan of each protocol is done through a dispatch function table.
* Each protocol that has a protocol header scanner attached, a scanner
* designed specifically for that protocol. The protocol id is also the
* index into the table. There are 2 types of scanners both have exactly
* the same signature and thus both are set in this table. The first is
* the native scanner that only performs a direct scan of the header.
* The second scanner is a java header scanner. It is based on
* JHeaderScanner class. A single dispatch method callJavaHeaderScanner
* uses the protocol ID to to dispatch to the appropriate java scanner.
* Uses a separate java specific table: sc_java_header_scanners[]. The
* java scanner is capable of calling the native scan method from java
* but also adds the ability to check all the attached JBinding[] for
* any additional registered bindings. Interesting fact is that if the
* java scanner doesn't have any bindings nor does it override the
* default scan method to perform a scan in java and is also setup to
* dispatch to native scanner, it is exactly same thing as if the
* native scanner was dispatched directly from here, but round
* about way through java land.
*/
if (scanner->sc_scan_table[scan.id] != NULL) {
scanner->sc_scan_table[scan.id](&scan); // Dispatch to scanner
}
#ifdef DEBUG
debug_scan("loop-middle", &scan);
#endif
if (scan.length == 0) {
#ifdef DEBUG
debug_scan("loop-length==0", &scan);
#endif
if (scan.id == PAYLOAD_ID) {
scan.next_id = END_OF_HEADERS;
} else {
scan.next_id = PAYLOAD_ID;
}
} else { // length != 0
#ifdef DEBUG
debug_scan("loop-length > 0", &scan);
#endif
/******************************************************
* ****************************************************
* * If override flag is set, then we reset the
* * discovered next protocol. If that is what the user
* * wants then that is what he gets.
* ****************************************************
******************************************************/
if (scanner->sc_flags[scan.id] & FLAG_OVERRIDE_BINDING) {
#ifdef DEBUG
debug_scan("TCP OVERRIDE", &scan);
#endif
scan.next_id = PAYLOAD_ID;
}
/******************************************************
* ****************************************************
* * Now do HEURISTIC discovery scans if the appropriate
* * flags are set. Heuristics allow us to provide nxt
* * protocol binding, using discovery (an educated
* * guess).
* ****************************************************
******************************************************/
if (scanner->sc_flags[scan.id] & FLAG_HEURISTIC_BINDING) {
/*
* Save these critical properties, in case heuristic changes them
* for this current header, not the next one its supposed to
* check for.
*/
int saved_offset = scan.offset;
int saved_length = scan.length;
/* Advance offset to next header, so that heuristics can get a
* peek. It will be restored at the end of heuristics block.
*/
scan.offset += scan.length + scan.hdr_gap;
/*
* 2 types of heuristic bindings. Pre and post.
* Pre - heuristics are run before the direct discovery method
* in scanner. Only after the pre-heuristic fail do we
* utilize the directly discovered binding.
*
* Post - heuristics are run after the direct discovery method
* didn't produce a binding.
*
* ------------------------------------------------------------
*
* In our case, since we have already ran the direct discovery
* in the header scanner, we save scan.next_id value, reset it,
* call the heuristic function, check its scan.next_id if it
* was set, if it was, then use that instead. Otherwise if it
* wasn't restore the original next_id and continue on normally.
*/
if (scanner->sc_flags[scan.id] & FLAG_HEURISTIC_PRE_BINDING) {
#ifdef DEBUG
debug_scan("heurists_pre", &scan);
#endif
int saved_next_id = scan.next_id;
scan.next_id = PAYLOAD_ID;
for (int i = 0; i < MAX_ID_COUNT; i++) {
native_validate_func_t validate_func;
validate_func
= scanner->sc_heuristics_table[scan.id][i];
if (validate_func == NULL) {
break;
}
if ((scan.next_id = validate_func(&scan)) != INVALID) {
break;
}
}
if (scan.next_id == PAYLOAD_ID) {
scan.next_id = saved_next_id;
}
} else if (scan.next_id == PAYLOAD_ID) {
#ifdef DEBUG
debug_scan("heurists_post", &scan);
#endif
for (int i = 0; i < MAX_ID_COUNT; i++) {
native_validate_func_t validate_func;
validate_func
= scanner->sc_heuristics_table[scan.id][i];
if (validate_func == NULL) {
break;
}
if ((scan.next_id = validate_func(&scan)) != INVALID) {
#ifdef DEBUG
debug_scan("heurists_post::found", &scan);
#endif
break;
}
}
}
/* Restore these 2 critical properties */
scan.offset = saved_offset;
scan.length = saved_length;
}
/******************************************************
* ****************************************************
* * Now record discovered information in structures
* ****************************************************
******************************************************/
record_header(&scan);
#ifdef DEBUG
debug_header("header_t", scan.header - 1);
#endif
} // End if len != 0
#ifdef DEBUG
debug_scan("loop-bottom", &scan);
#endif
scan.id = scan.next_id;
scan.offset += scan.length + scan.hdr_gap;
scan.length = 0;
scan.next_id = PAYLOAD_ID;
if (scan.offset >= scan.buf_len) {
scan.id = END_OF_HEADERS;
}
} // End for loop
/* record number of header entries found */
// scan.packet->pkt_header_count = count;
process_flow_key(&scan);
#ifdef DEBUG
debug_trace("loop-finished",
"header_count=%d offset=%d header_map=0x%X",
scan.packet->pkt_header_count, scan.offset,
scan.packet->pkt_header_map);
debug_exit("scan()");
#endif
return scan.offset;
} // End scan()
/**
* Record state of the header in the packet state structure.
*/
void record_header(scan_t *scan) {
#ifdef DEBUG
debug_enter("record_header");
debug_scan("top", scan);
#endif
/*
* Check if already recorded
*/
if (scan->is_recorded) {
#ifdef DEBUG
debug_exit("record_header");
#endif
return;
}
register int offset = scan->offset;
register header_t *header = scan->header;
register int buf_len = scan->buf_len;
packet_state_t *packet = scan->packet;
/*
* Decrease wire-length by postfix amount so that next header's payload
* will be reduced and won't go over this header's postfix
*/
scan->wire_len -= scan->hdr_postfix;
if (buf_len > scan->wire_len) {
buf_len = scan->buf_len = scan->wire_len; // Make sure that buf_len and wire_len sync up
#ifdef DEBUG
debug_scan("adj buf_len", scan);
#endif
}
/*
* If payload length hasn't explicitly been set to some length, set it
* to the remainder of the packet.
*/
if (scan->hdr_payload == 0 && scan->id != PAYLOAD_ID) {
scan->hdr_payload = scan->buf_len - (offset + scan->hdr_prefix
+ scan->length + scan->hdr_gap);
scan->hdr_payload = (scan->hdr_payload < 0) ? 0 : scan->hdr_payload;
#ifdef DEBUG
debug_scan("adj payload", scan);
#endif
}
adjustForTruncatedPacket(scan);
register int length = scan->length;
/*
* Initialize the header entry in our packet header array
*/
packet->pkt_header_map |= (1 << scan->id);
header->hdr_id = scan->id;
header->hdr_offset = offset + scan->hdr_prefix;
header->hdr_analysis = NULL;
/*
* This is a combination of regular header flags with cumulative flags
* which are accumulated by subsequent pass to the next header and pass on
* to their encapsulated headers. This is a way to pass flags such as
* the remaining header's are fragmented.
*/
header->hdr_flags = scan->hdr_flags | (scan->flags & CUMULATIVE_FLAG_MASK);
header->hdr_prefix = scan->hdr_prefix;
header->hdr_gap = scan->hdr_gap;
header->hdr_payload = scan->hdr_payload;
header->hdr_postfix = scan->hdr_postfix;
header->hdr_length = length;
scan->hdr_flags = 0;
scan->hdr_prefix = 0;
scan->hdr_gap = 0;
scan->hdr_payload = 0;
scan->hdr_postfix = 0;
scan->is_recorded = 1;
packet->pkt_header_count++; /* number of entries */
// scan->id = -1; // Indicates, that header is already recorded
/* Initialize key fields in a new header */
header = ++scan->header; /* point to next header entry *** ptr arithmatic */
memset(header, 0, sizeof(header_t));
#ifdef DEBUG
debug_scan("bottom", scan);
debug_exit("record_header");
#endif
}
/**
* Adjusts for a packet that has been truncated. Sets appropriate flags in the
* header flags field, resets lengths of prefix, header, gap, payload and
* postfix appropriately to account for shortened packet.
*/
void adjustForTruncatedPacket(scan_t *scan) {
#ifdef DEBUG
debug_enter("adjustForTruncatedPacket");
debug_trace("packet", "%ld", scan->scanner->sc_cur_frame_num);
#endif
/*
* Adjust for truncated packets. We check the end of the header record
* against the buf_len. If the end is past the buf_len, that means that we
* need to start trucating in the following order:
* postfix, payload, gap, header, prefix
*
* +-------------------------------------------+
* | prefix | header | gap | payload | postfix |
* +-------------------------------------------+
*
*/
register int start = scan->offset + scan->hdr_prefix + scan->length
+ scan->hdr_gap + scan->hdr_payload;
register int end = start + scan->hdr_postfix;
register int buf_len = scan->buf_len;
#ifdef DEBUG
debug_scan((char *)id2str(scan->id), scan);
debug_trace(id2str(scan->id), "offset=%d, pre=%d, len=%d, gap=%d, pay=%d, post=%d",
scan->offset,
scan->hdr_prefix,
scan->length,
scan->hdr_gap,
scan->hdr_payload,
scan->hdr_postfix);
debug_trace(id2str(scan->id), "start=%d end=%d buf_len=%d", start, end, buf_len);
#endif
if (end > buf_len) { // Check if postfix extends past the end of packet
/*
* Because postfix is at the end, whenever the packet is truncated
* postfix is always truncated, unless it wasn't set
*/
if (scan->hdr_postfix > 0) {
scan->hdr_flags |= HEADER_FLAG_PREFIX_TRUNCATED;
scan->hdr_postfix = (start > scan->mem_len) ? 0 : scan->mem_len
- start;
scan->hdr_postfix = (scan->hdr_postfix < 0) ? 0 : scan->hdr_postfix;
#ifdef DEBUG
debug_scan("adjust postfix", scan);
#endif
}
/* Position at payload and process */
start -= scan->hdr_payload;
end = start + scan->hdr_payload;
if (end > buf_len) {
scan->hdr_flags |= HEADER_FLAG_PAYLOAD_TRUNCATED;
scan->hdr_payload = (start > buf_len) ? 0 : buf_len - start;
scan->hdr_payload = (scan->hdr_payload < 0) ? 0 : scan->hdr_payload;
#ifdef DEBUG
debug_scan("adjust payload", scan);
debug_trace("adjust payload", "start=%d end=%d", start, end);
#endif
/* Position at gap and process */
start -= scan->hdr_gap;
end = start + scan->hdr_gap;
if (scan->hdr_gap > 0 && end > buf_len) {
scan->hdr_flags |= HEADER_FLAG_GAP_TRUNCATED;
scan->hdr_gap = (start > buf_len) ? 0 : buf_len - start;
scan->hdr_gap = (scan->hdr_gap < 0) ? 0 : scan->hdr_gap;
#ifdef DEBUG
debug_scan("adjust gap", scan);
#endif
}
/* Position at header and process */
start -= scan->length;
end = start + scan->length;
if (end > buf_len) {
scan->hdr_flags |= HEADER_FLAG_HEADER_TRUNCATED;
scan->length = (start > buf_len) ? 0 : buf_len - start;
scan->length = (scan->length < 0) ? 0 : scan->length;
#ifdef DEBUG
debug_scan("adjust header", scan);
#endif
/* Position at prefix and process */
start -= scan->hdr_prefix;
end = start + scan->hdr_prefix;
if (0 && scan->hdr_prefix > 0 && end > buf_len) {
scan->hdr_flags |= HEADER_FLAG_PREFIX_TRUNCATED;
scan->hdr_prefix = (start > buf_len) ? 0 : buf_len - start;
scan->hdr_prefix = (scan->hdr_prefix < 0) ? 0
: scan->hdr_prefix;
#ifdef DEBUG
debug_scan("adjust prefix", scan);
#endif
}
}
}
}
#ifdef DEBUG
debug_exit("adjustForTruncatedPacket");
#endif
#undef DEBUG
}
/**
* Scan packet buffer by dispatching to JBinding java objects
*/
void callJavaHeaderScanner(scan_t *scan) {
#ifdef DEBUG
debug_enter("callJavaHeaderScanner");
#endif
JNIEnv *env = scan->env;
jobject jscanner = scan->scanner->sc_java_header_scanners[scan->id];
if (jscanner == NULL) {
sprintf(str_buf, "java header scanner not set for ID=%d (%s)",
scan->id, id2str(scan->id));
#ifdef DEBUG
debug_error("callJavaHeaderScanner()", str_buf);
#endif
throwException(scan->env, NULL_PTR_EXCEPTION, str_buf);
return;
}
env->CallVoidMethod(jscanner, scanHeaderMID, scan->scanner->sc_jscan);
#ifdef DEBUG
debug_exit("callJavaHeaderScanner");
#endif
}
/**
* Prepares a scan of packet buffer
*/
int scanJPacket(JNIEnv *env, jobject obj, jobject jpacket, jobject jstate,
scanner_t *scanner, int first_id, char *buf, int buf_length,
uint32_t wirelen) {
#ifdef DEBUG
debug_enter("scanJPacket");
#endif
/* Check if we need to wrap our entry buffer around */
if (scanner->sc_offset > scanner->sc_len - sizeof(header_t)
* MAX_ENTRY_COUNT) {
scanner->sc_offset = 0;
}
packet_state_t *packet = (packet_state_t *) (((char *) scanner->sc_packet)
+ scanner->sc_offset);
/*
* Peer JPacket.state to packet_state_t structure
*/
// setJMemoryPhysical(env, jstate, toLong(packet));
// env->SetObjectField(jstate, jmemoryKeeperFID, obj); // Set it to JScanner
jmemoryPeer(env, jstate, packet, sizeof(packet_state_t), obj);
/*
* Reset the entire packet_state_t structure
*/
memset(packet, 0, sizeof(packet_state_t));
/*
* Initialize the packet_state_t structure for new packet entry. We need to
* initialize everything since we may be wrapping around and writting over
* previously stored data.
*/
packet->pkt_header_map = 0;
packet->pkt_header_count = 0;
packet->pkt_frame_num = scanner->sc_cur_frame_num++;
packet->pkt_wirelen = (uint32_t) wirelen;
packet->pkt_flags = 0;
if (buf_length != wirelen) {
packet->pkt_flags |= PACKET_FLAG_TRUNCATED;
}
#ifdef DEBUG
debug_trace("before scan", "buf_len=%d wire_len=%d", buf_length, wirelen);
#endif
scan(env, obj, jpacket, scanner, packet, first_id, buf, buf_length, wirelen);
#ifdef DEBUG
debug_trace("after scan", "buf_len=%d wire_len=%d", buf_length, wirelen);
#endif
const size_t len = sizeof(packet_state_t) + (sizeof(header_t)
* packet->pkt_header_count);
scanner->sc_offset += len;
jmemoryResize(env, jstate, len);
#ifdef DEBUG
debug_exit("scanJPacket");
#endif
}
/****************************************************************
* **************************************************************
*
* Java declared native functions
*
* **************************************************************
****************************************************************/
jclass jheaderScannerClass = NULL;
jmethodID scanHeaderMID = 0;
/*
* Class: org_jnetpcap_packet_JScanner
* Method: initIds
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_org_jnetpcap_packet_JScanner_initIds
(JNIEnv *env, jclass clazz) {
if ( (jheaderScannerClass = findClass(
env,
"org/jnetpcap/packet/JHeaderScanner")) == NULL) {
return;
}
if ( (scanHeaderMID = env->GetMethodID(
jheaderScannerClass,
"scanHeader",
"(Lorg/jnetpcap/packet/JScan;)V")) == NULL) {
return;
}
/*
* Initialize the global native scan function dispatch table.
* i.e. scan_ethernet(), scan_ip4(), etc...
*/
init_native_protocols();
}
/*
* Class: org_jnetpcap_packet_JScanner
* Method: sizeof
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_org_jnetpcap_packet_JScanner_sizeof(JNIEnv *env,
jclass obj) {
return (jint) sizeof(scanner_t);
}
/*
* Class: org_jnetpcap_packet_JScannerReference
* Method: disposeNative
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_org_jnetpcap_packet_JScannerReference_disposeNative
(JNIEnv *env, jobject obj, jlong size) {
jlong pt = env->GetLongField(obj, jmemoryRefAddressFID);
scanner_t *scanner = (scanner_t *)toPtr(pt);
if (scanner == NULL) {
return;
}
env->DeleteGlobalRef(scanner->sc_jscan);
scanner->sc_jscan = NULL;
if (scanner->sc_subheader != NULL) {
free(scanner->sc_subheader);
scanner->sc_subheader = NULL;
}
for (int i = 0; i < MAX_ID_COUNT; i ++) {
if (scanner->sc_java_header_scanners[i] != NULL) {
env->DeleteGlobalRef(scanner->sc_java_header_scanners[i]);
scanner->sc_java_header_scanners[i] = NULL;
}
}
/*
* Same as super.dispose(): call from JScannerReference.dispose for
* JMemoryReference.super.dispose.
*/
// Java_org_jnetpcap_nio_JMemoryReference_disposeNative0(env, obj, pt, size);
}
/*
* Class: org_jnetpcap_packet_JScanner
* Method: getFrameNumber
* Signature: ()J
*/
JNIEXPORT jlong JNICALL Java_org_jnetpcap_packet_JScanner_getFrameNumber(
JNIEnv *env, jobject obj) {
scanner_t *scanner = (scanner_t *) getJMemoryPhysical(env, obj);
if (scanner == NULL) {
return -1;
}
return (jlong) scanner->sc_cur_frame_num;
}
/*
* Class: org_jnetpcap_packet_JScanner
* Method: init
* Signature: (Lorg.jnetpcap.packet.JScan;)V
*/
JNIEXPORT void JNICALL Java_org_jnetpcap_packet_JScanner_init
(JNIEnv *env, jobject obj, jobject jscan) {
#ifdef DEBUG
debug_enter("JScanner_init");
#endif
if (jscan == NULL) {
throwException(env, NULL_PTR_EXCEPTION,
"JScan parameter can not be null");
return;
}
void *block = (char *)getJMemoryPhysical(env, obj);
size_t size = (size_t)env->GetIntField(obj, jmemorySizeFID);
memset(block, 0, size);
scanner_t *scanner = (scanner_t *)block;
scanner->sc_jscan = env->NewGlobalRef(jscan);
scanner->sc_len = size - sizeof(scanner_t);
scanner->sc_offset = 0;
scanner->sc_packet = (packet_state_t *)((char *)block + sizeof(scanner_t));
for (int i = 0; i < MAX_ID_COUNT; i++) {
scanner->sc_scan_table[i] = native_protocols[i];
}
for (int i = 0; i < MAX_ID_COUNT; i++) {
for (int j = 0; j < MAX_ID_COUNT; j++) {
scanner->sc_heuristics_table[i][j] = native_heuristics[i][j];
}
}
/* Initialize sub-header area - allocate 1/10th */
scanner->sc_sublen = size / 10;
scanner->sc_subindex = 0;
scanner->sc_subheader = (header_t *)malloc(scanner->sc_sublen);
#ifdef DEBUG
debug_exit("JScanner_init");
#endif
}
/*
* Class: org_jnetpcap_packet_JScanner
* Method: loadScanners
* Signature: (I[Lorg/jnetpcap/packet/JHeaderScanner;)V
*/
JNIEXPORT void JNICALL Java_org_jnetpcap_packet_JScanner_loadScanners
(JNIEnv *env, jobject obj, jobjectArray jascanners) {
#ifdef DEBUG
debug_enter("loadScanners");
#endif
scanner_t *scanner = (scanner_t *)getJMemoryPhysical(env, obj);
if (scanner == NULL) {
return;
}
jsize size = env->GetArrayLength(jascanners);
#ifdef DEBUG
debug_trace("load", "loaded %d scanners", (int)size);
#endif
if (size != MAX_ID_COUNT) {
throwException(env,
ILLEGAL_ARGUMENT_EXCEPTION,
"size of array must be MAX_ID_COUNT size");
#ifdef DEBUG
debug_error("IllegalArgumentException",
"size of array must be MAX_ID_COUNT size");
#endif
return;
}
for (int i = 0; i < MAX_ID_COUNT; i ++) {
jobject loc_ref = env->GetObjectArrayElement(jascanners, (jsize) i);
if (loc_ref == NULL) {
/*
* If we don't have a java header scanner, then setup the native
* scanner in its place. Any unused java scanner slot will be filled
* with native scanner.
*/
scanner->sc_scan_table[i] = native_protocols[i];
// printf("loadScanners::native(%s)\n", id2str(i));fflush(stdout);
} else {
// printf("loadScanners::java(%s)\n", id2str(i));fflush(stdout);
if (scanner->sc_java_header_scanners[i] != NULL) {
env->DeleteGlobalRef(scanner->sc_java_header_scanners[i]);
scanner->sc_java_header_scanners[i] = NULL;
}
/*
* Record the java header scanner and replace the native scanner with
* our java scanner in dispatch table.
*/
scanner->sc_java_header_scanners[i] = env->NewGlobalRef(loc_ref);
scanner->sc_scan_table[i] = callJavaHeaderScanner;
env->DeleteLocalRef(loc_ref);
}
}
#ifdef DEBUG
debug_exit("loadScanners");
#endif
}
/*
* Class: org_jnetpcap_packet_JScanner
* Method: loadFlags
* Signature: ([I)V
*/
JNIEXPORT void JNICALL Java_org_jnetpcap_packet_JScanner_loadFlags
(JNIEnv *env, jobject obj, jintArray jflags) {
#ifdef DEBUG
debug_enter("loadFlags");
#endif
scanner_t *scanner = (scanner_t *)getJMemoryPhysical(env, obj);
if (scanner == NULL) {
return;
}
jsize size = env->GetArrayLength(jflags);
#ifdef DEBUG
debug_trace("load", "loaded %d flags", (int)size);
#endif
if (size != MAX_ID_COUNT) {
throwException(env,
ILLEGAL_ARGUMENT_EXCEPTION,
"size of array must be MAX_ID_COUNT size");
#ifdef DEBUG
debug_error("IllegalArgumentException",
"size of array must be MAX_ID_COUNT size");
#endif
return;
}
env->GetIntArrayRegion(jflags, 0, size, (jint *)scanner->sc_flags);
#ifdef DEBUG
debug_exit("loadFlags");
#endif
}
/*
* Class: org_jnetpcap_packet_JScanner
* Method: scan
* Signature: (Lorg/jnetpcap/packet/JPacket;Lorg/jnetpcap/packet/JPacket$State;II)I
*/
JNIEXPORT jint JNICALL Java_org_jnetpcap_packet_JScanner_scan(JNIEnv *env,
jobject obj, jobject jpacket, jobject jstate, jint id, jint wirelen) {
scanner_t *scanner = (scanner_t *) getJMemoryPhysical(env, obj);
if (scanner == NULL) {
return -1;
}
char *buf = (char *) getJMemoryPhysical(env, jpacket);
if (buf == NULL) {
return -1;
}
int size = (int) env->GetIntField(jpacket, jmemorySizeFID);
if (wirelen < size) {
throwException(env, ILLEGAL_ARGUMENT_EXCEPTION, "wirelen < buffer len");
return -1;
}
return scanJPacket(env, obj, jpacket, jstate, scanner, id, buf, size,
(uint32_t) wirelen);
}
/*
* Class: org_jnetpcap_packet_JScanner
* Method: setFrameNumber
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_org_jnetpcap_packet_JScanner_setFrameNumber
(JNIEnv *env, jobject obj, jlong frame_no) {
scanner_t *scanner = (scanner_t *)getJMemoryPhysical(env, obj);
if (scanner == NULL) {
return;
}
scanner->sc_cur_frame_num = (uint64_t) frame_no;
return;
}
| universsky/diddler | jni/packet_jsmall_scanner.cpp | C++ | lgpl-3.0 | 27,196 |
<?php
/**
* This source file is part of GotCms.
*
* GotCms is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GotCms 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 GotCms. If not, see <http://www.gnu.org/licenses/lgpl-3.0.html>.
*
* PHP Version >=5.3
*
* @category Gc_Test
* @package Bootstrap
* @author Pierre Rambaud (GoT) <pierre.rambaud86@gmail.com>
* @license GNU/LGPL http://www.gnu.org/licenses/lgpl-3.0.html
* @link http://www.got-cms.com
*/
/**
* Override upload functions
*/
namespace Gc\Media\File;
namespace Zend\File\Transfer\Adapter;
function is_uploaded_file($filename)
{
return true;
}
function move_uploaded_file($filename, $destination)
{
return copy($filename, $destination);
}
namespace Zend\Validator\File;
function is_uploaded_file($filename)
{
return true;
}
function move_uploaded_file($filename, $destination)
{
return copy($filename, $destination);
}
/**
* Override Updater adapters
*/
namespace Gc\Core\Updater\Adapter;
function exec($command, &$output = array(), &$returnVar = null)
{
$output = array();
return '';
}
/**
* Override updater
*/
namespace Gc\Core;
use Gc\View\Stream;
function glob($pattern, $flags = 0)
{
Stream::register();
if (preg_match('~\.sql$~', $pattern)) {
$content = trim(file_get_contents('zend.view://test-updater'));
if (empty($content)) {
return false;
}
return array('zend.view://test-updater');
}
$scriptPath = GC_APPLICATION_PATH . '/tests/library/Gc/Core/_files/test.php';
if (file_exists($scriptPath) and in_array($pattern, array(GC_APPLICATION_PATH . '/data/update/*', '999/*.php'))) {
$content = file_get_contents($scriptPath);
if ($pattern == GC_APPLICATION_PATH . '/data/update/*') {
if (empty($content)) {
return array('0');
}
return array(999);
} else {
if (empty($content)) {
return array();
}
return array($scriptPath);
}
}
return array('9999.999.999');
}
function file_put_contents($filename, $data, $flags = 0, $context = null)
{
if (strpos($filename, GC_APPLICATION_PATH . '/data/translation') !== false) {
return true;
}
return \file_put_contents($filename, $data, $flags, $context);
}
/**
* Override Git adapter
*/
namespace Backup\Model;
function exec($command, &$output = array(), &$returnVar = null)
{
$output = array();
return '';
}
/**
* Override Elfinder connector
*/
namespace elFinder;
class elFinderConnector
{
public function run() {
return true;
}
}
/**
* Override Installer
*/
namespace GcFrontend\Controller;
function file_exists($string)
{
return false;
}
function ini_set($string, $value)
{
return true;
}
function file_get_contents($filename)
{
return 'DELETE FROM core_config_data WHERE id = "test";';
}
function file_put_contents($filename, $content)
{
return true;
}
function copy($source, $destination)
{
return true;
}
function glob($path)
{
return array(GC_MEDIA_PATH . '/fr_FR.php');
}
/**
* Override Zend\Mail\Transport
*/
namespace Zend\Mail\Transport;
function mail($to, $subject, $message, $additional_headers = null, $additional_parameters = null)
{
return true;
}
/**
* Override Zend\Mail\Transport
*/
namespace Gc;
function file_get_contents($filename)
{
return \file_get_contents(GC_MEDIA_PATH . '/github.tags');
}
| hmschreiner/GotCms | tests/config/override-php-functions.php | PHP | lgpl-3.0 | 3,982 |
<?php
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
namespace Twilio\Rest\Chat\V1\Service;
use Twilio\Deserialize;
use Twilio\Exceptions\TwilioException;
use Twilio\InstanceResource;
use Twilio\Version;
/**
* @property string sid
* @property string accountSid
* @property string serviceSid
* @property string friendlyName
* @property string type
* @property string permissions
* @property \DateTime dateCreated
* @property \DateTime dateUpdated
* @property string url
*/
class RoleInstance extends InstanceResource {
/**
* Initialize the RoleInstance
*
* @param \Twilio\Version $version Version that contains the resource
* @param mixed[] $payload The response payload
* @param string $serviceSid The service_sid
* @param string $sid The sid
* @return \Twilio\Rest\Chat\V1\Service\RoleInstance
*/
public function __construct(Version $version, array $payload, $serviceSid, $sid = null) {
parent::__construct($version);
// Marshaled Properties
$this->properties = array(
'sid' => $payload['sid'],
'accountSid' => $payload['account_sid'],
'serviceSid' => $payload['service_sid'],
'friendlyName' => $payload['friendly_name'],
'type' => $payload['type'],
'permissions' => $payload['permissions'],
'dateCreated' => Deserialize::dateTime($payload['date_created']),
'dateUpdated' => Deserialize::dateTime($payload['date_updated']),
'url' => $payload['url'],
);
$this->solution = array(
'serviceSid' => $serviceSid,
'sid' => $sid ?: $this->properties['sid'],
);
}
/**
* Generate an instance context for the instance, the context is capable of
* performing various actions. All instance actions are proxied to the context
*
* @return \Twilio\Rest\Chat\V1\Service\RoleContext Context for this
* RoleInstance
*/
protected function proxy() {
if (!$this->context) {
$this->context = new RoleContext(
$this->version,
$this->solution['serviceSid'],
$this->solution['sid']
);
}
return $this->context;
}
/**
* Fetch a RoleInstance
*
* @return RoleInstance Fetched RoleInstance
*/
public function fetch() {
return $this->proxy()->fetch();
}
/**
* Deletes the RoleInstance
*
* @return boolean True if delete succeeds, false otherwise
*/
public function delete() {
return $this->proxy()->delete();
}
/**
* Update the RoleInstance
*
* @param string $permission The permission
* @return RoleInstance Updated RoleInstance
*/
public function update($permission) {
return $this->proxy()->update(
$permission
);
}
/**
* Magic getter to access properties
*
* @param string $name Property to access
* @return mixed The requested property
* @throws TwilioException For unknown properties
*/
public function __get($name) {
if (array_key_exists($name, $this->properties)) {
return $this->properties[$name];
}
if (property_exists($this, '_' . $name)) {
$method = 'get' . ucfirst($name);
return $this->$method();
}
throw new TwilioException('Unknown property: ' . $name);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString() {
$context = array();
foreach ($this->solution as $key => $value) {
$context[] = "$key=$value";
}
return '[Twilio.Chat.V1.RoleInstance ' . implode(' ', $context) . ']';
}
} | tigerhawkvok/php-userhandler | twilio/Twilio/Rest/Chat/V1/Service/RoleInstance.php | PHP | lgpl-3.0 | 4,030 |
#!/usr/bin/env python
# vim: set et ts=4 sw=4:
#coding:utf-8
#############################################################################
#
# mga-dialogs.py - Show mga msg dialog and about dialog.
#
# License: GPLv3
# Author: Angelo Naselli <anaselli@linux.it>
#############################################################################
###########
# imports #
###########
import sys
sys.path.insert(0,'../../../build/swig/python')
import os
import yui
log = yui.YUILog.instance()
log.setLogFileName("/tmp/debug.log")
log.enableDebugLogging( True )
appl = yui.YUI.application()
appl.setApplicationTitle("Show dialogs example")
#################
# class mainGui #
#################
class Info(object):
def __init__(self,title,richtext,text):
self.title=title
self.richtext=richtext
self.text=text
class mainGui():
"""
Main class
"""
def __init__(self):
self.factory = yui.YUI.widgetFactory()
self.dialog = self.factory.createPopupDialog()
mainvbox = self.factory.createVBox(self.dialog)
frame = self.factory.createFrame(mainvbox,"Test frame")
HBox = self.factory.createHBox(frame)
self.aboutbutton = self.factory.createPushButton(HBox,"&About")
self.closebutton = self.factory.createPushButton(self.factory.createRight(HBox), "&Close")
def ask_YesOrNo(self, info):
yui.YUI.widgetFactory
mgafactory = yui.YMGAWidgetFactory.getYMGAWidgetFactory(yui.YExternalWidgets.externalWidgetFactory("mga"))
dlg = mgafactory.createDialogBox(yui.YMGAMessageBox.B_TWO)
dlg.setTitle(info.title)
dlg.setText(info.text, info.richtext)
dlg.setButtonLabel("Yes", yui.YMGAMessageBox.B_ONE)
dlg.setButtonLabel("No", yui.YMGAMessageBox.B_TWO)
dlg.setMinSize(50, 5);
return dlg.show() == yui.YMGAMessageBox.B_ONE
def aboutDialog(self):
yui.YUI.widgetFactory;
mgafactory = yui.YMGAWidgetFactory.getYMGAWidgetFactory(yui.YExternalWidgets.externalWidgetFactory("mga"))
dlg = mgafactory.createAboutDialog("About dialog title example", "1.0.0", "GPLv3",
"Angelo Naselli", "This beautiful test example shows how it is easy to play with libyui bindings", "")
dlg.show();
def handleevent(self):
"""
Event-handler for the 'widgets' demo
"""
while True:
event = self.dialog.waitForEvent()
if event.eventType() == yui.YEvent.CancelEvent:
self.dialog.destroy()
break
if event.widget() == self.closebutton:
info = Info("Quit confirmation", 1, "Are you sure you want to quit?")
if self.ask_YesOrNo(info):
self.dialog.destroy()
break
if event.widget() == self.aboutbutton:
self.aboutDialog()
if __name__ == "__main__":
main_gui = mainGui()
main_gui.handleevent()
| anaselli/libyui-bindings | swig/python/examples/mga-dialogs.py | Python | lgpl-3.0 | 3,012 |
<?php
/**
* @copyright Copyright (c) Metaways Infosystems GmbH, 2011
* @license LGPLv3, http://www.gnu.org/licenses/lgpl.html
* @package MW
* @subpackage Template
*/
/**
* Exception thrown by template objects.
*
* @package MW
* @subpackage Template
*/
class MW_Template_Exception extends MW_Exception
{
}
| Yvler/aimeos-core | lib/mwlib/src/MW/Template/Exception.php | PHP | lgpl-3.0 | 318 |
#!/usr/bin/env python
#
# Copyright 2007 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.
#
"""Serves static content for "static_dir" and "static_files" handlers."""
import base64
import errno
import httplib
import mimetypes
import os
import os.path
import re
import zlib
from google.appengine.api import appinfo
from google.appengine.tools import augment_mimetypes
from google.appengine.tools.devappserver2 import errors
from google.appengine.tools.devappserver2 import url_handler
_FILE_MISSING_ERRNO_CONSTANTS = frozenset([errno.ENOENT, errno.ENOTDIR])
# Run at import time so we only do this once.
augment_mimetypes.init()
class StaticContentHandler(url_handler.UserConfiguredURLHandler):
"""Abstract base class for subclasses serving static content."""
# Associate the full path of a static file with a 2-tuple containing the:
# - mtime at which the file was last read from disk
# - a etag constructed from a hash of the file's contents
# Statting a small file to retrieve its mtime is approximately 20x faster than
# reading it to generate a hash of its contents.
_filename_to_mtime_and_etag = {}
def __init__(self, root_path, url_map, url_pattern):
"""Initializer for StaticContentHandler.
Args:
root_path: A string containing the full path of the directory containing
the application's app.yaml file.
url_map: An appinfo.URLMap instance containing the configuration for this
handler.
url_pattern: A re.RegexObject that matches URLs that should be handled by
this handler. It may also optionally bind groups.
"""
super(StaticContentHandler, self).__init__(url_map, url_pattern)
self._root_path = root_path
def _get_mime_type(self, path):
"""Returns the mime type for the file at the given path."""
if self._url_map.mime_type is not None:
return self._url_map.mime_type
_, extension = os.path.splitext(path)
return mimetypes.types_map.get(extension, 'application/octet-stream')
def _handle_io_exception(self, start_response, e):
"""Serves the response to an OSError or IOError.
Args:
start_response: A function with semantics defined in PEP-333. This
function will be called with a status appropriate to the given
exception.
e: An instance of OSError or IOError used to generate an HTTP status.
Returns:
An emply iterable.
"""
if e.errno in _FILE_MISSING_ERRNO_CONSTANTS:
start_response('404 Not Found', [])
else:
start_response('403 Forbidden', [])
return []
@staticmethod
def _calculate_etag(data):
return base64.b64encode(str(zlib.crc32(data)))
def _handle_path(self, full_path, environ, start_response):
"""Serves the response to a request for a particular file.
Note that production App Engine treats all methods as "GET" except "HEAD".
Unless set explicitly, the "Expires" and "Cache-Control" headers are
deliberately different from their production values to make testing easier.
If set explicitly then the values are preserved because the user may
reasonably want to test for them.
Args:
full_path: A string containing the absolute path to the file to serve.
environ: An environ dict for the current request as defined in PEP-333.
start_response: A function with semantics defined in PEP-333.
Returns:
An iterable over strings containing the body of the HTTP response.
"""
data = None
if full_path in self._filename_to_mtime_and_etag:
last_mtime, etag = self._filename_to_mtime_and_etag[full_path]
else:
last_mtime = etag = None
user_headers = self._url_map.http_headers or appinfo.HttpHeadersDict()
if_match = environ.get('HTTP_IF_MATCH')
if_none_match = environ.get('HTTP_IF_NONE_MATCH')
try:
mtime = os.path.getmtime(full_path)
except (OSError, IOError) as e:
# RFC-2616 section 14.24 says:
# If none of the entity tags match, or if "*" is given and no current
# entity exists, the server MUST NOT perform the requested method, and
# MUST return a 412 (Precondition Failed) response.
if if_match:
start_response('412 Precondition Failed', [])
return []
elif self._url_map.require_matching_file:
return None
else:
return self._handle_io_exception(start_response, e)
if mtime != last_mtime:
try:
data = self._read_file(full_path)
except (OSError, IOError) as e:
return self._handle_io_exception(start_response, e)
etag = self._calculate_etag(data)
self._filename_to_mtime_and_etag[full_path] = mtime, etag
if if_match and not self._check_etag_match(if_match,
etag,
allow_weak_match=False):
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.24
start_response('412 Precondition Failed',
[('ETag', '"%s"' % etag)])
return []
elif if_none_match and self._check_etag_match(if_none_match,
etag,
allow_weak_match=True):
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
start_response('304 Not Modified',
[('ETag', '"%s"' % etag)])
return []
else:
if data is None:
try:
data = self._read_file(full_path)
except (OSError, IOError) as e:
return self._handle_io_exception(start_response, e)
etag = self._calculate_etag(data)
self._filename_to_mtime_and_etag[full_path] = mtime, etag
headers = [('Content-length', str(len(data)))]
if user_headers.Get('Content-type') is None:
headers.append(('Content-type', self._get_mime_type(full_path)))
if user_headers.Get('ETag') is None:
headers.append(('ETag', '"%s"' % etag))
if user_headers.Get('Expires') is None:
headers.append(('Expires', 'Fri, 01 Jan 1990 00:00:00 GMT'))
if user_headers.Get('Cache-Control') is None:
headers.append(('Cache-Control', 'no-cache'))
for name, value in user_headers.iteritems():
# "name" will always be unicode due to the way that ValidatedDict works.
headers.append((str(name), value))
start_response('200 OK', headers)
if environ['REQUEST_METHOD'] == 'HEAD':
return []
else:
return [data]
@staticmethod
def _read_file(full_path):
with open(full_path, 'rb') as f:
return f.read()
@staticmethod
def _check_etag_match(etag_headers, etag, allow_weak_match):
"""Checks if an etag header matches a given etag.
Args:
etag_headers: A string representing an e-tag header value e.g.
'"xyzzy", "r2d2xxxx", W/"c3piozzzz"' or '*'.
etag: The etag to match the header to. If None then only the '*' header
with match.
allow_weak_match: If True then weak etags are allowed to match.
Returns:
True if there is a match, False otherwise.
"""
# From RFC-2616:
# entity-tag = [ weak ] opaque-tag
# weak = "W/"
# opaque-tag = quoted-string
# quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
# qdtext = <any TEXT except <">>
# quoted-pair = "\" CHAR
# TEXT = <any OCTET except CTLs, but including LWS>
# CHAR = <any US-ASCII character (octets 0 - 127)>
# This parsing is not actually correct since it assumes that commas cannot
# appear in etags. But the generated etags do not contain commas so this
# still works.
for etag_header in etag_headers.split(','):
if etag_header.startswith('W/'):
if allow_weak_match:
etag_header = etag_header[2:]
else:
continue
etag_header = etag_header.strip().strip('"')
if etag_header == '*' or etag_header == etag:
return True
return False
@staticmethod
def _is_relative_path_valid(path):
"""Check if the relative path for a file is valid.
To match prod, redirection logic only fires on paths that contain a . or ..
as an entry, but ignores redundant separators. Since Dev App Server simply
passes the path to open, redundant separators are ignored (i.e. path/to/file
and path//to///file both map to the same thing). Since prod uses logic
that treats redundant separators as significant, we need to handle them
specially.
A related problem is that if a redundant separator is placed as the file
relative path, it can be passed to a StaticHandler as an absolute path.
As os.path.join causes an absolute path to throw away previous components
that could allow an attacker to read any file on the file system (i.e.
if there a static directory handle for /static and an attacker asks for the
path '/static//etc/passwd', '/etc/passwd' is passed as the relative path and
calling os.path.join([root_dir, '/etc/passwd']) returns '/etc/passwd'.)
Args:
path: a path relative to a static handler base.
Returns:
bool indicating whether the path is valid or not.
"""
# Note: can't do something like path == os.path.normpath(path) as Windows
# would normalize separators to backslashes.
return not os.path.isabs(path) and '' not in path.split('/')
@staticmethod
def _not_found_404(environ, start_response):
status = httplib.NOT_FOUND
start_response('%d %s' % (status, httplib.responses[status]),
[('Content-Type', 'text/plain')])
return ['%s not found' % environ['PATH_INFO']]
class StaticFilesHandler(StaticContentHandler):
"""Servers content for the "static_files" handler.
For example:
handlers:
- url: /(.*)/(.*)
static_files: \1/\2
upload: (.*)/(.*)
"""
def __init__(self, root_path, url_map):
"""Initializer for StaticFilesHandler.
Args:
root_path: A string containing the full path of the directory containing
the application's app.yaml file.
url_map: An appinfo.URLMap instance containing the configuration for this
handler.
"""
try:
url_pattern = re.compile('%s$' % url_map.url)
except re.error, e:
raise errors.InvalidAppConfigError(
'invalid url %r in static_files handler: %s' % (url_map.url, e))
super(StaticFilesHandler, self).__init__(root_path,
url_map,
url_pattern)
def handle(self, match, environ, start_response):
"""Serves the file content matching the request.
Args:
match: The re.MatchObject containing the result of matching the URL
against this handler's URL pattern.
environ: An environ dict for the current request as defined in PEP-333.
start_response: A function with semantics defined in PEP-333.
Returns:
An iterable over strings containing the body of the HTTP response.
"""
relative_path = match.expand(self._url_map.static_files)
if not self._is_relative_path_valid(relative_path):
if self._url_map.require_matching_file:
return None
else:
return self._not_found_404(environ, start_response)
full_path = os.path.join(self._root_path, relative_path)
return self._handle_path(full_path, environ, start_response)
class StaticDirHandler(StaticContentHandler):
"""Servers content for the "static_files" handler.
For example:
handlers:
- url: /css
static_dir: stylesheets
"""
def __init__(self, root_path, url_map):
"""Initializer for StaticDirHandler.
Args:
root_path: A string containing the full path of the directory containing
the application's app.yaml file.
url_map: An appinfo.URLMap instance containing the configuration for this
handler.
"""
url = url_map.url
# Take a url pattern like "/css" and transform it into a match pattern like
# "/css/(?P<file>.*)$"
if url[-1] != '/':
url += '/'
try:
url_pattern = re.compile('%s(?P<file>.*)$' % url)
except re.error, e:
raise errors.InvalidAppConfigError(
'invalid url %r in static_dir handler: %s' % (url, e))
super(StaticDirHandler, self).__init__(root_path,
url_map,
url_pattern)
def handle(self, match, environ, start_response):
"""Serves the file content matching the request.
Args:
match: The re.MatchObject containing the result of matching the URL
against this handler's URL pattern.
environ: An environ dict for the current request as defined in PEP-333.
start_response: A function with semantics defined in PEP-333.
Returns:
An iterable over strings containing the body of the HTTP response.
"""
relative_path = match.group('file')
if not self._is_relative_path_valid(relative_path):
return self._not_found_404(environ, start_response)
full_path = os.path.join(self._root_path,
self._url_map.static_dir,
relative_path)
return self._handle_path(full_path, environ, start_response)
| ProfessionalIT/professionalit-webiste | sdk/google_appengine/google/appengine/tools/devappserver2/static_files_handler.py | Python | lgpl-3.0 | 13,838 |
/*
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.batik.anim.dom;
import org.apache.batik.dom.AbstractDocument;
import org.apache.batik.util.SVG12Constants;
import org.w3c.dom.Node;
/**
* This class implements a multiImage extension to SVG.
*
* The 'multiImage' element is similar to the 'image' element (supports
* all the same attributes and properties) except.
* <ol>
* <li>It has two addtional attributes: 'pixel-width' and
* 'pixel-height' which are the maximum width and height of the
* image referenced by the xlink:href attribute.</li>
* <li>It can contain a child element 'subImage' which has
* two attributes, pixel-width, pixel-height.
* It holds SVG content to be rendered.</li>
* <li>It can contain a child element 'subImageRef' which has only
* three attributes, pixel-width, pixel-height and xlink:href.
* The image displayed is the smallest image such that
* pixel-width and pixel-height are greater than or equal to the
* required image size for display.</li>
* </ol>
*
* @author <a href="mailto:thomas.deweese@kodak.com">Thomas DeWeese</a>
* @version $Id$ */
public class SVGOMMultiImageElement
extends SVGStylableElement {
/**
* Creates a new SVG MultiImageElement object.
*/
protected SVGOMMultiImageElement() {
}
/**
* Creates a new SVG MultiImageElement object.
* @param prefix The namespace prefix.
* @param owner The owner document.
*/
public SVGOMMultiImageElement(String prefix, AbstractDocument owner) {
super(prefix, owner);
}
/**
* <b>DOM</b>: Implements {@link org.w3c.dom.Node#getLocalName()}.
*/
public String getLocalName() {
return SVG12Constants.SVG_MULTI_IMAGE_TAG;
}
/**
* Returns a new uninitialized instance of this object's class.
*/
protected Node newNode() {
return new SVGOMMultiImageElement();
}
}
| git-moss/Push2Display | lib/batik-1.8/sources/org/apache/batik/anim/dom/SVGOMMultiImageElement.java | Java | lgpl-3.0 | 2,733 |
package com.ctrip.hermes.producer.pipeline;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Future;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException;
import org.unidal.lookup.ContainerHolder;
import org.unidal.lookup.annotation.Inject;
import org.unidal.lookup.annotation.Named;
import com.ctrip.hermes.core.meta.MetaService;
import com.ctrip.hermes.core.pipeline.PipelineSink;
import com.ctrip.hermes.core.result.SendResult;
@Named(type = ProducerPipelineSinkManager.class)
public class DefaultProducerPipelineSinkManager extends ContainerHolder implements Initializable, ProducerPipelineSinkManager {
@Inject
private MetaService m_meta;
private Map<String, PipelineSink<Future<SendResult>>> m_sinks = new HashMap<String, PipelineSink<Future<SendResult>>>();
@Override
public PipelineSink<Future<SendResult>> getSink(String topic) {
String type = m_meta.findEndpointTypeByTopic(topic);
if (m_sinks.containsKey(type)) {
return m_sinks.get(type);
} else {
throw new IllegalArgumentException(String.format("Unknown message sink for topic %s", topic));
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void initialize() throws InitializationException {
Map<String, PipelineSink> sinks = lookupMap(PipelineSink.class);
for (Entry<String, PipelineSink> entry : sinks.entrySet()) {
m_sinks.put(entry.getKey(), entry.getValue());
}
}
}
| lejingw/hermes | hermes-producer/src/main/java/com/ctrip/hermes/producer/pipeline/DefaultProducerPipelineSinkManager.java | Java | apache-2.0 | 1,607 |
# Natural Language Toolkit: Sun Tsu-Bot
#
# Copyright (C) 2001-2011 NLTK Project
# Author: Sam Huston 2007
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
from util import *
"""
Tsu bot responds to all queries with a Sun Tsu sayings
Quoted from Sun Tsu's The Art of War
Translated by LIONEL GILES, M.A. 1910
Hosted by the Gutenberg Project
http://www.gutenberg.org/
"""
pairs = (
(r'quit',
( "Good-bye.",
"Plan well",
"May victory be your future")),
(r'[^\?]*\?',
("Please consider whether you can answer your own question.",
"Ask me no questions!")),
(r'[0-9]+(.*)',
("It is the rule in war, if our forces are ten to the enemy's one, to surround him; if five to one, to attack him; if twice as numerous, to divide our army into two.",
"There are five essentials for victory")),
(r'[A-Ca-c](.*)',
("The art of war is of vital importance to the State.",
"All warfare is based on deception.",
"If your opponent is secure at all points, be prepared for him. If he is in superior strength, evade him.",
"If the campaign is protracted, the resources of the State will not be equal to the strain.",
"Attack him where he is unprepared, appear where you are not expected.",
"There is no instance of a country having benefited from prolonged warfare.")),
(r'[D-Fd-f](.*)',
("The skillful soldier does not raise a second levy, neither are his supply-wagons loaded more than twice.",
"Bring war material with you from home, but forage on the enemy.",
"In war, then, let your great object be victory, not lengthy campaigns.",
"To fight and conquer in all your battles is not supreme excellence; supreme excellence consists in breaking the enemy's resistance without fighting.")),
(r'[G-Ig-i](.*)',
("Heaven signifies night and day, cold and heat, times and seasons.",
"It is the rule in war, if our forces are ten to the enemy's one, to surround him; if five to one, to attack him; if twice as numerous, to divide our army into two.",
"The good fighters of old first put themselves beyond the possibility of defeat, and then waited for an opportunity of defeating the enemy.",
"One may know how to conquer without being able to do it.")),
(r'[J-Lj-l](.*)',
("There are three ways in which a ruler can bring misfortune upon his army.",
"By commanding the army to advance or to retreat, being ignorant of the fact that it cannot obey. This is called hobbling the army.",
"By attempting to govern an army in the same way as he administers a kingdom, being ignorant of the conditions which obtain in an army. This causes restlessness in the soldier's minds.",
"By employing the officers of his army without discrimination, through ignorance of the military principle of adaptation to circumstances. This shakes the confidence of the soldiers.",
"There are five essentials for victory",
"He will win who knows when to fight and when not to fight.",
"He will win who knows how to handle both superior and inferior forces.",
"He will win whose army is animated by the same spirit throughout all its ranks.",
"He will win who, prepared himself, waits to take the enemy unprepared.",
"He will win who has military capacity and is not interfered with by the sovereign.")),
(r'[M-Om-o](.*)',
("If you know the enemy and know yourself, you need not fear the result of a hundred battles.",
"If you know yourself but not the enemy, for every victory gained you will also suffer a defeat.",
"If you know neither the enemy nor yourself, you will succumb in every battle.",
"The control of a large force is the same principle as the control of a few men: it is merely a question of dividing up their numbers.")),
(r'[P-Rp-r](.*)',
("Security against defeat implies defensive tactics; ability to defeat the enemy means taking the offensive.",
"Standing on the defensive indicates insufficient strength; attacking, a superabundance of strength.",
"He wins his battles by making no mistakes. Making no mistakes is what establishes the certainty of victory, for it means conquering an enemy that is already defeated.",
"A victorious army opposed to a routed one, is as a pound's weight placed in the scale against a single grain.",
"The onrush of a conquering force is like the bursting of pent-up waters into a chasm a thousand fathoms deep.")),
(r'[S-Us-u](.*)',
("What the ancients called a clever fighter is one who not only wins, but excels in winning with ease.",
"Hence his victories bring him neither reputation for wisdom nor credit for courage.",
"Hence the skillful fighter puts himself into a position which makes defeat impossible, and does not miss the moment for defeating the enemy.",
"In war the victorious strategist only seeks battle after the victory has been won, whereas he who is destined to defeat first fights and afterwards looks for victory.",
"There are not more than five musical notes, yet the combinations of these five give rise to more melodies than can ever be heard.",
"Appear at points which the enemy must hasten to defend; march swiftly to places where you are not expected.")),
(r'[V-Zv-z](.*)',
("It is a matter of life and death, a road either to safety or to ruin.",
"Hold out baits to entice the enemy. Feign disorder, and crush him.",
"All men can see the tactics whereby I conquer, but what none can see is the strategy out of which victory is evolved.",
"Do not repeat the tactics which have gained you one victory, but let your methods be regulated by the infinite variety of circumstances.",
"So in war, the way is to avoid what is strong and to strike at what is weak.",
"Just as water retains no constant shape, so in warfare there are no constant conditions.")),
(r'(.*)',
( "Your statement insults me.",
""))
)
suntsu_chatbot = Chat(pairs, reflections)
def suntsu_chat():
print "Talk to the program by typing in plain English, using normal upper-"
print 'and lower-case letters and punctuation. Enter "quit" when done.'
print '='*72
print "You seek enlightenment?"
suntsu_chatbot.converse()
def demo():
suntsu_chat()
if __name__ == "__main__":
demo()
| tadgh/ArgoRevisit | third_party/nltk/chat/suntsu.py | Python | apache-2.0 | 6,223 |
<?php
/**
* This file is part of Linfo (c) 2014 Joseph Gillotti.
*
* Linfo 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.
*
* Linfo 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 Linfo. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Linfo;
class Common
{
protected static $settings = array(),
$lang = array();
// Used for unit tests
public static $path_prefix = false;
public static function config(Linfo $linfo)
{
self::$settings = $linfo->getSettings();
self::$lang = $linfo->getLang();
}
public static function unconfig()
{
self::$settings = array();
self::$lang = array();
}
// Certain files, specifcally the pci/usb ids files, vary in location from
// linux distro to linux distro. This function, when passed an array of
// possible file location, picks the first it finds and returns it. When
// none are found, it returns false
public static function locateActualPath($paths)
{
foreach ((array) $paths as $path) {
if (is_file($path)) {
return $path;
}
}
return false;
}
// Append a string to the end of each element in a 2d array
public static function arrayAppendString($array, $string = '', $format = '%1s%2s')
{
// Get to it
foreach ($array as $k => $v) {
$array[$k] = is_string($v) ? sprintf($format, $v, $string) : $v;
}
// Give
return $array;
}
// Get a file who's contents should just be an int. Returns zero on failure.
public static function getIntFromFile($file)
{
return self::getContents($file, 0);
}
// Convert bytes to stuff like KB MB GB TB etc
public static function byteConvert($size, $precision = 2)
{
// Sanity check
if (!is_numeric($size)) {
return '?';
}
// Get the notation
$notation = self::$settings['byte_notation'] == 1000 ? 1000 : 1024;
// Fixes large disk size overflow issue
// Found at http://www.php.net/manual/en/function.disk-free-space.php#81207
$types = array('B', 'KB', 'MB', 'GB', 'TB');
$types_i = array('B', 'KiB', 'MiB', 'GiB', 'TiB');
for ($i = 0; $size >= $notation && $i < (count($types) - 1); $size /= $notation, $i++);
return(round($size, $precision).' '.($notation == 1000 ? $types[$i] : $types_i[$i]));
}
// Like above, but for seconds
public static function secondsConvert($uptime)
{
// Method here heavily based on freebsd's uptime source
$uptime += $uptime > 60 ? 30 : 0;
$years = floor($uptime / 31556926);
$uptime %= 31556926;
$days = floor($uptime / 86400);
$uptime %= 86400;
$hours = floor($uptime / 3600);
$uptime %= 3600;
$minutes = floor($uptime / 60);
$seconds = floor($uptime % 60);
// Send out formatted string
$return = array();
if ($years > 0) {
$return[] = $years.' '.($years > 1 ? self::$lang['years'] : substr(self::$lang['years'], 0, strlen(self::$lang['years']) - 1));
}
if ($days > 0) {
$return[] = $days.' '.self::$lang['days'];
}
if ($hours > 0) {
$return[] = $hours.' '.self::$lang['hours'];
}
if ($minutes > 0) {
$return[] = $minutes.' '.self::$lang['minutes'];
}
if ($seconds > 0) {
$return[] = $seconds.(date('m/d') == '06/03' ? ' sex' : ' '.self::$lang['seconds']);
}
return implode(', ', $return);
}
// Get a file's contents, or default to second param
public static function getContents($file, $default = '')
{
if (is_string(self::$path_prefix)) {
$file = self::$path_prefix.$file;
}
return !is_file($file) || !is_readable($file) || !($contents = @file_get_contents($file)) ? $default : trim($contents);
}
// Like above, but in lines instead of a big string
public static function getLines($file)
{
return !is_file($file) || !is_readable($file) || !($lines = @file($file, FILE_SKIP_EMPTY_LINES)) ? array() : $lines;
}
// Make a string safe for being in an xml tag name
public static function xmlStringSanitize($string)
{
return strtolower(preg_replace('/([^a-zA-Z]+)/', '_', $string));
}
// Get a variable from a file. Include it in this function to avoid
// clobbering the main namespace
public static function getVarFromFile($file, $variable)
{
// Let's not waste our time, now
if (!is_file($file)) {
return false;
}
require $file;
// Double dollar sign means treat variable contents
// as the name of a variable.
if (isset($$variable)) {
return $$variable;
}
return false;
}
// Prevent silly conditionals like if (in_array() || in_array() || in_array())
// Poor man's python's any() on a list comprehension kinda
public static function anyInArray($needles, $haystack)
{
if (!is_array($needles) || !is_array($haystack)) {
return false;
}
return count(array_intersect($needles, $haystack)) > 0;
}
}
| kenbrill/sugarcli-plus | vendor/linfo/linfo/src/Linfo/Common.php | PHP | apache-2.0 | 5,806 |
/*
* Copyright 2015 the original author or authors.
* @https://github.com/scouter-project/scouter
*
* 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 scouter.client.stack.data;
import scouter.client.stack.utils.NumberUtils;
public class StackAnalyzedValue {
private String m_value = null;
private int m_count = 0;
private int m_intPct = 0;
private int m_extPct = 0;
public StackAnalyzedValue(){
}
public StackAnalyzedValue(String value, int count, int intPct, int extPct){
m_value = value;
m_count = count;
m_intPct = intPct;
m_extPct = extPct;
}
public String getValue(){
return m_value;
}
public int getCount(){
return m_count;
}
public int getIntPct(){
return m_intPct;
}
public int getExtPct(){
return m_extPct;
}
public void setValue(String value){
m_value = value;
}
public void setCount(int value){
m_count = value;
}
public void setIntPct(int value){
m_intPct = value;
}
public void setExtPct(int value){
m_extPct = value;
}
public void addCount(){
m_count++;
}
public String [] toTableInfo(){
String [] info = new String[4];
info[0] = new StringBuilder().append(m_count).toString();
info[1] = new StringBuilder().append(NumberUtils.intToPercent(m_intPct)).append('%').toString();
info[2] = new StringBuilder().append(NumberUtils.intToPercent(m_extPct)).append('%').toString();
info[3] = m_value;
return info;
}
}
| yuyupapa/OpenSource | scouter.client/src/scouter/client/stack/data/StackAnalyzedValue.java | Java | apache-2.0 | 1,957 |
/*
* 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.vxquery.runtime.functions.cast;
import org.apache.vxquery.datamodel.values.ValueTag;
public class CastToPositiveIntegerOperation extends CastToIntegerOperation {
public CastToPositiveIntegerOperation() {
negativeAllowed = false;
returnTag = ValueTag.XS_POSITIVE_INTEGER_TAG;
}
} | innovimax/vxquery | vxquery-core/src/main/java/org/apache/vxquery/runtime/functions/cast/CastToPositiveIntegerOperation.java | Java | apache-2.0 | 1,127 |
import { MdDrawer, MdDrawerContainer } from './drawer';
export declare class MdSidenav extends MdDrawer {
}
export declare class MdSidenavContainer extends MdDrawerContainer {
_drawers: any;
}
| tongpa/pypollmanage | pypollmanage/public/javascript/node_modules/@angular_ols/material/typings/sidenav/sidenav.d.ts | TypeScript | apache-2.0 | 197 |
/**
* 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.metrics;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Slf4jReporter;
import org.apache.camel.Endpoint;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.impl.UriEndpointComponent;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.Registry;
import org.apache.camel.util.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Represents the component that manages metrics endpoints.
*/
public class MetricsComponent extends UriEndpointComponent {
public static final String METRIC_REGISTRY_NAME = "metricRegistry";
public static final MetricsType DEFAULT_METRICS_TYPE = MetricsType.METER;
public static final long DEFAULT_REPORTING_INTERVAL_SECONDS = 60L;
private static final Logger LOG = LoggerFactory.getLogger(MetricsComponent.class);
@Metadata(label = "advanced")
private MetricRegistry metricRegistry;
public MetricsComponent() {
super(MetricsEndpoint.class);
}
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
if (metricRegistry == null) {
Registry camelRegistry = getCamelContext().getRegistry();
metricRegistry = getOrCreateMetricRegistry(camelRegistry, METRIC_REGISTRY_NAME);
}
String metricsName = getMetricsName(remaining);
MetricsType metricsType = getMetricsType(remaining);
LOG.debug("Metrics type: {}; name: {}", metricsType, metricsName);
Endpoint endpoint = new MetricsEndpoint(uri, this, metricRegistry, metricsType, metricsName);
setProperties(endpoint, parameters);
return endpoint;
}
String getMetricsName(String remaining) {
String name = StringHelper.after(remaining, ":");
return name == null ? remaining : name;
}
MetricsType getMetricsType(String remaining) {
String name = StringHelper.before(remaining, ":");
MetricsType type;
if (name == null) {
type = DEFAULT_METRICS_TYPE;
} else {
type = MetricsType.getByName(name);
}
if (type == null) {
throw new RuntimeCamelException("Unknown metrics type \"" + name + "\"");
}
return type;
}
MetricRegistry getOrCreateMetricRegistry(Registry camelRegistry, String registryName) {
LOG.debug("Looking up MetricRegistry from Camel Registry for name \"{}\"", registryName);
MetricRegistry result = getMetricRegistryFromCamelRegistry(camelRegistry, registryName);
if (result == null) {
LOG.debug("MetricRegistry not found from Camel Registry for name \"{}\"", registryName);
LOG.info("Creating new default MetricRegistry");
result = createMetricRegistry();
}
return result;
}
MetricRegistry getMetricRegistryFromCamelRegistry(Registry camelRegistry, String registryName) {
MetricRegistry registry = camelRegistry.lookupByNameAndType(registryName, MetricRegistry.class);
if (registry != null) {
return registry;
} else {
Set<MetricRegistry> registries = camelRegistry.findByType(MetricRegistry.class);
if (registries.size() == 1) {
return registries.iterator().next();
}
}
return null;
}
MetricRegistry createMetricRegistry() {
MetricRegistry registry = new MetricRegistry();
final Slf4jReporter reporter = Slf4jReporter.forRegistry(registry)
.outputTo(LOG)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.withLoggingLevel(Slf4jReporter.LoggingLevel.DEBUG)
.build();
reporter.start(DEFAULT_REPORTING_INTERVAL_SECONDS, TimeUnit.SECONDS);
return registry;
}
public MetricRegistry getMetricRegistry() {
return metricRegistry;
}
/**
* To use a custom configured MetricRegistry.
*/
public void setMetricRegistry(MetricRegistry metricRegistry) {
this.metricRegistry = metricRegistry;
}
}
| onders86/camel | components/camel-metrics/src/main/java/org/apache/camel/component/metrics/MetricsComponent.java | Java | apache-2.0 | 5,110 |
// JapaneseVillagePrefabs.cpp
// Defines the prefabs in the group JapaneseVillage
// NOTE: This file has been generated automatically by GalExport!
// Any manual changes will be overwritten by the next automatic export!
#include "Globals.h"
#include "JapaneseVillagePrefabs.h"
const cPrefab::sDef g_JapaneseVillagePrefabs[] =
{
////////////////////////////////////////////////////////////////////////////////
// Arch:
// The data has been exported from the gallery Plains, area index 144, ID 488, created by Aloe_vera
{
// Size:
11, 7, 5, // SizeX = 11, SizeY = 7, SizeZ = 5
// Hitbox (relative to bounding box):
-1, 0, 0, // MinX, MinY, MinZ
11, 6, 4, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 2: 0\n" /* grass */
"b: 13: 0\n" /* gravel */
"c:113: 0\n" /* netherbrickfence */
"d: 50: 5\n" /* torch */
"e: 44: 8\n" /* step */
"f: 44: 0\n" /* step */
"g: 43: 0\n" /* doubleslab */
"m: 19: 0\n" /* sponge */,
// Block data:
// Level 0
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "aaaabbbaaaa"
/* 1 */ "aaaabbbaaaa"
/* 2 */ "aaaabbbaaaa"
/* 3 */ "aaaabbbaaaa"
/* 4 */ "aaaabbbaaaa"
// Level 1
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..c.....c.."
/* 1 */ "..c.....c.."
/* 2 */ "..c.....c.."
/* 3 */ "..c.....c.."
/* 4 */ "..c.....c.."
// Level 2
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..c.....c.."
/* 1 */ "..........."
/* 2 */ "..c.....c.."
/* 3 */ "..........."
/* 4 */ "..c.....c.."
// Level 3
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..d.....d.."
/* 1 */ "..........."
/* 2 */ "..c.....c.."
/* 3 */ "..........."
/* 4 */ "..d.....d.."
// Level 4
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "...eeeee..."
/* 1 */ "..........."
/* 2 */ "..c.....c.."
/* 3 */ "..........."
/* 4 */ "...eeeee..."
// Level 5
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..f.....f.."
/* 1 */ ".egfffffge."
/* 2 */ ".egeeeeege."
/* 3 */ ".egfffffge."
/* 4 */ "..f.....f.."
// Level 6
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..........."
/* 2 */ "gf.......fg"
/* 3 */ "..........."
/* 4 */ "...........",
// Connectors:
"2: 5, 1, 4: 3\n" /* Type 2, direction Z+ */
"2: 5, 1, 0: 2\n" /* Type 2, direction Z- */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // Arch
////////////////////////////////////////////////////////////////////////////////
// Farm:
// The data has been exported from the gallery Plains, area index 166, ID 554, created by Aloe_vera
{
// Size:
11, 8, 13, // SizeX = 11, SizeY = 8, SizeZ = 13
// Hitbox (relative to bounding box):
0, 0, 0, // MinX, MinY, MinZ
10, 7, 12, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 3: 0\n" /* dirt */
"b: 60: 7\n" /* tilleddirt */
"c: 8: 0\n" /* water */
"d: 43: 0\n" /* doubleslab */
"e: 44: 0\n" /* step */
"f: 59: 7\n" /* crops */
"g: 83: 0\n" /* reedblock */
"h:113: 0\n" /* netherbrickfence */
"i: 50: 5\n" /* torch */
"m: 19: 0\n" /* sponge */,
// Block data:
// Level 0
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "mmmmmmmmmmm"
/* 1 */ "maaaaaaaaam"
/* 2 */ "maaaaaaaaam"
/* 3 */ "maaaaaaaaam"
/* 4 */ "maaaaaaaaam"
/* 5 */ "maaaaaaaaam"
/* 6 */ "maaaaaaaaam"
/* 7 */ "maaaaaaaaam"
/* 8 */ "maaaaaaaaam"
/* 9 */ "maaaaaaaaam"
/* 10 */ "maaaaaaaaam"
/* 11 */ "maaaaaaaaam"
/* 12 */ "mmmmmmmmmmm"
// Level 1
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "mmmmmmmmmmm"
/* 1 */ "maaaaaaaaam"
/* 2 */ "mabbbbbbbam"
/* 3 */ "mabbbbbbbam"
/* 4 */ "mabbbbbbbam"
/* 5 */ "mabbbbbbbam"
/* 6 */ "mabcccccaam"
/* 7 */ "mabbbbbbbam"
/* 8 */ "mabbbbbbbam"
/* 9 */ "mabbbbbbbam"
/* 10 */ "mabbbbbbbam"
/* 11 */ "maaaaaaaaam"
/* 12 */ "mmmmmmmmmmm"
// Level 2
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ ".deeeeeeed."
/* 2 */ ".efffffffe."
/* 3 */ ".efffffffe."
/* 4 */ ".efffffffe."
/* 5 */ ".efgggggfe."
/* 6 */ ".eg.....ge."
/* 7 */ ".efgggggfe."
/* 8 */ ".efffffffe."
/* 9 */ ".efffffffe."
/* 10 */ ".efffffffe."
/* 11 */ ".deeeeeeed."
/* 12 */ "..........."
// Level 3
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ ".h.......h."
/* 2 */ "..........."
/* 3 */ "..........."
/* 4 */ "..........."
/* 5 */ "...ggggg..."
/* 6 */ "..g.....g.."
/* 7 */ "...ggggg..."
/* 8 */ "..........."
/* 9 */ "..........."
/* 10 */ "..........."
/* 11 */ ".h.......h."
/* 12 */ "..........."
// Level 4
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ ".h.......h."
/* 2 */ "..........."
/* 3 */ "..........."
/* 4 */ "..........."
/* 5 */ "...ggggg..."
/* 6 */ "..g.....g.."
/* 7 */ "...ggggg..."
/* 8 */ "..........."
/* 9 */ "..........."
/* 10 */ "..........."
/* 11 */ ".h.......h."
/* 12 */ "..........."
// Level 5
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ ".h.......h."
/* 2 */ "..........."
/* 3 */ "..........."
/* 4 */ "..........."
/* 5 */ "..........."
/* 6 */ "..........."
/* 7 */ "..........."
/* 8 */ "..........."
/* 9 */ "..........."
/* 10 */ "..........."
/* 11 */ ".h.......h."
/* 12 */ "..........."
// Level 6
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ ".h.......h."
/* 1 */ "hhh.....hhh"
/* 2 */ ".h.......h."
/* 3 */ "..........."
/* 4 */ "..........."
/* 5 */ "..........."
/* 6 */ "..........."
/* 7 */ "..........."
/* 8 */ "..........."
/* 9 */ "..........."
/* 10 */ ".h.......h."
/* 11 */ "hhh.....hhh"
/* 12 */ ".h.......h."
// Level 7
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ ".i.......i."
/* 1 */ "i.i.....i.i"
/* 2 */ ".i.......i."
/* 3 */ "..........."
/* 4 */ "..........."
/* 5 */ "..........."
/* 6 */ "..........."
/* 7 */ "..........."
/* 8 */ "..........."
/* 9 */ "..........."
/* 10 */ ".i.......i."
/* 11 */ "i.i.....i.i"
/* 12 */ ".i.......i.",
// Connectors:
"-1: 10, 2, 6: 5\n" /* Type -1, direction X+ */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // Farm
////////////////////////////////////////////////////////////////////////////////
// Forge:
// The data has been exported from the gallery Plains, area index 79, ID 145, created by Aloe_vera
{
// Size:
16, 11, 14, // SizeX = 16, SizeY = 11, SizeZ = 14
// Hitbox (relative to bounding box):
0, 0, -1, // MinX, MinY, MinZ
16, 10, 14, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 4: 0\n" /* cobblestone */
"b: 17: 1\n" /* tree */
"c: 67: 0\n" /* stairs */
"d: 5: 2\n" /* wood */
"e: 67: 2\n" /* stairs */
"f:113: 0\n" /* netherbrickfence */
"g:118: 2\n" /* cauldronblock */
"h: 67: 6\n" /* stairs */
"i: 67: 4\n" /* stairs */
"j: 87: 0\n" /* netherstone */
"k: 67: 7\n" /* stairs */
"l: 54: 5\n" /* chest */
"m: 19: 0\n" /* sponge */
"n: 61: 2\n" /* furnace */
"o:101: 0\n" /* ironbars */
"p: 51: 0\n" /* fire */
"q: 50: 4\n" /* torch */
"r: 50: 2\n" /* torch */
"s: 35: 0\n" /* wool */
"t: 67: 3\n" /* stairs */
"u: 50: 3\n" /* torch */
"v: 44: 8\n" /* step */
"w: 43: 0\n" /* doubleslab */
"x: 44: 0\n" /* step */
"y: 17: 5\n" /* tree */
"z: 17: 9\n" /* tree */,
// Block data:
// Level 0
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "mmmmmmmmmmmmmmmm"
/* 1 */ "mmmmmmmmmmmmmmmm"
/* 2 */ "mmaaaaaaaaaaaamm"
/* 3 */ "mmaaaaaaaaaaaamm"
/* 4 */ "mmaaaaaaaaaaaamm"
/* 5 */ "mmaaaaaaaaaaaamm"
/* 6 */ "mmaaaaaaaaaaaamm"
/* 7 */ "mmaaaaaaaaaaaamm"
/* 8 */ "mmaaaaaaaaaaaamm"
/* 9 */ "mmaaaaaaaaaaaamm"
/* 10 */ "mmaaaaaaaaaaaamm"
/* 11 */ "mmaaaaaaaaaaaamm"
/* 12 */ "mmmmmmmmmmmmmmmm"
/* 13 */ "mmmmmmmmmmmmmmmm"
// Level 1
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "................"
/* 2 */ ".....bbbbbbbbb.."
/* 3 */ ".....cdddddddb.."
/* 4 */ ".....cddaaaadb.."
/* 5 */ "..beeedaaaaadb.."
/* 6 */ "..bddddaaaaadb.."
/* 7 */ "..bddddaaaaadb.."
/* 8 */ "..bddddaaaaadb.."
/* 9 */ "..bddddaaaaadb.."
/* 10 */ "..bddddddddddb.."
/* 11 */ "..bbbbbbbbbbbb.."
/* 12 */ "................"
/* 13 */ "................"
// Level 2
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "................"
/* 2 */ ".....bfffbfffb.."
/* 3 */ ".............a.."
/* 4 */ ".............a.."
/* 5 */ "..b.....ghh..a.."
/* 6 */ "..f.....haa..b.."
/* 7 */ "..f.....ija..b.."
/* 8 */ "..f.....kaa..a.."
/* 9 */ "..f..........a.."
/* 10 */ "..fl.........a.."
/* 11 */ "..bffffbbffffb.."
/* 12 */ "................"
/* 13 */ "................"
// Level 3
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "................"
/* 2 */ ".....bfffbfffb.."
/* 3 */ ".............a.."
/* 4 */ ".............a.."
/* 5 */ "..b......nn..a.."
/* 6 */ "..f.....oaa..b.."
/* 7 */ "..f.....opa..b.."
/* 8 */ "..f.....oaa..a.."
/* 9 */ "..f..........a.."
/* 10 */ "..f..........a.."
/* 11 */ "..bffffbbffffb.."
/* 12 */ "................"
/* 13 */ "................"
// Level 4
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ ".........q...q.."
/* 2 */ "....rbsssbsssb.."
/* 3 */ ".............a.."
/* 4 */ "..q..........a.."
/* 5 */ "..b......ce..a.."
/* 6 */ "..s......ea..b.."
/* 7 */ "..s......aa..b.."
/* 8 */ "..s......ta..a.."
/* 9 */ "..s..........a.."
/* 10 */ "..s..........a.."
/* 11 */ ".rbssssbbssssb.."
/* 12 */ "..u....uu....u.."
/* 13 */ "................"
// Level 5
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ ".vwxxxxxxxxxxwv."
/* 1 */ "vvvvvvvvvvvvvvvv"
/* 2 */ "wvbyybyyybbyybvw"
/* 3 */ "xvz..........zvx"
/* 4 */ "xvz..........zvx"
/* 5 */ "xvb..........zvx"
/* 6 */ "xvz.......a..bvx"
/* 7 */ "xvz......ca..bvx"
/* 8 */ "xvz.......a..zvx"
/* 9 */ "xvz..........zvx"
/* 10 */ "xvz..........zvx"
/* 11 */ "wvbyyyyyyyyyybvw"
/* 12 */ "vvvvvvvvvvvvvvvv"
/* 13 */ ".vwxxxxxxxxxxwv."
// Level 6
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "wx............xw"
/* 1 */ "x..............x"
/* 2 */ "..xxxxxxxxxxxx.."
/* 3 */ "..xwwwwwwwwwwx.."
/* 4 */ "..xwvvvvvvvvvx.."
/* 5 */ "..xwv.......vx.."
/* 6 */ "..xwv.....a.vx.."
/* 7 */ "..xwv.....a.vx.."
/* 8 */ "..xwv.....a.vx.."
/* 9 */ "..xwvvvvvvvvvx.."
/* 10 */ "..xwwwwwwwwwwx.."
/* 11 */ "..xxxxxxxxxxxx.."
/* 12 */ "x..............x"
/* 13 */ "wx............xw"
// Level 7
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "................"
/* 2 */ "................"
/* 3 */ "................"
/* 4 */ "....xxxxxxxx...."
/* 5 */ "....xxxxxxxx...."
/* 6 */ "....xwwwwwax...."
/* 7 */ "....xwvvvvax...."
/* 8 */ "....xwwwwwax...."
/* 9 */ "....xxxxxxxx...."
/* 10 */ "................"
/* 11 */ "................"
/* 12 */ "................"
/* 13 */ "................"
// Level 8
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "................"
/* 2 */ "................"
/* 3 */ "................"
/* 4 */ "................"
/* 5 */ "................"
/* 6 */ "..........a....."
/* 7 */ ".......xx.a....."
/* 8 */ "..........a....."
/* 9 */ "................"
/* 10 */ "................"
/* 11 */ "................"
/* 12 */ "................"
/* 13 */ "................"
// Level 9
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "................"
/* 2 */ "................"
/* 3 */ "................"
/* 4 */ "................"
/* 5 */ "................"
/* 6 */ "..........a....."
/* 7 */ "..........a....."
/* 8 */ "..........a....."
/* 9 */ "................"
/* 10 */ "................"
/* 11 */ "................"
/* 12 */ "................"
/* 13 */ "................"
// Level 10
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "................"
/* 2 */ "................"
/* 3 */ "................"
/* 4 */ "................"
/* 5 */ "................"
/* 6 */ "..........a....."
/* 7 */ "..........a....."
/* 8 */ "..........a....."
/* 9 */ "................"
/* 10 */ "................"
/* 11 */ "................"
/* 12 */ "................"
/* 13 */ "................",
// Connectors:
"-1: 0, 1, 3: 4\n" /* Type -1, direction X- */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // Forge
////////////////////////////////////////////////////////////////////////////////
// Garden2:
// The data has been exported from the gallery Plains, area index 147, ID 491, created by Aloe_vera
{
// Size:
16, 5, 16, // SizeX = 16, SizeY = 5, SizeZ = 16
// Hitbox (relative to bounding box):
0, 0, 0, // MinX, MinY, MinZ
15, 4, 15, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 3: 0\n" /* dirt */
"b: 8: 0\n" /* water */
"c: 2: 0\n" /* grass */
"d: 17: 1\n" /* tree */
"e: 13: 0\n" /* gravel */
"f: 31: 2\n" /* tallgrass */
"g: 18: 5\n" /* leaves */
"h: 38: 7\n" /* rose */
"i: 17: 9\n" /* tree */
"m: 19: 0\n" /* sponge */,
// Block data:
// Level 0
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "aaaaaaaaaaaaaaaa"
/* 1 */ "aaaaaaaaaaaaaaaa"
/* 2 */ "aaaaaaaaaaaaaaaa"
/* 3 */ "aaaaaaaaaaaaaaaa"
/* 4 */ "aaaaaaaaaaaaaaaa"
/* 5 */ "aaaaaaaaaaaaaaaa"
/* 6 */ "aaaaaaaaaaaaaaaa"
/* 7 */ "aaaaaaaaaaaaaaaa"
/* 8 */ "aaaaaaaaaaaaaaaa"
/* 9 */ "aaaaaaaaaaaaaaaa"
/* 10 */ "aaaaaaaaaaaaaaaa"
/* 11 */ "aaaaaaaaaaaaaaaa"
/* 12 */ "aaaaaaaaaaaaaaaa"
/* 13 */ "aaaaaaaaaaaaaaaa"
/* 14 */ "aaaaaaaaaaaaaaaa"
/* 15 */ "aaaaaaaaaaaaaaaa"
// Level 1
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "aaaaaaaaaaaaaaaa"
/* 1 */ "aaaaaaaaaaaaaaaa"
/* 2 */ "aaaaaaaaaaaaaaaa"
/* 3 */ "aaaaaaaaaaaaaaaa"
/* 4 */ "aaaaaaaaaaaaaaaa"
/* 5 */ "aaaaaaaaaaaaaaaa"
/* 6 */ "aaaabbaaaaaaaaaa"
/* 7 */ "aaabbbaaaaaaaaaa"
/* 8 */ "aaabbaaaaaaaaaaa"
/* 9 */ "aaaabaaaaaaaaaaa"
/* 10 */ "aaaaaaaaaaaaaaaa"
/* 11 */ "aaaaaaaaaaaaaaaa"
/* 12 */ "aaaaaaaaaaaaaaaa"
/* 13 */ "aaaaaaaaaaaaaaaa"
/* 14 */ "aaaaaaaaaaaaaaaa"
/* 15 */ "aaaaaaaaaaaaaaaa"
// Level 2
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "cccccccccccccccc"
/* 1 */ "ccdccccccccdcccc"
/* 2 */ "cccccceecccccdcc"
/* 3 */ "ccccccceeccccccc"
/* 4 */ "cccccccceccccccc"
/* 5 */ "cccbbbbceccccccc"
/* 6 */ "cccbbbbceecccccc"
/* 7 */ "ccbbbbbcceeeeccc"
/* 8 */ "ccbbbbbccccceecc"
/* 9 */ "ccbbbbcccccccecc"
/* 10 */ "ccccbcccccccceec"
/* 11 */ "ccccccccccccccec"
/* 12 */ "ccccccccaaacccec"
/* 13 */ "cccccccccaccccec"
/* 14 */ "ccccccccccccceec"
/* 15 */ "cccccccccccceecc"
// Level 3
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "......f...gg.g.."
/* 1 */ "..gg.....gggggg."
/* 2 */ "ffgg......ghgggg"
/* 3 */ ".............gg."
/* 4 */ "...........f...."
/* 5 */ "...........h.ff."
/* 6 */ ".............fh."
/* 7 */ "...............f"
/* 8 */ "................"
/* 9 */ ".......ff.f....."
/* 10 */ ".f.....ffggf...."
/* 11 */ ".......gggg.f..."
/* 12 */ ".f......iddg...."
/* 13 */ ".....f..gdgg...."
/* 14 */ "....ff...gg....."
/* 15 */ "................"
// Level 4
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "...........g.g.."
/* 2 */ ".............gg."
/* 3 */ "................"
/* 4 */ "................"
/* 5 */ "................"
/* 6 */ "................"
/* 7 */ "................"
/* 8 */ "................"
/* 9 */ "................"
/* 10 */ ".........g......"
/* 11 */ "........ggg....."
/* 12 */ "........ggg....."
/* 13 */ ".........g......"
/* 14 */ "................"
/* 15 */ "................",
// Connectors:
"-1: 12, 3, 15: 3\n" /* Type -1, direction Z+ */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // Garden2
////////////////////////////////////////////////////////////////////////////////
// HouseMid:
// The data has been exported from the gallery Plains, area index 62, ID 119, created by Aloe_vera
{
// Size:
10, 9, 9, // SizeX = 10, SizeY = 9, SizeZ = 9
// Hitbox (relative to bounding box):
0, 0, -1, // MinX, MinY, MinZ
10, 8, 9, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 5: 2\n" /* wood */
"b:135: 2\n" /* 135 */
"c:135: 0\n" /* 135 */
"d: 17: 9\n" /* tree */
"e:135: 3\n" /* 135 */
"f: 85: 0\n" /* fence */
"g: 17: 1\n" /* tree */
"h:171: 0\n" /* carpet */
"i: 50: 5\n" /* torch */
"j: 35: 0\n" /* wool */
"k: 17: 5\n" /* tree */
"l:124: 0\n" /* redstonelampon */
"m: 19: 0\n" /* sponge */
"n: 69: 9\n" /* lever */
"o: 44: 8\n" /* step */
"p: 43: 0\n" /* doubleslab */
"q: 44: 0\n" /* step */,
// Block data:
// Level 0
/* z\x* */
/* * 0123456789 */
/* 0 */ "maaaaaaaaa"
/* 1 */ "maaaaaaaaa"
/* 2 */ "aaaaaaaaaa"
/* 3 */ "aaaaaaaaaa"
/* 4 */ "aaaaaaaaaa"
/* 5 */ "aaaaaaaaaa"
/* 6 */ "aaaaaaaaaa"
/* 7 */ "maaaaaaaaa"
/* 8 */ "maaaaaaaaa"
// Level 1
/* z\x* */
/* * 0123456789 */
/* 0 */ ".aaaaaaaaa"
/* 1 */ ".aaaaaaaaa"
/* 2 */ "baaaaaaaaa"
/* 3 */ "caaaaaaaaa"
/* 4 */ "caadaaaaaa"
/* 5 */ "caaaaaaaaa"
/* 6 */ "eaaaaaaaaa"
/* 7 */ ".aaaaaaaaa"
/* 8 */ ".aaaaaaaaa"
// Level 2
/* z\x* */
/* * 0123456789 */
/* 0 */ ".fffffffff"
/* 1 */ ".f.......f"
/* 2 */ ".f.ggggg.f"
/* 3 */ "...ghhhg.f"
/* 4 */ "....hhhg.f"
/* 5 */ "...ghhhg.f"
/* 6 */ ".f.ggggg.f"
/* 7 */ ".f.......f"
/* 8 */ ".fffffffff"
// Level 3
/* z\x* */
/* * 0123456789 */
/* 0 */ ".....i...i"
/* 1 */ ".........."
/* 2 */ ".i.jjgjj.."
/* 3 */ "...g...j.."
/* 4 */ ".......g.i"
/* 5 */ "...g...j.."
/* 6 */ ".i.jjgjj.."
/* 7 */ ".........."
/* 8 */ ".....i...i"
// Level 4
/* z\x* */
/* * 0123456789 */
/* 0 */ ".........."
/* 1 */ ".........."
/* 2 */ "...jjgjj.."
/* 3 */ "...g...j.."
/* 4 */ "...j...g.."
/* 5 */ "...g...j.."
/* 6 */ "...jjgjj.."
/* 7 */ ".........."
/* 8 */ ".........."
// Level 5
/* z\x* */
/* * 0123456789 */
/* 0 */ ".........."
/* 1 */ "...f...f.."
/* 2 */ "..fgkgkgf."
/* 3 */ "..fd...d.."
/* 4 */ "...d.lng.."
/* 5 */ "..fd...d.."
/* 6 */ "..fgkgkgf."
/* 7 */ "...f...f.."
/* 8 */ ".........."
// Level 6
/* z\x* */
/* * 0123456789 */
/* 0 */ "...ooooo.."
/* 1 */ "..opppppo."
/* 2 */ ".opgjjjgpo"
/* 3 */ ".opjgggjpo"
/* 4 */ ".opjgggjpo"
/* 5 */ ".opjgggjpo"
/* 6 */ ".opgjjjgpo"
/* 7 */ "..opppppo."
/* 8 */ "...ooooo.."
// Level 7
/* z\x* */
/* * 0123456789 */
/* 0 */ ".opq...qpo"
/* 1 */ ".pq.....qp"
/* 2 */ ".q.qqqqq.q"
/* 3 */ "...qpppq.."
/* 4 */ "...qpppq.."
/* 5 */ "...qpppq.."
/* 6 */ ".q.qqqqq.q"
/* 7 */ ".pq.....qp"
/* 8 */ ".opq...qpo"
// Level 8
/* z\x* */
/* * 0123456789 */
/* 0 */ ".q.......q"
/* 1 */ ".........."
/* 2 */ ".........."
/* 3 */ ".........."
/* 4 */ ".....q...."
/* 5 */ ".........."
/* 6 */ ".........."
/* 7 */ ".........."
/* 8 */ ".q.......q",
// Connectors:
"-1: 0, 1, 4: 4\n" /* Type -1, direction X- */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // HouseMid
////////////////////////////////////////////////////////////////////////////////
// HouseSmall:
// The data has been exported from the gallery Plains, area index 68, ID 131, created by Aloe_vera
{
// Size:
7, 6, 7, // SizeX = 7, SizeY = 6, SizeZ = 7
// Hitbox (relative to bounding box):
-1, 0, 0, // MinX, MinY, MinZ
7, 5, 7, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 5: 2\n" /* wood */
"b: 17: 1\n" /* tree */
"c: 35: 0\n" /* wool */
"d: 50: 4\n" /* torch */
"e: 85: 0\n" /* fence */
"f: 44: 8\n" /* step */
"g: 43: 0\n" /* doubleslab */
"h: 44: 0\n" /* step */
"m: 19: 0\n" /* sponge */,
// Block data:
// Level 0
/* z\x* 0123456 */
/* 0 */ "mmmmmmm"
/* 1 */ "maaaaam"
/* 2 */ "maaaaam"
/* 3 */ "maaaaam"
/* 4 */ "maaaaam"
/* 5 */ "maaaaam"
/* 6 */ "mmmmmmm"
// Level 1
/* z\x* 0123456 */
/* 0 */ "......."
/* 1 */ ".bcc.b."
/* 2 */ ".c...c."
/* 3 */ ".c...c."
/* 4 */ ".c...c."
/* 5 */ ".bcccb."
/* 6 */ "......."
// Level 2
/* z\x* 0123456 */
/* 0 */ ".....d."
/* 1 */ ".bee.b."
/* 2 */ ".c...c."
/* 3 */ ".e...e."
/* 4 */ ".c...c."
/* 5 */ ".beeeb."
/* 6 */ "......."
// Level 3
/* z\x* 0123456 */
/* 0 */ ".fffff."
/* 1 */ "fbcccbf"
/* 2 */ "fc...cf"
/* 3 */ "fc...cf"
/* 4 */ "fc...cf"
/* 5 */ "fbcccbf"
/* 6 */ ".fffff."
// Level 4
/* z\x* 0123456 */
/* 0 */ "gh...hg"
/* 1 */ "hhhhhhh"
/* 2 */ ".hgggh."
/* 3 */ ".hgggh."
/* 4 */ ".hgggh."
/* 5 */ "hhhhhhh"
/* 6 */ "gh...hg"
// Level 5
/* z\x* 0123456 */
/* 0 */ "......."
/* 1 */ "......."
/* 2 */ "......."
/* 3 */ "...h..."
/* 4 */ "......."
/* 5 */ "......."
/* 6 */ ".......",
// Connectors:
"-1: 4, 1, 0: 2\n" /* Type -1, direction Z- */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // HouseSmall
////////////////////////////////////////////////////////////////////////////////
// HouseSmallDblWithDoor:
// The data has been exported from the gallery Plains, area index 113, ID 265, created by Aloe_vera
{
// Size:
11, 6, 7, // SizeX = 11, SizeY = 6, SizeZ = 7
// Hitbox (relative to bounding box):
-1, 0, 0, // MinX, MinY, MinZ
11, 5, 7, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 5: 2\n" /* wood */
"b: 17: 9\n" /* tree */
"c: 17: 1\n" /* tree */
"d: 35: 0\n" /* wool */
"e: 64: 7\n" /* wooddoorblock */
"f:171:12\n" /* carpet */
"g:135: 1\n" /* 135 */
"h:126: 2\n" /* woodenslab */
"i:135: 2\n" /* 135 */
"j: 50: 4\n" /* torch */
"k: 64:12\n" /* wooddoorblock */
"l: 85: 0\n" /* fence */
"m: 19: 0\n" /* sponge */
"n: 44: 8\n" /* step */
"o: 43: 0\n" /* doubleslab */
"p: 44: 0\n" /* step */,
// Block data:
// Level 0
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "mmmmmmmmmmm"
/* 1 */ "maaaaaaaaam"
/* 2 */ "maaaabaaaam"
/* 3 */ "maaaabaaaam"
/* 4 */ "maaaabaaaam"
/* 5 */ "maaaaaaaaam"
/* 6 */ "mmmmmmmmmmm"
// Level 1
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ ".cdedcdddc."
/* 2 */ ".dfff.fffd."
/* 3 */ ".dgffdfhfd."
/* 4 */ ".diifdfffd."
/* 5 */ ".cdddcdddc."
/* 6 */ "..........."
// Level 2
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ ".j...j...j."
/* 1 */ ".cdkdclllc."
/* 2 */ ".d.......l."
/* 3 */ ".l...l...l."
/* 4 */ ".d...l...l."
/* 5 */ ".clllclllc."
/* 6 */ "..........."
// Level 3
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ ".nnnnnnnnn."
/* 1 */ "ncdddcdddcn"
/* 2 */ "nd...d...dn"
/* 3 */ "nd...d...dn"
/* 4 */ "nd...d...dn"
/* 5 */ "ncdddcdddcn"
/* 6 */ ".nnnnnnnnn."
// Level 4
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "op.......po"
/* 1 */ "ppppppppppp"
/* 2 */ ".pooooooop."
/* 3 */ ".ponndnnop."
/* 4 */ ".pooooooop."
/* 5 */ "ppppppppppp"
/* 6 */ "op.......po"
// Level 5
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..........."
/* 2 */ "..........."
/* 3 */ "...ppppp..."
/* 4 */ "..........."
/* 5 */ "..........."
/* 6 */ "...........",
// Connectors:
"-1: 3, 1, -1: 2\n" /* Type -1, direction Z- */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // HouseSmallDblWithDoor
////////////////////////////////////////////////////////////////////////////////
// HouseSmallDouble:
// The data has been exported from the gallery Plains, area index 72, ID 135, created by Aloe_vera
{
// Size:
11, 6, 7, // SizeX = 11, SizeY = 6, SizeZ = 7
// Hitbox (relative to bounding box):
-1, 0, 0, // MinX, MinY, MinZ
11, 5, 7, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 5: 2\n" /* wood */
"b: 17: 1\n" /* tree */
"c: 35: 0\n" /* wool */
"d:171:12\n" /* carpet */
"e:135: 1\n" /* 135 */
"f:126: 2\n" /* woodenslab */
"g:135: 2\n" /* 135 */
"h: 50: 4\n" /* torch */
"i: 85: 0\n" /* fence */
"j: 44: 8\n" /* step */
"k: 43: 0\n" /* doubleslab */
"l: 44: 0\n" /* step */
"m: 19: 0\n" /* sponge */,
// Block data:
// Level 0
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "mmmmmmmmmmm"
/* 1 */ "maaaaaaaaam"
/* 2 */ "maaaaaaaaam"
/* 3 */ "maaaaaaaaam"
/* 4 */ "maaaaaaaaam"
/* 5 */ "maaaaaaaaam"
/* 6 */ "mmmmmmmmmmm"
// Level 1
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ ".bcc.bcccb."
/* 2 */ ".cddd.dddc."
/* 3 */ ".ceddcdfdc."
/* 4 */ ".cggdcdddc."
/* 5 */ ".bcccbcccb."
/* 6 */ "..........."
// Level 2
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ ".h...h...h."
/* 1 */ ".bii.biiib."
/* 2 */ ".c.......c."
/* 3 */ ".i...i...i."
/* 4 */ ".c...i...c."
/* 5 */ ".biiibiiib."
/* 6 */ "..........."
// Level 3
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ ".jjjjjjjjj."
/* 1 */ "jbiiibiiibj"
/* 2 */ "jc.......cj"
/* 3 */ "jc...c...cj"
/* 4 */ "jc...c...cj"
/* 5 */ "jbcccbcccbj"
/* 6 */ ".jjjjjjjjj."
// Level 4
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "kl...l...lk"
/* 1 */ "lllllllllll"
/* 2 */ ".lkkklkkkl."
/* 3 */ ".lkjklkkkl."
/* 4 */ ".lkkklkkkl."
/* 5 */ "lllllllllll"
/* 6 */ "kl...l...lk"
// Level 5
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..........."
/* 2 */ "..........."
/* 3 */ "...l...l..."
/* 4 */ "..........."
/* 5 */ "..........."
/* 6 */ "...........",
// Connectors:
"-1: 4, 1, 0: 2\n" /* Type -1, direction Z- */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // HouseSmallDouble
////////////////////////////////////////////////////////////////////////////////
// HouseSmallWithDoor:
// The data has been exported from the gallery Plains, area index 112, ID 264, created by Aloe_vera
{
// Size:
7, 6, 7, // SizeX = 7, SizeY = 6, SizeZ = 7
// Hitbox (relative to bounding box):
-1, 0, 0, // MinX, MinY, MinZ
7, 5, 7, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 5: 2\n" /* wood */
"b: 17: 1\n" /* tree */
"c: 35: 0\n" /* wool */
"d: 64: 7\n" /* wooddoorblock */
"e: 50: 4\n" /* torch */
"f: 64:12\n" /* wooddoorblock */
"g: 85: 0\n" /* fence */
"h: 44: 8\n" /* step */
"i: 43: 0\n" /* doubleslab */
"j: 44: 0\n" /* step */
"m: 19: 0\n" /* sponge */,
// Block data:
// Level 0
/* z\x* 0123456 */
/* 0 */ "mmmmmmm"
/* 1 */ "maaaaam"
/* 2 */ "maaaaam"
/* 3 */ "maaaaam"
/* 4 */ "maaaaam"
/* 5 */ "maaaaam"
/* 6 */ "mmmmmmm"
// Level 1
/* z\x* 0123456 */
/* 0 */ "......."
/* 1 */ ".bcdcb."
/* 2 */ ".c...c."
/* 3 */ ".c...c."
/* 4 */ ".c...c."
/* 5 */ ".bcccb."
/* 6 */ "......."
// Level 2
/* z\x* 0123456 */
/* 0 */ ".....e."
/* 1 */ ".bcfcb."
/* 2 */ ".g...g."
/* 3 */ ".g...g."
/* 4 */ ".g...g."
/* 5 */ ".bgggb."
/* 6 */ "......."
// Level 3
/* z\x* 0123456 */
/* 0 */ ".hhhhh."
/* 1 */ "hbcccbh"
/* 2 */ "hc...ch"
/* 3 */ "hc...ch"
/* 4 */ "hc...ch"
/* 5 */ "hbcccbh"
/* 6 */ ".hhhhh."
// Level 4
/* z\x* 0123456 */
/* 0 */ "ij...ji"
/* 1 */ "jjjjjjj"
/* 2 */ ".jiiij."
/* 3 */ ".jiiij."
/* 4 */ ".jiiij."
/* 5 */ "jjjjjjj"
/* 6 */ "ij...ji"
// Level 5
/* z\x* 0123456 */
/* 0 */ "......."
/* 1 */ "......."
/* 2 */ "......."
/* 3 */ "...j..."
/* 4 */ "......."
/* 5 */ "......."
/* 6 */ ".......",
// Connectors:
"-1: 3, 1, 0: 2\n" /* Type -1, direction Z- */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // HouseSmallWithDoor
////////////////////////////////////////////////////////////////////////////////
// HouseWide:
// The data has been exported from the gallery Plains, area index 64, ID 121, created by STR_Warrior
{
// Size:
11, 6, 11, // SizeX = 11, SizeY = 6, SizeZ = 11
// Hitbox (relative to bounding box):
-1, 0, -1, // MinX, MinY, MinZ
11, 5, 10, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 5: 2\n" /* wood */
"b: 17: 1\n" /* tree */
"c: 35: 0\n" /* wool */
"d:171: 0\n" /* carpet */
"e:126: 1\n" /* woodenslab */
"f: 64: 5\n" /* wooddoorblock */
"g: 85: 0\n" /* fence */
"h: 50: 1\n" /* torch */
"i: 50: 2\n" /* torch */
"j: 64:12\n" /* wooddoorblock */
"k:126:11\n" /* woodenslab */
"l: 17: 5\n" /* tree */
"m: 19: 0\n" /* sponge */
"n:126: 3\n" /* woodenslab */
"o:125: 3\n" /* woodendoubleslab */
"p: 5: 3\n" /* wood */,
// Block data:
// Level 0
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "mmmmmmmmmmm"
/* 1 */ "mmaaaaaaamm"
/* 2 */ "maaaaaaaaam"
/* 3 */ "maaaaaaaaam"
/* 4 */ "maaaaaaaaam"
/* 5 */ "maaaaaaaaam"
/* 6 */ "maaaaaaaaam"
/* 7 */ "maaaaaaaaam"
/* 8 */ "maaaaaaaaam"
/* 9 */ "mmaaaaaaamm"
/* 10 */ "mmmmmmmmmmm"
// Level 1
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..bcbcbcb.."
/* 2 */ ".b.d.....b."
/* 3 */ ".cded....c."
/* 4 */ ".bded....b."
/* 5 */ ".c.d.....c."
/* 6 */ ".b.......b."
/* 7 */ ".c.......c."
/* 8 */ ".b.......b."
/* 9 */ "..bcbfbcb.."
/* 10 */ "..........."
// Level 2
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..bgbgbgb.."
/* 2 */ ".b.......b."
/* 3 */ ".g.......g."
/* 4 */ ".bh.....ib."
/* 5 */ ".g.......g."
/* 6 */ ".b.......b."
/* 7 */ ".g.......g."
/* 8 */ ".b.......b."
/* 9 */ "..bgbjbgb.."
/* 10 */ "..........."
// Level 3
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "...kkkkk..."
/* 1 */ "..bcbcbcb.."
/* 2 */ ".b.......b."
/* 3 */ "kc.......ck"
/* 4 */ "kb.......bk"
/* 5 */ "kc.......ck"
/* 6 */ "kb.......bk"
/* 7 */ "kc.......ck"
/* 8 */ ".b.......b."
/* 9 */ "..bcblbcb.."
/* 10 */ "...kkkkk..."
// Level 4
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ ".kn.....nk."
/* 1 */ "konnnnnnnok"
/* 2 */ "nnnnnnnnnnn"
/* 3 */ ".nnpppppnn."
/* 4 */ ".nnpkkkpnn."
/* 5 */ ".nnpkkkpnn."
/* 6 */ ".nnpkkkpnn."
/* 7 */ ".nnpppppnn."
/* 8 */ "nnnnnnnnnnn"
/* 9 */ "kknnnnnnnok"
/* 10 */ ".kn.....nk."
// Level 5
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "n.........n"
/* 1 */ "..........."
/* 2 */ "..........."
/* 3 */ "..........."
/* 4 */ "....nnn...."
/* 5 */ "....non...."
/* 6 */ "....nnn...."
/* 7 */ "..........."
/* 8 */ "..........."
/* 9 */ "..........."
/* 10 */ "n.........n",
// Connectors:
"-1: 5, 1, 10: 3\n" /* Type -1, direction Z+ */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // HouseWide
////////////////////////////////////////////////////////////////////////////////
// HouseWithGarden:
// The data has been exported from the gallery Plains, area index 67, ID 130, created by Aloe_vera
{
// Size:
16, 9, 16, // SizeX = 16, SizeY = 9, SizeZ = 16
// Hitbox (relative to bounding box):
-1, 0, 0, // MinX, MinY, MinZ
16, 8, 16, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 3: 0\n" /* dirt */
"b: 5: 2\n" /* wood */
"c: 2: 0\n" /* grass */
"d:113: 0\n" /* netherbrickfence */
"e: 17: 1\n" /* tree */
"f: 35: 0\n" /* wool */
"g:126: 2\n" /* woodenslab */
"h: 31: 2\n" /* tallgrass */
"i:125: 2\n" /* woodendoubleslab */
"j: 38: 3\n" /* rose */
"k: 38: 2\n" /* rose */
"l: 38: 1\n" /* rose */
"m: 19: 0\n" /* sponge */
"n: 17: 2\n" /* tree */
"o: 50: 4\n" /* torch */
"p: 85: 0\n" /* fence */
"q:140: 0\n" /* flowerpotblock */
"r: 50: 3\n" /* torch */
"s: 44: 8\n" /* step */
"t: 50: 1\n" /* torch */
"u: 50: 2\n" /* torch */
"v: 43: 0\n" /* doubleslab */
"w: 44: 0\n" /* step */
"x: 18:10\n" /* leaves */,
// Block data:
// Level 0
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "mmmmmmmmmaammmmm"
/* 1 */ "aabbbbbbbbbbaaam"
/* 2 */ "aabbbbbbbbbbaaam"
/* 3 */ "aabbbbbbbbbbaaam"
/* 4 */ "aabbbbbbbbbbaaam"
/* 5 */ "aabbbbbbbbbbaaam"
/* 6 */ "aabbbbbbbbbbaaam"
/* 7 */ "aabbbbbbbbbbaaam"
/* 8 */ "aabbbbbbbbbbaaam"
/* 9 */ "aabbbbbbbbbbaaam"
/* 10 */ "aaaaaaaaaaaaaaam"
/* 11 */ "aaaaaaaaaaaaaaam"
/* 12 */ "aaaaaaaaaaaaaaam"
/* 13 */ "aaaaaaaaaaaaaaam"
/* 14 */ "aaaaaaaaaaaaaaam"
/* 15 */ "mmmmmmmmmmmmmmmm"
// Level 1
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "mmmmmmmmmccmmmmm"
/* 1 */ "ccbbbbbbbbbbcccm"
/* 2 */ "ccbbbbbbbbbbcccm"
/* 3 */ "ccbbbbbbbbbbcccm"
/* 4 */ "ccbbbbbbbbbbcccm"
/* 5 */ "ccbbbbbbbbbbcccm"
/* 6 */ "ccbbbbbbbbbbcccm"
/* 7 */ "ccbbbbbbbbbbcccm"
/* 8 */ "ccbbbbbbbbbbcccm"
/* 9 */ "ccbbbbbbbbbbcccm"
/* 10 */ "cccccccccccccccm"
/* 11 */ "cccccccccccccccm"
/* 12 */ "cccccccccccccccm"
/* 13 */ "cccccccccccccacm"
/* 14 */ "cccccccccccccccm"
/* 15 */ "mmmmmmmmmmmmmmmm"
// Level 2
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "ddeffeffe..eddd."
/* 2 */ "d.fbbgggg..f..d."
/* 3 */ "d.fbgggggggf.hd."
/* 4 */ "d.fbgggggggf..d."
/* 5 */ "d.eggggggggehhd."
/* 6 */ "d.fgiiggiigf.hd."
/* 7 */ "d.fgiiggiigf..d."
/* 8 */ "d.fggggggggf..d."
/* 9 */ "d.efffeefffe.hd."
/* 10 */ "d.............d."
/* 11 */ "djhhk.jhh..hh.d."
/* 12 */ "d.jlk.hj.h....d."
/* 13 */ "d..jh.hh..h..nd."
/* 14 */ "ddddddddddddddd."
/* 15 */ "................"
// Level 3
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "........o..o...."
/* 1 */ "..eppeffe..e...."
/* 2 */ "..pqq......p...."
/* 3 */ "..pq.......p...."
/* 4 */ "..pq.......p...."
/* 5 */ "..e........e...."
/* 6 */ "..p........p...."
/* 7 */ "..p........p...."
/* 8 */ "..p........p...."
/* 9 */ "..epppeepppe...."
/* 10 */ "......rr........"
/* 11 */ "................"
/* 12 */ "................"
/* 13 */ ".............n.."
/* 14 */ "................"
/* 15 */ "................"
// Level 4
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "..ssssssssss...."
/* 1 */ ".seffeffeffes..."
/* 2 */ ".sf..r.....fs..."
/* 3 */ ".sf........fs..."
/* 4 */ ".sf........fs..."
/* 5 */ ".set......ues..."
/* 6 */ ".sf........fs..."
/* 7 */ ".sf........fs..."
/* 8 */ ".sf........fs..."
/* 9 */ ".sefffeefffes..."
/* 10 */ "..ssssssssss...."
/* 11 */ "................"
/* 12 */ "................"
/* 13 */ ".............n.."
/* 14 */ "................"
/* 15 */ "................"
// Level 5
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ ".vw........wv..."
/* 1 */ ".wwwwwwwwwwww..."
/* 2 */ "..wvvvvvvvvw...."
/* 3 */ "..wvvvvvvvvw...."
/* 4 */ "..wvvvvvvvvw...."
/* 5 */ "..wvvvvvvvvw...."
/* 6 */ "..wvvvvvvvvw...."
/* 7 */ "..wvvvvvvvvw...."
/* 8 */ "..wvvvvvvvvw...."
/* 9 */ ".wwwwwwwwwwww..."
/* 10 */ ".vw........wv..."
/* 11 */ "............xxx."
/* 12 */ "...........xxxxx"
/* 13 */ "...........xxnxx"
/* 14 */ "...........xxxxx"
/* 15 */ "............xxx."
// Level 6
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "................"
/* 2 */ "................"
/* 3 */ "....wwwwww......"
/* 4 */ "....wvvvvw......"
/* 5 */ "....wvvvvw......"
/* 6 */ "....wvvvvw......"
/* 7 */ "....wwwwww......"
/* 8 */ "................"
/* 9 */ "................"
/* 10 */ "................"
/* 11 */ "............xxx."
/* 12 */ "...........xxxxx"
/* 13 */ "...........xxnxx"
/* 14 */ "...........xxxxx"
/* 15 */ "............xxx."
// Level 7
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "................"
/* 2 */ "................"
/* 3 */ "................"
/* 4 */ "................"
/* 5 */ "......ww........"
/* 6 */ "................"
/* 7 */ "................"
/* 8 */ "................"
/* 9 */ "................"
/* 10 */ "................"
/* 11 */ "................"
/* 12 */ "............xxx."
/* 13 */ "............xnx."
/* 14 */ "............xx.."
/* 15 */ "................"
// Level 8
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "................"
/* 2 */ "................"
/* 3 */ "................"
/* 4 */ "................"
/* 5 */ "................"
/* 6 */ "................"
/* 7 */ "................"
/* 8 */ "................"
/* 9 */ "................"
/* 10 */ "................"
/* 11 */ "................"
/* 12 */ ".............x.."
/* 13 */ "............xxx."
/* 14 */ ".............x.."
/* 15 */ "................",
// Connectors:
"-1: 9, 2, 0: 2\n" /* Type -1, direction Z- */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // HouseWithGarden
////////////////////////////////////////////////////////////////////////////////
// HouseWithSakura1:
// The data has been exported from the gallery Plains, area index 75, ID 141, created by Aloe_vera
{
// Size:
13, 7, 15, // SizeX = 13, SizeY = 7, SizeZ = 15
// Hitbox (relative to bounding box):
-1, 0, 0, // MinX, MinY, MinZ
13, 6, 15, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 3: 0\n" /* dirt */
"b: 2: 0\n" /* grass */
"c: 17: 5\n" /* tree */
"d: 5: 2\n" /* wood */
"e: 17: 9\n" /* tree */
"f:113: 0\n" /* netherbrickfence */
"g: 17: 1\n" /* tree */
"h: 35: 0\n" /* wool */
"i: 31: 2\n" /* tallgrass */
"j: 54: 2\n" /* chest */
"k: 38: 6\n" /* rose */
"l: 38: 2\n" /* rose */
"m: 19: 0\n" /* sponge */
"n: 50: 4\n" /* torch */
"o: 85: 0\n" /* fence */
"p: 44: 8\n" /* step */
"q: 35: 6\n" /* wool */
"r: 43: 0\n" /* doubleslab */
"s: 44: 0\n" /* step */,
// Block data:
// Level 0
/* z\x* 111 */
/* * 0123456789012 */
/* 0 */ "aaaaaaaaaaaaa"
/* 1 */ "aaaaaaaaaaaaa"
/* 2 */ "aaaaaaaaaaaaa"
/* 3 */ "aaaaaaaaaaaaa"
/* 4 */ "aaaaaaaaaaaaa"
/* 5 */ "aaaaaaaaaaaaa"
/* 6 */ "aaaaaaaaaaaaa"
/* 7 */ "aaaaaaaaaaaaa"
/* 8 */ "aaaaaaaaaaaaa"
/* 9 */ "aaaaaaaaaaaaa"
/* 10 */ "aaaaaaaaaaaaa"
/* 11 */ "aaaaaaaaaaaaa"
/* 12 */ "aaaaaaaaaaaaa"
/* 13 */ "aaaaaaaaaaaaa"
/* 14 */ "aaaaaaaaaaaaa"
// Level 1
/* z\x* 111 */
/* * 0123456789012 */
/* 0 */ "bbbbbbbbbbbbb"
/* 1 */ "bbbbbbbbbbbbb"
/* 2 */ "bbbaccdabbbbb"
/* 3 */ "bbbedddebbbbb"
/* 4 */ "bbbedddebbbbb"
/* 5 */ "bbbedddebbbbb"
/* 6 */ "bbbacccabbbbb"
/* 7 */ "bbbbbbbbbbbbb"
/* 8 */ "bbbbbbbbbbbbb"
/* 9 */ "bbbbbbbbbbbbb"
/* 10 */ "bbbbbbbbbbabb"
/* 11 */ "bbbbbbbbbbbbb"
/* 12 */ "bbbbbbbbbbbbb"
/* 13 */ "bbbbbbbbbbbbb"
/* 14 */ "bbbbbbbbbbbbb"
// Level 2
/* z\x* 111 */
/* * 0123456789012 */
/* 0 */ "ffff...ffffff"
/* 1 */ "f...........f"
/* 2 */ "f..ghh.g..i.f"
/* 3 */ "f..h...h..i.f"
/* 4 */ "f..h...h....f"
/* 5 */ "fi.h..jh..i.f"
/* 6 */ "f..ghhhg....f"
/* 7 */ "f.........i.f"
/* 8 */ "fii.........f"
/* 9 */ "f.k..k.i....f"
/* 10 */ "fl.i..i...g.f"
/* 11 */ "f.i..i.k....f"
/* 12 */ "f.l.k.......f"
/* 13 */ "f.....l.....f"
/* 14 */ "fffffffffffff"
// Level 3
/* z\x* 111 */
/* * 0123456789012 */
/* 0 */ "............."
/* 1 */ ".......n....."
/* 2 */ "...goo.g....."
/* 3 */ "...h...h....."
/* 4 */ "...o...o....."
/* 5 */ "...h...h....."
/* 6 */ "...gooog....."
/* 7 */ "............."
/* 8 */ "............."
/* 9 */ "............."
/* 10 */ "..........g.."
/* 11 */ "............."
/* 12 */ "............."
/* 13 */ "............."
/* 14 */ "............."
// Level 4
/* z\x* 111 */
/* * 0123456789012 */
/* 0 */ "............."
/* 1 */ "...ppppp....."
/* 2 */ "..pghhhgp...."
/* 3 */ "..ph...hp...."
/* 4 */ "..ph...hp...."
/* 5 */ "..ph...hp...."
/* 6 */ "..pghhhgp...."
/* 7 */ "...ppppp....."
/* 8 */ "............."
/* 9 */ "..........q.."
/* 10 */ ".........qgq."
/* 11 */ "..........q.."
/* 12 */ "............."
/* 13 */ "............."
/* 14 */ "............."
// Level 5
/* z\x* 111 */
/* * 0123456789012 */
/* 0 */ "............."
/* 1 */ "..rs...sr...."
/* 2 */ "..sssssss...."
/* 3 */ "...srrrs....."
/* 4 */ "...srrrs....."
/* 5 */ "...srrrs....."
/* 6 */ "..sssssss...."
/* 7 */ "..rs...sr...."
/* 8 */ "............."
/* 9 */ ".........qqq."
/* 10 */ ".........qqq."
/* 11 */ ".........qqq."
/* 12 */ "............."
/* 13 */ "............."
/* 14 */ "............."
// Level 6
/* z\x* 111 */
/* * 0123456789012 */
/* 0 */ "............."
/* 1 */ "............."
/* 2 */ "............."
/* 3 */ "............."
/* 4 */ ".....s......."
/* 5 */ "............."
/* 6 */ "............."
/* 7 */ "............."
/* 8 */ "............."
/* 9 */ "............."
/* 10 */ "..........q.."
/* 11 */ "............."
/* 12 */ "............."
/* 13 */ "............."
/* 14 */ ".............",
// Connectors:
"-1: 5, 2, 0: 2\n" /* Type -1, direction Z- */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // HouseWithSakura1
////////////////////////////////////////////////////////////////////////////////
// HouseWithSpa:
// The data has been exported from the gallery Plains, area index 73, ID 139, created by Aloe_vera
{
// Size:
16, 8, 14, // SizeX = 16, SizeY = 8, SizeZ = 14
// Hitbox (relative to bounding box):
0, 0, 0, // MinX, MinY, MinZ
15, 7, 13, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 5: 2\n" /* wood */
"b: 3: 0\n" /* dirt */
"c: 2: 0\n" /* grass */
"d: 8: 0\n" /* water */
"e:135: 3\n" /* 135 */
"f:135: 1\n" /* 135 */
"g:113: 0\n" /* netherbrickfence */
"h: 17: 1\n" /* tree */
"i: 35: 0\n" /* wool */
"j:171:12\n" /* carpet */
"k: 64: 6\n" /* wooddoorblock */
"l:126: 2\n" /* woodenslab */
"m: 19: 0\n" /* sponge */
"n:135: 2\n" /* 135 */
"o: 64: 7\n" /* wooddoorblock */
"p: 50: 4\n" /* torch */
"q: 85: 0\n" /* fence */
"r: 64:12\n" /* wooddoorblock */
"s: 50: 3\n" /* torch */
"t: 44: 8\n" /* step */
"u: 43: 0\n" /* doubleslab */
"v: 44: 0\n" /* step */,
// Block data:
// Level 0
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ ".aaaaaaaaaaaaaa."
/* 2 */ ".aaaaaaaaaaaaaa."
/* 3 */ ".aaaaaaaaaaaaaa."
/* 4 */ ".aaaaaaaaaaaaaa."
/* 5 */ ".aaaaaaaaaaaaaa."
/* 6 */ ".aaaaaaaaaaaaaa."
/* 7 */ ".aaaaaabbbbbbbbb"
/* 8 */ ".aaaaaabbbbbbbbb"
/* 9 */ ".aaaaaabbbbbbbbb"
/* 10 */ ".aaaaaabbbbbbbbb"
/* 11 */ ".aaaaaabbbbbbbbb"
/* 12 */ ".aaaaaabbbbbbbbb"
/* 13 */ ".......bbbbbbbbb"
// Level 1
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "mmmmmmmmmmmmmmmm"
/* 1 */ "maaaaaaaaaaaaaam"
/* 2 */ "maaaaaaaaaaaaaam"
/* 3 */ "maaaaaaaaaaaaaam"
/* 4 */ "maaaaaaaaaaaaaam"
/* 5 */ "maaaaaaaaaaaaaam"
/* 6 */ "maaaaaaaaaaaaaam"
/* 7 */ "maaaaaaaaaaccccc"
/* 8 */ "maaaaaaacccccccc"
/* 9 */ "maaaaaaacccccccc"
/* 10 */ "maaaaaaacccccccc"
/* 11 */ "maaaaaaccccccccc"
/* 12 */ "maaaaaaccccccccc"
/* 13 */ "mmmmmmmccccccccc"
// Level 2
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ ".aaaaaaaaaaaaaa."
/* 2 */ ".aaaaaaaaaaaaaa."
/* 3 */ ".aaaaaaaaaaaaaa."
/* 4 */ ".aaaaaaaaaaaaaa."
/* 5 */ ".aaaaaaaaaaaaaa."
/* 6 */ ".aaddaaaaaaaaaa."
/* 7 */ ".aaddaaeeef....."
/* 8 */ ".aaddaaf........"
/* 9 */ ".aaddaaf........"
/* 10 */ ".aaddaae........"
/* 11 */ ".aaddaa........."
/* 12 */ ".aaaaaa........."
/* 13 */ "................"
// Level 3
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ ".ggggghiiihiiih."
/* 2 */ ".geee.ijjjjjjji."
/* 3 */ ".gf...kjjjijlji."
/* 4 */ ".gf...innjijjji."
/* 5 */ ".g....hiiohiiih."
/* 6 */ ".g....g........."
/* 7 */ ".g.............."
/* 8 */ ".g.............."
/* 9 */ ".g.............."
/* 10 */ ".g....g........."
/* 11 */ ".g....g........."
/* 12 */ ".gggggg........."
/* 13 */ "................"
// Level 4
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "......p...p...p."
/* 1 */ ".g....hqqqhqqqh."
/* 2 */ "......i.......i."
/* 3 */ "......r...q...q."
/* 4 */ "......i...q...i."
/* 5 */ "......hqqrhqqqh."
/* 6 */ "......g...s....."
/* 7 */ "................"
/* 8 */ "................"
/* 9 */ "................"
/* 10 */ "................"
/* 11 */ "................"
/* 12 */ ".g....g........."
/* 13 */ "................"
// Level 5
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ ".tttttttttttttt."
/* 1 */ "tggggghqqqhqqqht"
/* 2 */ "tg....i.......it"
/* 3 */ "tg....i...i...it"
/* 4 */ "tg....i...i...it"
/* 5 */ "tg....hiiihiiiht"
/* 6 */ "tg....gtttttttt."
/* 7 */ "tg....gt........"
/* 8 */ "tg....gt........"
/* 9 */ "tg....gt........"
/* 10 */ "tg....gt........"
/* 11 */ "tg....gt........"
/* 12 */ "tggggggt........"
/* 13 */ ".tttttt........."
// Level 6
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "uv............vu"
/* 1 */ "vvvvvvvvvvvvvvvv"
/* 2 */ ".vuuuuuuuuuuuuv."
/* 3 */ ".vuuuuuutuuuuuv."
/* 4 */ ".vuuuuuuuuuuuuv."
/* 5 */ ".vuuuuvvvvvvvvvv"
/* 6 */ ".vuuuuv.......vu"
/* 7 */ ".vuuuuv........."
/* 8 */ ".vuuuuv........."
/* 9 */ ".vuuuuv........."
/* 10 */ ".vuuuuv........."
/* 11 */ ".vuuuuv........."
/* 12 */ "vvvvvvvv........"
/* 13 */ "uv....vu........"
// Level 7
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "................"
/* 2 */ "................"
/* 3 */ "...vvvvvvvvvv..."
/* 4 */ "...vv..........."
/* 5 */ "...vv..........."
/* 6 */ "...vv..........."
/* 7 */ "...vv..........."
/* 8 */ "...vv..........."
/* 9 */ "...vv..........."
/* 10 */ "...vv..........."
/* 11 */ "................"
/* 12 */ "................"
/* 13 */ "................",
// Connectors:
"",
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // HouseWithSpa
////////////////////////////////////////////////////////////////////////////////
// MediumSakuraTree:
// The data has been exported from the gallery Plains, area index 146, ID 490, created by STR_Warrior
{
// Size:
7, 10, 7, // SizeX = 7, SizeY = 10, SizeZ = 7
// Hitbox (relative to bounding box):
0, 0, 0, // MinX, MinY, MinZ
6, 9, 6, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 3: 0\n" /* dirt */
"b: 2: 0\n" /* grass */
"c: 31: 1\n" /* tallgrass */
"d: 38: 7\n" /* rose */
"e: 17: 1\n" /* tree */
"f: 38: 0\n" /* rose */
"g: 38: 8\n" /* rose */
"h: 38: 5\n" /* rose */
"i: 35: 6\n" /* wool */
"m: 19: 0\n" /* sponge */,
// Block data:
// Level 0
/* z\x* 0123456 */
/* 0 */ "aaaaaaa"
/* 1 */ "aaaaaaa"
/* 2 */ "aaaaaaa"
/* 3 */ "aaaaaaa"
/* 4 */ "aaaaaaa"
/* 5 */ "aaaaaaa"
/* 6 */ "aaaaaaa"
// Level 1
/* z\x* 0123456 */
/* 0 */ "bbbbbbb"
/* 1 */ "bbbbbbb"
/* 2 */ "bbbbbbb"
/* 3 */ "bbbabbb"
/* 4 */ "bbbbbbb"
/* 5 */ "bbbbbbb"
/* 6 */ "bbbbbbb"
// Level 2
/* z\x* 0123456 */
/* 0 */ "mm...mm"
/* 1 */ "m.c...m"
/* 2 */ ".dccdc."
/* 3 */ "..cefc."
/* 4 */ ".ccfgh."
/* 5 */ "m.ccc.m"
/* 6 */ "mm...mm"
// Level 3
/* z\x* 0123456 */
/* 0 */ "m.....m"
/* 1 */ "......."
/* 2 */ "......."
/* 3 */ "...e..."
/* 4 */ "......."
/* 5 */ "......."
/* 6 */ "m.....m"
// Level 4
/* z\x* 0123456 */
/* 0 */ "......."
/* 1 */ "..i...."
/* 2 */ "......."
/* 3 */ "...e.i."
/* 4 */ ".i....."
/* 5 */ "......."
/* 6 */ "......."
// Level 5
/* z\x* 0123456 */
/* 0 */ "......."
/* 1 */ "..i...."
/* 2 */ "...i..."
/* 3 */ "..ieii."
/* 4 */ ".i.ii.."
/* 5 */ "...i..."
/* 6 */ "......."
// Level 6
/* z\x* 0123456 */
/* 0 */ "......."
/* 1 */ "..ii..."
/* 2 */ "..iii.."
/* 3 */ ".iieii."
/* 4 */ ".iiii.."
/* 5 */ "..iii.."
/* 6 */ "......."
// Level 7
/* z\x* 0123456 */
/* 0 */ "......."
/* 1 */ "..iii.."
/* 2 */ ".iiiii."
/* 3 */ ".iieii."
/* 4 */ ".iiiii."
/* 5 */ "..iii.."
/* 6 */ "......."
// Level 8
/* z\x* 0123456 */
/* 0 */ "......."
/* 1 */ "...i..."
/* 2 */ "..iiii."
/* 3 */ ".iiiii."
/* 4 */ "..iii.."
/* 5 */ "...i..."
/* 6 */ "......."
// Level 9
/* z\x* 0123456 */
/* 0 */ "......."
/* 1 */ "......."
/* 2 */ "...i..."
/* 3 */ "..iii.."
/* 4 */ "...i..."
/* 5 */ "......."
/* 6 */ ".......",
// Connectors:
"-1: 3, 2, 0: 2\n" /* Type -1, direction Z- */
"3: 6, 2, 3: 5\n" /* Type 3, direction X+ */
"-3: 0, 2, 3: 4\n" /* Type -3, direction X- */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // MediumSakuraTree
////////////////////////////////////////////////////////////////////////////////
// Restaurant:
// The data has been exported from the gallery Plains, area index 61, ID 117, created by Aloe_vera
{
// Size:
15, 10, 15, // SizeX = 15, SizeY = 10, SizeZ = 15
// Hitbox (relative to bounding box):
-1, 0, -1, // MinX, MinY, MinZ
14, 9, 15, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 5: 2\n" /* wood */
"b:135: 0\n" /* 135 */
"c:135: 2\n" /* 135 */
"d:135: 1\n" /* 135 */
"e: 17: 9\n" /* tree */
"f:135: 3\n" /* 135 */
"g: 85: 0\n" /* fence */
"h: 17: 1\n" /* tree */
"i:171: 0\n" /* carpet */
"j:171:12\n" /* carpet */
"k:126: 1\n" /* woodenslab */
"l: 50: 5\n" /* torch */
"m: 19: 0\n" /* sponge */
"n: 35: 0\n" /* wool */
"o: 50: 3\n" /* torch */
"p: 50: 1\n" /* torch */
"q: 50: 4\n" /* torch */
"r: 35:14\n" /* wool */
"s: 44: 8\n" /* step */
"t: 43: 0\n" /* doubleslab */
"u: 44: 0\n" /* step */
"v: 17: 5\n" /* tree */,
// Block data:
// Level 0
/* z\x* 11111 */
/* * 012345678901234 */
/* 0 */ "mmmmaaaaaaammmm"
/* 1 */ "maaaaaaaaaaaaam"
/* 2 */ "maaaaaaaaaaaaam"
/* 3 */ "maaaaaaaaaaaaam"
/* 4 */ "aaaaaaaaaaaaaaa"
/* 5 */ "aaaaaaaaaaaaaaa"
/* 6 */ "aaaaaaaaaaaaaaa"
/* 7 */ "aaaaaaaaaaaaaaa"
/* 8 */ "aaaaaaaaaaaaaaa"
/* 9 */ "aaaaaaaaaaaaaaa"
/* 10 */ "aaaaaaaaaaaaaaa"
/* 11 */ "maaaaaaaaaaaaam"
/* 12 */ "maaaaaaaaaaaaam"
/* 13 */ "maaaaaaaaaaaaam"
/* 14 */ "mmmmaaaaaaammmm"
// Level 1
/* z\x* 11111 */
/* * 012345678901234 */
/* 0 */ "....bcccccd...."
/* 1 */ ".aaaaaaaaaaaaa."
/* 2 */ ".aaaaaaaaaaaaa."
/* 3 */ ".aaaaaaaaaaaaa."
/* 4 */ "caaaaaaaaaaaaac"
/* 5 */ "baaaaaaaaaaaaad"
/* 6 */ "baaaaaaaaaaaaad"
/* 7 */ "baaaaaaaaaaeaad"
/* 8 */ "baaaaaaaaaaaaad"
/* 9 */ "baaaaaaaaaaaaad"
/* 10 */ "faaaaaaaaaaaaaf"
/* 11 */ ".aaaaaaaaaaaaa."
/* 12 */ ".aaaaaaaaaaaaa."
/* 13 */ ".aaaaaaaaaaaaa."
/* 14 */ "....bfffffd...."
// Level 2
/* z\x* 11111 */
/* * 012345678901234 */
/* 0 */ "..............."
/* 1 */ ".gggg.....gggg."
/* 2 */ ".g...........g."
/* 3 */ ".g.hhhhhhhhh.g."
/* 4 */ ".g.hiiijiiih.g."
/* 5 */ "...hikijikih..."
/* 6 */ "...hiiijiiihg.."
/* 7 */ "...hjjjjjjj...."
/* 8 */ "...hiiijiiihg.."
/* 9 */ "...hikijikih..."
/* 10 */ ".g.hiiijiiih.g."
/* 11 */ ".g.hhhhhhhhh.g."
/* 12 */ ".g...........g."
/* 13 */ ".gggg.....gggg."
/* 14 */ "..............."
// Level 3
/* z\x* 11111 */
/* * 012345678901234 */
/* 0 */ "..............."
/* 1 */ ".l..g.....g..l."
/* 2 */ "..............."
/* 3 */ "...hnnnhnnnh..."
/* 4 */ ".g.n.......n.g."
/* 5 */ "...n.......n..."
/* 6 */ "...n.......hl.."
/* 7 */ "...h..........."
/* 8 */ "...n.......hl.."
/* 9 */ "...n.......n..."
/* 10 */ ".g.n.......n.g."
/* 11 */ "...hnnnhnnnh..."
/* 12 */ "..............."
/* 13 */ ".l..g.....g..l."
/* 14 */ "..............."
// Level 4
/* z\x* 11111 */
/* * 012345678901234 */
/* 0 */ "..............."
/* 1 */ "....g.....g...."
/* 2 */ "..............."
/* 3 */ "...hn.nhn.nh..."
/* 4 */ ".g.n...o...n.g."
/* 5 */ "...n.......n..."
/* 6 */ "...n.......h..."
/* 7 */ "...hp......e..."
/* 8 */ "...n.......h..."
/* 9 */ "...n.......n..."
/* 10 */ ".g.n...q...n.g."
/* 11 */ "...hn.nhn.nh..."
/* 12 */ "..............."
/* 13 */ "....g.....g...."
/* 14 */ "..............."
// Level 5
/* z\x* 11111 */
/* * 012345678901234 */
/* 0 */ "..............."
/* 1 */ "....g.....g...."
/* 2 */ "....ggggggg...."
/* 3 */ "...hnnnhnnnh..."
/* 4 */ ".ggn.......ngg."
/* 5 */ "..gn.......ng.."
/* 6 */ "..gn.......hg.."
/* 7 */ "..gh..r.r..ng.."
/* 8 */ "..gn.......hg.."
/* 9 */ "..gn.......ng.."
/* 10 */ ".ggn.......ngg."
/* 11 */ "...hnnnhnnnh..."
/* 12 */ "....ggggggg...."
/* 13 */ "....g.....g...."
/* 14 */ "..............."
// Level 6
/* z\x* 11111 */
/* * 012345678901234 */
/* 0 */ "..............."
/* 1 */ "...stuuuuuts..."
/* 2 */ "..sttttttttts.."
/* 3 */ ".sthvvvhvvvhts."
/* 4 */ ".tte.......ett."
/* 5 */ ".ute.......etu."
/* 6 */ ".ute.......htu."
/* 7 */ ".uth..g.g..etu."
/* 8 */ ".ute.......htu."
/* 9 */ ".ute.......etu."
/* 10 */ ".tte.......ett."
/* 11 */ ".sthvvvhvvvhts."
/* 12 */ "..sttttttttts.."
/* 13 */ "...stuuuuuts..."
/* 14 */ "..............."
// Level 7
/* z\x* 11111 */
/* * 012345678901234 */
/* 0 */ "..............."
/* 1 */ ".stu.......uts."
/* 2 */ ".tu.........ut."
/* 3 */ ".u.uuuuuuuuu.u."
/* 4 */ "...utttttttu..."
/* 5 */ "...utttttttu..."
/* 6 */ "...utttttttu..."
/* 7 */ "...utttttttu..."
/* 8 */ "...utttttttu..."
/* 9 */ "...utttttttu..."
/* 10 */ "...utttttttu..."
/* 11 */ ".u.uuuuuuuuu.u."
/* 12 */ ".tu.........ut."
/* 13 */ ".stu.......uts."
/* 14 */ "..............."
// Level 8
/* z\x* 11111 */
/* * 012345678901234 */
/* 0 */ "..............."
/* 1 */ ".u...........u."
/* 2 */ "..............."
/* 3 */ "..............."
/* 4 */ "..............."
/* 5 */ ".....uuuuu....."
/* 6 */ ".....utttu....."
/* 7 */ ".....utttu....."
/* 8 */ ".....utttu....."
/* 9 */ ".....uuuuu....."
/* 10 */ "..............."
/* 11 */ "..............."
/* 12 */ "..............."
/* 13 */ ".u...........u."
/* 14 */ "..............."
// Level 9
/* z\x* 11111 */
/* * 012345678901234 */
/* 0 */ "..............."
/* 1 */ "..............."
/* 2 */ "..............."
/* 3 */ "..............."
/* 4 */ "..............."
/* 5 */ "..............."
/* 6 */ "..............."
/* 7 */ ".......u......."
/* 8 */ "..............."
/* 9 */ "..............."
/* 10 */ "..............."
/* 11 */ "..............."
/* 12 */ "..............."
/* 13 */ "..............."
/* 14 */ "...............",
// Connectors:
"-1: 14, 1, 7: 5\n" /* Type -1, direction X+ */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // Restaurant
////////////////////////////////////////////////////////////////////////////////
// SakuraDouble:
// The data has been exported from the gallery Plains, area index 76, ID 142, created by Aloe_vera
{
// Size:
12, 8, 6, // SizeX = 12, SizeY = 8, SizeZ = 6
// Hitbox (relative to bounding box):
-1, 0, -1, // MinX, MinY, MinZ
12, 7, 6, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 3: 0\n" /* dirt */
"b: 2: 0\n" /* grass */
"c: 17: 1\n" /* tree */
"d: 35: 6\n" /* wool */
"m: 19: 0\n" /* sponge */,
// Block data:
// Level 0
/* z\x* 11 */
/* * 012345678901 */
/* 0 */ "aaaaaaaaaaaa"
/* 1 */ "aaaaaaaaaaaa"
/* 2 */ "aaaaaaaaaaaa"
/* 3 */ "aaaaaaaaaaaa"
/* 4 */ "aaaaaaaaaaaa"
/* 5 */ "aaaaaaaaaaaa"
// Level 1
/* z\x* 11 */
/* * 012345678901 */
/* 0 */ "bbbbbbbbbbbb"
/* 1 */ "bbbbbbbbbbbb"
/* 2 */ "bbabbbbbbbbb"
/* 3 */ "bbbbbbbbbabb"
/* 4 */ "bbbbbbbbbbbb"
/* 5 */ "bbbbbbbbbbbb"
// Level 2
/* z\x* 11 */
/* * 012345678901 */
/* 0 */ "............"
/* 1 */ "............"
/* 2 */ "..c........."
/* 3 */ ".........c.."
/* 4 */ "............"
/* 5 */ "............"
// Level 3
/* z\x* 11 */
/* * 012345678901 */
/* 0 */ "............"
/* 1 */ "............"
/* 2 */ "..c........."
/* 3 */ ".........c.."
/* 4 */ "............"
/* 5 */ "............"
// Level 4
/* z\x* 11 */
/* * 012345678901 */
/* 0 */ "..d........."
/* 1 */ "ddddd......."
/* 2 */ "ddcdd...ddd."
/* 3 */ "ddddd...dcd."
/* 4 */ "..d.....ddd."
/* 5 */ "............"
// Level 5
/* z\x* 11 */
/* * 012345678901 */
/* 0 */ ".ddd........"
/* 1 */ ".ddd....ddd."
/* 2 */ "ddddd..ddddd"
/* 3 */ ".ddd...ddcdd"
/* 4 */ ".ddd...ddddd"
/* 5 */ "........ddd."
// Level 6
/* z\x* 11 */
/* * 012345678901 */
/* 0 */ "............"
/* 1 */ "..d......d.."
/* 2 */ ".ddd....ddd."
/* 3 */ "..d....ddddd"
/* 4 */ "........ddd."
/* 5 */ ".........d.."
// Level 7
/* z\x* 11 */
/* * 012345678901 */
/* 0 */ "............"
/* 1 */ "............"
/* 2 */ "............"
/* 3 */ ".........d.."
/* 4 */ "............"
/* 5 */ "............",
// Connectors:
"-1: -1, 2, 2: 4\n" /* Type -1, direction X- */
"3: 5, 2, 6: 3\n" /* Type 3, direction Z+ */
"-3: 6, 2, -1: 2\n" /* Type -3, direction Z- */
"-3: 12, 2, 2: 5\n" /* Type -3, direction X+ */
"3: 12, 2, 2: 5\n" /* Type 3, direction X+ */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // SakuraDouble
////////////////////////////////////////////////////////////////////////////////
// SakuraSmall:
// The data has been exported from the gallery Plains, area index 145, ID 489, created by Aloe_vera
{
// Size:
5, 7, 5, // SizeX = 5, SizeY = 7, SizeZ = 5
// Hitbox (relative to bounding box):
-1, 0, -1, // MinX, MinY, MinZ
5, 6, 5, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 3: 0\n" /* dirt */
"b: 2: 0\n" /* grass */
"c: 17: 1\n" /* tree */
"d: 35: 6\n" /* wool */
"m: 19: 0\n" /* sponge */,
// Block data:
// Level 0
/* z\x* 01234 */
/* 0 */ "aaaaa"
/* 1 */ "aaaaa"
/* 2 */ "aaaaa"
/* 3 */ "aaaaa"
/* 4 */ "aaaaa"
// Level 1
/* z\x* 01234 */
/* 0 */ "bbbbb"
/* 1 */ "bbbbb"
/* 2 */ "bbabb"
/* 3 */ "bbbbb"
/* 4 */ "bbbbb"
// Level 2
/* z\x* 01234 */
/* 0 */ "....."
/* 1 */ "....."
/* 2 */ "..c.."
/* 3 */ "....."
/* 4 */ "....."
// Level 3
/* z\x* 01234 */
/* 0 */ "....."
/* 1 */ "....."
/* 2 */ "..c.."
/* 3 */ "....."
/* 4 */ "....."
// Level 4
/* z\x* 01234 */
/* 0 */ "..d.."
/* 1 */ "ddddd"
/* 2 */ "ddcdd"
/* 3 */ "ddddd"
/* 4 */ "..d.."
// Level 5
/* z\x* 01234 */
/* 0 */ ".ddd."
/* 1 */ ".ddd."
/* 2 */ "ddddd"
/* 3 */ ".ddd."
/* 4 */ ".ddd."
// Level 6
/* z\x* 01234 */
/* 0 */ "....."
/* 1 */ "..d.."
/* 2 */ ".ddd."
/* 3 */ "..d.."
/* 4 */ ".....",
// Connectors:
"-1: 2, 2, -1: 2\n" /* Type -1, direction Z- */
"3: 5, 2, 2: 5\n" /* Type 3, direction X+ */
"-3: -1, 2, 2: 4\n" /* Type -3, direction X- */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // SakuraSmall
}; // g_JapaneseVillagePrefabs
const cPrefab::sDef g_JapaneseVillageStartingPrefabs[] =
{
////////////////////////////////////////////////////////////////////////////////
// HighTemple:
// The data has been exported from the gallery Plains, area index 70, ID 133, created by Aloe_vera
{
// Size:
11, 19, 11, // SizeX = 11, SizeY = 19, SizeZ = 11
// Hitbox (relative to bounding box):
0, 0, 0, // MinX, MinY, MinZ
10, 18, 10, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 5: 2\n" /* wood */
"b:135: 0\n" /* 135 */
"c:135: 2\n" /* 135 */
"d:135: 1\n" /* 135 */
"e: 17: 9\n" /* tree */
"f:135: 3\n" /* 135 */
"g: 85: 0\n" /* fence */
"h: 17: 1\n" /* tree */
"i:171: 0\n" /* carpet */
"j: 50: 5\n" /* torch */
"k: 35: 0\n" /* wool */
"l: 17: 5\n" /* tree */
"m: 19: 0\n" /* sponge */
"n:124: 0\n" /* redstonelampon */
"o: 69: 9\n" /* lever */
"p: 44: 8\n" /* step */
"q: 43: 0\n" /* doubleslab */
"r: 44: 0\n" /* step */
"s: 50: 4\n" /* torch */
"t: 50: 1\n" /* torch */
"u: 50: 3\n" /* torch */,
// Block data:
// Level 0
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "mmmaaaaammm"
/* 1 */ "maaaaaaaaam"
/* 2 */ "maaaaaaaaam"
/* 3 */ "aaaaaaaaaaa"
/* 4 */ "aaaaaaaaaaa"
/* 5 */ "aaaaaaaaaaa"
/* 6 */ "aaaaaaaaaaa"
/* 7 */ "aaaaaaaaaaa"
/* 8 */ "maaaaaaaaam"
/* 9 */ "maaaaaaaaam"
/* 10 */ "mmmaaaaammm"
// Level 1
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "...bcccd..."
/* 1 */ ".aaaaaaaaa."
/* 2 */ ".aaaaaaaaa."
/* 3 */ "caaaaaaaaac"
/* 4 */ "baaaaaaaaad"
/* 5 */ "baaeaaaaaad"
/* 6 */ "baaaaaaaaad"
/* 7 */ "faaaaaaaaaf"
/* 8 */ ".aaaaaaaaa."
/* 9 */ ".aaaaaaaaa."
/* 10 */ "...bfffd..."
// Level 2
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ ".ggg...ggg."
/* 2 */ ".g.......g."
/* 3 */ ".g.hhhhh.g."
/* 4 */ "...hiiih..."
/* 5 */ "....iiih..."
/* 6 */ "...hiiih..."
/* 7 */ ".g.hhhhh.g."
/* 8 */ ".g.......g."
/* 9 */ ".ggg...ggg."
/* 10 */ "..........."
// Level 3
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ ".j.g...g.j."
/* 2 */ "..........."
/* 3 */ ".g.kkhkk.g."
/* 4 */ "...h...k..."
/* 5 */ ".......h..."
/* 6 */ "...h...k..."
/* 7 */ ".g.kkhkk.g."
/* 8 */ "..........."
/* 9 */ ".j.g...g.j."
/* 10 */ "..........."
// Level 4
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "...g...g..."
/* 2 */ "..........."
/* 3 */ ".g.kkhkk.g."
/* 4 */ "...h...k..."
/* 5 */ "...k...h..."
/* 6 */ "...h...k..."
/* 7 */ ".g.kkhkk.g."
/* 8 */ "..........."
/* 9 */ "...g...g..."
/* 10 */ "..........."
// Level 5
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "...g...g..."
/* 2 */ "...ggggg..."
/* 3 */ ".gghlhlhgg."
/* 4 */ "..ge...eg.."
/* 5 */ "..ge.nohg.."
/* 6 */ "..ge...eg.."
/* 7 */ ".gghlhlhgg."
/* 8 */ "...ggggg..."
/* 9 */ "...g...g..."
/* 10 */ "..........."
// Level 6
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..pqrrrqp.."
/* 2 */ ".pqqqqqqqp."
/* 3 */ ".qqhkkkhqq."
/* 4 */ ".rqkhhhkqr."
/* 5 */ ".rqkhhhkqr."
/* 6 */ ".rqkhhhkqr."
/* 7 */ ".qqhkkkhqq."
/* 8 */ ".pqqqqqqqp."
/* 9 */ "..pqrrrqp.."
/* 10 */ "..........."
// Level 7
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ ".qr.....rq."
/* 2 */ ".........r."
/* 3 */ "...hhhhh..."
/* 4 */ "...hiiih..."
/* 5 */ "....iiih..."
/* 6 */ "...hiiih..."
/* 7 */ "...hhhhh..."
/* 8 */ ".r.......r."
/* 9 */ ".qr.....rq."
/* 10 */ "..........."
// Level 8
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..........."
/* 2 */ "..........."
/* 3 */ "...kkhkk..."
/* 4 */ "...h...k..."
/* 5 */ ".......h..."
/* 6 */ "...h...k..."
/* 7 */ "...kkhkk..."
/* 8 */ "..........."
/* 9 */ "..........."
/* 10 */ "..........."
// Level 9
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..........."
/* 2 */ ".....s....."
/* 3 */ "...kkhkk..."
/* 4 */ "...h...k..."
/* 5 */ "...k...ht.."
/* 6 */ "...h...k..."
/* 7 */ "...kkhkk..."
/* 8 */ ".....u....."
/* 9 */ "..........."
/* 10 */ "..........."
// Level 10
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..........."
/* 2 */ "...ggggg..."
/* 3 */ "..ghlhlhg.."
/* 4 */ "..ge...eg.."
/* 5 */ "..ge.nohg.."
/* 6 */ "..ge...eg.."
/* 7 */ "..ghlhlhg.."
/* 8 */ "...ggggg..."
/* 9 */ "..........."
/* 10 */ "..........."
// Level 11
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..prrrrrp.."
/* 2 */ ".pqqqqqqqp."
/* 3 */ ".qqhkkkhqq."
/* 4 */ ".rqkhhhkqr."
/* 5 */ ".rqkhhhkqr."
/* 6 */ ".rqkhhhkqr."
/* 7 */ ".qqhkkkhqr."
/* 8 */ ".pqqqqqqqp."
/* 9 */ "..pqrrrqp.."
/* 10 */ "..........."
// Level 12
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ ".qr.....rq."
/* 2 */ ".r.......r."
/* 3 */ "...hhhhh..."
/* 4 */ "...hiiih..."
/* 5 */ "....iiih..."
/* 6 */ "...hiiih..."
/* 7 */ "...hhhhh..."
/* 8 */ ".r.......r."
/* 9 */ ".qr.....rq."
/* 10 */ "..........."
// Level 13
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..........."
/* 2 */ "..........."
/* 3 */ "...kkhkk..."
/* 4 */ "...h...k..."
/* 5 */ ".......h..."
/* 6 */ "...h...k..."
/* 7 */ "...kkhkk..."
/* 8 */ "..........."
/* 9 */ "..........."
/* 10 */ "..........."
// Level 14
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..........."
/* 2 */ ".....s....."
/* 3 */ "...kkhkk..."
/* 4 */ "...h...k..."
/* 5 */ "...k...ht.."
/* 6 */ "...h...k..."
/* 7 */ "...kkhkk..."
/* 8 */ ".....u....."
/* 9 */ "..........."
/* 10 */ "..........."
// Level 15
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..........."
/* 2 */ "...ggggg..."
/* 3 */ "..ghlhlhg.."
/* 4 */ "..ge...eg.."
/* 5 */ "..ge.nohg.."
/* 6 */ "..ge...eg.."
/* 7 */ "..ghlhlhg.."
/* 8 */ "...ggggg..."
/* 9 */ "..........."
/* 10 */ "..........."
// Level 16
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..pqrrrqp.."
/* 2 */ ".pqqqqqqqp."
/* 3 */ ".qqrrrrrqq."
/* 4 */ ".rqrrrrrqr."
/* 5 */ ".rqrrrrrqr."
/* 6 */ ".rqrrrrrqr."
/* 7 */ ".qqrrrrrqq."
/* 8 */ ".pqqqqqqqp."
/* 9 */ "..pqrrrqp.."
/* 10 */ "..........."
// Level 17
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ ".qr.....rq."
/* 2 */ ".rr.....rr."
/* 3 */ "...rrrrr..."
/* 4 */ "...rqqqr..."
/* 5 */ "...rqqqr..."
/* 6 */ "...rqqqr..."
/* 7 */ "...rrrrr..."
/* 8 */ ".rr.....rr."
/* 9 */ ".qr.....rq."
/* 10 */ "..........."
// Level 18
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..........."
/* 2 */ "..........."
/* 3 */ "..........."
/* 4 */ "..........."
/* 5 */ ".....r....."
/* 6 */ "..........."
/* 7 */ "..........."
/* 8 */ "..........."
/* 9 */ "..........."
/* 10 */ "...........",
// Connectors:
"2: 0, 1, 5: 4\n" /* Type 2, direction X- */
"2: 5, 1, 0: 2\n" /* Type 2, direction Z- */
"2: 10, 1, 5: 5\n" /* Type 2, direction X+ */
"2: 5, 1, 10: 3\n" /* Type 2, direction Z+ */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // HighTemple
////////////////////////////////////////////////////////////////////////////////
// Well:
// The data has been exported from the gallery Plains, area index 143, ID 487, created by STR_Warrior
{
// Size:
7, 14, 7, // SizeX = 7, SizeY = 14, SizeZ = 7
// Hitbox (relative to bounding box):
0, 0, 0, // MinX, MinY, MinZ
6, 13, 6, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 1: 0\n" /* stone */
"b: 4: 0\n" /* cobblestone */
"c: 8: 0\n" /* water */
"d: 13: 0\n" /* gravel */
"e: 67: 1\n" /* stairs */
"f: 67: 2\n" /* stairs */
"g: 67: 0\n" /* stairs */
"h: 67: 3\n" /* stairs */
"i: 85: 0\n" /* fence */
"j: 44: 8\n" /* step */
"k: 44: 0\n" /* step */
"l: 43: 0\n" /* doubleslab */
"m: 19: 0\n" /* sponge */,
// Block data:
// Level 0
/* z\x* 0123456 */
/* 0 */ "mmmmmmm"
/* 1 */ "maaaaam"
/* 2 */ "maaaaam"
/* 3 */ "maaaaam"
/* 4 */ "maaaaam"
/* 5 */ "maaaaam"
/* 6 */ "mmmmmmm"
// Level 1
/* z\x* 0123456 */
/* 0 */ "mmmmmmm"
/* 1 */ "mbbbbbm"
/* 2 */ "mbcc.bm"
/* 3 */ "mbcccbm"
/* 4 */ "mbcccbm"
/* 5 */ "mbbbbbm"
/* 6 */ "mmmmmmm"
// Level 2
/* z\x* 0123456 */
/* 0 */ "mmmmmmm"
/* 1 */ "mbbbbbm"
/* 2 */ "mbcccbm"
/* 3 */ "mbcccbm"
/* 4 */ "mbcccbm"
/* 5 */ "mbbbbbm"
/* 6 */ "mmmmmmm"
// Level 3
/* z\x* 0123456 */
/* 0 */ "mmmmmmm"
/* 1 */ "mbbbbbm"
/* 2 */ "mbcccbm"
/* 3 */ "mbcccbm"
/* 4 */ "mbcccbm"
/* 5 */ "mbbbbbm"
/* 6 */ "mmmmmmm"
// Level 4
/* z\x* 0123456 */
/* 0 */ "mmmmmmm"
/* 1 */ "mbbbbbm"
/* 2 */ "mbcccbm"
/* 3 */ "mbcccbm"
/* 4 */ "mbcccbm"
/* 5 */ "mbbbbbm"
/* 6 */ "mmmmmmm"
// Level 5
/* z\x* 0123456 */
/* 0 */ "mmmmmmm"
/* 1 */ "mbbbbbm"
/* 2 */ "mbcccbm"
/* 3 */ "mbcccbm"
/* 4 */ "mbcccbm"
/* 5 */ "mbbbbbm"
/* 6 */ "mmmmmmm"
// Level 6
/* z\x* 0123456 */
/* 0 */ "mmmmmmm"
/* 1 */ "mbbbbbm"
/* 2 */ "mbcccbm"
/* 3 */ "mbcccbm"
/* 4 */ "mbcccbm"
/* 5 */ "mbbbbbm"
/* 6 */ "mmmmmmm"
// Level 7
/* z\x* 0123456 */
/* 0 */ "mmbbbmm"
/* 1 */ "mbbbbbm"
/* 2 */ "bbcccbb"
/* 3 */ "bbcccbb"
/* 4 */ "bbcccbb"
/* 5 */ "mbbbbbm"
/* 6 */ "mmbbbmm"
// Level 8
/* z\x* 0123456 */
/* 0 */ "mmdddmm"
/* 1 */ "mbbbbbm"
/* 2 */ "dbcccbd"
/* 3 */ "dbcccbd"
/* 4 */ "dbcccbd"
/* 5 */ "mbbbbbm"
/* 6 */ "mmdddmm"
// Level 9
/* z\x* 0123456 */
/* 0 */ "mm...mm"
/* 1 */ "mbefgbm"
/* 2 */ ".h...h."
/* 3 */ ".g...e."
/* 4 */ ".f...f."
/* 5 */ "mbehgbm"
/* 6 */ "mm...mm"
// Level 10
/* z\x* 0123456 */
/* 0 */ "mm...mm"
/* 1 */ "mi...im"
/* 2 */ "......."
/* 3 */ "......."
/* 4 */ "......."
/* 5 */ "mi...im"
/* 6 */ "mm...mm"
// Level 11
/* z\x* 0123456 */
/* 0 */ "mm...mm"
/* 1 */ "mi...im"
/* 2 */ "......."
/* 3 */ "......."
/* 4 */ "......."
/* 5 */ "mi...im"
/* 6 */ "mm...mm"
// Level 12
/* z\x* 0123456 */
/* 0 */ "mjkkkjm"
/* 1 */ "jlllllj"
/* 2 */ "klllllk"
/* 3 */ "klllllk"
/* 4 */ "klllllk"
/* 5 */ "jlllllj"
/* 6 */ "mjkkkjm"
// Level 13
/* z\x* 0123456 */
/* 0 */ "k.....k"
/* 1 */ "......."
/* 2 */ "..kkk.."
/* 3 */ "..klk.."
/* 4 */ "..kkk.."
/* 5 */ "......."
/* 6 */ "k.....k",
// Connectors:
"2: 0, 9, 3: 4\n" /* Type 2, direction X- */
"2: 3, 9, 0: 2\n" /* Type 2, direction Z- */
"2: 6, 9, 3: 5\n" /* Type 2, direction X+ */
"2: 3, 9, 6: 3\n" /* Type 2, direction Z+ */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // Well
};
// The prefab counts:
const size_t g_JapaneseVillagePrefabsCount = ARRAYCOUNT(g_JapaneseVillagePrefabs);
const size_t g_JapaneseVillageStartingPrefabsCount = ARRAYCOUNT(g_JapaneseVillageStartingPrefabs);
| linnemannr/MCServer | src/Generating/Prefabs/JapaneseVillagePrefabs.cpp | C++ | apache-2.0 | 77,972 |
/*
* Copyright 2015 the original author or authors.
* @https://github.com/scouter-project/scouter
*
* 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 scouter.client.stack.config.preprocessor;
import org.w3c.dom.Node;
public class ProcessorReplace extends Processor{
private String m_source = null;
private String m_target = null;
private boolean m_isAll = true;
public ProcessorReplace(){
setType(Processor.TYPE.REPLACE);
}
public String process(String line) {
if(m_isAll){
return line.replaceAll(m_source, m_target);
}else{
return line.replaceFirst(m_source, m_target);
}
}
public void readConfig(ParserPreProcessorReader reader, Node node) {
try {
m_source = reader.getAttribute(node, "source");
m_target = reader.getAttribute(node, "target");
}catch(Exception ex){
throw new RuntimeException(ex);
}
String isAll = null;
try {
isAll = reader.getAttribute(node, "all");
}catch(Exception ex){
}
if(isAll != null){
try {
m_isAll = Boolean.parseBoolean(isAll);
}catch(Exception ex){
throw new RuntimeException("all attribute(true/false) of replace type processor is abnormal!(" + isAll + ")");
}
}
}
}
| yuyupapa/OpenSource | scouter.client/src/scouter/client/stack/config/preprocessor/ProcessorReplace.java | Java | apache-2.0 | 1,720 |
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2005, 2006, 2007, 2008 The Sakai Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.portal.service;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pluto.core.PortletContextManager;
import org.apache.pluto.descriptors.portlet.PortletAppDD;
import org.apache.pluto.descriptors.portlet.PortletDD;
import org.apache.pluto.internal.InternalPortletContext;
import org.apache.pluto.spi.optional.PortletRegistryService;
import org.exolab.castor.util.LocalConfiguration;
import org.exolab.castor.util.Configuration.Property;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.portal.api.BaseEditor;
import org.sakaiproject.portal.api.Editor;
import org.sakaiproject.portal.api.EditorRegistry;
import org.sakaiproject.portal.api.Portal;
import org.sakaiproject.portal.api.PortalHandler;
import org.sakaiproject.portal.api.PortalRenderEngine;
import org.sakaiproject.portal.api.PortalService;
import org.sakaiproject.portal.api.PortletApplicationDescriptor;
import org.sakaiproject.portal.api.PortletDescriptor;
import org.sakaiproject.portal.api.SiteNeighbourhoodService;
import org.sakaiproject.portal.api.StoredState;
import org.sakaiproject.portal.api.StyleAbleProvider;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.tool.api.Placement;
import org.sakaiproject.tool.api.Session;
import org.sakaiproject.tool.cover.SessionManager;
/**
* @author ieb
* @since Sakai 2.4
* @version $Rev$
*/
public class PortalServiceImpl implements PortalService
{
private static final Log log = LogFactory.getLog(PortalServiceImpl.class);
/**
* Parameter to force state reset
*/
public static final String PARM_STATE_RESET = "sakai.state.reset";
private static final String PORTAL_SKIN_NEOPREFIX_PROPERTY = "portal.neoprefix";
private static final String PORTAL_SKIN_NEOPREFIX_DEFAULT = "neo-";
private static String portalSkinPrefix;
private Map<String, PortalRenderEngine> renderEngines = new ConcurrentHashMap<String, PortalRenderEngine>();
private Map<String, Map<String, PortalHandler>> handlerMaps = new ConcurrentHashMap<String, Map<String, PortalHandler>>();
private Map<String, Portal> portals = new ConcurrentHashMap<String, Portal>();
private ServerConfigurationService serverConfigurationService;
private StyleAbleProvider stylableServiceProvider;
private SiteNeighbourhoodService siteNeighbourhoodService;
private String m_portalLinks;
private ContentHostingService contentHostingService;
private EditorRegistry editorRegistry;
private Editor noopEditor = new BaseEditor("noop", "noop", "", "");
public void init()
{
try
{
stylableServiceProvider = (StyleAbleProvider) ComponentManager
.get(StyleAbleProvider.class.getName());
serverConfigurationService = (ServerConfigurationService) ComponentManager
.get(ServerConfigurationService.class.getName());
try
{
// configure the parser for castor.. before anything else get a
// chance
Properties castorProperties = LocalConfiguration.getDefault();
String parser = serverConfigurationService.getString(
"sakai.xml.sax.parser",
"com.sun.org.apache.xerces.internal.parsers.SAXParser");
log.info("Configured Castor to use SAX Parser " + parser);
castorProperties.put(Property.Parser, parser);
}
catch (Exception ex)
{
log.error("Failed to configure Castor", ex);
}
portalSkinPrefix = serverConfigurationService.getString(PORTAL_SKIN_NEOPREFIX_PROPERTY, PORTAL_SKIN_NEOPREFIX_DEFAULT);
if (portalSkinPrefix == null) {
portalSkinPrefix = "";
}
}
catch (Exception ex)
{
}
if (stylableServiceProvider == null)
{
log.info("No Styleable Provider found, the portal will not be stylable");
}
}
public StoredState getStoredState()
{
Session s = SessionManager.getCurrentSession();
StoredState ss = (StoredState) s.getAttribute("direct-stored-state");
log.debug("Got Stored State as [" + ss + "]");
return ss;
}
public void setStoredState(StoredState ss)
{
Session s = SessionManager.getCurrentSession();
if (s.getAttribute("direct-stored-state") == null || ss == null)
{
StoredState ssx = (StoredState) s.getAttribute("direct-stored-state");
log.debug("Removing Stored state " + ssx);
if (ssx != null)
{
Exception ex = new Exception("traceback");
log.debug("Removing active Stored State Traceback gives location ", ex);
}
s.setAttribute("direct-stored-state", ss);
log.debug(" Set StoredState as [" + ss + "]");
}
}
private static final String TOOLSTATE_PARAM_PREFIX = "toolstate-";
private static String computeToolStateParameterName(String placementId)
{
return TOOLSTATE_PARAM_PREFIX + placementId;
}
public String decodeToolState(Map<String, String[]> params, String placementId)
{
String attrname = computeToolStateParameterName(placementId);
String[] attrval = params.get(attrname);
return attrval == null ? null : attrval[0];
}
public Map<String, String[]> encodeToolState(String placementId, String URLstub)
{
String attrname = computeToolStateParameterName(placementId);
Map<String, String[]> togo = new HashMap<String, String[]>();
// could assemble state from other visible tools here
togo.put(attrname, new String[] { URLstub });
return togo;
}
// To allow us to retain reset state across redirects
public String getResetState()
{
Session s = SessionManager.getCurrentSession();
String ss = (String) s.getAttribute("reset-stored-state");
return ss;
}
public void setResetState(String ss)
{
Session s = SessionManager.getCurrentSession();
if (s.getAttribute("reset-stored-state") == null || ss == null)
{
s.setAttribute("reset-stored-state", ss);
}
}
public boolean isEnableDirect()
{
boolean directEnable = "true".equals(serverConfigurationService.getString(
"charon.directurl", "true"));
log.debug("Direct Enable is " + directEnable);
return directEnable;
}
public boolean isResetRequested(HttpServletRequest req)
{
return "true".equals(req.getParameter(PARM_STATE_RESET))
|| "true".equals(getResetState());
}
public String getResetStateParam()
{
// TODO Auto-generated method stub
return PARM_STATE_RESET;
}
public StoredState newStoredState(String marker, String replacement)
{
log.debug("Storing State for Marker=[" + marker + "] replacement=[" + replacement
+ "]");
return new StoredStateImpl(marker, replacement);
}
public Iterator<PortletApplicationDescriptor> getRegisteredApplications()
{
PortletRegistryService registry = PortletContextManager.getManager();
final Iterator apps = registry.getRegisteredPortletApplications();
return new Iterator<PortletApplicationDescriptor>()
{
public boolean hasNext()
{
return apps.hasNext();
}
public PortletApplicationDescriptor next()
{
final InternalPortletContext pc = (InternalPortletContext) apps.next();
final PortletAppDD appDD = pc.getPortletApplicationDefinition();
return new PortletApplicationDescriptor()
{
public String getApplicationContext()
{
return pc.getPortletContextName();
}
public String getApplicationId()
{
return pc.getApplicationId();
}
public String getApplicationName()
{
return pc.getApplicationId();
}
public Iterator<PortletDescriptor> getPortlets()
{
if (appDD != null)
{
List portlets = appDD.getPortlets();
final Iterator portletsI = portlets.iterator();
return new Iterator<PortletDescriptor>()
{
public boolean hasNext()
{
return portletsI.hasNext();
}
public PortletDescriptor next()
{
final PortletDD pdd = (PortletDD) portletsI.next();
return new PortletDescriptor()
{
public String getPortletId()
{
return pdd.getPortletName();
}
public String getPortletName()
{
return pdd.getPortletName();
}
};
}
public void remove()
{
}
};
}
else
{
log.warn(" Portlet Application has no portlets "
+ pc.getPortletContextName());
return new Iterator<PortletDescriptor>()
{
public boolean hasNext()
{
return false;
}
public PortletDescriptor next()
{
return null;
}
public void remove()
{
}
};
}
}
};
}
public void remove()
{
}
};
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.portal.api.PortalService#getRenderEngine(javax.servlet.http.HttpServletRequest)
*/
public PortalRenderEngine getRenderEngine(String context, HttpServletRequest request)
{
// at this point we ignore request but we might use ut to return more
// than one render engine
if (context == null || context.length() == 0)
{
context = Portal.DEFAULT_PORTAL_CONTEXT;
}
return (PortalRenderEngine) renderEngines.get(context);
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.portal.api.PortalService#addRenderEngine(org.sakaiproject.portal.api.PortalRenderEngine)
*/
public void addRenderEngine(String context, PortalRenderEngine vengine)
{
renderEngines.put(context, vengine);
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.portal.api.PortalService#removeRenderEngine(org.sakaiproject.portal.api.PortalRenderEngine)
*/
public void removeRenderEngine(String context, PortalRenderEngine vengine)
{
renderEngines.remove(context);
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.portal.api.PortalService#addHandler(java.lang.String,
* org.sakaiproject.portal.api.PortalHandler)
*/
public void addHandler(Portal portal, PortalHandler handler)
{
String portalContext = portal.getPortalContext();
Map<String, PortalHandler> handlerMap = getHandlerMap(portal);
String urlFragment = handler.getUrlFragment();
PortalHandler ph = handlerMap.get(urlFragment);
if (ph != null)
{
handler.deregister(portal);
log.warn("Handler Present on " + urlFragment + " will replace " + ph
+ " with " + handler);
}
handler.register(portal, this, portal.getServletContext());
handlerMap.put(urlFragment, handler);
log.info("URL " + portalContext + ":/" + urlFragment + " will be handled by "
+ handler);
}
public void addHandler(String portalContext, PortalHandler handler)
{
Portal portal = portals.get(portalContext);
if (portal == null)
{
Map<String, PortalHandler> handlerMap = getHandlerMap(portalContext, true);
handlerMap.put(handler.getUrlFragment(), handler);
log.debug("Registered handler ("+ handler+ ") for portal ("+portalContext+ ") that doesn't yet exist.");
}
else
{
addHandler(portal, handler);
}
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.portal.api.PortalService#getHandlerMap(java.lang.String)
*/
public Map<String, PortalHandler> getHandlerMap(Portal portal)
{
return getHandlerMap(portal.getPortalContext(), true);
}
private Map<String, PortalHandler> getHandlerMap(String portalContext, boolean create)
{
Map<String, PortalHandler> handlerMap = handlerMaps.get(portalContext);
if (create && handlerMap == null)
{
handlerMap = new ConcurrentHashMap<String, PortalHandler>();
handlerMaps.put(portalContext, handlerMap);
}
return handlerMap;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.portal.api.PortalService#removeHandler(java.lang.String,
* java.lang.String) This method it NOT thread safe, but the likelyhood
* of a co
*/
public void removeHandler(Portal portal, String urlFragment)
{
Map<String, PortalHandler> handlerMap = getHandlerMap(portal.getPortalContext(), false);
if (handlerMap != null)
{
PortalHandler ph = handlerMap.get(urlFragment);
if (ph != null)
{
ph.deregister(portal);
handlerMap.remove(urlFragment);
log.warn("Handler Present on " + urlFragment + " " + ph
+ " will be removed ");
}
}
}
public void removeHandler(String portalContext, String urlFragment)
{
Portal portal = portals.get(portalContext);
if (portal == null)
{
log.warn("Attempted to remove handler("+ urlFragment+ ") from non existent portal ("+portalContext+")");
}
else
{
removeHandler(portal, urlFragment);
}
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.portal.api.PortalService#addPortal(org.sakaiproject.portal.api.Portal)
*/
public void addPortal(Portal portal)
{
String portalContext = portal.getPortalContext();
portals.put(portalContext, portal);
// reconnect any handlers
Map<String, PortalHandler> phm = getHandlerMap(portal);
for (Iterator<PortalHandler> pIterator = phm.values().iterator(); pIterator
.hasNext();)
{
PortalHandler ph = pIterator.next();
ph.register(portal, this, portal.getServletContext());
}
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.portal.api.PortalService#removePortal(org.sakaiproject.portal.api.Portal)
*/
public void removePortal(Portal portal)
{
String portalContext = portal.getPortalContext();
portals.remove(portalContext);
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.portal.api.PortalService#getStylableService()
*/
public StyleAbleProvider getStylableService()
{
return stylableServiceProvider;
}
/* (non-Javadoc)
* @see org.sakaiproject.portal.api.PortalService#getSiteNeighbourhoodService()
*/
public SiteNeighbourhoodService getSiteNeighbourhoodService()
{
return siteNeighbourhoodService;
}
/**
* @param siteNeighbourhoodService the siteNeighbourhoodService to set
*/
public void setSiteNeighbourhoodService(SiteNeighbourhoodService siteNeighbourhoodService)
{
this.siteNeighbourhoodService = siteNeighbourhoodService;
}
/* optional portal links for portal header (SAK-22912)
*/
public String getPortalLinks()
{
return m_portalLinks;
}
public ContentHostingService getContentHostingService() {
return contentHostingService;
}
/**
* @param portalLinks the portal icons to set
*/
public void setPortalLinks(String portalLinks)
{
m_portalLinks = portalLinks;
}
public void setContentHostingService(ContentHostingService contentHostingService) {
this.contentHostingService = contentHostingService;
}
public String getBrowserCollectionId(Placement placement) {
String collectionId = null;
if (placement != null) {
collectionId = getContentHostingService().getSiteCollection(placement.getContext());
}
if (collectionId == null) {
collectionId = getContentHostingService().getSiteCollection("~" + SessionManager.getCurrentSessionUserId());
}
return collectionId;
}
public Editor getActiveEditor() {
return getActiveEditor(null);
}
public Editor getActiveEditor(Placement placement) {
String systemEditor = serverConfigurationService.getString("wysiwyg.editor", "ckeditor");
String activeEditor = systemEditor;
if (placement != null) {
//Allow tool- or user-specific editors?
try {
Site site = SiteService.getSite(placement.getContext());
Object o = site.getProperties().get("wysiwyg.editor");
if (o != null) {
activeEditor = o.toString();
}
}
catch (IdUnusedException ex) {
if (log.isDebugEnabled()) {
log.debug(ex.getMessage());
}
}
}
Editor editor = getEditorRegistry().getEditor(activeEditor);
if (editor == null) {
// Load a base no-op editor so sakai.editor.launch calls succeed.
// We may decide to offer some textarea infrastructure as well. In
// this case, there are editor and launch files being consulted
// already from /library/, which is easier to patch and deploy.
editor = getEditorRegistry().getEditor("textarea");
}
if (editor == null) {
// If, for some reason, our stub editor is null, give an instance
// that doesn't even try to load files. This will result in script
// errors because sakai.editor.launch will not be defined, but
// this way, we can't suffer NPEs. In some cases, this degradation
// will be graceful enough that the page can function.
editor = noopEditor;
}
return editor;
}
public EditorRegistry getEditorRegistry() {
return editorRegistry;
}
public void setEditorRegistry(EditorRegistry editorRegistry) {
this.editorRegistry = editorRegistry;
}
public String getSkinPrefix() {
return portalSkinPrefix;
}
}
| marktriggs/nyu-sakai-10.4 | portal/portal-service-impl/impl/src/java/org/sakaiproject/portal/service/PortalServiceImpl.java | Java | apache-2.0 | 17,816 |
/*
* 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.giraph.hive.input.vertex;
import org.apache.giraph.edge.Edge;
import org.apache.giraph.edge.OutEdges;
import org.apache.giraph.graph.Vertex;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import com.facebook.hiveio.record.HiveReadableRecord;
import java.util.Iterator;
/**
* Simple implementation of {@link HiveToVertex} when each vertex is in the one
* row of the input.
*
* @param <I> Vertex ID
* @param <V> Vertex Value
* @param <E> Edge Value
*/
public abstract class SimpleHiveToVertex<I extends WritableComparable,
V extends Writable, E extends Writable>
extends AbstractHiveToVertex<I, V, E> {
/** Hive records which we are reading from */
private Iterator<HiveReadableRecord> records;
/** Reusable vertex object */
private Vertex<I, V, E> reusableVertex;
/** Reusable vertex id */
private I reusableVertexId;
/** Reusable vertex value */
private V reusableVertexValue;
/** Reusable edges */
private OutEdges<I, E> reusableOutEdges;
/**
* Read the Vertex's ID from the HiveRecord given.
*
* @param record HiveRecord to read from.
* @return Vertex ID
*/
public abstract I getVertexId(HiveReadableRecord record);
/**
* Read the Vertex's Value from the HiveRecord given.
*
* @param record HiveRecord to read from.
* @return Vertex Value
*/
public abstract V getVertexValue(HiveReadableRecord record);
/**
* Read Vertex's edges from the HiveRecord given.
*
* @param record HiveRecord to read from.
* @return iterable of edges
*/
public abstract Iterable<Edge<I, E>> getEdges(HiveReadableRecord record);
@Override
public void initializeRecords(Iterator<HiveReadableRecord> records) {
this.records = records;
reusableVertex = getConf().createVertex();
reusableVertexId = getConf().createVertexId();
reusableVertexValue = getConf().createVertexValue();
reusableOutEdges = getConf().createOutEdges();
}
@Override
public boolean hasNext() {
return records.hasNext();
}
@Override
public Vertex<I, V, E> next() {
HiveReadableRecord record = records.next();
I id = getVertexId(record);
V value = getVertexValue(record);
Iterable<Edge<I, E>> edges = getEdges(record);
reusableVertex.initialize(id, value, edges);
return reusableVertex;
}
protected I getReusableVertexId() {
return reusableVertexId;
}
protected V getReusableVertexValue() {
return reusableVertexValue;
}
/**
* Get reusable OutEdges object
*
* @param <OE> Type of OutEdges
* @return Reusable OutEdges object
*/
protected <OE extends OutEdges<I, E>> OE getReusableOutEdges() {
return (OE) reusableOutEdges;
}
}
| basio/graph | giraph-hive/src/main/java/org/apache/giraph/hive/input/vertex/SimpleHiveToVertex.java | Java | apache-2.0 | 3,548 |
//-----------------------------------------------------------------------
// <copyright file="GraphMatValueSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Linq;
using System.Threading.Tasks;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit;
using Akka.TestKit;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
using Akka.Actor;
// ReSharper disable InvokeAsExtensionMethod
namespace Akka.Streams.Tests.Dsl
{
public class GraphMatValueSpec : AkkaSpec
{
public GraphMatValueSpec(ITestOutputHelper helper) : base(helper) { }
private static Sink<int, Task<int>> FoldSink => Sink.Aggregate<int,int>(0, (sum, i) => sum + i);
private IMaterializer CreateMaterializer(bool autoFusing)
{
var settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(2, 16).WithAutoFusing(autoFusing);
return Sys.Materializer(settings);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_Graph_with_materialized_value_must_expose_the_materialized_value_as_source(bool autoFusing)
{
var materializer = CreateMaterializer(autoFusing);
var sub = this.CreateManualSubscriberProbe<int>();
var f = RunnableGraph.FromGraph(GraphDsl.Create(FoldSink, (b, fold) =>
{
var source = Source.From(Enumerable.Range(1, 10)).MapMaterializedValue(_ => Task.FromResult(0));
b.From(source).To(fold);
b.From(b.MaterializedValue)
.Via(Flow.Create<Task<int>>().SelectAsync(4, x => x))
.To(Sink.FromSubscriber(sub).MapMaterializedValue(_ => Task.FromResult(0)));
return ClosedShape.Instance;
})).Run(materializer);
f.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
var r1 = f.Result;
sub.ExpectSubscription().Request(1);
var r2 = sub.ExpectNext();
r1.Should().Be(r2);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_Graph_with_materialized_value_must_expose_the_materialized_value_as_source_multiple_times(bool autoFusing)
{
var materializer = CreateMaterializer(autoFusing);
var sub = this.CreateManualSubscriberProbe<int>();
var f = RunnableGraph.FromGraph(GraphDsl.Create(FoldSink, (b, fold) =>
{
var zip = b.Add(new ZipWith<int, int, int>((i, i1) => i + i1));
var source = Source.From(Enumerable.Range(1, 10)).MapMaterializedValue(_ => Task.FromResult(0));
b.From(source).To(fold);
b.From(b.MaterializedValue)
.Via(Flow.Create<Task<int>>().SelectAsync(4, x => x))
.To(zip.In0);
b.From(b.MaterializedValue)
.Via(Flow.Create<Task<int>>().SelectAsync(4, x => x))
.To(zip.In1);
b.From(zip.Out).To(Sink.FromSubscriber(sub).MapMaterializedValue(_ => Task.FromResult(0)));
return ClosedShape.Instance;
})).Run(materializer);
f.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
var r1 = f.Result;
sub.ExpectSubscription().Request(1);
var r2 = sub.ExpectNext();
r1.Should().Be(r2/2);
}
// Exposes the materialized value as a stream value
private static Source<Task<int>, Task<int>> FoldFeedbackSource => Source.FromGraph(GraphDsl.Create(FoldSink,
(b, fold) =>
{
var source = Source.From(Enumerable.Range(1, 10));
var shape = b.Add(source);
b.From(shape).To(fold);
return new SourceShape<Task<int>>(b.MaterializedValue);
}));
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_Graph_with_materialized_value_must_allow_exposing_the_materialized_value_as_port(bool autoFusing)
{
var materializer = CreateMaterializer(autoFusing);
var t =
FoldFeedbackSource.SelectAsync(4, x => x)
.Select(x => x + 100)
.ToMaterialized(Sink.First<int>(), Keep.Both)
.Run(materializer);
var f1 = t.Item1;
var f2 = t.Item2;
f1.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
f1.Result.Should().Be(55);
f2.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
f2.Result.Should().Be(155);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_Graph_with_materialized_value_must_allow_exposing_the_materialized_values_as_port_even_if_wrapped_and_the_final_materialized_value_is_unit(bool autoFusing)
{
var materializer = CreateMaterializer(autoFusing);
var noMatSource =
FoldFeedbackSource.SelectAsync(4, x => x).Select(x => x + 100).MapMaterializedValue(_ => NotUsed.Instance);
var t = noMatSource.RunWith(Sink.First<int>(), materializer);
t.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
t.Result.Should().Be(155);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_Graph_with_materialized_value_must_work_properly_with_nesting_and_reusing(bool autoFusing)
{
var materializer = CreateMaterializer(autoFusing);
var compositeSource1 = Source.FromGraph(GraphDsl.Create(FoldFeedbackSource, FoldFeedbackSource, Keep.Both,
(b, s1, s2) =>
{
var zip = b.Add(new ZipWith<int, int, int>((i, i1) => i + i1));
b.From(s1.Outlet).Via(Flow.Create<Task<int>>().SelectAsync(4, x => x)).To(zip.In0);
b.From(s2.Outlet).Via(Flow.Create<Task<int>>().SelectAsync(4, x => x).Select(x => x*100)).To(zip.In1);
return new SourceShape<int>(zip.Out);
}));
var compositeSource2 = Source.FromGraph(GraphDsl.Create(compositeSource1, compositeSource1, Keep.Both,
(b, s1, s2) =>
{
var zip = b.Add(new ZipWith<int, int, int>((i, i1) => i + i1));
b.From(s1.Outlet).To(zip.In0);
b.From(s2.Outlet).Via(Flow.Create<int>().Select(x => x*10000)).To(zip.In1);
return new SourceShape<int>(zip.Out);
}));
var t = compositeSource2.ToMaterialized(Sink.First<int>(), Keep.Both).Run(materializer);
var task = Task.WhenAll(t.Item1.Item1.Item1, t.Item1.Item1.Item2, t.Item1.Item2.Item1, t.Item1.Item2.Item2, t.Item2);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result[0].Should().Be(55);
task.Result[1].Should().Be(55);
task.Result[2].Should().Be(55);
task.Result[3].Should().Be(55);
task.Result[4].Should().Be(55555555);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_Graph_with_materialized_value_must_work_also_when_the_sources_module_is_copied(bool autoFusing)
{
var materializer = CreateMaterializer(autoFusing);
var foldFlow = Flow.FromGraph(GraphDsl.Create(Sink.Aggregate<int, int>(0, (sum, i) => sum + i), (b, fold) =>
{
var o = b.From(b.MaterializedValue).Via(Flow.Create<Task<int>>().SelectAsync(4, x => x));
return new FlowShape<int,int>(fold.Inlet, o.Out);
}));
var t = Source.From(Enumerable.Range(1, 10)).Via(foldFlow).RunWith(Sink.First<int>(), materializer);
t.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
t.Result.Should().Be(55);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_Graph_with_materialized_value_must_perform_side_effecting_transformations_even_when_not_used_as_source(bool autoFusing)
{
var materializer = CreateMaterializer(autoFusing);
var done = false;
var g = GraphDsl.Create(b =>
{
b.From(Source.Empty<int>().MapMaterializedValue(_ =>
{
done = true;
return _;
})).To(Sink.Ignore<int>().MapMaterializedValue(_ => NotUsed.Instance));
return ClosedShape.Instance;
});
var r = RunnableGraph.FromGraph(GraphDsl.Create(Sink.Ignore<int>(), (b, sink) =>
{
var source = Source.From(Enumerable.Range(1, 10)).MapMaterializedValue(_ => Task.FromResult(0));
b.Add(g);
b.From(source).To(sink);
return ClosedShape.Instance;
}));
var task = r.Run(materializer);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
done.Should().BeTrue();
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_Graph_with_materialized_value_must_produce_NotUsed_when_not_importing_materialized_value(bool autoFusing)
{
var materializer = CreateMaterializer(autoFusing);
var source = Source.FromGraph(GraphDsl.Create(b => new SourceShape<NotUsed>(b.MaterializedValue)));
var task = source.RunWith(Sink.Seq<NotUsed>(), materializer);
task.Wait(TimeSpan.FromSeconds(3));
task.Result.ShouldAllBeEquivalentTo(NotUsed.Instance);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_Graph_with_materialized_value_must_produce_NotUsed_when_starting_from_Flow_Via_with_transformation(bool autoFusing)
{
var materializer = CreateMaterializer(autoFusing);
var done = false;
Source.Empty<int>().ViaMaterialized(Flow.Create<int>().Via(Flow.Create<int>().MapMaterializedValue(_ =>
{
done = true;
return _;
})), Keep.Right).To(Sink.Ignore<int>()).Run(materializer).Should().Be(NotUsed.Instance);
done.Should().BeTrue();
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_Graph_with_materialized_value_must_ignore_materialized_values_for_a_graph_with_no_materialized_values_exposed(bool autoFusing)
{
// The bug here was that the default behavior for "compose" in Module is Keep.left, but
// EmptyModule.compose broke this by always returning the other module intact, which means
// that the materialized value was that of the other module (which is inconsistent with Keep.left behavior).
var sink = Sink.Ignore<int>();
var g = RunnableGraph.FromGraph(GraphDsl.Create(b =>
{
var s = b.Add(sink);
var source = b.Add(Source.From(Enumerable.Range(1, 3)));
var flow = b.Add(Flow.Create<int>());
b.From(source).Via(flow).To(s);
return ClosedShape.Instance;
}));
var result = g.Run(CreateMaterializer(autoFusing));
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_Graph_with_materialized_value_must_ignore_materialized_values_for_a_graph_with_no_materialized_values_exposed_but_keep_side_effects(bool autoFusing)
{
// The bug here was that the default behavior for "compose" in Module is Keep.left, but
// EmptyModule.compose broke this by always returning the other module intact, which means
// that the materialized value was that of the other module (which is inconsistent with Keep.left behavior).
var sink = Sink.Ignore<int>().MapMaterializedValue(_=>
{
TestActor.Tell("side effect!");
return _;
});
var g = RunnableGraph.FromGraph(GraphDsl.Create(b =>
{
var s = b.Add(sink);
var source = b.Add(Source.From(Enumerable.Range(1, 3)));
var flow = b.Add(Flow.Create<int>());
b.From(source).Via(flow).To(s);
return ClosedShape.Instance;
}));
var result = g.Run(CreateMaterializer(autoFusing));
ExpectMsg("side effect!");
}
[Fact]
public void A_Graph_with_Identity_Flow_optimization_even_if_port_are_wired_in_an_arbitrary_higher_nesting_level()
{
var mat2 = Sys.Materializer(ActorMaterializerSettings.Create(Sys).WithAutoFusing(false));
var subFlow = GraphDsl.Create(b =>
{
var zip = b.Add(new Zip<string, string>());
var bc = b.Add(new Broadcast<string>(2));
b.From(bc.Out(0)).To(zip.In0);
b.From(bc.Out(1)).To(zip.In1);
return new FlowShape<string, Tuple<string, string>>(bc.In, zip.Out);
}).Named("NestedFlow");
var nest1 = Flow.Create<string>().Via(subFlow);
var nest2 = Flow.Create<string>().Via(nest1);
var nest3 = Flow.Create<string>().Via(nest2);
var nest4 = Flow.Create<string>().Via(nest3);
//fails
var matValue = Source.Single("").Via(nest4).To(Sink.Ignore<Tuple<string, string>>()).Run(mat2);
matValue.Should().Be(NotUsed.Instance);
}
}
}
| willieferguson/akka.net | src/core/Akka.Streams.Tests/Dsl/GraphMatValueSpec.cs | C# | apache-2.0 | 13,972 |
/*
* 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.builder.endpoint.dsl;
import javax.annotation.Generated;
import org.apache.camel.builder.EndpointConsumerBuilder;
import org.apache.camel.builder.EndpointProducerBuilder;
import org.apache.camel.builder.endpoint.AbstractEndpointBuilder;
/**
* Transform messages using an MVEL template.
*
* Generated by camel build tools - do NOT edit this file!
*/
@Generated("org.apache.camel.maven.packaging.EndpointDslMojo")
public interface MvelEndpointBuilderFactory {
/**
* Builder for endpoint for the MVEL component.
*/
public interface MvelEndpointBuilder extends EndpointProducerBuilder {
default AdvancedMvelEndpointBuilder advanced() {
return (AdvancedMvelEndpointBuilder) this;
}
/**
* Sets whether the context map should allow access to all details. By
* default only the message body and headers can be accessed. This
* option can be enabled for full access to the current Exchange and
* CamelContext. Doing so impose a potential security risk as this opens
* access to the full power of CamelContext API.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*/
default MvelEndpointBuilder allowContextMapAll(
boolean allowContextMapAll) {
doSetProperty("allowContextMapAll", allowContextMapAll);
return this;
}
/**
* Sets whether the context map should allow access to all details. By
* default only the message body and headers can be accessed. This
* option can be enabled for full access to the current Exchange and
* CamelContext. Doing so impose a potential security risk as this opens
* access to the full power of CamelContext API.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer
*/
default MvelEndpointBuilder allowContextMapAll(String allowContextMapAll) {
doSetProperty("allowContextMapAll", allowContextMapAll);
return this;
}
/**
* Whether to allow to use resource template from header or not (default
* false). Enabling this allows to specify dynamic templates via message
* header. However this can be seen as a potential security
* vulnerability if the header is coming from a malicious user, so use
* this with care.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*/
default MvelEndpointBuilder allowTemplateFromHeader(
boolean allowTemplateFromHeader) {
doSetProperty("allowTemplateFromHeader", allowTemplateFromHeader);
return this;
}
/**
* Whether to allow to use resource template from header or not (default
* false). Enabling this allows to specify dynamic templates via message
* header. However this can be seen as a potential security
* vulnerability if the header is coming from a malicious user, so use
* this with care.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer
*/
default MvelEndpointBuilder allowTemplateFromHeader(
String allowTemplateFromHeader) {
doSetProperty("allowTemplateFromHeader", allowTemplateFromHeader);
return this;
}
/**
* Sets whether to use resource content cache or not.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*/
default MvelEndpointBuilder contentCache(boolean contentCache) {
doSetProperty("contentCache", contentCache);
return this;
}
/**
* Sets whether to use resource content cache or not.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer
*/
default MvelEndpointBuilder contentCache(String contentCache) {
doSetProperty("contentCache", contentCache);
return this;
}
/**
* Character encoding of the resource content.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*/
default MvelEndpointBuilder encoding(String encoding) {
doSetProperty("encoding", encoding);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*/
default MvelEndpointBuilder lazyStartProducer(boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer
*/
default MvelEndpointBuilder lazyStartProducer(String lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
}
/**
* Advanced builder for endpoint for the MVEL component.
*/
public interface AdvancedMvelEndpointBuilder
extends
EndpointProducerBuilder {
default MvelEndpointBuilder basic() {
return (MvelEndpointBuilder) this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedMvelEndpointBuilder basicPropertyBinding(
boolean basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Whether the endpoint should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedMvelEndpointBuilder basicPropertyBinding(
String basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedMvelEndpointBuilder synchronous(boolean synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
/**
* Sets whether synchronous processing should be strictly used, or Camel
* is allowed to use asynchronous processing (if supported).
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AdvancedMvelEndpointBuilder synchronous(String synchronous) {
doSetProperty("synchronous", synchronous);
return this;
}
}
public interface MvelBuilders {
/**
* MVEL (camel-mvel)
* Transform messages using an MVEL template.
*
* Category: transformation,script
* Since: 2.12
* Maven coordinates: org.apache.camel:camel-mvel
*
* Syntax: <code>mvel:resourceUri</code>
*
* Path parameter: resourceUri (required)
* Path to the resource. You can prefix with: classpath, file, http,
* ref, or bean. classpath, file and http loads the resource using these
* protocols (classpath is default). ref will lookup the resource in the
* registry. bean will call a method on a bean to be used as the
* resource. For bean you can specify the method name after dot, eg
* bean:myBean.myMethod.
*
* @param path resourceUri
*/
default MvelEndpointBuilder mvel(String path) {
return MvelEndpointBuilderFactory.endpointBuilder("mvel", path);
}
/**
* MVEL (camel-mvel)
* Transform messages using an MVEL template.
*
* Category: transformation,script
* Since: 2.12
* Maven coordinates: org.apache.camel:camel-mvel
*
* Syntax: <code>mvel:resourceUri</code>
*
* Path parameter: resourceUri (required)
* Path to the resource. You can prefix with: classpath, file, http,
* ref, or bean. classpath, file and http loads the resource using these
* protocols (classpath is default). ref will lookup the resource in the
* registry. bean will call a method on a bean to be used as the
* resource. For bean you can specify the method name after dot, eg
* bean:myBean.myMethod.
*
* @param componentName to use a custom component name for the endpoint
* instead of the default name
* @param path resourceUri
*/
default MvelEndpointBuilder mvel(String componentName, String path) {
return MvelEndpointBuilderFactory.endpointBuilder(componentName, path);
}
}
static MvelEndpointBuilder endpointBuilder(String componentName, String path) {
class MvelEndpointBuilderImpl extends AbstractEndpointBuilder implements MvelEndpointBuilder, AdvancedMvelEndpointBuilder {
public MvelEndpointBuilderImpl(String path) {
super(componentName, path);
}
}
return new MvelEndpointBuilderImpl(path);
}
} | adessaigne/camel | core/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/MvelEndpointBuilderFactory.java | Java | apache-2.0 | 12,497 |
/**
* 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.storm.task;
public interface IErrorReporter {
void reportError(Throwable error);
}
| twitter/heron | storm-compatibility/v2.2.0/src/java/org/apache/storm/task/IErrorReporter.java | Java | apache-2.0 | 915 |
# Copyright 2012 OpenStack Foundation
# Copyright 2013 IBM Corp.
#
# 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.
import tempfile
import uuid
from keystone import config
from keystone import exception
from keystone.openstack.common import jsonutils
from keystone.policy.backends import rules
from keystone import tests
from keystone.tests import test_v3
CONF = config.CONF
DEFAULT_DOMAIN_ID = CONF.identity.default_domain_id
class IdentityTestProtectedCase(test_v3.RestfulTestCase):
"""Test policy enforcement on the v3 Identity API."""
def setUp(self):
"""Setup for Identity Protection Test Cases.
As well as the usual housekeeping, create a set of domains,
users, roles and projects for the subsequent tests:
- Three domains: A,B & C. C is disabled.
- DomainA has user1, DomainB has user2 and user3
- DomainA has group1 and group2, DomainB has group3
- User1 has two roles on DomainA
- User2 has one role on DomainA
Remember that there will also be a fourth domain in existence,
the default domain.
"""
# Ensure that test_v3.RestfulTestCase doesn't load its own
# sample data, which would make checking the results of our
# tests harder
super(IdentityTestProtectedCase, self).setUp()
# Initialize the policy engine and allow us to write to a temp
# file in each test to create the policies
self.addCleanup(rules.reset)
rules.reset()
_unused, self.tmpfilename = tempfile.mkstemp()
self.config_fixture.config(policy_file=self.tmpfilename)
# A default auth request we can use - un-scoped user token
self.auth = self.build_authentication_request(
user_id=self.user1['id'],
password=self.user1['password'])
def load_sample_data(self):
# Start by creating a couple of domains
self.domainA = self.new_domain_ref()
self.assignment_api.create_domain(self.domainA['id'], self.domainA)
self.domainB = self.new_domain_ref()
self.assignment_api.create_domain(self.domainB['id'], self.domainB)
self.domainC = self.new_domain_ref()
self.domainC['enabled'] = False
self.assignment_api.create_domain(self.domainC['id'], self.domainC)
# Now create some users, one in domainA and two of them in domainB
self.user1 = self.new_user_ref(domain_id=self.domainA['id'])
self.user1['password'] = uuid.uuid4().hex
self.identity_api.create_user(self.user1['id'], self.user1)
self.user2 = self.new_user_ref(domain_id=self.domainB['id'])
self.user2['password'] = uuid.uuid4().hex
self.identity_api.create_user(self.user2['id'], self.user2)
self.user3 = self.new_user_ref(domain_id=self.domainB['id'])
self.user3['password'] = uuid.uuid4().hex
self.identity_api.create_user(self.user3['id'], self.user3)
self.group1 = self.new_group_ref(domain_id=self.domainA['id'])
self.identity_api.create_group(self.group1['id'], self.group1)
self.group2 = self.new_group_ref(domain_id=self.domainA['id'])
self.identity_api.create_group(self.group2['id'], self.group2)
self.group3 = self.new_group_ref(domain_id=self.domainB['id'])
self.identity_api.create_group(self.group3['id'], self.group3)
self.role = self.new_role_ref()
self.assignment_api.create_role(self.role['id'], self.role)
self.role1 = self.new_role_ref()
self.assignment_api.create_role(self.role1['id'], self.role1)
self.assignment_api.create_grant(self.role['id'],
user_id=self.user1['id'],
domain_id=self.domainA['id'])
self.assignment_api.create_grant(self.role['id'],
user_id=self.user2['id'],
domain_id=self.domainA['id'])
self.assignment_api.create_grant(self.role1['id'],
user_id=self.user1['id'],
domain_id=self.domainA['id'])
def _get_id_list_from_ref_list(self, ref_list):
result_list = []
for x in ref_list:
result_list.append(x['id'])
return result_list
def _set_policy(self, new_policy):
with open(self.tmpfilename, "w") as policyfile:
policyfile.write(jsonutils.dumps(new_policy))
def test_list_users_unprotected(self):
"""GET /users (unprotected)
Test Plan:
- Update policy so api is unprotected
- Use an un-scoped token to make sure we can get back all
the users independent of domain
"""
self._set_policy({"identity:list_users": []})
r = self.get('/users', auth=self.auth)
id_list = self._get_id_list_from_ref_list(r.result.get('users'))
self.assertIn(self.user1['id'], id_list)
self.assertIn(self.user2['id'], id_list)
self.assertIn(self.user3['id'], id_list)
def test_list_users_filtered_by_domain(self):
"""GET /users?domain_id=mydomain (filtered)
Test Plan:
- Update policy so api is unprotected
- Use an un-scoped token to make sure we can filter the
users by domainB, getting back the 2 users in that domain
"""
self._set_policy({"identity:list_users": []})
url_by_name = '/users?domain_id=%s' % self.domainB['id']
r = self.get(url_by_name, auth=self.auth)
# We should get back two users, those in DomainB
id_list = self._get_id_list_from_ref_list(r.result.get('users'))
self.assertIn(self.user2['id'], id_list)
self.assertIn(self.user3['id'], id_list)
def test_get_user_protected_match_id(self):
"""GET /users/{id} (match payload)
Test Plan:
- Update policy to protect api by user_id
- List users with user_id of user1 as filter, to check that
this will correctly match user_id in the flattened
payload
"""
# TODO(henry-nash, ayoung): It would be good to expand this
# test for further test flattening, e.g. protect on, say, an
# attribute of an object being created
new_policy = {"identity:get_user": [["user_id:%(user_id)s"]]}
self._set_policy(new_policy)
url_by_name = '/users/%s' % self.user1['id']
r = self.get(url_by_name, auth=self.auth)
self.assertEqual(self.user1['id'], r.result['user']['id'])
def test_get_user_protected_match_target(self):
"""GET /users/{id} (match target)
Test Plan:
- Update policy to protect api by domain_id
- Try and read a user who is in DomainB with a token scoped
to Domain A - this should fail
- Retry this for a user who is in Domain A, which should succeed.
- Finally, try getting a user that does not exist, which should
still return UserNotFound
"""
new_policy = {'identity:get_user':
[["domain_id:%(target.user.domain_id)s"]]}
self._set_policy(new_policy)
self.auth = self.build_authentication_request(
user_id=self.user1['id'],
password=self.user1['password'],
domain_id=self.domainA['id'])
url_by_name = '/users/%s' % self.user2['id']
r = self.get(url_by_name, auth=self.auth,
expected_status=exception.ForbiddenAction.code)
url_by_name = '/users/%s' % self.user1['id']
r = self.get(url_by_name, auth=self.auth)
self.assertEqual(self.user1['id'], r.result['user']['id'])
url_by_name = '/users/%s' % uuid.uuid4().hex
r = self.get(url_by_name, auth=self.auth,
expected_status=exception.UserNotFound.code)
def test_revoke_grant_protected_match_target(self):
"""DELETE /domains/{id}/users/{id}/roles/{id} (match target)
Test Plan:
- Update policy to protect api by domain_id of entities in
the grant
- Try and delete the existing grant that has a user who is
from a different domain - this should fail.
- Retry this for a user who is in Domain A, which should succeed.
"""
new_policy = {'identity:revoke_grant':
[["domain_id:%(target.user.domain_id)s"]]}
self._set_policy(new_policy)
collection_url = (
'/domains/%(domain_id)s/users/%(user_id)s/roles' % {
'domain_id': self.domainA['id'],
'user_id': self.user2['id']})
member_url = '%(collection_url)s/%(role_id)s' % {
'collection_url': collection_url,
'role_id': self.role['id']}
self.auth = self.build_authentication_request(
user_id=self.user1['id'],
password=self.user1['password'],
domain_id=self.domainA['id'])
self.delete(member_url, auth=self.auth,
expected_status=exception.ForbiddenAction.code)
collection_url = (
'/domains/%(domain_id)s/users/%(user_id)s/roles' % {
'domain_id': self.domainA['id'],
'user_id': self.user1['id']})
member_url = '%(collection_url)s/%(role_id)s' % {
'collection_url': collection_url,
'role_id': self.role1['id']}
self.delete(member_url, auth=self.auth)
def test_list_users_protected_by_domain(self):
"""GET /users?domain_id=mydomain (protected)
Test Plan:
- Update policy to protect api by domain_id
- List groups using a token scoped to domainA with a filter
specifying domainA - we should only get back the one user
that is in domainA.
- Try and read the users from domainB - this should fail since
we don't have a token scoped for domainB
"""
new_policy = {"identity:list_users": ["domain_id:%(domain_id)s"]}
self._set_policy(new_policy)
self.auth = self.build_authentication_request(
user_id=self.user1['id'],
password=self.user1['password'],
domain_id=self.domainA['id'])
url_by_name = '/users?domain_id=%s' % self.domainA['id']
r = self.get(url_by_name, auth=self.auth)
# We should only get back one user, the one in DomainA
id_list = self._get_id_list_from_ref_list(r.result.get('users'))
self.assertEqual(1, len(id_list))
self.assertIn(self.user1['id'], id_list)
# Now try for domainB, which should fail
url_by_name = '/users?domain_id=%s' % self.domainB['id']
r = self.get(url_by_name, auth=self.auth,
expected_status=exception.ForbiddenAction.code)
def test_list_groups_protected_by_domain(self):
"""GET /groups?domain_id=mydomain (protected)
Test Plan:
- Update policy to protect api by domain_id
- List groups using a token scoped to domainA and make sure
we only get back the two groups that are in domainA
- Try and read the groups from domainB - this should fail since
we don't have a token scoped for domainB
"""
new_policy = {"identity:list_groups": ["domain_id:%(domain_id)s"]}
self._set_policy(new_policy)
self.auth = self.build_authentication_request(
user_id=self.user1['id'],
password=self.user1['password'],
domain_id=self.domainA['id'])
url_by_name = '/groups?domain_id=%s' % self.domainA['id']
r = self.get(url_by_name, auth=self.auth)
# We should only get back two groups, the ones in DomainA
id_list = self._get_id_list_from_ref_list(r.result.get('groups'))
self.assertEqual(2, len(id_list))
self.assertIn(self.group1['id'], id_list)
self.assertIn(self.group2['id'], id_list)
# Now try for domainB, which should fail
url_by_name = '/groups?domain_id=%s' % self.domainB['id']
r = self.get(url_by_name, auth=self.auth,
expected_status=exception.ForbiddenAction.code)
def test_list_groups_protected_by_domain_and_filtered(self):
"""GET /groups?domain_id=mydomain&name=myname (protected)
Test Plan:
- Update policy to protect api by domain_id
- List groups using a token scoped to domainA with a filter
specifying both domainA and the name of group.
- We should only get back the group in domainA that matches
the name
"""
new_policy = {"identity:list_groups": ["domain_id:%(domain_id)s"]}
self._set_policy(new_policy)
self.auth = self.build_authentication_request(
user_id=self.user1['id'],
password=self.user1['password'],
domain_id=self.domainA['id'])
url_by_name = '/groups?domain_id=%s&name=%s' % (
self.domainA['id'], self.group2['name'])
r = self.get(url_by_name, auth=self.auth)
# We should only get back one user, the one in DomainA that matches
# the name supplied
id_list = self._get_id_list_from_ref_list(r.result.get('groups'))
self.assertEqual(1, len(id_list))
self.assertIn(self.group2['id'], id_list)
class IdentityTestv3CloudPolicySample(test_v3.RestfulTestCase):
"""Test policy enforcement of the sample v3 cloud policy file."""
def setUp(self):
"""Setup for v3 Cloud Policy Sample Test Cases.
The following data is created:
- Three domains: domainA, domainB and admin_domain
- One project, which name is 'project'
- domainA has three users: domain_admin_user, project_admin_user and
just_a_user:
- domain_admin_user has role 'admin' on domainA,
- project_admin_user has role 'admin' on the project,
- just_a_user has a non-admin role on both domainA and the project.
- admin_domain has user cloud_admin_user, with an 'admin' role
on admin_domain.
We test various api protection rules from the cloud sample policy
file to make sure the sample is valid and that we correctly enforce it.
"""
# Ensure that test_v3.RestfulTestCase doesn't load its own
# sample data, which would make checking the results of our
# tests harder
super(IdentityTestv3CloudPolicySample, self).setUp()
# Finally, switch to the v3 sample policy file
self.addCleanup(rules.reset)
rules.reset()
self.config_fixture.config(
policy_file=tests.dirs.etc('policy.v3cloudsample.json'))
def load_sample_data(self):
# Start by creating a couple of domains
self.domainA = self.new_domain_ref()
self.assignment_api.create_domain(self.domainA['id'], self.domainA)
self.domainB = self.new_domain_ref()
self.assignment_api.create_domain(self.domainB['id'], self.domainB)
self.admin_domain = {'id': 'admin_domain_id', 'name': 'Admin_domain'}
self.assignment_api.create_domain(self.admin_domain['id'],
self.admin_domain)
# And our users
self.cloud_admin_user = self.new_user_ref(
domain_id=self.admin_domain['id'])
self.cloud_admin_user['password'] = uuid.uuid4().hex
self.identity_api.create_user(self.cloud_admin_user['id'],
self.cloud_admin_user)
self.just_a_user = self.new_user_ref(domain_id=self.domainA['id'])
self.just_a_user['password'] = uuid.uuid4().hex
self.identity_api.create_user(self.just_a_user['id'], self.just_a_user)
self.domain_admin_user = self.new_user_ref(
domain_id=self.domainA['id'])
self.domain_admin_user['password'] = uuid.uuid4().hex
self.identity_api.create_user(self.domain_admin_user['id'],
self.domain_admin_user)
self.project_admin_user = self.new_user_ref(
domain_id=self.domainA['id'])
self.project_admin_user['password'] = uuid.uuid4().hex
self.identity_api.create_user(self.project_admin_user['id'],
self.project_admin_user)
# The admin role and another plain role
self.admin_role = {'id': uuid.uuid4().hex, 'name': 'admin'}
self.assignment_api.create_role(self.admin_role['id'], self.admin_role)
self.role = self.new_role_ref()
self.assignment_api.create_role(self.role['id'], self.role)
# The cloud admin just gets the admin role
self.assignment_api.create_grant(self.admin_role['id'],
user_id=self.cloud_admin_user['id'],
domain_id=self.admin_domain['id'])
# Assign roles to the domain
self.assignment_api.create_grant(self.admin_role['id'],
user_id=self.domain_admin_user['id'],
domain_id=self.domainA['id'])
self.assignment_api.create_grant(self.role['id'],
user_id=self.just_a_user['id'],
domain_id=self.domainA['id'])
# Create a assign roles to the project
self.project = self.new_project_ref(domain_id=self.domainA['id'])
self.assignment_api.create_project(self.project['id'], self.project)
self.assignment_api.create_grant(self.admin_role['id'],
user_id=self.project_admin_user['id'],
project_id=self.project['id'])
self.assignment_api.create_grant(self.role['id'],
user_id=self.just_a_user['id'],
project_id=self.project['id'])
def _stati(self, expected_status):
# Return the expected return codes for APIs with and without data
# with any specified status overriding the normal values
if expected_status is None:
return (200, 201, 204)
else:
return (expected_status, expected_status, expected_status)
def _test_user_management(self, domain_id, expected=None):
status_OK, status_created, status_no_data = self._stati(expected)
entity_url = '/users/%s' % self.just_a_user['id']
list_url = '/users?domain_id=%s' % domain_id
self.get(entity_url, auth=self.auth,
expected_status=status_OK)
self.get(list_url, auth=self.auth,
expected_status=status_OK)
user = {'description': 'Updated'}
self.patch(entity_url, auth=self.auth, body={'user': user},
expected_status=status_OK)
self.delete(entity_url, auth=self.auth,
expected_status=status_no_data)
user_ref = self.new_user_ref(domain_id=domain_id)
self.post('/users', auth=self.auth, body={'user': user_ref},
expected_status=status_created)
def _test_project_management(self, domain_id, expected=None):
status_OK, status_created, status_no_data = self._stati(expected)
entity_url = '/projects/%s' % self.project['id']
list_url = '/projects?domain_id=%s' % domain_id
self.get(entity_url, auth=self.auth,
expected_status=status_OK)
self.get(list_url, auth=self.auth,
expected_status=status_OK)
project = {'description': 'Updated'}
self.patch(entity_url, auth=self.auth, body={'project': project},
expected_status=status_OK)
self.delete(entity_url, auth=self.auth,
expected_status=status_no_data)
proj_ref = self.new_project_ref(domain_id=domain_id)
self.post('/projects', auth=self.auth, body={'project': proj_ref},
expected_status=status_created)
def _test_domain_management(self, expected=None):
status_OK, status_created, status_no_data = self._stati(expected)
entity_url = '/domains/%s' % self.domainB['id']
list_url = '/domains'
self.get(entity_url, auth=self.auth,
expected_status=status_OK)
self.get(list_url, auth=self.auth,
expected_status=status_OK)
domain = {'description': 'Updated', 'enabled': False}
self.patch(entity_url, auth=self.auth, body={'domain': domain},
expected_status=status_OK)
self.delete(entity_url, auth=self.auth,
expected_status=status_no_data)
domain_ref = self.new_domain_ref()
self.post('/domains', auth=self.auth, body={'domain': domain_ref},
expected_status=status_created)
def _test_grants(self, target, entity_id, expected=None):
status_OK, status_created, status_no_data = self._stati(expected)
a_role = {'id': uuid.uuid4().hex, 'name': uuid.uuid4().hex}
self.assignment_api.create_role(a_role['id'], a_role)
collection_url = (
'/%(target)s/%(target_id)s/users/%(user_id)s/roles' % {
'target': target,
'target_id': entity_id,
'user_id': self.just_a_user['id']})
member_url = '%(collection_url)s/%(role_id)s' % {
'collection_url': collection_url,
'role_id': a_role['id']}
self.put(member_url, auth=self.auth,
expected_status=status_no_data)
self.head(member_url, auth=self.auth,
expected_status=status_no_data)
self.get(collection_url, auth=self.auth,
expected_status=status_OK)
self.delete(member_url, auth=self.auth,
expected_status=status_no_data)
def test_user_management(self):
# First, authenticate with a user that does not have the domain
# admin role - shouldn't be able to do much.
self.auth = self.build_authentication_request(
user_id=self.just_a_user['id'],
password=self.just_a_user['password'],
domain_id=self.domainA['id'])
self._test_user_management(
self.domainA['id'], expected=exception.ForbiddenAction.code)
# Now, authenticate with a user that does have the domain admin role
self.auth = self.build_authentication_request(
user_id=self.domain_admin_user['id'],
password=self.domain_admin_user['password'],
domain_id=self.domainA['id'])
self._test_user_management(self.domainA['id'])
def test_user_management_by_cloud_admin(self):
# Test users management with a cloud admin. This user should
# be able to manage users in any domain.
self.auth = self.build_authentication_request(
user_id=self.cloud_admin_user['id'],
password=self.cloud_admin_user['password'],
domain_id=self.admin_domain['id'])
self._test_user_management(self.domainA['id'])
def test_project_management(self):
# First, authenticate with a user that does not have the project
# admin role - shouldn't be able to do much.
self.auth = self.build_authentication_request(
user_id=self.just_a_user['id'],
password=self.just_a_user['password'],
domain_id=self.domainA['id'])
self._test_project_management(
self.domainA['id'], expected=exception.ForbiddenAction.code)
# ...but should still be able to list projects of which they are
# a member
url = '/users/%s/projects' % self.just_a_user['id']
self.get(url, auth=self.auth)
# Now, authenticate with a user that does have the domain admin role
self.auth = self.build_authentication_request(
user_id=self.domain_admin_user['id'],
password=self.domain_admin_user['password'],
domain_id=self.domainA['id'])
self._test_project_management(self.domainA['id'])
def test_domain_grants(self):
self.auth = self.build_authentication_request(
user_id=self.just_a_user['id'],
password=self.just_a_user['password'],
domain_id=self.domainA['id'])
self._test_grants('domains', self.domainA['id'],
expected=exception.ForbiddenAction.code)
# Now, authenticate with a user that does have the domain admin role
self.auth = self.build_authentication_request(
user_id=self.domain_admin_user['id'],
password=self.domain_admin_user['password'],
domain_id=self.domainA['id'])
self._test_grants('domains', self.domainA['id'])
# Check that with such a token we cannot modify grants on a
# different domain
self._test_grants('domains', self.domainB['id'],
expected=exception.ForbiddenAction.code)
def test_domain_grants_by_cloud_admin(self):
# Test domain grants with a cloud admin. This user should be
# able to manage roles on any domain.
self.auth = self.build_authentication_request(
user_id=self.cloud_admin_user['id'],
password=self.cloud_admin_user['password'],
domain_id=self.admin_domain['id'])
self._test_grants('domains', self.domainA['id'])
def test_project_grants(self):
self.auth = self.build_authentication_request(
user_id=self.just_a_user['id'],
password=self.just_a_user['password'],
project_id=self.project['id'])
self._test_grants('projects', self.project['id'],
expected=exception.ForbiddenAction.code)
# Now, authenticate with a user that does have the project
# admin role
self.auth = self.build_authentication_request(
user_id=self.project_admin_user['id'],
password=self.project_admin_user['password'],
project_id=self.project['id'])
self._test_grants('projects', self.project['id'])
def test_project_grants_by_domain_admin(self):
# Test project grants with a domain admin. This user should be
# able to manage roles on any project in its own domain.
self.auth = self.build_authentication_request(
user_id=self.domain_admin_user['id'],
password=self.domain_admin_user['password'],
domain_id=self.domainA['id'])
self._test_grants('projects', self.project['id'])
def test_cloud_admin(self):
self.auth = self.build_authentication_request(
user_id=self.domain_admin_user['id'],
password=self.domain_admin_user['password'],
domain_id=self.domainA['id'])
self._test_domain_management(
expected=exception.ForbiddenAction.code)
self.auth = self.build_authentication_request(
user_id=self.cloud_admin_user['id'],
password=self.cloud_admin_user['password'],
domain_id=self.admin_domain['id'])
self._test_domain_management()
| Sazzadmasud/Keystone_hash_token | keystone/tests/test_v3_protection.py | Python | apache-2.0 | 27,778 |
import { isLeapYear } from "../../Source/Cesium.js";
describe("Core/isLeapYear", function () {
it("Check for valid leap years", function () {
expect(isLeapYear(2000)).toEqual(true);
expect(isLeapYear(2004)).toEqual(true);
expect(isLeapYear(2003)).toEqual(false);
expect(isLeapYear(2300)).toEqual(false);
expect(isLeapYear(2400)).toEqual(true);
expect(isLeapYear(-1)).toEqual(false);
expect(isLeapYear(-2000)).toEqual(true);
});
it("Fail with null value", function () {
expect(function () {
isLeapYear(null);
}).toThrowDeveloperError();
});
it("Fail with undefined value", function () {
expect(function () {
isLeapYear(undefined);
}).toThrowDeveloperError();
});
it("Fail with non-numerical value", function () {
expect(function () {
isLeapYear("asd");
}).toThrowDeveloperError();
});
});
| likangning93/cesium | Specs/Core/isLeapYearSpec.js | JavaScript | apache-2.0 | 878 |
/**
* Define a namespace for the application.
*/
window.app = {};
var app = window.app;
/**
* @constructor
* @extends {ol.interaction.Pointer}
*/
app.Drag = function() {
ol.interaction.Pointer.call(this, {
handleDownEvent: app.Drag.prototype.handleDownEvent,
handleDragEvent: app.Drag.prototype.handleDragEvent,
handleMoveEvent: app.Drag.prototype.handleMoveEvent,
handleUpEvent: app.Drag.prototype.handleUpEvent
});
/**
* @type {ol.Pixel}
* @private
*/
this.coordinate_ = null;
/**
* @type {string|undefined}
* @private
*/
this.cursor_ = 'pointer';
/**
* @type {ol.Feature}
* @private
*/
this.feature_ = null;
/**
* @type {string|undefined}
* @private
*/
this.previousCursor_ = undefined;
};
ol.inherits(app.Drag, ol.interaction.Pointer);
/**
* @param {ol.MapBrowserEvent} evt Map browser event.
* @return {boolean} `true` to start the drag sequence.
*/
app.Drag.prototype.handleDownEvent = function(evt) {
var map = evt.map;
var feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature, layer) {
return feature;
});
if (feature) {
this.coordinate_ = evt.coordinate;
this.feature_ = feature;
}
return !!feature;
};
/**
* @param {ol.MapBrowserEvent} evt Map browser event.
*/
app.Drag.prototype.handleDragEvent = function(evt) {
var map = evt.map;
var feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature, layer) {
return feature;
});
var deltaX = evt.coordinate[0] - this.coordinate_[0];
var deltaY = evt.coordinate[1] - this.coordinate_[1];
var geometry = /** @type {ol.geom.SimpleGeometry} */
(this.feature_.getGeometry());
geometry.translate(deltaX, deltaY);
this.coordinate_[0] = evt.coordinate[0];
this.coordinate_[1] = evt.coordinate[1];
};
/**
* @param {ol.MapBrowserEvent} evt Event.
*/
app.Drag.prototype.handleMoveEvent = function(evt) {
if (this.cursor_) {
var map = evt.map;
var feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature, layer) {
return feature;
});
var element = evt.map.getTargetElement();
if (feature) {
if (element.style.cursor != this.cursor_) {
this.previousCursor_ = element.style.cursor;
element.style.cursor = this.cursor_;
}
} else if (this.previousCursor_ !== undefined) {
element.style.cursor = this.previousCursor_;
this.previousCursor_ = undefined;
}
}
};
/**
* @param {ol.MapBrowserEvent} evt Map browser event.
* @return {boolean} `false` to stop the drag sequence.
*/
app.Drag.prototype.handleUpEvent = function(evt) {
this.coordinate_ = null;
this.feature_ = null;
return false;
};
var lat = 50;
var lng = -70;
var zoom = 5;
//var extent = [-83, 44, -57, 55];
var extent = [-9259955, 5467881, -6324773, 7424669];
var osmLayer = new ol.layer.Tile({
source: new ol.source.OSM(),
visible: false
});
var map = new ol.Map({
// use OL3-Google-Maps recommended default interactions
interactions: olgm.interaction.defaults().extend([
new app.Drag()
]),
layers: [
osmLayer,
new olgm.layer.Google()
],
target: 'map',
view: new ol.View({
center: ol.proj.transform([lng, lat], 'EPSG:4326', 'EPSG:3857'),
zoom: zoom
})
});
// FIXME - style override, this should be managed internally
/*
gmap.data.setStyle({
icon: 'resources/evouala.png'
});
*/
var vector = new ol.layer.Vector({
source: new ol.source.Vector()
});
map.addLayer(vector);
var generateCoordinate = function() {
var extent = [-9259955, 5467881, -6324773, 7424669];
var deltaX = extent[2] - extent[0];
var deltaY = extent[3] - extent[1];
return [
extent[0] + (deltaX * Math.random()),
extent[1] + (deltaY * Math.random())
];
};
var generatePointFeature = function() {
return new ol.Feature(
new ol.geom.Point(generateCoordinate())
);
};
var generateLineFeature = function() {
var coordinates = [];
for (var i = 0, len = 3; i < len; i++) {
coordinates.push(generateCoordinate());
}
return new ol.Feature(
new ol.geom.LineString(coordinates)
);
};
var addPointFeatures = function(len, opt_style) {
var feature;
for (var i = 0; i < len; i++) {
feature = generatePointFeature();
if (opt_style) {
var style = new ol.style.Style(opt_style);
style.setZIndex(Math.floor(Math.random() * 1000));
feature.setStyle(style);
}
vector.getSource().addFeature(feature);
}
};
var addMarkerFeatures = function(len) {
addPointFeatures(len, {
image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.75,
src: 'data/icon.png'
})),
text: new ol.style.Text({
offsetX: 0,
offsetY: -32,
font: 'normal 14pt Courrier',
text: 'hi',
fill: new ol.style.Fill({color: 'black'}),
stroke: new ol.style.Stroke({color: '#ffffff', width: 5}),
})
});
};
var addCircleFeatures = function(len) {
addPointFeatures(len, {
image: new ol.style.Circle({
'fill': new ol.style.Fill({color: 'rgba(153,51,51,0.3)'}),
'stroke': new ol.style.Stroke({color: 'rgb(153,51,51)', width: 2}),
'radius': 20
})
});
};
var addLineFeatures = function(len, opt_style) {
var feature;
for (var i = 0; i < len; i++) {
feature = generateLineFeature();
if (opt_style) {
feature.setStyle(opt_style);
}
vector.getSource().addFeature(feature);
}
};
addPointFeatures(3);
addPointFeatures(3, {
image: new ol.style.Circle({
'fill': new ol.style.Fill({color: '#3F5D7D'}),
'stroke': new ol.style.Stroke({color: 'rgb(30,30,30)', width: 2}),
'radius': 20
}),
text: new ol.style.Text({
font: 'normal 16pt Arial',
text: '42',
fill: new ol.style.Fill({color: 'black'}),
stroke: new ol.style.Stroke({color: 'white', width: 3})
})
});
addMarkerFeatures(3);
addCircleFeatures(3);
addLineFeatures(1);
// line with custom style
addLineFeatures(1, new ol.style.Style({
stroke: new ol.style.Stroke({
width: 4,
color: '#CC3333'
})
}));
// add polygon feature
vector.getSource().addFeature(new ol.Feature(
new ol.geom.Polygon.fromExtent([-8259955, 6067881, -7324773, 6524669])
));
// add polygon feature with custom style
var poly2 = new ol.Feature(
new ol.geom.Polygon.fromExtent([-8159955, 6167881, -7124773, 6724669])
);
poly2.setStyle(new ol.style.Style({
fill: new ol.style.Stroke({
color: 'rgba(63,93,125,0.4)'
}),
stroke: new ol.style.Stroke({
width: 4,
color: 'rgba(63,93,125,0.8)'
})
}));
vector.getSource().addFeature(poly2);
var olGM = new olgm.OLGoogleMaps({
map: map,
mapIconOptions: {
useCanvas: true
}});
olGM.activate();
document.getElementById('toggle').onclick = function() {
olGM.toggle();
};
document.getElementById('add-point').onclick = function() {
addMarkerFeatures(3);
};
document.getElementById('clear-point').onclick = function() {
vector.getSource().clear();
};
var toggleOsmLayer = function(opt_visible) {
var visible = opt_visible !== undefined ? opt_visible :
!osmLayer.getVisible();
osmLayer.setVisible(visible);
};
document.getElementById('toggle-osm').onclick = function() {
toggleOsmLayer();
};
document.getElementById('gm-rm-last').onclick = function() {
var found = null;
var layers = map.getLayers();
// remove last one
layers.getArray().slice(0).reverse().every(function(layer) {
if (layer instanceof olgm.layer.Google) {
found = layer;
return false;
}
return true;
}, this);
if (found) {
layers.remove(found);
}
};
document.getElementById('gm-add-sat').onclick = function() {
map.getLayers().push(new olgm.layer.Google({
mapTypeId: google.maps.MapTypeId.SATELLITE
}));
};
document.getElementById('gm-add-ter').onclick = function() {
map.getLayers().push(new olgm.layer.Google({
mapTypeId: google.maps.MapTypeId.TERRAIN
}));
};
document.getElementById('gm-toggle-last').onclick = function() {
var found = null;
var layers = map.getLayers();
// remove last one
layers.getArray().slice(0).reverse().every(function(layer) {
if (layer instanceof olgm.layer.Google) {
found = layer;
return false;
}
return true;
}, this);
if (found) {
found.setVisible(!found.getVisible());
}
};
| dsmiley/hhypermap-bop | bop-ui/assets/lib/ol3-google-maps/examples/concept.js | JavaScript | apache-2.0 | 8,430 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* 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.intellij.codeInsight.daemon.impl;
import com.intellij.codeHighlighting.MainHighlightingPassFactory;
import com.intellij.codeHighlighting.Pass;
import com.intellij.codeHighlighting.TextEditorHighlightingPass;
import com.intellij.codeHighlighting.TextEditorHighlightingPassRegistrar;
import com.intellij.lang.Language;
import com.intellij.openapi.components.AbstractProjectComponent;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.HighlighterColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.ProperTextRange;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.SyntaxTraverser;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.IFileElementType;
import com.intellij.psi.tree.ILazyParseableElementType;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.TreeTraversal;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import static com.intellij.psi.SyntaxTraverser.psiTraverser;
class ChameleonSyntaxHighlightingPass extends GeneralHighlightingPass {
public static class Factory extends AbstractProjectComponent implements MainHighlightingPassFactory {
protected Factory(Project project, TextEditorHighlightingPassRegistrar registrar) {
super(project);
registrar.registerTextEditorHighlightingPass(this, null, new int[]{Pass.UPDATE_ALL}, false, -1);
}
@Nullable
@Override
public TextEditorHighlightingPass createHighlightingPass(@NotNull PsiFile file, @NotNull Editor editor) {
TextRange restrict = FileStatusMap.getDirtyTextRange(editor, Pass.UPDATE_ALL);
if (restrict == null) return new ProgressableTextEditorHighlightingPass.EmptyPass(myProject, editor.getDocument());
ProperTextRange priority = VisibleHighlightingPassFactory.calculateVisibleRange(editor);
return new ChameleonSyntaxHighlightingPass(myProject, file, editor.getDocument(), ProperTextRange.create(restrict),
priority, editor, new DefaultHighlightInfoProcessor());
}
@Nullable
@Override
public TextEditorHighlightingPass createMainHighlightingPass(@NotNull PsiFile file,
@NotNull Document document,
@NotNull HighlightInfoProcessor highlightInfoProcessor) {
ProperTextRange range = ProperTextRange.from(0, document.getTextLength());
return new ChameleonSyntaxHighlightingPass(myProject, file, document, range, range, null, highlightInfoProcessor);
}
}
ChameleonSyntaxHighlightingPass(@NotNull Project project,
@NotNull PsiFile file,
@NotNull Document document,
@NotNull ProperTextRange restrictRange,
@NotNull ProperTextRange priorityRange,
@Nullable Editor editor,
@NotNull HighlightInfoProcessor highlightInfoProcessor) {
super(project, file, document, restrictRange.getStartOffset(), restrictRange.getEndOffset(), true, priorityRange, editor,
highlightInfoProcessor);
}
@Override
public void collectInformationWithProgress(@NotNull ProgressIndicator progress) {
SyntaxTraverser<PsiElement> s = psiTraverser(myFile)
.filter(o -> {
IElementType type = PsiUtilCore.getElementType(o);
return type instanceof ILazyParseableElementType && !(type instanceof IFileElementType);
});
List<PsiElement> lazyOutside = ContainerUtil.newArrayListWithCapacity(100);
List<PsiElement> lazyInside = ContainerUtil.newArrayListWithCapacity(100);
List<HighlightInfo> outside = ContainerUtil.newArrayListWithCapacity(100);
List<HighlightInfo> inside = ContainerUtil.newArrayListWithCapacity(100);
for (PsiElement e : s) {
(e.getTextRange().intersects(myPriorityRange) ? lazyInside : lazyOutside).add(e);
}
for (PsiElement e : lazyInside) {
collectHighlights(e, inside, outside, myPriorityRange);
}
myHighlightInfoProcessor.highlightsInsideVisiblePartAreProduced(myHighlightingSession, getEditor(), inside, myPriorityRange, myRestrictRange, getId());
for (PsiElement e : lazyOutside) {
collectHighlights(e, inside, outside, myPriorityRange);
}
myHighlightInfoProcessor.highlightsOutsideVisiblePartAreProduced(myHighlightingSession, getEditor(), outside, myPriorityRange, myRestrictRange, getId());
myHighlights.addAll(inside);
myHighlights.addAll(outside);
}
private void collectHighlights(@NotNull PsiElement element,
@NotNull List<HighlightInfo> inside,
@NotNull List<HighlightInfo> outside,
@NotNull ProperTextRange priorityRange) {
EditorColorsScheme scheme = ObjectUtils.notNull(getColorsScheme(), EditorColorsManager.getInstance().getGlobalScheme());
TextAttributes defaultAttrs = scheme.getAttributes(HighlighterColors.TEXT);
Language language = ILazyParseableElementType.LANGUAGE_KEY.get(element.getNode());
if (language == null) return;
SyntaxHighlighter syntaxHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(language, myProject, myFile.getVirtualFile());
for (PsiElement token : psiTraverser(element).traverse(TreeTraversal.LEAVES_DFS)) {
TextRange tr = token.getTextRange();
if (tr.isEmpty()) continue;
IElementType type = PsiUtilCore.getElementType(token);
TextAttributesKey[] keys = syntaxHighlighter.getTokenHighlights(type);
// force attribute colors to override host' ones
TextAttributes attributes = null;
for (TextAttributesKey key : keys) {
TextAttributes attrs2 = scheme.getAttributes(key);
if (attrs2 != null) {
attributes = attributes == null ? attrs2 : TextAttributes.merge(attributes, attrs2);
}
}
TextAttributes forcedAttributes;
if (attributes == null || attributes.isEmpty() || attributes.equals(defaultAttrs)) {
forcedAttributes = TextAttributes.ERASE_MARKER;
}
else {
HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.INJECTED_LANGUAGE_FRAGMENT).
range(tr).
textAttributes(TextAttributes.ERASE_MARKER).
createUnconditionally();
(priorityRange.contains(tr) ? inside : outside).add(info);
forcedAttributes = new TextAttributes(attributes.getForegroundColor(), attributes.getBackgroundColor(),
attributes.getEffectColor(), attributes.getEffectType(), attributes.getFontType());
}
HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.INJECTED_LANGUAGE_FRAGMENT).
range(tr).
textAttributes(forcedAttributes).
createUnconditionally();
(priorityRange.contains(tr) ? inside : outside).add(info);
}
}
@Override
protected void applyInformationWithProgress() {
}
@Nullable
@Override
protected String getPresentableName() {
return null; // do not show progress for
}
}
| ThiagoGarciaAlves/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ChameleonSyntaxHighlightingPass.java | Java | apache-2.0 | 8,538 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* 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.jetbrains.jsonSchema.impl;
import com.intellij.util.SmartList;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author Irina.Chernushina on 4/20/2017.
*/
public class JsonSchemaTreeNode {
private boolean myAny;
private boolean myNothing;
private int myExcludingGroupNumber = -1;
@NotNull private SchemaResolveState myResolveState = SchemaResolveState.normal;
@Nullable private final JsonSchemaObject mySchema;
@NotNull private final List<JsonSchemaVariantsTreeBuilder.Step> mySteps = new SmartList<>();
@Nullable private final JsonSchemaTreeNode myParent;
@NotNull private final List<JsonSchemaTreeNode> myChildren = new ArrayList<>();
public JsonSchemaTreeNode(@Nullable JsonSchemaTreeNode parent,
@Nullable JsonSchemaObject schema) {
assert schema != null || parent != null;
myParent = parent;
mySchema = schema;
if (parent != null && !parent.getSteps().isEmpty()) {
mySteps.addAll(parent.getSteps().subList(1, parent.getSteps().size()));
}
}
public void anyChild() {
final JsonSchemaTreeNode node = new JsonSchemaTreeNode(this, null);
node.myAny = true;
myChildren.add(node);
}
public void nothingChild() {
final JsonSchemaTreeNode node = new JsonSchemaTreeNode(this, null);
node.myNothing = true;
myChildren.add(node);
}
public void createChildrenFromOperation(@NotNull JsonSchemaVariantsTreeBuilder.Operation operation) {
if (!SchemaResolveState.normal.equals(operation.myState)) {
final JsonSchemaTreeNode node = new JsonSchemaTreeNode(this, null);
node.myResolveState = operation.myState;
myChildren.add(node);
return;
}
if (!operation.myAnyOfGroup.isEmpty()) {
myChildren.addAll(convertToNodes(operation.myAnyOfGroup));
}
if (!operation.myOneOfGroup.isEmpty()) {
for (int i = 0; i < operation.myOneOfGroup.size(); i++) {
final List<JsonSchemaObject> group = operation.myOneOfGroup.get(i);
final List<JsonSchemaTreeNode> children = convertToNodes(group);
final int number = i;
children.forEach(c -> c.myExcludingGroupNumber = number);
myChildren.addAll(children);
}
}
}
private List<JsonSchemaTreeNode> convertToNodes(List<JsonSchemaObject> children) {
return children.stream().map(s -> new JsonSchemaTreeNode(this, s)).collect(Collectors.toList());
}
@NotNull
public SchemaResolveState getResolveState() {
return myResolveState;
}
public boolean isAny() {
return myAny;
}
public boolean isNothing() {
return myNothing;
}
public void setChild(@NotNull final JsonSchemaObject schema) {
myChildren.add(new JsonSchemaTreeNode(this, schema));
}
@Nullable
public JsonSchemaObject getSchema() {
return mySchema;
}
@NotNull
public List<JsonSchemaVariantsTreeBuilder.Step> getSteps() {
return mySteps;
}
@Nullable
public JsonSchemaTreeNode getParent() {
return myParent;
}
@NotNull
public List<JsonSchemaTreeNode> getChildren() {
return myChildren;
}
public int getExcludingGroupNumber() {
return myExcludingGroupNumber;
}
public void setSteps(@NotNull List<JsonSchemaVariantsTreeBuilder.Step> steps) {
mySteps.clear();
mySteps.addAll(steps);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
JsonSchemaTreeNode node = (JsonSchemaTreeNode)o;
if (myAny != node.myAny) return false;
if (myNothing != node.myNothing) return false;
if (myResolveState != node.myResolveState) return false;
if (mySchema != null ? !mySchema.equals(node.mySchema) : node.mySchema != null) return false;
//noinspection RedundantIfStatement
if (!mySteps.equals(node.mySteps)) return false;
return true;
}
@Override
public int hashCode() {
int result = (myAny ? 1 : 0);
result = 31 * result + (myNothing ? 1 : 0);
result = 31 * result + myResolveState.hashCode();
result = 31 * result + (mySchema != null ? mySchema.hashCode() : 0);
result = 31 * result + mySteps.hashCode();
return result;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("NODE#" + hashCode() + "\n");
sb.append(mySteps.stream().map(Object::toString).collect(Collectors.joining("->", "steps: <", ">")));
sb.append("\n");
if (myExcludingGroupNumber >= 0) sb.append("in excluding group\n");
if (myAny) sb.append("any");
else if (myNothing) sb.append("nothing");
else if (!SchemaResolveState.normal.equals(myResolveState)) sb.append(myResolveState.name());
else {
assert mySchema != null;
final String name = mySchema.getSchemaFile().getName();
sb.append("schema from file: ").append(name).append("\n");
if (mySchema.getRef() != null) sb.append("$ref: ").append(mySchema.getRef()).append("\n");
else if (!mySchema.getProperties().isEmpty()) {
sb.append("properties: ");
sb.append(mySchema.getProperties().keySet().stream().collect(Collectors.joining(", "))).append("\n");
}
if (!myChildren.isEmpty()) {
sb.append("OR children of NODE#").append(hashCode()).append(":\n----------------\n")
.append(myChildren.stream().map(Object::toString).collect(Collectors.joining("\n")))
.append("\n=================\n");
}
}
return sb.toString();
}
}
| ThiagoGarciaAlves/intellij-community | json/src/com/jetbrains/jsonSchema/impl/JsonSchemaTreeNode.java | Java | apache-2.0 | 6,194 |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
export default [
'en-ZM',
[
['a', 'p'],
['AM', 'PM'],
],
[
['AM', 'PM'],
,
],
[
['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
],
,
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
[
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',
'October', 'November', 'December'
]
],
,
[['B', 'A'], ['BC', 'AD'], ['Before Christ', 'Anno Domini']], 1, [6, 0],
['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE, d MMMM y'],
['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'],
[
'{1}, {0}',
,
'{1} \'at\' {0}',
],
['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'], 'K', 'Zambian Kwacha',
function (n) {
var i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length;
if (i === 1 && v === 0)
return 1;
return 5;
}
];
//# sourceMappingURL=en-ZM.js.map | N03297857/2017Fall | node_modules/@angular/common/locales/en-ZM.js | JavaScript | apache-2.0 | 1,661 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Senparc.Weixin.Entities;
namespace Senparc.Weixin.QY.Entities.Request.KF
{
public class RequestPack : IEntityBase
{
public AgentType AgentType { get; set; }
public string ToUserName { get; set; }
public int ItemCount { get; set; }
public List<RequestBase> Items { get; set; }
public long PackageId { get; set; }
}
public enum AgentType
{
/// <summary>
/// 内部客服
/// </summary>
kf_internal,
/// <summary>
/// 外部客服
/// </summary>
kf_external
}
}
| lishewen/WeiXinMPSDK | src/Senparc.Weixin.QY/Senparc.Weixin.QY/Entities/Request/KF/RequestMessagePack.cs | C# | apache-2.0 | 714 |
/*
* Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Protocol utils
*/
package com.hazelcast.client.impl.protocol.util;
| dbrimley/hazelcast | hazelcast/src/main/java/com/hazelcast/client/impl/protocol/util/package-info.java | Java | apache-2.0 | 702 |
/*
* Copyright by 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
*
* 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 wallettemplate;
import com.google.common.util.concurrent.*;
import javafx.scene.input.*;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.kits.WalletAppKit;
import org.bitcoinj.params.*;
import org.bitcoinj.utils.BriefLogFormatter;
import org.bitcoinj.utils.Threading;
import org.bitcoinj.wallet.DeterministicSeed;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import wallettemplate.controls.NotificationBarPane;
import wallettemplate.utils.GuiUtils;
import wallettemplate.utils.TextFieldValidator;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import static wallettemplate.utils.GuiUtils.*;
public class Main extends Application {
public static NetworkParameters params = MainNetParams.get();
public static final String APP_NAME = "WalletTemplate";
private static final String WALLET_FILE_NAME = APP_NAME.replaceAll("[^a-zA-Z0-9.-]", "_") + "-"
+ params.getPaymentProtocolId();
public static WalletAppKit bitcoin;
public static Main instance;
private StackPane uiStack;
private Pane mainUI;
public MainController controller;
public NotificationBarPane notificationBar;
public Stage mainWindow;
@Override
public void start(Stage mainWindow) throws Exception {
try {
realStart(mainWindow);
} catch (Throwable e) {
GuiUtils.crashAlert(e);
throw e;
}
}
private void realStart(Stage mainWindow) throws IOException {
this.mainWindow = mainWindow;
instance = this;
// Show the crash dialog for any exceptions that we don't handle and that hit the main loop.
GuiUtils.handleCrashesOnThisThread();
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
// We could match the Mac Aqua style here, except that (a) Modena doesn't look that bad, and (b)
// the date picker widget is kinda broken in AquaFx and I can't be bothered fixing it.
// AquaFx.style();
}
// Load the GUI. The MainController class will be automagically created and wired up.
URL location = getClass().getResource("main.fxml");
FXMLLoader loader = new FXMLLoader(location);
mainUI = loader.load();
controller = loader.getController();
// Configure the window with a StackPane so we can overlay things on top of the main UI, and a
// NotificationBarPane so we can slide messages and progress bars in from the bottom. Note that
// ordering of the construction and connection matters here, otherwise we get (harmless) CSS error
// spew to the logs.
notificationBar = new NotificationBarPane(mainUI);
mainWindow.setTitle(APP_NAME);
uiStack = new StackPane();
Scene scene = new Scene(uiStack);
TextFieldValidator.configureScene(scene); // Add CSS that we need.
scene.getStylesheets().add(getClass().getResource("wallet.css").toString());
uiStack.getChildren().add(notificationBar);
mainWindow.setScene(scene);
// Make log output concise.
BriefLogFormatter.init();
// Tell bitcoinj to run event handlers on the JavaFX UI thread. This keeps things simple and means
// we cannot forget to switch threads when adding event handlers. Unfortunately, the DownloadListener
// we give to the app kit is currently an exception and runs on a library thread. It'll get fixed in
// a future version.
Threading.USER_THREAD = Platform::runLater;
// Create the app kit. It won't do any heavyweight initialization until after we start it.
setupWalletKit(null);
if (bitcoin.isChainFileLocked()) {
informationalAlert("Already running", "This application is already running and cannot be started twice.");
Platform.exit();
return;
}
mainWindow.show();
WalletSetPasswordController.estimateKeyDerivationTimeMsec();
bitcoin.addListener(new Service.Listener() {
@Override
public void failed(Service.State from, Throwable failure) {
GuiUtils.crashAlert(failure);
}
}, Platform::runLater);
bitcoin.startAsync();
scene.getAccelerators().put(KeyCombination.valueOf("Shortcut+F"), () -> bitcoin.peerGroup().getDownloadPeer().close());
}
public void setupWalletKit(@Nullable DeterministicSeed seed) {
// If seed is non-null it means we are restoring from backup.
bitcoin = new WalletAppKit(params, new File("."), WALLET_FILE_NAME) {
@Override
protected void onSetupCompleted() {
// Don't make the user wait for confirmations for now, as the intention is they're sending it
// their own money!
bitcoin.wallet().allowSpendingUnconfirmedTransactions();
Platform.runLater(controller::onBitcoinSetup);
}
};
// Now configure and start the appkit. This will take a second or two - we could show a temporary splash screen
// or progress widget to keep the user engaged whilst we initialise, but we don't.
if (params == RegTestParams.get()) {
bitcoin.connectToLocalHost(); // You should run a regtest mode bitcoind locally.
} else if (params == TestNet3Params.get()) {
// As an example!
bitcoin.useTor();
// bitcoin.setDiscovery(new HttpDiscovery(params, URI.create("http://localhost:8080/peers"), ECKey.fromPublicOnly(BaseEncoding.base16().decode("02cba68cfd0679d10b186288b75a59f9132b1b3e222f6332717cb8c4eb2040f940".toUpperCase()))));
}
bitcoin.setDownloadListener(controller.progressBarUpdater())
.setBlockingStartup(false)
.setUserAgent(APP_NAME, "1.0");
if (seed != null)
bitcoin.restoreWalletFromSeed(seed);
}
private Node stopClickPane = new Pane();
public class OverlayUI<T> {
public Node ui;
public T controller;
public OverlayUI(Node ui, T controller) {
this.ui = ui;
this.controller = controller;
}
public void show() {
checkGuiThread();
if (currentOverlay == null) {
uiStack.getChildren().add(stopClickPane);
uiStack.getChildren().add(ui);
blurOut(mainUI);
//darken(mainUI);
fadeIn(ui);
zoomIn(ui);
} else {
// Do a quick transition between the current overlay and the next.
// Bug here: we don't pay attention to changes in outsideClickDismisses.
explodeOut(currentOverlay.ui);
fadeOutAndRemove(uiStack, currentOverlay.ui);
uiStack.getChildren().add(ui);
ui.setOpacity(0.0);
fadeIn(ui, 100);
zoomIn(ui, 100);
}
currentOverlay = this;
}
public void outsideClickDismisses() {
stopClickPane.setOnMouseClicked((ev) -> done());
}
public void done() {
checkGuiThread();
if (ui == null) return; // In the middle of being dismissed and got an extra click.
explodeOut(ui);
fadeOutAndRemove(uiStack, ui, stopClickPane);
blurIn(mainUI);
//undark(mainUI);
this.ui = null;
this.controller = null;
currentOverlay = null;
}
}
@Nullable
private OverlayUI currentOverlay;
public <T> OverlayUI<T> overlayUI(Node node, T controller) {
checkGuiThread();
OverlayUI<T> pair = new OverlayUI<T>(node, controller);
// Auto-magically set the overlayUI member, if it's there.
try {
controller.getClass().getField("overlayUI").set(controller, pair);
} catch (IllegalAccessException | NoSuchFieldException ignored) {
}
pair.show();
return pair;
}
/** Loads the FXML file with the given name, blurs out the main UI and puts this one on top. */
public <T> OverlayUI<T> overlayUI(String name) {
try {
checkGuiThread();
// Load the UI from disk.
URL location = GuiUtils.getResource(name);
FXMLLoader loader = new FXMLLoader(location);
Pane ui = loader.load();
T controller = loader.getController();
OverlayUI<T> pair = new OverlayUI<T>(ui, controller);
// Auto-magically set the overlayUI member, if it's there.
try {
if (controller != null)
controller.getClass().getField("overlayUI").set(controller, pair);
} catch (IllegalAccessException | NoSuchFieldException ignored) {
ignored.printStackTrace();
}
pair.show();
return pair;
} catch (IOException e) {
throw new RuntimeException(e); // Can't happen.
}
}
@Override
public void stop() throws Exception {
bitcoin.stopAsync();
bitcoin.awaitTerminated();
// Forcibly terminate the JVM because Orchid likes to spew non-daemon threads everywhere.
Runtime.getRuntime().exit(0);
}
public static void main(String[] args) {
launch(args);
}
}
| paulminer/bitcoinj | wallettemplate/src/main/java/wallettemplate/Main.java | Java | apache-2.0 | 10,314 |
/*
* Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.internal.util.filter;
/**
* Filter matching only when both sub-filters are matching
*
* @param <T>
*/
public final class AndFilter<T> implements Filter<T> {
private final Filter<T> filter1;
private final Filter<T> filter2;
public AndFilter(Filter<T> filter1, Filter<T> filter2) {
this.filter1 = filter1;
this.filter2 = filter2;
}
@Override
public boolean accept(T object) {
return filter1.accept(object) && filter2.accept(object);
}
}
| Donnerbart/hazelcast | hazelcast/src/main/java/com/hazelcast/internal/util/filter/AndFilter.java | Java | apache-2.0 | 1,144 |
/*
* Copyright 2012-2021 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.docs.appendix.configurationmetadata.annotationprocessor.automaticmetadatageneration;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "my.server")
public class MyServerProperties {
/**
* Name of the server.
*/
private String name;
/**
* IP address to listen to.
*/
private String ip = "127.0.0.1";
/**
* Port to listener to.
*/
private int port = 9797;
// @fold:on // getters/setters ...
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getIp() {
return this.ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
// fold:off
}
| spring-projects/spring-boot | spring-boot-project/spring-boot-docs/src/main/java/org/springframework/boot/docs/appendix/configurationmetadata/annotationprocessor/automaticmetadatageneration/MyServerProperties.java | Java | apache-2.0 | 1,460 |
/**
* 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;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.ScheduledChore;
import org.apache.hadoop.hbase.Stoppable;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.master.cleaner.TimeToLiveHFileCleaner;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
import org.apache.hadoop.util.StringUtils;
/**
* A chore for refreshing the store files for secondary regions hosted in the region server.
*
* This chore should run periodically with a shorter interval than HFile TTL
* ("hbase.master.hfilecleaner.ttl", default 5 minutes).
* It ensures that if we cannot refresh files longer than that amount, the region
* will stop serving read requests because the referenced files might have been deleted (by the
* primary region).
*/
@InterfaceAudience.Private
public class StorefileRefresherChore extends ScheduledChore {
private static final Log LOG = LogFactory.getLog(StorefileRefresherChore.class);
/**
* The period (in milliseconds) for refreshing the store files for the secondary regions.
*/
public static final String REGIONSERVER_STOREFILE_REFRESH_PERIOD
= "hbase.regionserver.storefile.refresh.period";
static final int DEFAULT_REGIONSERVER_STOREFILE_REFRESH_PERIOD = 0; //disabled by default
/**
* Whether all storefiles should be refreshed, as opposed to just hbase:meta's
* Meta region doesn't have WAL replication for replicas enabled yet
*/
public static final String REGIONSERVER_META_STOREFILE_REFRESH_PERIOD
= "hbase.regionserver.meta.storefile.refresh.period";
private HRegionServer regionServer;
private long hfileTtl;
private int period;
private boolean onlyMetaRefresh = true;
//ts of last time regions store files are refreshed
private Map<String, Long> lastRefreshTimes; // encodedName -> long
public StorefileRefresherChore(int period, boolean onlyMetaRefresh, HRegionServer regionServer,
Stoppable stoppable) {
super("StorefileRefresherChore", stoppable, period);
this.period = period;
this.regionServer = regionServer;
this.hfileTtl = this.regionServer.getConfiguration().getLong(
TimeToLiveHFileCleaner.TTL_CONF_KEY, TimeToLiveHFileCleaner.DEFAULT_TTL);
this.onlyMetaRefresh = onlyMetaRefresh;
if (period > hfileTtl / 2) {
throw new RuntimeException(REGIONSERVER_STOREFILE_REFRESH_PERIOD +
" should be set smaller than half of " + TimeToLiveHFileCleaner.TTL_CONF_KEY);
}
lastRefreshTimes = new HashMap<String, Long>();
}
@Override
protected void chore() {
for (HRegion r : regionServer.getOnlineRegionsLocalContext()) {
if (!r.writestate.isReadOnly()) {
// skip checking for this region if it can accept writes
continue;
}
// don't refresh unless enabled for all files, or it the meta region
// meta region don't have WAL replication for replicas enabled yet
if (onlyMetaRefresh && !r.getRegionInfo().isMetaTable()) continue;
String encodedName = r.getRegionInfo().getEncodedName();
long time = EnvironmentEdgeManager.currentTime();
if (!lastRefreshTimes.containsKey(encodedName)) {
lastRefreshTimes.put(encodedName, time);
}
try {
for (Store store : r.getStores().values()) {
// TODO: some stores might see new data from flush, while others do not which
// MIGHT break atomic edits across column families. We can fix this with setting
// mvcc read numbers that we know every store has seen
store.refreshStoreFiles();
}
} catch (IOException ex) {
LOG.warn("Exception while trying to refresh store files for region:" + r.getRegionInfo()
+ ", exception:" + StringUtils.stringifyException(ex));
// Store files have a TTL in the archive directory. If we fail to refresh for that long, we stop serving reads
if (isRegionStale(encodedName, time)) {
r.setReadsEnabled(false); // stop serving reads
}
continue;
}
lastRefreshTimes.put(encodedName, time);
r.setReadsEnabled(true); // restart serving reads
}
// remove closed regions
Iterator<String> lastRefreshTimesIter = lastRefreshTimes.keySet().iterator();
while (lastRefreshTimesIter.hasNext()) {
String encodedName = lastRefreshTimesIter.next();
if (regionServer.getFromOnlineRegions(encodedName) == null) {
lastRefreshTimesIter.remove();
}
}
}
protected boolean isRegionStale(String encodedName, long time) {
long lastRefreshTime = lastRefreshTimes.get(encodedName);
return time - lastRefreshTime > hfileTtl - period;
}
}
| justintung/hbase | hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/StorefileRefresherChore.java | Java | apache-2.0 | 5,683 |
define(["require", "exports", "./base", "./layer", "./util", "./view"], function (require, exports, base_1, layer_1, util_1, view_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.COL_LABELS = base_1.COL_LABELS;
class Board extends view_1.View {
constructor(parent, position, layers) {
super();
this.position = position;
this.layers = [];
if (typeof (parent) == 'string') {
parent = util_1.getElement(parent);
}
this.elem = parent;
this.backgroundColor = '#db6';
let canvas = document.createElement('canvas');
this.ctx = canvas.getContext('2d');
parent.appendChild(canvas);
window.addEventListener('resize', () => {
this.resizeCanvas();
this.draw();
});
this.resizeCanvas();
this.addLayer(new layer_1.Grid());
this.addLayers(layers);
}
resizeCanvas() {
let pr = util_1.pixelRatio();
let canvas = this.ctx.canvas;
let parent = canvas.parentElement;
canvas.width = pr * (parent.offsetWidth);
canvas.height = pr * (parent.offsetHeight);
canvas.style.width = `${parent.offsetWidth}px`;
canvas.style.height = `${parent.offsetHeight}px`;
this.pointW = this.ctx.canvas.width / (base_1.N + 1);
this.pointH = this.ctx.canvas.height / (base_1.N + 1);
this.stoneRadius = 0.96 * Math.min(this.pointW, this.pointH) / 2;
}
newGame(rootPosition) {
this.position = rootPosition;
for (let layer of this.layers) {
layer.clear();
}
this.draw();
}
addLayer(layer) {
this.layers.push(layer);
layer.addToBoard(this);
}
addLayers(layers) {
for (let layer of layers) {
this.addLayer(layer);
}
}
setPosition(position) {
if (this.position == position) {
return;
}
this.position = position;
let allProps = new Set(Object.keys(position));
for (let layer of this.layers) {
layer.update(allProps);
}
this.draw();
}
update(update) {
let anythingChanged = false;
let keys = new Set(Object.keys(update));
for (let layer of this.layers) {
if (layer.update(keys)) {
anythingChanged = true;
}
}
if (anythingChanged) {
this.draw();
}
}
drawImpl() {
let ctx = this.ctx;
ctx.fillStyle = this.backgroundColor;
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
for (let layer of this.layers) {
if (layer.show) {
layer.draw();
}
}
}
getStone(p) {
return this.position.stones[p.row * base_1.N + p.col];
}
canvasToBoard(x, y, threshold) {
let pr = util_1.pixelRatio();
x *= pr;
y *= pr;
let canvas = this.ctx.canvas;
y = y * (base_1.N + 1) / canvas.height - 0.5;
x = x * (base_1.N + 1) / canvas.width - 0.5;
let row = Math.floor(y);
let col = Math.floor(x);
if (row < 0 || row >= base_1.N || col < 0 || col >= base_1.N) {
return null;
}
if (threshold) {
let fx = 0.5 - (x - col);
let fy = 0.5 - (y - row);
let disSqr = fx * fx + fy * fy;
if (disSqr > threshold * threshold) {
return null;
}
}
return { row: row, col: col };
}
boardToCanvas(row, col) {
let canvas = this.ctx.canvas;
return {
x: canvas.width * (col + 1.0) / (base_1.N + 1),
y: canvas.height * (row + 1.0) / (base_1.N + 1)
};
}
drawStones(ps, color, alpha) {
if (ps.length == 0) {
return;
}
let ctx = this.ctx;
let pr = util_1.pixelRatio();
if (alpha == 1) {
ctx.shadowBlur = 4 * pr;
ctx.shadowOffsetX = 1.5 * pr;
ctx.shadowOffsetY = 1.5 * pr;
ctx.shadowColor = `rgba(0, 0, 0, ${color == base_1.Color.Black ? 0.4 : 0.3})`;
}
ctx.fillStyle = this.stoneFill(color, alpha);
let r = this.stoneRadius;
for (let p of ps) {
let c = this.boardToCanvas(p.row, p.col);
ctx.beginPath();
ctx.translate(c.x + 0.5, c.y + 0.5);
ctx.arc(0, 0, r, 0, 2 * Math.PI);
ctx.fill();
ctx.setTransform(1, 0, 0, 1, 0, 0);
}
if (alpha == 1) {
ctx.shadowColor = 'rgba(0, 0, 0, 0)';
}
}
stoneFill(color, alpha) {
let grad;
if (color == base_1.Color.Black) {
let ofs = -0.5 * this.stoneRadius;
grad = this.ctx.createRadialGradient(ofs, ofs, 0, ofs, ofs, 2 * this.stoneRadius);
grad.addColorStop(0, `rgba(68, 68, 68, ${alpha})`);
grad.addColorStop(1, `rgba(16, 16, 16, ${alpha})`);
}
else if (color == base_1.Color.White) {
let ofs = -0.2 * this.stoneRadius;
grad = this.ctx.createRadialGradient(ofs, ofs, 0, ofs, ofs, 1.2 * this.stoneRadius);
grad.addColorStop(0.4, `rgba(255, 255, 255, ${alpha})`);
grad.addColorStop(1, `rgba(204, 204, 204, ${alpha})`);
}
else {
throw new Error(`Invalid color ${color}`);
}
return grad;
}
}
exports.Board = Board;
class ClickableBoard extends Board {
constructor(parent, position, layerDescs) {
super(parent, position, layerDescs);
this.enabled = false;
this.listeners = [];
this.ctx.canvas.addEventListener('mousemove', (e) => {
let p = this.canvasToBoard(e.offsetX, e.offsetY, 0.45);
if (p != null && this.getStone(p) != base_1.Color.Empty) {
p = null;
}
let changed;
if (p != null) {
changed = this.p == null || this.p.row != p.row || this.p.col != p.col;
}
else {
changed = this.p != null;
}
if (changed) {
this.p = p;
this.draw();
}
});
this.ctx.canvas.addEventListener('mouseleave', (e) => {
if (this.p != null) {
this.p = null;
this.draw();
}
});
this.ctx.canvas.addEventListener('click', (e) => {
if (!this.p || !this.enabled) {
return;
}
for (let listener of this.listeners) {
listener(this.p);
}
this.p = null;
this.draw();
});
}
onClick(cb) {
this.listeners.push(cb);
}
setPosition(position) {
if (position != this.position) {
this.p = null;
super.setPosition(position);
}
}
drawImpl() {
super.drawImpl();
let p = this.enabled ? this.p : null;
this.ctx.canvas.style.cursor = p ? 'pointer' : '';
if (p) {
this.drawStones([p], this.position.toPlay, 0.6);
}
}
}
exports.ClickableBoard = ClickableBoard;
});
//# sourceMappingURL=board.js.map | tensorflow/minigo | minigui/static/board.js | JavaScript | apache-2.0 | 8,219 |
package com.rincliu.library.common.persistence.image.core.assist;
/**
* Source image loaded from.
*
* @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
*/
public enum LoadedFrom {
NETWORK, DISC_CACHE, MEMORY_CACHE
}
| hugoYe/Roid-Library | src/com/rincliu/library/common/persistence/image/core/assist/LoadedFrom.java | Java | apache-2.0 | 240 |
package com.way.beans;
import android.os.Parcel;
import android.os.Parcelable;
public class City implements Parcelable {
private String province;
private String city;
private String name;
private String pinyin;
private String py;
private String phoneCode;
private String areaCode;
private String postID;
private long refreshTime;
private int isLocation;
private long pubTime;
private String weatherInfoStr;
public City() {
}
public City(String name, String postID, long refreshTime, int isLocation, long pubTime, String weatherInfoStr) {
super();
this.name = name;
this.postID = postID;
this.refreshTime = refreshTime;
this.isLocation = isLocation;
this.pubTime = pubTime;
this.weatherInfoStr = weatherInfoStr;
}
public City(String name, String postID) {
super();
this.name = name;
this.postID = postID;
}
public City(String province, String city, String name, String pinyin,
String py, String phoneCode, String areaCode, String postID) {
super();
this.province = province;
this.city = city;
this.name = name;
this.pinyin = pinyin;
this.py = py;
this.phoneCode = phoneCode;
this.areaCode = areaCode;
this.postID = postID;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPinyin() {
return pinyin;
}
public void setPinyin(String pinyin) {
this.pinyin = pinyin;
}
public String getPy() {
return py;
}
public void setPy(String py) {
this.py = py;
}
public String getPhoneCode() {
return phoneCode;
}
public void setPhoneCode(String phoneCode) {
this.phoneCode = phoneCode;
}
public String getAreaCode() {
return areaCode;
}
public void setAreaCode(String areaCode) {
this.areaCode = areaCode;
}
public String getPostID() {
return postID;
}
public void setPostID(String postID) {
this.postID = postID;
}
public boolean getIsLocation() {
return isLocation == 0 ? false : true;
}
public void setIsLocation(int isLocation) {
this.isLocation = isLocation;
}
public long getRefreshTime() {
return refreshTime;
}
public void setRefreshTime(long refreshTime) {
this.refreshTime = refreshTime;
}
public long getPubTime() {
return pubTime;
}
public void setPubTime(long pubTime) {
this.pubTime = pubTime;
}
public String getWeatherInfoStr() {
return weatherInfoStr;
}
public void setWeatherInfoStr(String weatherInfoStr) {
this.weatherInfoStr = weatherInfoStr;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + postID != null ? postID.hashCode() : 0;
return result;
}
@Override
public boolean equals(Object o) {
if (o == null)
return false;
if (o == this)
return true;
if (o instanceof City) {
City item = (City) o;
if (item.getPostID().equals(this.postID))
return true;
}
return false;
}
@Override
public String toString() {
return "City [province=" + province + ", city=" + city + ", name="
+ name + ", pinyin=" + pinyin + ", py=" + py + ", phoneCode="
+ phoneCode + ", areaCode=" + areaCode + ", postID=" + postID
+ ", refreshTime=" + refreshTime + ", isLocation=" + isLocation
+ "]";
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(province);
dest.writeString(city);
dest.writeString(name);
dest.writeString(pinyin);
dest.writeString(py);
dest.writeString(phoneCode);
dest.writeString(areaCode);
dest.writeString(postID);
dest.writeLong(refreshTime);
dest.writeInt(isLocation);
}
public static final Parcelable.Creator<City> CREATOR = new Creator<City>() {
@Override
public City createFromParcel(Parcel source) {
City city = new City();
city.province = source.readString();
city.city = source.readString();
city.name = source.readString();
city.pinyin = source.readString();
city.py = source.readString();
city.phoneCode = source.readString();
city.areaCode = source.readString();
city.postID = source.readString();
city.refreshTime = source.readLong();
city.isLocation = source.readInt();
return city;
}
@Override
public City[] newArray(int size) {
return new City[size];
}
};
}
| hnyzwtf/WayHoo | WayHoo/src/com/way/beans/City.java | Java | apache-2.0 | 4,503 |
package org.wikidata.wdtk.dumpfiles.wmf;
/*
* #%L
* Wikidata Toolkit Dump File Handling
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* 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.
* #L%
*/
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Paths;
import org.junit.Before;
import org.junit.Test;
import org.wikidata.wdtk.dumpfiles.DumpContentType;
import org.wikidata.wdtk.testing.MockDirectoryManager;
import org.wikidata.wdtk.testing.MockWebResourceFetcher;
import org.wikidata.wdtk.util.CompressionType;
public class WmfOnlineDailyDumpFileTest {
MockWebResourceFetcher wrf;
MockDirectoryManager dm;
@Before
public void setUp() throws IOException {
dm = new MockDirectoryManager(Paths.get(System.getProperty("user.dir")));
wrf = new MockWebResourceFetcher();
}
@Test
public void validDumpProperties() throws IOException {
String dateStamp = "20140220";
wrf.setWebResourceContents(
"http://dumps.wikimedia.org/other/incr/wikidatawiki/"
+ dateStamp + "/status.txt", "done");
wrf.setWebResourceContents(
"http://dumps.wikimedia.org/other/incr/wikidatawiki/"
+ dateStamp + "/wikidatawiki-" + dateStamp
+ "-pages-meta-hist-incr.xml.bz2", "Line1",
CompressionType.BZ2);
WmfOnlineDailyDumpFile dump = new WmfOnlineDailyDumpFile(dateStamp,
"wikidatawiki", wrf, dm);
BufferedReader br = dump.getDumpFileReader();
assertEquals(br.readLine(), "Line1");
assertEquals(br.readLine(), null);
assertTrue(dump.isAvailable());
assertTrue(dump.isAvailable()); // second time should use cached entry
assertEquals(dateStamp, dump.getDateStamp());
assertEquals("wikidatawiki", dump.getProjectName());
assertEquals("wikidatawiki-daily-" + dateStamp, dump.toString());
assertEquals(DumpContentType.DAILY, dump.getDumpContentType());
}
@Test
public void missingDumpProperties() {
String dateStamp = "20140220";
WmfOnlineDailyDumpFile dump = new WmfOnlineDailyDumpFile(dateStamp,
"wikidatawiki", wrf, dm);
assertTrue(!dump.isAvailable());
assertEquals(dateStamp, dump.getDateStamp());
}
@Test
public void emptyDumpProperties() throws IOException {
String dateStamp = "20140220";
wrf.setWebResourceContents(
"http://dumps.wikimedia.org/other/incr/wikidatawiki/"
+ dateStamp + "/status.txt", "");
WmfOnlineDailyDumpFile dump = new WmfOnlineDailyDumpFile(dateStamp,
"wikidatawiki", wrf, dm);
assertTrue(!dump.isAvailable());
assertEquals(dateStamp, dump.getDateStamp());
}
@Test
public void inaccessibleStatus() throws IOException {
String dateStamp = "20140220";
wrf.setWebResourceContents(
"http://dumps.wikimedia.org/other/incr/wikidatawiki/"
+ dateStamp + "/status.txt", "done");
wrf.setReturnFailingReaders(true);
WmfOnlineDailyDumpFile dump = new WmfOnlineDailyDumpFile(dateStamp,
"wikidatawiki", wrf, dm);
assertTrue(!dump.isAvailable());
}
@Test(expected = IOException.class)
public void downloadNoRevisionId() throws IOException {
String dateStamp = "20140220";
wrf.setWebResourceContents(
"http://dumps.wikimedia.org/other/incr/wikidatawiki/"
+ dateStamp + "/wikidatawiki-" + dateStamp
+ "-pages-meta-hist-incr.xml.bz2", "Line1",
CompressionType.BZ2);
WmfOnlineDailyDumpFile dump = new WmfOnlineDailyDumpFile(dateStamp,
"wikidatawiki", wrf, dm);
dump.getDumpFileReader();
}
@Test(expected = IOException.class)
public void downloadNoDumpFile() throws IOException {
String dateStamp = "20140220";
wrf.setWebResourceContents(
"http://dumps.wikimedia.org/other/incr/wikidatawiki/"
+ dateStamp + "/status.txt", "done");
WmfOnlineDailyDumpFile dump = new WmfOnlineDailyDumpFile(dateStamp,
"wikidatawiki", wrf, dm);
dump.getDumpFileReader();
}
}
| zazi/Wikidata-Toolkit | wdtk-dumpfiles/src/test/java/org/wikidata/wdtk/dumpfiles/wmf/WmfOnlineDailyDumpFileTest.java | Java | apache-2.0 | 4,391 |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# 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.
""" metrichandler.py """
import traceback
import tornado.gen
import tornado.web
from heron.common.src.python.utils.log import Log
from heron.proto import common_pb2
from heron.proto import tmaster_pb2
from heron.tools.tracker.src.python import constants
from heron.tools.tracker.src.python.handlers import BaseHandler
class MetricsHandler(BaseHandler):
"""
URL - /topologies/metrics
Parameters:
- cluster (required)
- role - (optional) Role used to submit the topology.
- environ (required)
- topology (required) name of the requested topology
- component (required)
- metricname (required, repeated)
- interval (optional)
- instance (optional, repeated)
The response JSON is a map of all the requested
(or if nothing is mentioned, all) components
of the topology, to the metrics that are reported
by that component.
"""
# pylint: disable=attribute-defined-outside-init
def initialize(self, tracker):
""" initialize """
self.tracker = tracker
@tornado.gen.coroutine
def get(self):
""" get method """
try:
cluster = self.get_argument_cluster()
role = self.get_argument_role()
environ = self.get_argument_environ()
topology_name = self.get_argument_topology()
component = self.get_argument_component()
metric_names = self.get_required_arguments_metricnames()
topology = self.tracker.getTopologyByClusterRoleEnvironAndName(
cluster, role, environ, topology_name)
interval = int(self.get_argument(constants.PARAM_INTERVAL, default=-1))
instances = self.get_arguments(constants.PARAM_INSTANCE)
metrics = yield tornado.gen.Task(
self.getComponentMetrics,
topology.tmaster, component, metric_names, instances, interval)
self.write_success_response(metrics)
except Exception as e:
Log.debug(traceback.format_exc())
self.write_error_response(e)
# pylint: disable=too-many-locals, no-self-use, unused-argument
@tornado.gen.coroutine
def getComponentMetrics(self,
tmaster,
componentName,
metricNames,
instances,
interval,
callback=None):
"""
Get the specified metrics for the given component name of this topology.
Returns the following dict on success:
{
"metrics": {
<metricname>: {
<instance>: <numeric value>,
<instance>: <numeric value>,
...
}, ...
},
"interval": <numeric value>,
"component": "..."
}
Raises exception on failure.
"""
if not tmaster or not tmaster.host or not tmaster.stats_port:
raise Exception("No Tmaster found")
host = tmaster.host
port = tmaster.stats_port
metricRequest = tmaster_pb2.MetricRequest()
metricRequest.component_name = componentName
if len(instances) > 0:
for instance in instances:
metricRequest.instance_id.append(instance)
for metricName in metricNames:
metricRequest.metric.append(metricName)
metricRequest.interval = interval
# Serialize the metricRequest to send as a payload
# with the HTTP request.
metricRequestString = metricRequest.SerializeToString()
url = "http://{0}:{1}/stats".format(host, port)
request = tornado.httpclient.HTTPRequest(url,
body=metricRequestString,
method='POST',
request_timeout=5)
Log.debug("Making HTTP call to fetch metrics")
Log.debug("url: " + url)
try:
client = tornado.httpclient.AsyncHTTPClient()
result = yield client.fetch(request)
Log.debug("HTTP call complete.")
except tornado.httpclient.HTTPError as e:
raise Exception(str(e))
# Check the response code - error if it is in 400s or 500s
responseCode = result.code
if responseCode >= 400:
message = "Error in getting metrics from Tmaster, code: " + responseCode
Log.error(message)
raise Exception(message)
# Parse the response from tmaster.
metricResponse = tmaster_pb2.MetricResponse()
metricResponse.ParseFromString(result.body)
if metricResponse.status.status == common_pb2.NOTOK:
if metricResponse.status.HasField("message"):
Log.warn("Received response from Tmaster: %s", metricResponse.status.message)
# Form the response.
ret = {}
ret["interval"] = metricResponse.interval
ret["component"] = componentName
ret["metrics"] = {}
for metric in metricResponse.metric:
instance = metric.instance_id
for im in metric.metric:
metricname = im.name
value = im.value
if metricname not in ret["metrics"]:
ret["metrics"][metricname] = {}
ret["metrics"][metricname][instance] = value
raise tornado.gen.Return(ret)
| mycFelix/heron | heron/tools/tracker/src/python/handlers/metricshandler.py | Python | apache-2.0 | 5,834 |
# Copyright 2014, Jeff Buttars, A10 Networks.
#
# 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.
import acos_client.errors as acos_errors
import acos_client.v30.base as base
class HealthMonitor(base.BaseV30):
# Valid method objects
ICMP = 'icmp'
TCP = 'tcp'
HTTP = 'http'
HTTPS = 'https'
url_prefix = "/health/monitor/"
_method_objects = {
ICMP: {
"icmp": 1
},
HTTP: {
"http": 1,
"http-port": 80,
"http-expect": 1,
"http-response-code": "200",
"http-url": 1,
"url-type": "GET",
"url-path": "/",
},
HTTPS: {
"https": 1,
"web-port": 443,
"https-expect": 1,
"https-response-code": "200",
"https-url": 1,
"url-type": "GET",
"url-path": "/",
"disable-sslv2hello": 0
},
TCP: {
"method-tcp": 1,
"tcp-port": 80
},
}
def get(self, name, **kwargs):
return self._get(self.url_prefix + name, **kwargs)
def _set(self, action, name, mon_method, interval, timeout, max_retries,
method=None, url=None, expect_code=None, port=None, update=False,
**kwargs):
params = {
"monitor": {
"name": name,
"retry": int(max_retries),
"interval": int(interval),
"timeout": int(timeout),
"method": {
mon_method: self._method_objects[mon_method]
}
}
}
if method:
params['monitor']['method'][mon_method]['url-type'] = method
if url:
params['monitor']['method'][mon_method]['url-path'] = url
if expect_code:
k = "%s-response-code" % mon_method
params['monitor']['method'][mon_method][k] = str(expect_code)
if port:
if mon_method == self.HTTPS:
k = 'web-port'
else:
k = '%s-port' % mon_method
params['monitor']['method'][mon_method][k] = int(port)
if update:
action += name
self._post(action, params, **kwargs)
def create(self, name, mon_type, interval, timeout, max_retries,
method=None, url=None, expect_code=None, port=None, **kwargs):
try:
self.get(name)
except acos_errors.NotFound:
pass
else:
raise acos_errors.Exists()
self._set(self.url_prefix, name, mon_type, interval, timeout,
max_retries, method, url, expect_code, port, **kwargs)
def update(self, name, mon_type, interval, timeout, max_retries,
method=None, url=None, expect_code=None, port=None, **kwargs):
self.get(name) # We want a NotFound if it does not exist
self._set(self.url_prefix, name, mon_type, interval, timeout,
max_retries, method, url, expect_code, port, update=True,
**kwargs)
def delete(self, name):
self._delete(self.url_prefix + name)
| dougwig/acos-client | acos_client/v30/slb/hm.py | Python | apache-2.0 | 3,696 |
// 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;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Microsoft.DiaSymReader;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// The compilation object is an immutable representation of a single invocation of the
/// compiler. Although immutable, a compilation is also on-demand, and will realize and cache
/// data as necessary. A compilation can produce a new compilation from existing compilation
/// with the application of small deltas. In many cases, it is more efficient than creating a
/// new compilation from scratch, as the new compilation can reuse information from the old
/// compilation.
/// </summary>
public abstract partial class Compilation
{
/// <summary>
/// Returns true if this is a case sensitive compilation, false otherwise. Case sensitivity
/// affects compilation features such as name lookup as well as choosing what names to emit
/// when there are multiple different choices (for example between a virtual method and an
/// override).
/// </summary>
public abstract bool IsCaseSensitive { get; }
/// <summary>
/// Used for test purposes only to emulate missing members.
/// </summary>
private SmallDictionary<int, bool>? _lazyMakeWellKnownTypeMissingMap;
/// <summary>
/// Used for test purposes only to emulate missing members.
/// </summary>
private SmallDictionary<int, bool>? _lazyMakeMemberMissingMap;
// Protected for access in CSharpCompilation.WithAdditionalFeatures
protected readonly IReadOnlyDictionary<string, string> _features;
public ScriptCompilationInfo? ScriptCompilationInfo => CommonScriptCompilationInfo;
internal abstract ScriptCompilationInfo? CommonScriptCompilationInfo { get; }
internal Compilation(
string? name,
ImmutableArray<MetadataReference> references,
IReadOnlyDictionary<string, string> features,
bool isSubmission,
SemanticModelProvider? semanticModelProvider,
AsyncQueue<CompilationEvent>? eventQueue)
{
RoslynDebug.Assert(!references.IsDefault);
RoslynDebug.Assert(features != null);
this.AssemblyName = name;
this.ExternalReferences = references;
this.SemanticModelProvider = semanticModelProvider;
this.EventQueue = eventQueue;
_lazySubmissionSlotIndex = isSubmission ? SubmissionSlotIndexToBeAllocated : SubmissionSlotIndexNotApplicable;
_features = features;
}
protected static IReadOnlyDictionary<string, string> SyntaxTreeCommonFeatures(IEnumerable<SyntaxTree> trees)
{
IReadOnlyDictionary<string, string>? set = null;
foreach (var tree in trees)
{
var treeFeatures = tree.Options.Features;
if (set == null)
{
set = treeFeatures;
}
else
{
if ((object)set != treeFeatures && !set.SetEquals(treeFeatures))
{
throw new ArgumentException(CodeAnalysisResources.InconsistentSyntaxTreeFeature, nameof(trees));
}
}
}
if (set == null)
{
// Edge case where there are no syntax trees
set = ImmutableDictionary<string, string>.Empty;
}
return set;
}
internal abstract AnalyzerDriver CreateAnalyzerDriver(ImmutableArray<DiagnosticAnalyzer> analyzers, AnalyzerManager analyzerManager, SeverityFilter severityFilter);
/// <summary>
/// Gets the source language ("C#" or "Visual Basic").
/// </summary>
public abstract string Language { get; }
internal abstract void SerializePdbEmbeddedCompilationOptions(BlobBuilder builder);
internal static void ValidateScriptCompilationParameters(Compilation? previousScriptCompilation, Type? returnType, ref Type? globalsType)
{
if (globalsType != null && !IsValidHostObjectType(globalsType))
{
throw new ArgumentException(CodeAnalysisResources.ReturnTypeCannotBeValuePointerbyRefOrOpen, nameof(globalsType));
}
if (returnType != null && !IsValidSubmissionReturnType(returnType))
{
throw new ArgumentException(CodeAnalysisResources.ReturnTypeCannotBeVoidByRefOrOpen, nameof(returnType));
}
if (previousScriptCompilation != null)
{
if (globalsType == null)
{
globalsType = previousScriptCompilation.HostObjectType;
}
else if (globalsType != previousScriptCompilation.HostObjectType)
{
throw new ArgumentException(CodeAnalysisResources.TypeMustBeSameAsHostObjectTypeOfPreviousSubmission, nameof(globalsType));
}
// Force the previous submission to be analyzed. This is required for anonymous types unification.
if (previousScriptCompilation.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error))
{
throw new InvalidOperationException(CodeAnalysisResources.PreviousSubmissionHasErrors);
}
}
}
/// <summary>
/// Checks options passed to submission compilation constructor.
/// Throws an exception if the options are not applicable to submissions.
/// </summary>
internal static void CheckSubmissionOptions(CompilationOptions? options)
{
if (options == null)
{
return;
}
if (options.OutputKind.IsValid() && options.OutputKind != OutputKind.DynamicallyLinkedLibrary)
{
throw new ArgumentException(CodeAnalysisResources.InvalidOutputKindForSubmission, nameof(options));
}
if (options.CryptoKeyContainer != null ||
options.CryptoKeyFile != null ||
options.DelaySign != null ||
!options.CryptoPublicKey.IsEmpty ||
(options.DelaySign == true && options.PublicSign))
{
throw new ArgumentException(CodeAnalysisResources.InvalidCompilationOptions, nameof(options));
}
}
/// <summary>
/// Creates a new compilation equivalent to this one with different symbol instances.
/// </summary>
public Compilation Clone()
{
return CommonClone();
}
protected abstract Compilation CommonClone();
/// <summary>
/// Returns a new compilation with a given event queue.
/// </summary>
internal abstract Compilation WithEventQueue(AsyncQueue<CompilationEvent>? eventQueue);
/// <summary>
/// Returns a new compilation with a given semantic model provider.
/// </summary>
internal abstract Compilation WithSemanticModelProvider(SemanticModelProvider semanticModelProvider);
/// <summary>
/// Gets a new <see cref="SemanticModel"/> for the specified syntax tree.
/// </summary>
/// <param name="syntaxTree">The specified syntax tree.</param>
/// <param name="ignoreAccessibility">
/// True if the SemanticModel should ignore accessibility rules when answering semantic questions.
/// </param>
public SemanticModel GetSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility = false)
=> CommonGetSemanticModel(syntaxTree, ignoreAccessibility);
/// <summary>
/// Gets a <see cref="SemanticModel"/> for the given <paramref name="syntaxTree"/>.
/// If <see cref="SemanticModelProvider"/> is non-null, it attempts to use <see cref="SemanticModelProvider.GetSemanticModel(SyntaxTree, Compilation, bool)"/>
/// to get a semantic model. Otherwise, it creates a new semantic model using <see cref="CreateSemanticModel(SyntaxTree, bool)"/>.
/// </summary>
/// <param name="syntaxTree"></param>
/// <param name="ignoreAccessibility"></param>
/// <returns></returns>
protected abstract SemanticModel CommonGetSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility);
/// <summary>
/// Creates a new <see cref="SemanticModel"/> for the given <paramref name="syntaxTree"/>.
/// Unlike the <see cref="GetSemanticModel(SyntaxTree, bool)"/> and <see cref="CommonGetSemanticModel(SyntaxTree, bool)"/>,
/// it does not attempt to use the <see cref="SemanticModelProvider"/> to get a semantic model, but instead always creates a new semantic model.
/// </summary>
/// <param name="syntaxTree"></param>
/// <param name="ignoreAccessibility"></param>
/// <returns></returns>
internal abstract SemanticModel CreateSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility);
/// <summary>
/// Returns a new INamedTypeSymbol representing an error type with the given name and arity
/// in the given optional container.
/// </summary>
public INamedTypeSymbol CreateErrorTypeSymbol(INamespaceOrTypeSymbol? container, string name, int arity)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (arity < 0)
{
throw new ArgumentException($"{nameof(arity)} must be >= 0", nameof(arity));
}
return CommonCreateErrorTypeSymbol(container, name, arity);
}
protected abstract INamedTypeSymbol CommonCreateErrorTypeSymbol(INamespaceOrTypeSymbol? container, string name, int arity);
/// <summary>
/// Returns a new INamespaceSymbol representing an error (missing) namespace with the given name.
/// </summary>
public INamespaceSymbol CreateErrorNamespaceSymbol(INamespaceSymbol container, string name)
{
if (container == null)
{
throw new ArgumentNullException(nameof(container));
}
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
return CommonCreateErrorNamespaceSymbol(container, name);
}
protected abstract INamespaceSymbol CommonCreateErrorNamespaceSymbol(INamespaceSymbol container, string name);
#region Name
internal const string UnspecifiedModuleAssemblyName = "?";
/// <summary>
/// Simple assembly name, or null if not specified.
/// </summary>
/// <remarks>
/// The name is used for determining internals-visible-to relationship with referenced assemblies.
///
/// If the compilation represents an assembly the value of <see cref="AssemblyName"/> is its simple name.
///
/// Unless <see cref="CompilationOptions.ModuleName"/> specifies otherwise the module name
/// written to metadata is <see cref="AssemblyName"/> with an extension based upon <see cref="CompilationOptions.OutputKind"/>.
/// </remarks>
public string? AssemblyName { get; }
internal void CheckAssemblyName(DiagnosticBag diagnostics)
{
// We could only allow name == null if OutputKind is Module.
// However, it does no harm that we allow name == null for assemblies as well, so we don't enforce it.
if (this.AssemblyName != null)
{
MetadataHelpers.CheckAssemblyOrModuleName(this.AssemblyName, MessageProvider, MessageProvider.ERR_BadAssemblyName, diagnostics);
}
}
internal string MakeSourceAssemblySimpleName()
{
return AssemblyName ?? UnspecifiedModuleAssemblyName;
}
internal string MakeSourceModuleName()
{
return Options.ModuleName ??
(AssemblyName != null ? AssemblyName + Options.OutputKind.GetDefaultExtension() : UnspecifiedModuleAssemblyName);
}
/// <summary>
/// Creates a compilation with the specified assembly name.
/// </summary>
/// <param name="assemblyName">The new assembly name.</param>
/// <returns>A new compilation.</returns>
public Compilation WithAssemblyName(string? assemblyName)
{
return CommonWithAssemblyName(assemblyName);
}
protected abstract Compilation CommonWithAssemblyName(string? outputName);
#endregion
#region Options
/// <summary>
/// Gets the options the compilation was created with.
/// </summary>
public CompilationOptions Options { get { return CommonOptions; } }
protected abstract CompilationOptions CommonOptions { get; }
/// <summary>
/// Creates a new compilation with the specified compilation options.
/// </summary>
/// <param name="options">The new options.</param>
/// <returns>A new compilation.</returns>
public Compilation WithOptions(CompilationOptions options)
{
return CommonWithOptions(options);
}
protected abstract Compilation CommonWithOptions(CompilationOptions options);
#endregion
#region Submissions
// An index in the submission slot array. Allocated lazily in compilation phase based upon the slot index of the previous submission.
// Special values:
// -1 ... neither this nor previous submissions in the chain allocated a slot (the submissions don't contain code)
// -2 ... the slot of this submission hasn't been determined yet
// -3 ... this is not a submission compilation
private int _lazySubmissionSlotIndex;
private const int SubmissionSlotIndexNotApplicable = -3;
private const int SubmissionSlotIndexToBeAllocated = -2;
/// <summary>
/// True if the compilation represents an interactive submission.
/// </summary>
internal bool IsSubmission
{
get
{
return _lazySubmissionSlotIndex != SubmissionSlotIndexNotApplicable;
}
}
/// <summary>
/// The previous submission, if any, or null.
/// </summary>
private Compilation? PreviousSubmission
{
get
{
return ScriptCompilationInfo?.PreviousScriptCompilation;
}
}
/// <summary>
/// Gets or allocates a runtime submission slot index for this compilation.
/// </summary>
/// <returns>Non-negative integer if this is a submission and it or a previous submission contains code, negative integer otherwise.</returns>
internal int GetSubmissionSlotIndex()
{
if (_lazySubmissionSlotIndex == SubmissionSlotIndexToBeAllocated)
{
// TODO (tomat): remove recursion
int lastSlotIndex = ScriptCompilationInfo!.PreviousScriptCompilation?.GetSubmissionSlotIndex() ?? 0;
_lazySubmissionSlotIndex = HasCodeToEmit() ? lastSlotIndex + 1 : lastSlotIndex;
}
return _lazySubmissionSlotIndex;
}
// The type of interactive submission result requested by the host, or null if this compilation doesn't represent a submission.
//
// The type is resolved to a symbol when the Script's instance ctor symbol is constructed. The symbol needs to be resolved against
// the references of this compilation.
//
// Consider (tomat): As an alternative to Reflection Type we could hold onto any piece of information that lets us
// resolve the type symbol when needed.
/// <summary>
/// The type object that represents the type of submission result the host requested.
/// </summary>
internal Type? SubmissionReturnType => ScriptCompilationInfo?.ReturnTypeOpt;
internal static bool IsValidSubmissionReturnType(Type type)
{
return !(type == typeof(void) || type.IsByRef || type.GetTypeInfo().ContainsGenericParameters);
}
/// <summary>
/// The type of the globals object or null if not specified for this compilation.
/// </summary>
internal Type? HostObjectType => ScriptCompilationInfo?.GlobalsType;
internal static bool IsValidHostObjectType(Type type)
{
var info = type.GetTypeInfo();
return !(info.IsValueType || info.IsPointer || info.IsByRef || info.ContainsGenericParameters);
}
internal abstract bool HasSubmissionResult();
public Compilation WithScriptCompilationInfo(ScriptCompilationInfo? info) => CommonWithScriptCompilationInfo(info);
protected abstract Compilation CommonWithScriptCompilationInfo(ScriptCompilationInfo? info);
#endregion
#region Syntax Trees
/// <summary>
/// Gets the syntax trees (parsed from source code) that this compilation was created with.
/// </summary>
public IEnumerable<SyntaxTree> SyntaxTrees { get { return CommonSyntaxTrees; } }
protected abstract IEnumerable<SyntaxTree> CommonSyntaxTrees { get; }
/// <summary>
/// Creates a new compilation with additional syntax trees.
/// </summary>
/// <param name="trees">The new syntax trees.</param>
/// <returns>A new compilation.</returns>
public Compilation AddSyntaxTrees(params SyntaxTree[] trees)
{
return CommonAddSyntaxTrees(trees);
}
/// <summary>
/// Creates a new compilation with additional syntax trees.
/// </summary>
/// <param name="trees">The new syntax trees.</param>
/// <returns>A new compilation.</returns>
public Compilation AddSyntaxTrees(IEnumerable<SyntaxTree> trees)
{
return CommonAddSyntaxTrees(trees);
}
protected abstract Compilation CommonAddSyntaxTrees(IEnumerable<SyntaxTree> trees);
/// <summary>
/// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees
/// added later.
/// </summary>
/// <param name="trees">The new syntax trees.</param>
/// <returns>A new compilation.</returns>
public Compilation RemoveSyntaxTrees(params SyntaxTree[] trees)
{
return CommonRemoveSyntaxTrees(trees);
}
/// <summary>
/// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees
/// added later.
/// </summary>
/// <param name="trees">The new syntax trees.</param>
/// <returns>A new compilation.</returns>
public Compilation RemoveSyntaxTrees(IEnumerable<SyntaxTree> trees)
{
return CommonRemoveSyntaxTrees(trees);
}
protected abstract Compilation CommonRemoveSyntaxTrees(IEnumerable<SyntaxTree> trees);
/// <summary>
/// Creates a new compilation without any syntax trees. Preserves metadata info for use with
/// trees added later.
/// </summary>
public Compilation RemoveAllSyntaxTrees()
{
return CommonRemoveAllSyntaxTrees();
}
protected abstract Compilation CommonRemoveAllSyntaxTrees();
/// <summary>
/// Creates a new compilation with an old syntax tree replaced with a new syntax tree.
/// Reuses metadata from old compilation object.
/// </summary>
/// <param name="newTree">The new tree.</param>
/// <param name="oldTree">The old tree.</param>
/// <returns>A new compilation.</returns>
public Compilation ReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree newTree)
{
return CommonReplaceSyntaxTree(oldTree, newTree);
}
protected abstract Compilation CommonReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree newTree);
/// <summary>
/// Returns true if this compilation contains the specified tree. False otherwise.
/// </summary>
/// <param name="syntaxTree">A syntax tree.</param>
public bool ContainsSyntaxTree(SyntaxTree syntaxTree)
{
return CommonContainsSyntaxTree(syntaxTree);
}
protected abstract bool CommonContainsSyntaxTree(SyntaxTree? syntaxTree);
/// <summary>
/// Optional semantic model provider for this compilation.
/// </summary>
internal SemanticModelProvider? SemanticModelProvider { get; }
/// <summary>
/// The event queue that this compilation was created with.
/// </summary>
internal AsyncQueue<CompilationEvent>? EventQueue { get; }
#endregion
#region References
internal static ImmutableArray<MetadataReference> ValidateReferences<T>(IEnumerable<MetadataReference>? references)
where T : CompilationReference
{
var result = references.AsImmutableOrEmpty();
for (int i = 0; i < result.Length; i++)
{
var reference = result[i];
if (reference == null)
{
throw new ArgumentNullException($"{nameof(references)}[{i}]");
}
var peReference = reference as PortableExecutableReference;
if (peReference == null && !(reference is T))
{
Debug.Assert(reference is UnresolvedMetadataReference || reference is CompilationReference);
throw new ArgumentException(string.Format(CodeAnalysisResources.ReferenceOfTypeIsInvalid1, reference.GetType()),
$"{nameof(references)}[{i}]");
}
}
return result;
}
internal CommonReferenceManager GetBoundReferenceManager()
{
return CommonGetBoundReferenceManager();
}
internal abstract CommonReferenceManager CommonGetBoundReferenceManager();
/// <summary>
/// Metadata references passed to the compilation constructor.
/// </summary>
public ImmutableArray<MetadataReference> ExternalReferences { get; }
/// <summary>
/// Unique metadata references specified via #r directive in the source code of this compilation.
/// </summary>
public abstract ImmutableArray<MetadataReference> DirectiveReferences { get; }
/// <summary>
/// All reference directives used in this compilation.
/// </summary>
internal abstract IEnumerable<ReferenceDirective> ReferenceDirectives { get; }
/// <summary>
/// Maps values of #r references to resolved metadata references.
/// </summary>
internal abstract IDictionary<(string path, string content), MetadataReference> ReferenceDirectiveMap { get; }
/// <summary>
/// All metadata references -- references passed to the compilation
/// constructor as well as references specified via #r directives.
/// </summary>
public IEnumerable<MetadataReference> References
{
get
{
foreach (var reference in ExternalReferences)
{
yield return reference;
}
foreach (var reference in DirectiveReferences)
{
yield return reference;
}
}
}
/// <summary>
/// Creates a metadata reference for this compilation.
/// </summary>
/// <param name="aliases">
/// Optional aliases that can be used to refer to the compilation root namespace via extern alias directive.
/// </param>
/// <param name="embedInteropTypes">
/// Embed the COM types from the reference so that the compiled
/// application no longer requires a primary interop assembly (PIA).
/// </param>
public abstract CompilationReference ToMetadataReference(ImmutableArray<string> aliases = default(ImmutableArray<string>), bool embedInteropTypes = false);
/// <summary>
/// Creates a new compilation with the specified references.
/// </summary>
/// <param name="newReferences">
/// The new references.
/// </param>
/// <returns>A new compilation.</returns>
public Compilation WithReferences(IEnumerable<MetadataReference> newReferences)
{
return this.CommonWithReferences(newReferences);
}
/// <summary>
/// Creates a new compilation with the specified references.
/// </summary>
/// <param name="newReferences">The new references.</param>
/// <returns>A new compilation.</returns>
public Compilation WithReferences(params MetadataReference[] newReferences)
{
return this.WithReferences((IEnumerable<MetadataReference>)newReferences);
}
/// <summary>
/// Creates a new compilation with the specified references.
/// </summary>
protected abstract Compilation CommonWithReferences(IEnumerable<MetadataReference> newReferences);
/// <summary>
/// Creates a new compilation with additional metadata references.
/// </summary>
/// <param name="references">The new references.</param>
/// <returns>A new compilation.</returns>
public Compilation AddReferences(params MetadataReference[] references)
{
return AddReferences((IEnumerable<MetadataReference>)references);
}
/// <summary>
/// Creates a new compilation with additional metadata references.
/// </summary>
/// <param name="references">The new references.</param>
/// <returns>A new compilation.</returns>
public Compilation AddReferences(IEnumerable<MetadataReference> references)
{
if (references == null)
{
throw new ArgumentNullException(nameof(references));
}
if (references.IsEmpty())
{
return this;
}
return CommonWithReferences(this.ExternalReferences.Union(references));
}
/// <summary>
/// Creates a new compilation without the specified metadata references.
/// </summary>
/// <param name="references">The new references.</param>
/// <returns>A new compilation.</returns>
public Compilation RemoveReferences(params MetadataReference[] references)
{
return RemoveReferences((IEnumerable<MetadataReference>)references);
}
/// <summary>
/// Creates a new compilation without the specified metadata references.
/// </summary>
/// <param name="references">The new references.</param>
/// <returns>A new compilation.</returns>
public Compilation RemoveReferences(IEnumerable<MetadataReference> references)
{
if (references == null)
{
throw new ArgumentNullException(nameof(references));
}
if (references.IsEmpty())
{
return this;
}
var refSet = new HashSet<MetadataReference>(this.ExternalReferences);
//EDMAURER if AddingReferences accepts duplicates, then a consumer supplying a list with
//duplicates to add will not know exactly which to remove. Let them supply a list with
//duplicates here.
foreach (var r in references.Distinct())
{
if (!refSet.Remove(r))
{
throw new ArgumentException(string.Format(CodeAnalysisResources.MetadataRefNotFoundToRemove1, r),
nameof(references));
}
}
return CommonWithReferences(refSet);
}
/// <summary>
/// Creates a new compilation without any metadata references.
/// </summary>
public Compilation RemoveAllReferences()
{
return CommonWithReferences(SpecializedCollections.EmptyEnumerable<MetadataReference>());
}
/// <summary>
/// Creates a new compilation with an old metadata reference replaced with a new metadata
/// reference.
/// </summary>
/// <param name="newReference">The new reference.</param>
/// <param name="oldReference">The old reference.</param>
/// <returns>A new compilation.</returns>
public Compilation ReplaceReference(MetadataReference oldReference, MetadataReference? newReference)
{
if (oldReference == null)
{
throw new ArgumentNullException(nameof(oldReference));
}
if (newReference == null)
{
return this.RemoveReferences(oldReference);
}
return this.RemoveReferences(oldReference).AddReferences(newReference);
}
/// <summary>
/// Gets the <see cref="IAssemblySymbol"/> or <see cref="IModuleSymbol"/> for a metadata reference used to create this
/// compilation.
/// </summary>
/// <param name="reference">The target reference.</param>
/// <returns>
/// Assembly or module symbol corresponding to the given reference or null if there is none.
/// </returns>
public ISymbol? GetAssemblyOrModuleSymbol(MetadataReference reference)
{
return CommonGetAssemblyOrModuleSymbol(reference);
}
protected abstract ISymbol? CommonGetAssemblyOrModuleSymbol(MetadataReference reference);
/// <summary>
/// Gets the <see cref="MetadataReference"/> that corresponds to the assembly symbol.
/// </summary>
/// <param name="assemblySymbol">The target symbol.</param>
public MetadataReference? GetMetadataReference(IAssemblySymbol assemblySymbol)
{
return CommonGetMetadataReference(assemblySymbol);
}
private protected abstract MetadataReference? CommonGetMetadataReference(IAssemblySymbol assemblySymbol);
/// <summary>
/// Assembly identities of all assemblies directly referenced by this compilation.
/// </summary>
/// <remarks>
/// Includes identities of references passed in the compilation constructor
/// as well as those specified via directives in source code.
/// </remarks>
public abstract IEnumerable<AssemblyIdentity> ReferencedAssemblyNames { get; }
#endregion
#region Symbols
/// <summary>
/// The <see cref="IAssemblySymbol"/> that represents the assembly being created.
/// </summary>
public IAssemblySymbol Assembly { get { return CommonAssembly; } }
protected abstract IAssemblySymbol CommonAssembly { get; }
/// <summary>
/// Gets the <see cref="IModuleSymbol"/> for the module being created by compiling all of
/// the source code.
/// </summary>
public IModuleSymbol SourceModule { get { return CommonSourceModule; } }
protected abstract IModuleSymbol CommonSourceModule { get; }
/// <summary>
/// The root namespace that contains all namespaces and types defined in source code or in
/// referenced metadata, merged into a single namespace hierarchy.
/// </summary>
public INamespaceSymbol GlobalNamespace { get { return CommonGlobalNamespace; } }
protected abstract INamespaceSymbol CommonGlobalNamespace { get; }
/// <summary>
/// Gets the corresponding compilation namespace for the specified module or assembly namespace.
/// </summary>
public INamespaceSymbol? GetCompilationNamespace(INamespaceSymbol namespaceSymbol)
{
return CommonGetCompilationNamespace(namespaceSymbol);
}
protected abstract INamespaceSymbol? CommonGetCompilationNamespace(INamespaceSymbol namespaceSymbol);
internal abstract CommonAnonymousTypeManager CommonAnonymousTypeManager { get; }
/// <summary>
/// Returns the Main method that will serves as the entry point of the assembly, if it is
/// executable (and not a script).
/// </summary>
public IMethodSymbol? GetEntryPoint(CancellationToken cancellationToken)
{
return CommonGetEntryPoint(cancellationToken);
}
protected abstract IMethodSymbol? CommonGetEntryPoint(CancellationToken cancellationToken);
/// <summary>
/// Get the symbol for the predefined type from the Cor Library referenced by this
/// compilation.
/// </summary>
public INamedTypeSymbol GetSpecialType(SpecialType specialType)
{
return (INamedTypeSymbol)CommonGetSpecialType(specialType).GetITypeSymbol();
}
/// <summary>
/// Get the symbol for the predefined type member from the COR Library referenced by this compilation.
/// </summary>
internal abstract ISymbolInternal CommonGetSpecialTypeMember(SpecialMember specialMember);
/// <summary>
/// Returns true if the type is System.Type.
/// </summary>
internal abstract bool IsSystemTypeReference(ITypeSymbolInternal type);
private protected abstract INamedTypeSymbolInternal CommonGetSpecialType(SpecialType specialType);
/// <summary>
/// Lookup member declaration in well known type used by this Compilation.
/// </summary>
internal abstract ISymbolInternal? CommonGetWellKnownTypeMember(WellKnownMember member);
/// <summary>
/// Lookup well-known type used by this Compilation.
/// </summary>
internal abstract ITypeSymbolInternal CommonGetWellKnownType(WellKnownType wellknownType);
/// <summary>
/// Returns true if the specified type is equal to or derives from System.Attribute well-known type.
/// </summary>
internal abstract bool IsAttributeType(ITypeSymbol type);
/// <summary>
/// The INamedTypeSymbol for the .NET System.Object type, which could have a TypeKind of
/// Error if there was no COR Library in this Compilation.
/// </summary>
public INamedTypeSymbol ObjectType { get { return CommonObjectType; } }
protected abstract INamedTypeSymbol CommonObjectType { get; }
/// <summary>
/// The TypeSymbol for the type 'dynamic' in this Compilation.
/// </summary>
/// <exception cref="NotSupportedException">If the compilation is a VisualBasic compilation.</exception>
public ITypeSymbol DynamicType { get { return CommonDynamicType; } }
protected abstract ITypeSymbol CommonDynamicType { get; }
/// <summary>
/// A symbol representing the script globals type.
/// </summary>
internal ITypeSymbol? ScriptGlobalsType => CommonScriptGlobalsType;
protected abstract ITypeSymbol? CommonScriptGlobalsType { get; }
/// <summary>
/// A symbol representing the implicit Script class. This is null if the class is not
/// defined in the compilation.
/// </summary>
public INamedTypeSymbol? ScriptClass { get { return CommonScriptClass; } }
protected abstract INamedTypeSymbol? CommonScriptClass { get; }
/// <summary>
/// Resolves a symbol that represents script container (Script class). Uses the
/// full name of the container class stored in <see cref="CompilationOptions.ScriptClassName"/> to find the symbol.
/// </summary>
/// <returns>The Script class symbol or null if it is not defined.</returns>
protected INamedTypeSymbol? CommonBindScriptClass()
{
string scriptClassName = this.Options.ScriptClassName ?? "";
string[] parts = scriptClassName.Split('.');
INamespaceSymbol container = this.SourceModule.GlobalNamespace;
for (int i = 0; i < parts.Length - 1; i++)
{
INamespaceSymbol? next = container.GetNestedNamespace(parts[i]);
if (next == null)
{
AssertNoScriptTrees();
return null;
}
container = next;
}
foreach (INamedTypeSymbol candidate in container.GetTypeMembers(parts[parts.Length - 1]))
{
if (candidate.IsScriptClass)
{
return candidate;
}
}
AssertNoScriptTrees();
return null;
}
[Conditional("DEBUG")]
private void AssertNoScriptTrees()
{
foreach (var tree in this.SyntaxTrees)
{
Debug.Assert(tree.Options.Kind != SourceCodeKind.Script);
}
}
/// <summary>
/// Returns a new ArrayTypeSymbol representing an array type tied to the base types of the
/// COR Library in this Compilation.
/// </summary>
public IArrayTypeSymbol CreateArrayTypeSymbol(ITypeSymbol elementType, int rank = 1, NullableAnnotation elementNullableAnnotation = NullableAnnotation.None)
{
return CommonCreateArrayTypeSymbol(elementType, rank, elementNullableAnnotation);
}
/// <summary>
/// Returns a new ArrayTypeSymbol representing an array type tied to the base types of the
/// COR Library in this Compilation.
/// </summary>
/// <remarks>This overload is for backwards compatibility. Do not remove.</remarks>
public IArrayTypeSymbol CreateArrayTypeSymbol(ITypeSymbol elementType, int rank)
{
return CreateArrayTypeSymbol(elementType, rank, elementNullableAnnotation: default);
}
protected abstract IArrayTypeSymbol CommonCreateArrayTypeSymbol(ITypeSymbol elementType, int rank, NullableAnnotation elementNullableAnnotation);
/// <summary>
/// Returns a new IPointerTypeSymbol representing a pointer type tied to a type in this
/// Compilation.
/// </summary>
/// <exception cref="NotSupportedException">If the compilation is a VisualBasic compilation.</exception>
public IPointerTypeSymbol CreatePointerTypeSymbol(ITypeSymbol pointedAtType)
{
return CommonCreatePointerTypeSymbol(pointedAtType);
}
protected abstract IPointerTypeSymbol CommonCreatePointerTypeSymbol(ITypeSymbol elementType);
/// <summary>
/// Returns a new IFunctionPointerTypeSymbol representing a function pointer type tied to types in this
/// Compilation.
/// </summary>
/// <exception cref="NotSupportedException">If the compilation is a VisualBasic compilation.</exception>
/// <exception cref="ArgumentException">
/// If:
/// * <see cref="RefKind.Out"/> is passed as the returnRefKind.
/// * parameterTypes and parameterRefKinds do not have the same length.
/// </exception>
/// <exception cref="ArgumentNullException">
/// If returnType is <see langword="null"/>, or if parameterTypes or parameterRefKinds are default,
/// or if any of the types in parameterTypes are null.</exception>
public IFunctionPointerTypeSymbol CreateFunctionPointerTypeSymbol(
ITypeSymbol returnType,
RefKind returnRefKind,
ImmutableArray<ITypeSymbol> parameterTypes,
ImmutableArray<RefKind> parameterRefKinds,
SignatureCallingConvention callingConvention = SignatureCallingConvention.Default,
ImmutableArray<INamedTypeSymbol> callingConventionTypes = default)
{
return CommonCreateFunctionPointerTypeSymbol(returnType, returnRefKind, parameterTypes, parameterRefKinds, callingConvention, callingConventionTypes);
}
protected abstract IFunctionPointerTypeSymbol CommonCreateFunctionPointerTypeSymbol(
ITypeSymbol returnType,
RefKind returnRefKind,
ImmutableArray<ITypeSymbol> parameterTypes,
ImmutableArray<RefKind> parameterRefKinds,
SignatureCallingConvention callingConvention,
ImmutableArray<INamedTypeSymbol> callingConventionTypes);
/// <summary>
/// Returns a new INamedTypeSymbol representing a native integer.
/// </summary>
/// <exception cref="NotSupportedException">If the compilation is a VisualBasic compilation.</exception>
public INamedTypeSymbol CreateNativeIntegerTypeSymbol(bool signed)
{
return CommonCreateNativeIntegerTypeSymbol(signed);
}
protected abstract INamedTypeSymbol CommonCreateNativeIntegerTypeSymbol(bool signed);
// PERF: ETW Traces show that analyzers may use this method frequently, often requesting
// the same symbol over and over again. XUnit analyzers, in particular, were consuming almost
// 1% of CPU time when building Roslyn itself. This is an extremely simple cache that evicts on
// hash code conflicts, but seems to do the trick. The size is mostly arbitrary. My guess
// is that there are maybe a couple dozen analyzers in the solution and each one has
// ~0-2 unique well-known types, and the chance of hash collision is very low.
private readonly ConcurrentCache<string, INamedTypeSymbol?> _getTypeCache =
new ConcurrentCache<string, INamedTypeSymbol?>(50, ReferenceEqualityComparer.Instance);
/// <summary>
/// Gets the type within the compilation's assembly and all referenced assemblies (other than
/// those that can only be referenced via an extern alias) using its canonical CLR metadata name.
/// </summary>
/// <returns>Null if the type can't be found.</returns>
/// <remarks>
/// Since VB does not have the concept of extern aliases, it considers all referenced assemblies.
/// </remarks>
public INamedTypeSymbol? GetTypeByMetadataName(string fullyQualifiedMetadataName)
{
if (!_getTypeCache.TryGetValue(fullyQualifiedMetadataName, out INamedTypeSymbol? val))
{
val = CommonGetTypeByMetadataName(fullyQualifiedMetadataName);
// Ignore if someone added the same value before us
_ = _getTypeCache.TryAdd(fullyQualifiedMetadataName, val);
}
return val;
}
protected abstract INamedTypeSymbol? CommonGetTypeByMetadataName(string metadataName);
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
/// <summary>
/// Returns a new INamedTypeSymbol with the given element types and
/// (optional) element names, locations, and nullable annotations.
/// </summary>
public INamedTypeSymbol CreateTupleTypeSymbol(
ImmutableArray<ITypeSymbol> elementTypes,
ImmutableArray<string?> elementNames = default,
ImmutableArray<Location?> elementLocations = default,
ImmutableArray<NullableAnnotation> elementNullableAnnotations = default)
{
if (elementTypes.IsDefault)
{
throw new ArgumentNullException(nameof(elementTypes));
}
int n = elementTypes.Length;
if (elementTypes.Length <= 1)
{
throw new ArgumentException(CodeAnalysisResources.TuplesNeedAtLeastTwoElements, nameof(elementNames));
}
elementNames = CheckTupleElementNames(n, elementNames);
CheckTupleElementLocations(n, elementLocations);
CheckTupleElementNullableAnnotations(n, elementNullableAnnotations);
for (int i = 0; i < n; i++)
{
if (elementTypes[i] == null)
{
throw new ArgumentNullException($"{nameof(elementTypes)}[{i}]");
}
if (!elementLocations.IsDefault && elementLocations[i] == null)
{
throw new ArgumentNullException($"{nameof(elementLocations)}[{i}]");
}
}
return CommonCreateTupleTypeSymbol(elementTypes, elementNames, elementLocations, elementNullableAnnotations);
}
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
/// <summary>
/// Returns a new INamedTypeSymbol with the given element types, names, and locations.
/// </summary>
/// <remarks>This overload is for backwards compatibility. Do not remove.</remarks>
public INamedTypeSymbol CreateTupleTypeSymbol(
ImmutableArray<ITypeSymbol> elementTypes,
ImmutableArray<string?> elementNames,
ImmutableArray<Location?> elementLocations)
{
return CreateTupleTypeSymbol(elementTypes, elementNames, elementLocations, elementNullableAnnotations: default);
}
protected static void CheckTupleElementNullableAnnotations(
int cardinality,
ImmutableArray<NullableAnnotation> elementNullableAnnotations)
{
if (!elementNullableAnnotations.IsDefault)
{
if (elementNullableAnnotations.Length != cardinality)
{
throw new ArgumentException(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, nameof(elementNullableAnnotations));
}
}
}
/// <summary>
/// Check that if any names are provided, and their number matches the expected cardinality.
/// Returns a normalized version of the element names (empty array if all the names are null).
/// </summary>
protected static ImmutableArray<string?> CheckTupleElementNames(int cardinality, ImmutableArray<string?> elementNames)
{
if (!elementNames.IsDefault)
{
if (elementNames.Length != cardinality)
{
throw new ArgumentException(CodeAnalysisResources.TupleElementNameCountMismatch, nameof(elementNames));
}
for (int i = 0; i < elementNames.Length; i++)
{
if (elementNames[i] == "")
{
throw new ArgumentException(CodeAnalysisResources.TupleElementNameEmpty, $"{nameof(elementNames)}[{i}]");
}
}
if (elementNames.All(n => n == null))
{
return default;
}
}
return elementNames;
}
protected static void CheckTupleElementLocations(
int cardinality,
ImmutableArray<Location?> elementLocations)
{
if (!elementLocations.IsDefault)
{
if (elementLocations.Length != cardinality)
{
throw new ArgumentException(CodeAnalysisResources.TupleElementLocationCountMismatch, nameof(elementLocations));
}
}
}
protected abstract INamedTypeSymbol CommonCreateTupleTypeSymbol(
ImmutableArray<ITypeSymbol> elementTypes,
ImmutableArray<string?> elementNames,
ImmutableArray<Location?> elementLocations,
ImmutableArray<NullableAnnotation> elementNullableAnnotations);
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
/// <summary>
/// Returns a new INamedTypeSymbol with the given underlying type and
/// (optional) element names, locations, and nullable annotations.
/// The underlying type needs to be tuple-compatible.
/// </summary>
public INamedTypeSymbol CreateTupleTypeSymbol(
INamedTypeSymbol underlyingType,
ImmutableArray<string?> elementNames = default,
ImmutableArray<Location?> elementLocations = default,
ImmutableArray<NullableAnnotation> elementNullableAnnotations = default)
{
if ((object)underlyingType == null)
{
throw new ArgumentNullException(nameof(underlyingType));
}
return CommonCreateTupleTypeSymbol(underlyingType, elementNames, elementLocations, elementNullableAnnotations);
}
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
/// <summary>
/// Returns a new INamedTypeSymbol with the given underlying type and element names and locations.
/// The underlying type needs to be tuple-compatible.
/// </summary>
/// <remarks>This overload is for backwards compatibility. Do not remove.</remarks>
public INamedTypeSymbol CreateTupleTypeSymbol(
INamedTypeSymbol underlyingType,
ImmutableArray<string?> elementNames,
ImmutableArray<Location?> elementLocations)
{
return CreateTupleTypeSymbol(underlyingType, elementNames, elementLocations, elementNullableAnnotations: default);
}
protected abstract INamedTypeSymbol CommonCreateTupleTypeSymbol(
INamedTypeSymbol underlyingType,
ImmutableArray<string?> elementNames,
ImmutableArray<Location?> elementLocations,
ImmutableArray<NullableAnnotation> elementNullableAnnotations);
/// <summary>
/// Returns a new anonymous type symbol with the given member types, names, source locations, and nullable annotations.
/// Anonymous type members will be readonly by default. Writable properties are
/// supported in VB and can be created by passing in <see langword="false"/> in the
/// appropriate locations in <paramref name="memberIsReadOnly"/>.
/// </summary>
public INamedTypeSymbol CreateAnonymousTypeSymbol(
ImmutableArray<ITypeSymbol> memberTypes,
ImmutableArray<string> memberNames,
ImmutableArray<bool> memberIsReadOnly = default,
ImmutableArray<Location> memberLocations = default,
ImmutableArray<NullableAnnotation> memberNullableAnnotations = default)
{
if (memberTypes.IsDefault)
{
throw new ArgumentNullException(nameof(memberTypes));
}
if (memberNames.IsDefault)
{
throw new ArgumentNullException(nameof(memberNames));
}
if (memberTypes.Length != memberNames.Length)
{
throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeMemberAndNamesCountMismatch2,
nameof(memberTypes), nameof(memberNames)));
}
if (!memberLocations.IsDefault && memberLocations.Length != memberTypes.Length)
{
throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeArgumentCountMismatch2,
nameof(memberLocations), nameof(memberNames)));
}
if (!memberIsReadOnly.IsDefault && memberIsReadOnly.Length != memberTypes.Length)
{
throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeArgumentCountMismatch2,
nameof(memberIsReadOnly), nameof(memberNames)));
}
if (!memberNullableAnnotations.IsDefault && memberNullableAnnotations.Length != memberTypes.Length)
{
throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeArgumentCountMismatch2,
nameof(memberNullableAnnotations), nameof(memberNames)));
}
for (int i = 0, n = memberTypes.Length; i < n; i++)
{
if (memberTypes[i] == null)
{
throw new ArgumentNullException($"{nameof(memberTypes)}[{i}]");
}
if (memberNames[i] == null)
{
throw new ArgumentNullException($"{nameof(memberNames)}[{i}]");
}
if (!memberLocations.IsDefault && memberLocations[i] == null)
{
throw new ArgumentNullException($"{nameof(memberLocations)}[{i}]");
}
}
return CommonCreateAnonymousTypeSymbol(memberTypes, memberNames, memberLocations, memberIsReadOnly, memberNullableAnnotations);
}
/// <summary>
/// Returns a new anonymous type symbol with the given member types, names, and source locations.
/// Anonymous type members will be readonly by default. Writable properties are
/// supported in VB and can be created by passing in <see langword="false"/> in the
/// appropriate locations in <paramref name="memberIsReadOnly"/>.
/// </summary>
/// <remarks>This overload is for backwards compatibility. Do not remove.</remarks>
public INamedTypeSymbol CreateAnonymousTypeSymbol(
ImmutableArray<ITypeSymbol> memberTypes,
ImmutableArray<string> memberNames,
ImmutableArray<bool> memberIsReadOnly,
ImmutableArray<Location> memberLocations)
{
return CreateAnonymousTypeSymbol(memberTypes, memberNames, memberIsReadOnly, memberLocations, memberNullableAnnotations: default);
}
protected abstract INamedTypeSymbol CommonCreateAnonymousTypeSymbol(
ImmutableArray<ITypeSymbol> memberTypes,
ImmutableArray<string> memberNames,
ImmutableArray<Location> memberLocations,
ImmutableArray<bool> memberIsReadOnly,
ImmutableArray<NullableAnnotation> memberNullableAnnotations);
/// <summary>
/// Classifies a conversion from <paramref name="source"/> to <paramref name="destination"/> according
/// to this compilation's programming language.
/// </summary>
/// <param name="source">Source type of value to be converted</param>
/// <param name="destination">Destination type of value to be converted</param>
/// <returns>A <see cref="CommonConversion"/> that classifies the conversion from the
/// <paramref name="source"/> type to the <paramref name="destination"/> type.</returns>
public abstract CommonConversion ClassifyCommonConversion(ITypeSymbol source, ITypeSymbol destination);
/// <summary>
/// Returns true if there is an implicit (C#) or widening (VB) conversion from
/// <paramref name="fromType"/> to <paramref name="toType"/>. Returns false if
/// either <paramref name="fromType"/> or <paramref name="toType"/> is null, or
/// if no such conversion exists.
/// </summary>
public bool HasImplicitConversion(ITypeSymbol? fromType, ITypeSymbol? toType)
=> fromType != null && toType != null && this.ClassifyCommonConversion(fromType, toType).IsImplicit;
/// <summary>
/// Checks if <paramref name="symbol"/> is accessible from within <paramref name="within"/>. An optional qualifier of type
/// <paramref name="throughType"/> is used to resolve protected access for instance members. All symbols are
/// required to be from this compilation or some assembly referenced (<see cref="References"/>) by this
/// compilation. <paramref name="within"/> is required to be an <see cref="INamedTypeSymbol"/> or <see cref="IAssemblySymbol"/>.
/// </summary>
/// <remarks>
/// <para>Submissions can reference symbols from previous submissions and their referenced assemblies, even
/// though those references are missing from <see cref="References"/>.
/// See https://github.com/dotnet/roslyn/issues/27356.
/// This implementation works around that by permitting symbols from previous submissions as well.</para>
/// <para>It is advised to avoid the use of this API within the compilers, as the compilers have additional
/// requirements for access checking that are not satisfied by this implementation, including the
/// avoidance of infinite recursion that could result from the use of the ISymbol APIs here, the detection
/// of use-site diagnostics, and additional returned details (from the compiler's internal APIs) that are
/// helpful for more precisely diagnosing reasons for accessibility failure.</para>
/// </remarks>
public bool IsSymbolAccessibleWithin(
ISymbol symbol,
ISymbol within,
ITypeSymbol? throughType = null)
{
if (symbol is null)
{
throw new ArgumentNullException(nameof(symbol));
}
if (within is null)
{
throw new ArgumentNullException(nameof(within));
}
if (!(within is INamedTypeSymbol || within is IAssemblySymbol))
{
throw new ArgumentException(string.Format(CodeAnalysisResources.IsSymbolAccessibleBadWithin, nameof(within)), nameof(within));
}
checkInCompilationReferences(symbol, nameof(symbol));
checkInCompilationReferences(within, nameof(within));
if (throughType is object)
{
checkInCompilationReferences(throughType, nameof(throughType));
}
return IsSymbolAccessibleWithinCore(symbol, within, throughType);
void checkInCompilationReferences(ISymbol s, string parameterName)
{
if (!isContainingAssemblyInReferences(s))
{
throw new ArgumentException(string.Format(CodeAnalysisResources.IsSymbolAccessibleWrongAssembly, parameterName), parameterName);
}
}
bool assemblyIsInReferences(IAssemblySymbol a)
{
if (assemblyIsInCompilationReferences(a, this))
{
return true;
}
if (this.IsSubmission)
{
// Submissions can reference symbols from previous submissions and their referenced assemblies, even
// though those references are missing from this.References. We work around that by digging in
// to find references of previous submissions. See https://github.com/dotnet/roslyn/issues/27356
for (Compilation? c = this.PreviousSubmission; c != null; c = c.PreviousSubmission)
{
if (assemblyIsInCompilationReferences(a, c))
{
return true;
}
}
}
return false;
}
bool assemblyIsInCompilationReferences(IAssemblySymbol a, Compilation compilation)
{
if (a.Equals(compilation.Assembly))
{
return true;
}
foreach (var reference in compilation.References)
{
if (a.Equals(compilation.GetAssemblyOrModuleSymbol(reference)))
{
return true;
}
}
return false;
}
bool isContainingAssemblyInReferences(ISymbol s)
{
while (true)
{
switch (s.Kind)
{
case SymbolKind.Assembly:
return assemblyIsInReferences((IAssemblySymbol)s);
case SymbolKind.PointerType:
s = ((IPointerTypeSymbol)s).PointedAtType;
continue;
case SymbolKind.ArrayType:
s = ((IArrayTypeSymbol)s).ElementType;
continue;
case SymbolKind.Alias:
s = ((IAliasSymbol)s).Target;
continue;
case SymbolKind.Discard:
s = ((IDiscardSymbol)s).Type;
continue;
case SymbolKind.FunctionPointerType:
var funcPtr = (IFunctionPointerTypeSymbol)s;
if (!isContainingAssemblyInReferences(funcPtr.Signature.ReturnType))
{
return false;
}
foreach (var param in funcPtr.Signature.Parameters)
{
if (!isContainingAssemblyInReferences(param.Type))
{
return false;
}
}
return true;
case SymbolKind.DynamicType:
case SymbolKind.ErrorType:
case SymbolKind.Preprocessing:
case SymbolKind.Namespace:
// these symbols are not restricted in where they can be accessed, so unless they report
// a containing assembly, we treat them as in the current assembly for access purposes
return assemblyIsInReferences(s.ContainingAssembly ?? this.Assembly);
default:
return assemblyIsInReferences(s.ContainingAssembly);
}
}
}
}
private protected abstract bool IsSymbolAccessibleWithinCore(
ISymbol symbol,
ISymbol within,
ITypeSymbol? throughType);
internal abstract IConvertibleConversion ClassifyConvertibleConversion(IOperation source, ITypeSymbol destination, out ConstantValue? constantValue);
#endregion
#region Diagnostics
internal const CompilationStage DefaultDiagnosticsStage = CompilationStage.Compile;
/// <summary>
/// Gets the diagnostics produced during the parsing stage.
/// </summary>
public abstract ImmutableArray<Diagnostic> GetParseDiagnostics(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the diagnostics produced during symbol declaration.
/// </summary>
public abstract ImmutableArray<Diagnostic> GetDeclarationDiagnostics(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the diagnostics produced during the analysis of method bodies and field initializers.
/// </summary>
public abstract ImmutableArray<Diagnostic> GetMethodBodyDiagnostics(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the diagnostics for the compilation, including syntax, declaration, and
/// binding. Does not include any diagnostics that might be produced during emit, see
/// <see cref="EmitResult"/>.
/// </summary>
public abstract ImmutableArray<Diagnostic> GetDiagnostics(CancellationToken cancellationToken = default(CancellationToken));
internal abstract void GetDiagnostics(CompilationStage stage, bool includeEarlierStages, DiagnosticBag diagnostics, CancellationToken cancellationToken = default);
/// <summary>
/// Unique metadata assembly references that are considered to be used by this compilation.
/// For example, if a type declared in a referenced assembly is referenced in source code
/// within this compilation, the reference is considered to be used. Etc.
/// The returned set is a subset of references returned by <see cref="References"/> API.
/// The result is undefined if the compilation contains errors.
/// </summary>
public abstract ImmutableArray<MetadataReference> GetUsedAssemblyReferences(CancellationToken cancellationToken = default(CancellationToken));
internal void EnsureCompilationEventQueueCompleted()
{
RoslynDebug.Assert(EventQueue != null);
lock (EventQueue)
{
if (!EventQueue.IsCompleted)
{
CompleteCompilationEventQueue_NoLock();
}
}
}
internal void CompleteCompilationEventQueue_NoLock()
{
RoslynDebug.Assert(EventQueue != null);
// Signal the end of compilation.
EventQueue.TryEnqueue(new CompilationCompletedEvent(this));
EventQueue.PromiseNotToEnqueue();
EventQueue.TryComplete();
}
internal abstract CommonMessageProvider MessageProvider { get; }
/// <summary>
/// Filter out warnings based on the compiler options (/nowarn, /warn and /warnaserror) and the pragma warning directives.
/// 'incoming' is freed.
/// </summary>
/// <param name="accumulator">Bag to which filtered diagnostics will be added.</param>
/// <param name="incoming">Diagnostics to be filtered.</param>
/// <returns>True if there are no unsuppressed errors (i.e., no errors which fail compilation).</returns>
internal bool FilterAndAppendAndFreeDiagnostics(DiagnosticBag accumulator, [DisallowNull] ref DiagnosticBag? incoming, CancellationToken cancellationToken)
{
RoslynDebug.Assert(incoming is object);
bool result = FilterAndAppendDiagnostics(accumulator, incoming.AsEnumerableWithoutResolution(), exclude: null, cancellationToken);
incoming.Free();
incoming = null;
return result;
}
/// <summary>
/// Filter out warnings based on the compiler options (/nowarn, /warn and /warnaserror) and the pragma warning directives.
/// </summary>
/// <returns>True if there are no unsuppressed errors (i.e., no errors which fail compilation).</returns>
internal bool FilterAndAppendDiagnostics(DiagnosticBag accumulator, IEnumerable<Diagnostic> incoming, HashSet<int>? exclude, CancellationToken cancellationToken)
{
bool hasError = false;
bool reportSuppressedDiagnostics = Options.ReportSuppressedDiagnostics;
foreach (Diagnostic d in incoming)
{
if (exclude?.Contains(d.Code) == true)
{
continue;
}
var filtered = Options.FilterDiagnostic(d, cancellationToken);
if (filtered == null ||
(!reportSuppressedDiagnostics && filtered.IsSuppressed))
{
continue;
}
else if (filtered.IsUnsuppressableError())
{
hasError = true;
}
accumulator.Add(filtered);
}
return !hasError;
}
#endregion
#region Resources
/// <summary>
/// Create a stream filled with default win32 resources.
/// </summary>
public Stream CreateDefaultWin32Resources(bool versionResource, bool noManifest, Stream? manifestContents, Stream? iconInIcoFormat)
{
//Win32 resource encodings use a lot of 16bit values. Do all of the math checked with the
//expectation that integer types are well-chosen with size in mind.
checked
{
var result = new MemoryStream(1024);
//start with a null resource just as rc.exe does
AppendNullResource(result);
if (versionResource)
AppendDefaultVersionResource(result);
if (!noManifest)
{
if (this.Options.OutputKind.IsApplication())
{
// Applications use a default manifest if one is not specified.
if (manifestContents == null)
{
manifestContents = typeof(Compilation).GetTypeInfo().Assembly.GetManifestResourceStream("Microsoft.CodeAnalysis.Resources.default.win32manifest");
}
}
else
{
// Modules never have manifests, even if one is specified.
//Debug.Assert(!this.Options.OutputKind.IsNetModule() || manifestContents == null);
}
if (manifestContents != null)
{
Win32ResourceConversions.AppendManifestToResourceStream(result, manifestContents, !this.Options.OutputKind.IsApplication());
}
}
if (iconInIcoFormat != null)
{
Win32ResourceConversions.AppendIconToResourceStream(result, iconInIcoFormat);
}
result.Position = 0;
return result;
}
}
internal static void AppendNullResource(Stream resourceStream)
{
var writer = new BinaryWriter(resourceStream);
writer.Write((UInt32)0);
writer.Write((UInt32)0x20);
writer.Write((UInt16)0xFFFF);
writer.Write((UInt16)0);
writer.Write((UInt16)0xFFFF);
writer.Write((UInt16)0);
writer.Write((UInt32)0); //DataVersion
writer.Write((UInt16)0); //MemoryFlags
writer.Write((UInt16)0); //LanguageId
writer.Write((UInt32)0); //Version
writer.Write((UInt32)0); //Characteristics
}
protected abstract void AppendDefaultVersionResource(Stream resourceStream);
internal enum Win32ResourceForm : byte
{
UNKNOWN,
COFF,
RES
}
internal static Win32ResourceForm DetectWin32ResourceForm(Stream win32Resources)
{
var reader = new BinaryReader(win32Resources, Encoding.Unicode);
var initialPosition = win32Resources.Position;
var initial32Bits = reader.ReadUInt32();
win32Resources.Position = initialPosition;
//RC.EXE output starts with a resource that contains no data.
if (initial32Bits == 0)
return Win32ResourceForm.RES;
else if ((initial32Bits & 0xFFFF0000) != 0 || (initial32Bits & 0x0000FFFF) != 0xFFFF)
// See CLiteWeightStgdbRW::FindObjMetaData in peparse.cpp
return Win32ResourceForm.COFF;
else
return Win32ResourceForm.UNKNOWN;
}
internal Cci.ResourceSection? MakeWin32ResourcesFromCOFF(Stream? win32Resources, DiagnosticBag diagnostics)
{
if (win32Resources == null)
{
return null;
}
Cci.ResourceSection resources;
try
{
resources = COFFResourceReader.ReadWin32ResourcesFromCOFF(win32Resources);
}
catch (BadImageFormatException ex)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message));
return null;
}
catch (IOException ex)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message));
return null;
}
catch (ResourceException ex)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message));
return null;
}
return resources;
}
internal List<Win32Resource>? MakeWin32ResourceList(Stream? win32Resources, DiagnosticBag diagnostics)
{
if (win32Resources == null)
{
return null;
}
List<RESOURCE> resources;
try
{
resources = CvtResFile.ReadResFile(win32Resources);
}
catch (ResourceException ex)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message));
return null;
}
if (resources == null)
{
return null;
}
var resourceList = new List<Win32Resource>();
foreach (var r in resources)
{
var result = new Win32Resource(
data: r.data,
codePage: 0,
languageId: r.LanguageId,
//EDMAURER converting to int from ushort.
//Go to short first to avoid sign extension.
id: unchecked((short)r.pstringName!.Ordinal),
name: r.pstringName.theString,
typeId: unchecked((short)r.pstringType!.Ordinal),
typeName: r.pstringType.theString
);
resourceList.Add(result);
}
return resourceList;
}
internal void SetupWin32Resources(CommonPEModuleBuilder moduleBeingBuilt, Stream? win32Resources, DiagnosticBag diagnostics)
{
if (win32Resources == null)
return;
Win32ResourceForm resourceForm;
try
{
resourceForm = DetectWin32ResourceForm(win32Resources);
}
catch (EndOfStreamException)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, NoLocation.Singleton, CodeAnalysisResources.UnrecognizedResourceFileFormat));
return;
}
catch (Exception ex)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, NoLocation.Singleton, ex.Message));
return;
}
switch (resourceForm)
{
case Win32ResourceForm.COFF:
moduleBeingBuilt.Win32ResourceSection = MakeWin32ResourcesFromCOFF(win32Resources, diagnostics);
break;
case Win32ResourceForm.RES:
moduleBeingBuilt.Win32Resources = MakeWin32ResourceList(win32Resources, diagnostics);
break;
default:
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, NoLocation.Singleton, CodeAnalysisResources.UnrecognizedResourceFileFormat));
break;
}
}
internal void ReportManifestResourceDuplicates(
IEnumerable<ResourceDescription>? manifestResources,
IEnumerable<string> addedModuleNames,
IEnumerable<string> addedModuleResourceNames,
DiagnosticBag diagnostics)
{
if (Options.OutputKind == OutputKind.NetModule && !(manifestResources != null && manifestResources.Any()))
{
return;
}
var uniqueResourceNames = new HashSet<string>();
if (manifestResources != null && manifestResources.Any())
{
var uniqueFileNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var resource in manifestResources)
{
if (!uniqueResourceNames.Add(resource.ResourceName))
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceNotUnique, Location.None, resource.ResourceName));
}
// file name could be null if resource is embedded
var fileName = resource.FileName;
if (fileName != null && !uniqueFileNames.Add(fileName))
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceFileNameNotUnique, Location.None, fileName));
}
}
foreach (var fileName in addedModuleNames)
{
if (!uniqueFileNames.Add(fileName))
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceFileNameNotUnique, Location.None, fileName));
}
}
}
if (Options.OutputKind != OutputKind.NetModule)
{
foreach (string name in addedModuleResourceNames)
{
if (!uniqueResourceNames.Add(name))
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceNotUnique, Location.None, name));
}
}
}
}
#endregion
#region Emit
/// <summary>
/// There are two ways to sign PE files
/// 1. By directly signing the <see cref="PEBuilder"/>
/// 2. Write the unsigned PE to disk and use CLR COM APIs to sign.
/// The preferred method is #1 as it's more efficient and more resilient (no reliance on %TEMP%). But
/// we must continue to support #2 as it's the only way to do the following:
/// - Access private keys stored in a key container
/// - Do proper counter signature verification for AssemblySignatureKey attributes
/// </summary>
internal bool SignUsingBuilder =>
string.IsNullOrEmpty(StrongNameKeys.KeyContainer) &&
!StrongNameKeys.HasCounterSignature &&
!_features.ContainsKey("UseLegacyStrongNameProvider");
/// <summary>
/// Constructs the module serialization properties out of the compilation options of this compilation.
/// </summary>
internal Cci.ModulePropertiesForSerialization ConstructModuleSerializationProperties(
EmitOptions emitOptions,
string? targetRuntimeVersion,
Guid moduleVersionId = default(Guid))
{
CompilationOptions compilationOptions = this.Options;
Platform platform = compilationOptions.Platform;
OutputKind outputKind = compilationOptions.OutputKind;
if (!platform.IsValid())
{
platform = Platform.AnyCpu;
}
if (!outputKind.IsValid())
{
outputKind = OutputKind.DynamicallyLinkedLibrary;
}
bool requires64Bit = platform.Requires64Bit();
bool requires32Bit = platform.Requires32Bit();
ushort fileAlignment;
if (emitOptions.FileAlignment == 0 || !CompilationOptions.IsValidFileAlignment(emitOptions.FileAlignment))
{
fileAlignment = requires64Bit
? Cci.ModulePropertiesForSerialization.DefaultFileAlignment64Bit
: Cci.ModulePropertiesForSerialization.DefaultFileAlignment32Bit;
}
else
{
fileAlignment = (ushort)emitOptions.FileAlignment;
}
ulong baseAddress = unchecked(emitOptions.BaseAddress + 0x8000) & (requires64Bit ? 0xffffffffffff0000 : 0x00000000ffff0000);
// cover values smaller than 0x8000, overflow and default value 0):
if (baseAddress == 0)
{
if (outputKind == OutputKind.ConsoleApplication ||
outputKind == OutputKind.WindowsApplication ||
outputKind == OutputKind.WindowsRuntimeApplication)
{
baseAddress = (requires64Bit) ? Cci.ModulePropertiesForSerialization.DefaultExeBaseAddress64Bit : Cci.ModulePropertiesForSerialization.DefaultExeBaseAddress32Bit;
}
else
{
baseAddress = (requires64Bit) ? Cci.ModulePropertiesForSerialization.DefaultDllBaseAddress64Bit : Cci.ModulePropertiesForSerialization.DefaultDllBaseAddress32Bit;
}
}
ulong sizeOfHeapCommit = requires64Bit
? Cci.ModulePropertiesForSerialization.DefaultSizeOfHeapCommit64Bit
: Cci.ModulePropertiesForSerialization.DefaultSizeOfHeapCommit32Bit;
// Dev10 always uses the default value for 32bit for sizeOfHeapReserve.
// check with link -dump -headers <filename>
const ulong sizeOfHeapReserve = Cci.ModulePropertiesForSerialization.DefaultSizeOfHeapReserve32Bit;
ulong sizeOfStackReserve = requires64Bit
? Cci.ModulePropertiesForSerialization.DefaultSizeOfStackReserve64Bit
: Cci.ModulePropertiesForSerialization.DefaultSizeOfStackReserve32Bit;
ulong sizeOfStackCommit = requires64Bit
? Cci.ModulePropertiesForSerialization.DefaultSizeOfStackCommit64Bit
: Cci.ModulePropertiesForSerialization.DefaultSizeOfStackCommit32Bit;
SubsystemVersion subsystemVersion;
if (emitOptions.SubsystemVersion.Equals(SubsystemVersion.None) || !emitOptions.SubsystemVersion.IsValid)
{
subsystemVersion = SubsystemVersion.Default(outputKind, platform);
}
else
{
subsystemVersion = emitOptions.SubsystemVersion;
}
Machine machine;
switch (platform)
{
case Platform.Arm64:
machine = Machine.Arm64;
break;
case Platform.Arm:
machine = Machine.ArmThumb2;
break;
case Platform.X64:
machine = Machine.Amd64;
break;
case Platform.Itanium:
machine = Machine.IA64;
break;
case Platform.X86:
machine = Machine.I386;
break;
case Platform.AnyCpu:
case Platform.AnyCpu32BitPreferred:
machine = Machine.Unknown;
break;
default:
throw ExceptionUtilities.UnexpectedValue(platform);
}
return new Cci.ModulePropertiesForSerialization(
persistentIdentifier: moduleVersionId,
corFlags: GetCorHeaderFlags(machine, HasStrongName, prefers32Bit: platform == Platform.AnyCpu32BitPreferred),
fileAlignment: fileAlignment,
sectionAlignment: Cci.ModulePropertiesForSerialization.DefaultSectionAlignment,
targetRuntimeVersion: targetRuntimeVersion,
machine: machine,
baseAddress: baseAddress,
sizeOfHeapReserve: sizeOfHeapReserve,
sizeOfHeapCommit: sizeOfHeapCommit,
sizeOfStackReserve: sizeOfStackReserve,
sizeOfStackCommit: sizeOfStackCommit,
dllCharacteristics: GetDllCharacteristics(emitOptions.HighEntropyVirtualAddressSpace, compilationOptions.OutputKind == OutputKind.WindowsRuntimeApplication),
imageCharacteristics: GetCharacteristics(outputKind, requires32Bit),
subsystem: GetSubsystem(outputKind),
majorSubsystemVersion: (ushort)subsystemVersion.Major,
minorSubsystemVersion: (ushort)subsystemVersion.Minor,
linkerMajorVersion: this.LinkerMajorVersion,
linkerMinorVersion: 0);
}
private static CorFlags GetCorHeaderFlags(Machine machine, bool strongNameSigned, bool prefers32Bit)
{
CorFlags result = CorFlags.ILOnly;
if (machine == Machine.I386)
{
result |= CorFlags.Requires32Bit;
}
if (strongNameSigned)
{
result |= CorFlags.StrongNameSigned;
}
if (prefers32Bit)
{
result |= CorFlags.Requires32Bit | CorFlags.Prefers32Bit;
}
return result;
}
internal static DllCharacteristics GetDllCharacteristics(bool enableHighEntropyVA, bool configureToExecuteInAppContainer)
{
var result =
DllCharacteristics.DynamicBase |
DllCharacteristics.NxCompatible |
DllCharacteristics.NoSeh |
DllCharacteristics.TerminalServerAware;
if (enableHighEntropyVA)
{
result |= DllCharacteristics.HighEntropyVirtualAddressSpace;
}
if (configureToExecuteInAppContainer)
{
result |= DllCharacteristics.AppContainer;
}
return result;
}
private static Characteristics GetCharacteristics(OutputKind outputKind, bool requires32Bit)
{
var characteristics = Characteristics.ExecutableImage;
if (requires32Bit)
{
// 32 bit machine (The standard says to always set this, the linker team says otherwise)
// The loader team says that this is not used for anything in the OS.
characteristics |= Characteristics.Bit32Machine;
}
else
{
// Large address aware (the standard says never to set this, the linker team says otherwise).
// The loader team says that this is not overridden for managed binaries and will be respected if set.
characteristics |= Characteristics.LargeAddressAware;
}
switch (outputKind)
{
case OutputKind.WindowsRuntimeMetadata:
case OutputKind.DynamicallyLinkedLibrary:
case OutputKind.NetModule:
characteristics |= Characteristics.Dll;
break;
case OutputKind.ConsoleApplication:
case OutputKind.WindowsRuntimeApplication:
case OutputKind.WindowsApplication:
break;
default:
throw ExceptionUtilities.UnexpectedValue(outputKind);
}
return characteristics;
}
private static Subsystem GetSubsystem(OutputKind outputKind)
{
switch (outputKind)
{
case OutputKind.ConsoleApplication:
case OutputKind.DynamicallyLinkedLibrary:
case OutputKind.NetModule:
case OutputKind.WindowsRuntimeMetadata:
return Subsystem.WindowsCui;
case OutputKind.WindowsRuntimeApplication:
case OutputKind.WindowsApplication:
return Subsystem.WindowsGui;
default:
throw ExceptionUtilities.UnexpectedValue(outputKind);
}
}
/// <summary>
/// The value is not used by Windows loader, but the OS appcompat infrastructure uses it to identify apps.
/// It is useful for us to have a mechanism to identify the compiler that produced the binary.
/// This is the appropriate value to use for that. That is what it was invented for.
/// We don't want to have the high bit set for this in case some users perform a signed comparison to
/// determine if the value is less than some version. The C++ linker is at 0x0B.
/// We'll start our numbering at 0x30 for C#, 0x50 for VB.
/// </summary>
internal abstract byte LinkerMajorVersion { get; }
internal bool HasStrongName
{
get
{
return !IsDelaySigned
&& Options.OutputKind != OutputKind.NetModule
&& StrongNameKeys.CanProvideStrongName;
}
}
internal bool IsRealSigned
{
get
{
// A module cannot be signed. The native compiler allowed one to create a netmodule with an AssemblyKeyFile
// or Container attribute (or specify a key via the cmd line). When the module was linked into an assembly,
// alink would sign the assembly. So rather than give an error we just don't sign when outputting a module.
return !IsDelaySigned
&& !Options.PublicSign
&& Options.OutputKind != OutputKind.NetModule
&& StrongNameKeys.CanSign;
}
}
/// <summary>
/// Return true if the compilation contains any code or types.
/// </summary>
internal abstract bool HasCodeToEmit();
internal abstract bool IsDelaySigned { get; }
internal abstract StrongNameKeys StrongNameKeys { get; }
internal abstract CommonPEModuleBuilder? CreateModuleBuilder(
EmitOptions emitOptions,
IMethodSymbol? debugEntryPoint,
Stream? sourceLinkStream,
IEnumerable<EmbeddedText>? embeddedTexts,
IEnumerable<ResourceDescription>? manifestResources,
CompilationTestData? testData,
DiagnosticBag diagnostics,
CancellationToken cancellationToken);
/// <summary>
/// Report declaration diagnostics and compile and synthesize method bodies.
/// </summary>
/// <returns>True if successful.</returns>
internal abstract bool CompileMethods(
CommonPEModuleBuilder moduleBuilder,
bool emittingPdb,
bool emitMetadataOnly,
bool emitTestCoverageData,
DiagnosticBag diagnostics,
Predicate<ISymbolInternal>? filterOpt,
CancellationToken cancellationToken);
internal bool CreateDebugDocuments(DebugDocumentsBuilder documentsBuilder, IEnumerable<EmbeddedText> embeddedTexts, DiagnosticBag diagnostics)
{
// Check that all syntax trees are debuggable:
bool allTreesDebuggable = true;
foreach (var tree in SyntaxTrees)
{
if (!string.IsNullOrEmpty(tree.FilePath) && tree.GetText().Encoding == null)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_EncodinglessSyntaxTree, tree.GetRoot().GetLocation()));
allTreesDebuggable = false;
}
}
if (!allTreesDebuggable)
{
return false;
}
// Add debug documents for all embedded text first. This ensures that embedding
// takes priority over the syntax tree pass, which will not embed.
if (!embeddedTexts.IsEmpty())
{
foreach (var text in embeddedTexts)
{
Debug.Assert(!string.IsNullOrEmpty(text.FilePath));
string normalizedPath = documentsBuilder.NormalizeDebugDocumentPath(text.FilePath, basePath: null);
var existingDoc = documentsBuilder.TryGetDebugDocumentForNormalizedPath(normalizedPath);
if (existingDoc == null)
{
var document = new Cci.DebugSourceDocument(
normalizedPath,
DebugSourceDocumentLanguageId,
() => text.GetDebugSourceInfo());
documentsBuilder.AddDebugDocument(document);
}
}
}
// Add debug documents for all trees with distinct paths.
foreach (var tree in SyntaxTrees)
{
if (!string.IsNullOrEmpty(tree.FilePath))
{
// compilation does not guarantee that all trees will have distinct paths.
// Do not attempt adding a document for a particular path if we already added one.
string normalizedPath = documentsBuilder.NormalizeDebugDocumentPath(tree.FilePath, basePath: null);
var existingDoc = documentsBuilder.TryGetDebugDocumentForNormalizedPath(normalizedPath);
if (existingDoc == null)
{
documentsBuilder.AddDebugDocument(new Cci.DebugSourceDocument(
normalizedPath,
DebugSourceDocumentLanguageId,
() => tree.GetDebugSourceInfo()));
}
}
}
// Add debug documents for all pragmas.
// If there are clashes with already processed directives, report warnings.
// If there are clashes with debug documents that came from actual trees, ignore the pragma.
// Therefore we need to add these in a separate pass after documents for syntax trees were added.
foreach (var tree in SyntaxTrees)
{
AddDebugSourceDocumentsForChecksumDirectives(documentsBuilder, tree, diagnostics);
}
return true;
}
internal abstract Guid DebugSourceDocumentLanguageId { get; }
internal abstract void AddDebugSourceDocumentsForChecksumDirectives(DebugDocumentsBuilder documentsBuilder, SyntaxTree tree, DiagnosticBag diagnostics);
/// <summary>
/// Update resources and generate XML documentation comments.
/// </summary>
/// <returns>True if successful.</returns>
internal abstract bool GenerateResourcesAndDocumentationComments(
CommonPEModuleBuilder moduleBeingBuilt,
Stream? xmlDocumentationStream,
Stream? win32ResourcesStream,
string? outputNameOverride,
DiagnosticBag diagnostics,
CancellationToken cancellationToken);
/// <summary>
/// Reports all unused imports/usings so far (and thus it must be called as a last step of Emit)
/// </summary>
internal abstract void ReportUnusedImports(
SyntaxTree? filterTree,
DiagnosticBag diagnostics,
CancellationToken cancellationToken);
internal static bool ReportUnusedImportsInTree(SyntaxTree tree)
{
return tree.Options.DocumentationMode != DocumentationMode.None;
}
/// <summary>
/// Signals the event queue, if any, that we are done compiling.
/// There should not be more compiling actions after this step.
/// NOTE: once we signal about completion to analyzers they will cancel and thus in some cases we
/// may be effectively cutting off some diagnostics.
/// It is not clear if behavior is desirable.
/// See: https://github.com/dotnet/roslyn/issues/11470
/// </summary>
/// <param name="filterTree">What tree to complete. null means complete all trees. </param>
internal abstract void CompleteTrees(SyntaxTree? filterTree);
internal bool Compile(
CommonPEModuleBuilder moduleBuilder,
bool emittingPdb,
DiagnosticBag diagnostics,
Predicate<ISymbolInternal>? filterOpt,
CancellationToken cancellationToken)
{
try
{
return CompileMethods(
moduleBuilder,
emittingPdb,
emitMetadataOnly: false,
emitTestCoverageData: false,
diagnostics: diagnostics,
filterOpt: filterOpt,
cancellationToken: cancellationToken);
}
finally
{
moduleBuilder.CompilationFinished();
}
}
internal void EnsureAnonymousTypeTemplates(CancellationToken cancellationToken)
{
Debug.Assert(IsSubmission);
if (this.GetSubmissionSlotIndex() >= 0 && HasCodeToEmit())
{
if (!this.CommonAnonymousTypeManager.AreTemplatesSealed)
{
var discardedDiagnostics = DiagnosticBag.GetInstance();
var moduleBeingBuilt = this.CreateModuleBuilder(
emitOptions: EmitOptions.Default,
debugEntryPoint: null,
manifestResources: null,
sourceLinkStream: null,
embeddedTexts: null,
testData: null,
diagnostics: discardedDiagnostics,
cancellationToken: cancellationToken);
if (moduleBeingBuilt != null)
{
Compile(
moduleBeingBuilt,
diagnostics: discardedDiagnostics,
emittingPdb: false,
filterOpt: null,
cancellationToken: cancellationToken);
}
discardedDiagnostics.Free();
}
Debug.Assert(this.CommonAnonymousTypeManager.AreTemplatesSealed);
}
else
{
this.ScriptCompilationInfo?.PreviousScriptCompilation?.EnsureAnonymousTypeTemplates(cancellationToken);
}
}
// 1.0 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
[EditorBrowsable(EditorBrowsableState.Never)]
public EmitResult Emit(
Stream peStream,
Stream? pdbStream,
Stream? xmlDocumentationStream,
Stream? win32Resources,
IEnumerable<ResourceDescription>? manifestResources,
EmitOptions options,
CancellationToken cancellationToken)
{
return Emit(
peStream,
pdbStream,
xmlDocumentationStream,
win32Resources,
manifestResources,
options,
debugEntryPoint: null,
sourceLinkStream: null,
embeddedTexts: null,
cancellationToken);
}
// 1.3 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
[EditorBrowsable(EditorBrowsableState.Never)]
public EmitResult Emit(
Stream peStream,
Stream pdbStream,
Stream xmlDocumentationStream,
Stream win32Resources,
IEnumerable<ResourceDescription> manifestResources,
EmitOptions options,
IMethodSymbol debugEntryPoint,
CancellationToken cancellationToken)
{
return Emit(
peStream,
pdbStream,
xmlDocumentationStream,
win32Resources,
manifestResources,
options,
debugEntryPoint,
sourceLinkStream: null,
embeddedTexts: null,
cancellationToken);
}
// 2.0 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
public EmitResult Emit(
Stream peStream,
Stream? pdbStream,
Stream? xmlDocumentationStream,
Stream? win32Resources,
IEnumerable<ResourceDescription>? manifestResources,
EmitOptions options,
IMethodSymbol? debugEntryPoint,
Stream? sourceLinkStream,
IEnumerable<EmbeddedText>? embeddedTexts,
CancellationToken cancellationToken)
{
return Emit(
peStream,
pdbStream,
xmlDocumentationStream,
win32Resources,
manifestResources,
options,
debugEntryPoint,
sourceLinkStream,
embeddedTexts,
metadataPEStream: null,
cancellationToken: cancellationToken);
}
/// <summary>
/// Emit the IL for the compiled source code into the specified stream.
/// </summary>
/// <param name="peStream">Stream to which the compilation will be written.</param>
/// <param name="metadataPEStream">Stream to which the metadata-only output will be written.</param>
/// <param name="pdbStream">Stream to which the compilation's debug info will be written. Null to forego PDB generation.</param>
/// <param name="xmlDocumentationStream">Stream to which the compilation's XML documentation will be written. Null to forego XML generation.</param>
/// <param name="win32Resources">Stream from which the compilation's Win32 resources will be read (in RES format).
/// Null to indicate that there are none. The RES format begins with a null resource entry.</param>
/// <param name="manifestResources">List of the compilation's managed resources. Null to indicate that there are none.</param>
/// <param name="options">Emit options.</param>
/// <param name="debugEntryPoint">
/// Debug entry-point of the assembly. The method token is stored in the generated PDB stream.
///
/// When a program launches with a debugger attached the debugger places the first breakpoint to the start of the debug entry-point method.
/// The CLR starts executing the static Main method of <see cref="CompilationOptions.MainTypeName"/> type. When the first breakpoint is hit
/// the debugger steps thru the code statement by statement until user code is reached, skipping methods marked by <see cref="DebuggerHiddenAttribute"/>,
/// and taking other debugging attributes into consideration.
///
/// By default both entry points in an executable program (<see cref="OutputKind.ConsoleApplication"/>, <see cref="OutputKind.WindowsApplication"/>, <see cref="OutputKind.WindowsRuntimeApplication"/>)
/// are the same method (Main). A non-executable program has no entry point. Runtimes that implement a custom loader may specify debug entry-point
/// to force the debugger to skip over complex custom loader logic executing at the beginning of the .exe and thus improve debugging experience.
///
/// Unlike ordinary entry-point which is limited to a non-generic static method of specific signature, there are no restrictions on the <paramref name="debugEntryPoint"/>
/// method other than having a method body (extern, interface, or abstract methods are not allowed).
/// </param>
/// <param name="sourceLinkStream">
/// Stream containing information linking the compilation to a source control.
/// </param>
/// <param name="embeddedTexts">
/// Texts to embed in the PDB.
/// Only supported when emitting Portable PDBs.
/// </param>
/// <param name="cancellationToken">To cancel the emit process.</param>
public EmitResult Emit(
Stream peStream,
Stream? pdbStream = null,
Stream? xmlDocumentationStream = null,
Stream? win32Resources = null,
IEnumerable<ResourceDescription>? manifestResources = null,
EmitOptions? options = null,
IMethodSymbol? debugEntryPoint = null,
Stream? sourceLinkStream = null,
IEnumerable<EmbeddedText>? embeddedTexts = null,
Stream? metadataPEStream = null,
CancellationToken cancellationToken = default(CancellationToken))
{
if (peStream == null)
{
throw new ArgumentNullException(nameof(peStream));
}
if (!peStream.CanWrite)
{
throw new ArgumentException(CodeAnalysisResources.StreamMustSupportWrite, nameof(peStream));
}
if (pdbStream != null)
{
if (options?.DebugInformationFormat == DebugInformationFormat.Embedded)
{
throw new ArgumentException(CodeAnalysisResources.PdbStreamUnexpectedWhenEmbedding, nameof(pdbStream));
}
if (!pdbStream.CanWrite)
{
throw new ArgumentException(CodeAnalysisResources.StreamMustSupportWrite, nameof(pdbStream));
}
if (options?.EmitMetadataOnly == true)
{
throw new ArgumentException(CodeAnalysisResources.PdbStreamUnexpectedWhenEmittingMetadataOnly, nameof(pdbStream));
}
}
if (metadataPEStream != null && options?.EmitMetadataOnly == true)
{
throw new ArgumentException(CodeAnalysisResources.MetadataPeStreamUnexpectedWhenEmittingMetadataOnly, nameof(metadataPEStream));
}
if (metadataPEStream != null && options?.IncludePrivateMembers == true)
{
throw new ArgumentException(CodeAnalysisResources.IncludingPrivateMembersUnexpectedWhenEmittingToMetadataPeStream, nameof(metadataPEStream));
}
if (metadataPEStream == null && options?.EmitMetadataOnly == false)
{
// EmitOptions used to default to IncludePrivateMembers=false, so to preserve binary compatibility we silently correct that unless emitting regular assemblies
options = options.WithIncludePrivateMembers(true);
}
if (options?.DebugInformationFormat == DebugInformationFormat.Embedded &&
options?.EmitMetadataOnly == true)
{
throw new ArgumentException(CodeAnalysisResources.EmbeddingPdbUnexpectedWhenEmittingMetadata, nameof(metadataPEStream));
}
if (this.Options.OutputKind == OutputKind.NetModule)
{
if (metadataPEStream != null)
{
throw new ArgumentException(CodeAnalysisResources.CannotTargetNetModuleWhenEmittingRefAssembly, nameof(metadataPEStream));
}
else if (options?.EmitMetadataOnly == true)
{
throw new ArgumentException(CodeAnalysisResources.CannotTargetNetModuleWhenEmittingRefAssembly, nameof(options.EmitMetadataOnly));
}
}
if (win32Resources != null)
{
if (!win32Resources.CanRead || !win32Resources.CanSeek)
{
throw new ArgumentException(CodeAnalysisResources.StreamMustSupportReadAndSeek, nameof(win32Resources));
}
}
if (sourceLinkStream != null && !sourceLinkStream.CanRead)
{
throw new ArgumentException(CodeAnalysisResources.StreamMustSupportRead, nameof(sourceLinkStream));
}
if (embeddedTexts != null &&
!embeddedTexts.IsEmpty() &&
pdbStream == null &&
options?.DebugInformationFormat != DebugInformationFormat.Embedded)
{
throw new ArgumentException(CodeAnalysisResources.EmbeddedTextsRequirePdb, nameof(embeddedTexts));
}
return Emit(
peStream,
metadataPEStream,
pdbStream,
xmlDocumentationStream,
win32Resources,
manifestResources,
options,
debugEntryPoint,
sourceLinkStream,
embeddedTexts,
testData: null,
cancellationToken: cancellationToken);
}
/// <summary>
/// This overload is only intended to be directly called by tests that want to pass <paramref name="testData"/>.
/// The map is used for storing a list of methods and their associated IL.
/// </summary>
internal EmitResult Emit(
Stream peStream,
Stream? metadataPEStream,
Stream? pdbStream,
Stream? xmlDocumentationStream,
Stream? win32Resources,
IEnumerable<ResourceDescription>? manifestResources,
EmitOptions? options,
IMethodSymbol? debugEntryPoint,
Stream? sourceLinkStream,
IEnumerable<EmbeddedText>? embeddedTexts,
CompilationTestData? testData,
CancellationToken cancellationToken)
{
options = options ?? EmitOptions.Default.WithIncludePrivateMembers(metadataPEStream == null);
bool embedPdb = options.DebugInformationFormat == DebugInformationFormat.Embedded;
Debug.Assert(!embedPdb || pdbStream == null);
Debug.Assert(metadataPEStream == null || !options.IncludePrivateMembers); // you may not use a secondary stream and include private members together
var diagnostics = DiagnosticBag.GetInstance();
var moduleBeingBuilt = CheckOptionsAndCreateModuleBuilder(
diagnostics,
manifestResources,
options,
debugEntryPoint,
sourceLinkStream,
embeddedTexts,
testData,
cancellationToken);
bool success = false;
if (moduleBeingBuilt != null)
{
try
{
success = CompileMethods(
moduleBeingBuilt,
emittingPdb: pdbStream != null || embedPdb,
emitMetadataOnly: options.EmitMetadataOnly,
emitTestCoverageData: options.EmitTestCoverageData,
diagnostics: diagnostics,
filterOpt: null,
cancellationToken: cancellationToken);
if (!options.EmitMetadataOnly)
{
// NOTE: We generate documentation even in presence of compile errors.
// https://github.com/dotnet/roslyn/issues/37996 tracks revisiting this behavior.
if (!GenerateResourcesAndDocumentationComments(
moduleBeingBuilt,
xmlDocumentationStream,
win32Resources,
options.OutputNameOverride,
diagnostics,
cancellationToken))
{
success = false;
}
if (success)
{
ReportUnusedImports(null, diagnostics, cancellationToken);
}
}
}
finally
{
moduleBeingBuilt.CompilationFinished();
}
RSAParameters? privateKeyOpt = null;
if (Options.StrongNameProvider != null && SignUsingBuilder && !Options.PublicSign)
{
privateKeyOpt = StrongNameKeys.PrivateKey;
}
if (!options.EmitMetadataOnly && CommonCompiler.HasUnsuppressedErrors(diagnostics))
{
success = false;
}
if (success)
{
success = SerializeToPeStream(
moduleBeingBuilt,
new SimpleEmitStreamProvider(peStream),
(metadataPEStream != null) ? new SimpleEmitStreamProvider(metadataPEStream) : null,
(pdbStream != null) ? new SimpleEmitStreamProvider(pdbStream) : null,
testData?.SymWriterFactory,
diagnostics,
emitOptions: options,
privateKeyOpt: privateKeyOpt,
cancellationToken: cancellationToken);
}
}
return new EmitResult(success, diagnostics.ToReadOnlyAndFree());
}
/// <summary>
/// Emit the differences between the compilation and the previous generation
/// for Edit and Continue. The differences are expressed as added and changed
/// symbols, and are emitted as metadata, IL, and PDB deltas. A representation
/// of the current compilation is returned as an EmitBaseline for use in a
/// subsequent Edit and Continue.
/// </summary>
public EmitDifferenceResult EmitDifference(
EmitBaseline baseline,
IEnumerable<SemanticEdit> edits,
Stream metadataStream,
Stream ilStream,
Stream pdbStream,
ICollection<MethodDefinitionHandle> updatedMethods,
CancellationToken cancellationToken = default(CancellationToken))
{
return EmitDifference(baseline, edits, s => false, metadataStream, ilStream, pdbStream, updatedMethods, cancellationToken);
}
/// <summary>
/// Emit the differences between the compilation and the previous generation
/// for Edit and Continue. The differences are expressed as added and changed
/// symbols, and are emitted as metadata, IL, and PDB deltas. A representation
/// of the current compilation is returned as an EmitBaseline for use in a
/// subsequent Edit and Continue.
/// </summary>
public EmitDifferenceResult EmitDifference(
EmitBaseline baseline,
IEnumerable<SemanticEdit> edits,
Func<ISymbol, bool> isAddedSymbol,
Stream metadataStream,
Stream ilStream,
Stream pdbStream,
ICollection<MethodDefinitionHandle> updatedMethods,
CancellationToken cancellationToken = default(CancellationToken))
{
if (baseline == null)
{
throw new ArgumentNullException(nameof(baseline));
}
// TODO: check if baseline is an assembly manifest module/netmodule
// Do we support EnC on netmodules?
if (edits == null)
{
throw new ArgumentNullException(nameof(edits));
}
if (isAddedSymbol == null)
{
throw new ArgumentNullException(nameof(isAddedSymbol));
}
if (metadataStream == null)
{
throw new ArgumentNullException(nameof(metadataStream));
}
if (ilStream == null)
{
throw new ArgumentNullException(nameof(ilStream));
}
if (pdbStream == null)
{
throw new ArgumentNullException(nameof(pdbStream));
}
return this.EmitDifference(baseline, edits, isAddedSymbol, metadataStream, ilStream, pdbStream, updatedMethods, testData: null, cancellationToken);
}
internal abstract EmitDifferenceResult EmitDifference(
EmitBaseline baseline,
IEnumerable<SemanticEdit> edits,
Func<ISymbol, bool> isAddedSymbol,
Stream metadataStream,
Stream ilStream,
Stream pdbStream,
ICollection<MethodDefinitionHandle> updatedMethodHandles,
CompilationTestData? testData,
CancellationToken cancellationToken);
/// <summary>
/// Check compilation options and create <see cref="CommonPEModuleBuilder"/>.
/// </summary>
/// <returns><see cref="CommonPEModuleBuilder"/> if successful.</returns>
internal CommonPEModuleBuilder? CheckOptionsAndCreateModuleBuilder(
DiagnosticBag diagnostics,
IEnumerable<ResourceDescription>? manifestResources,
EmitOptions options,
IMethodSymbol? debugEntryPoint,
Stream? sourceLinkStream,
IEnumerable<EmbeddedText>? embeddedTexts,
CompilationTestData? testData,
CancellationToken cancellationToken)
{
options.ValidateOptions(diagnostics, MessageProvider, Options.Deterministic);
if (debugEntryPoint != null)
{
ValidateDebugEntryPoint(debugEntryPoint, diagnostics);
}
if (Options.OutputKind == OutputKind.NetModule && manifestResources != null)
{
foreach (ResourceDescription res in manifestResources)
{
if (res.FileName != null)
{
// Modules can have only embedded resources, not linked ones.
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceInModule, Location.None));
}
}
}
if (CommonCompiler.HasUnsuppressableErrors(diagnostics))
{
return null;
}
// Do not waste a slot in the submission chain for submissions that contain no executable code
// (they may only contain #r directives, usings, etc.)
if (IsSubmission && !HasCodeToEmit())
{
// Still report diagnostics since downstream submissions will assume there are no errors.
diagnostics.AddRange(this.GetDiagnostics(cancellationToken));
return null;
}
return this.CreateModuleBuilder(
options,
debugEntryPoint,
sourceLinkStream,
embeddedTexts,
manifestResources,
testData,
diagnostics,
cancellationToken);
}
internal abstract void ValidateDebugEntryPoint(IMethodSymbol debugEntryPoint, DiagnosticBag diagnostics);
internal bool IsEmitDeterministic => this.Options.Deterministic;
internal bool SerializeToPeStream(
CommonPEModuleBuilder moduleBeingBuilt,
EmitStreamProvider peStreamProvider,
EmitStreamProvider? metadataPEStreamProvider,
EmitStreamProvider? pdbStreamProvider,
Func<ISymWriterMetadataProvider, SymUnmanagedWriter>? testSymWriterFactory,
DiagnosticBag diagnostics,
EmitOptions emitOptions,
RSAParameters? privateKeyOpt,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
Cci.PdbWriter? nativePdbWriter = null;
DiagnosticBag? metadataDiagnostics = null;
DiagnosticBag? pdbBag = null;
bool deterministic = IsEmitDeterministic;
// PDB Stream provider should not be given if PDB is to be embedded into the PE file:
Debug.Assert(moduleBeingBuilt.DebugInformationFormat != DebugInformationFormat.Embedded || pdbStreamProvider == null);
string? pePdbFilePath = emitOptions.PdbFilePath;
if (moduleBeingBuilt.DebugInformationFormat == DebugInformationFormat.Embedded || pdbStreamProvider != null)
{
pePdbFilePath = pePdbFilePath ?? FileNameUtilities.ChangeExtension(SourceModule.Name, "pdb");
}
else
{
pePdbFilePath = null;
}
if (moduleBeingBuilt.DebugInformationFormat == DebugInformationFormat.Embedded && !RoslynString.IsNullOrEmpty(pePdbFilePath))
{
pePdbFilePath = PathUtilities.GetFileName(pePdbFilePath);
}
EmitStream? emitPeStream = null;
EmitStream? emitMetadataStream = null;
try
{
var signKind = IsRealSigned
? (SignUsingBuilder ? EmitStreamSignKind.SignedWithBuilder : EmitStreamSignKind.SignedWithFile)
: EmitStreamSignKind.None;
emitPeStream = new EmitStream(peStreamProvider, signKind, Options.StrongNameProvider);
emitMetadataStream = metadataPEStreamProvider == null
? null
: new EmitStream(metadataPEStreamProvider, signKind, Options.StrongNameProvider);
metadataDiagnostics = DiagnosticBag.GetInstance();
if (moduleBeingBuilt.DebugInformationFormat == DebugInformationFormat.Pdb && pdbStreamProvider != null)
{
// The algorithm must be specified for deterministic builds (checked earlier).
Debug.Assert(!deterministic || moduleBeingBuilt.PdbChecksumAlgorithm.Name != null);
// The calls ISymUnmanagedWriter2.GetDebugInfo require a file name in order to succeed. This is
// frequently used during PDB writing. Ensure a name is provided here in the case we were given
// only a Stream value.
nativePdbWriter = new Cci.PdbWriter(pePdbFilePath, testSymWriterFactory, deterministic ? moduleBeingBuilt.PdbChecksumAlgorithm : default);
}
Func<Stream?>? getPortablePdbStream =
moduleBeingBuilt.DebugInformationFormat != DebugInformationFormat.PortablePdb || pdbStreamProvider == null
? null
: (Func<Stream?>)(() => ConditionalGetOrCreateStream(pdbStreamProvider, metadataDiagnostics));
try
{
if (SerializePeToStream(
moduleBeingBuilt,
metadataDiagnostics,
MessageProvider,
emitPeStream.GetCreateStreamFunc(metadataDiagnostics),
emitMetadataStream?.GetCreateStreamFunc(metadataDiagnostics),
getPortablePdbStream,
nativePdbWriter,
pePdbFilePath,
emitOptions.EmitMetadataOnly,
emitOptions.IncludePrivateMembers,
deterministic,
emitOptions.EmitTestCoverageData,
privateKeyOpt,
cancellationToken))
{
if (nativePdbWriter != null)
{
var nativePdbStream = pdbStreamProvider!.GetOrCreateStream(metadataDiagnostics);
Debug.Assert(nativePdbStream != null || metadataDiagnostics.HasAnyErrors());
if (nativePdbStream != null)
{
nativePdbWriter.WriteTo(nativePdbStream);
}
}
}
}
catch (SymUnmanagedWriterException ex)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PdbWritingFailed, Location.None, ex.Message));
return false;
}
catch (Cci.PeWritingException e)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PeWritingFailure, Location.None, e.InnerException?.ToString() ?? ""));
return false;
}
catch (ResourceException e)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_CantReadResource, Location.None, e.Message, e.InnerException?.Message ?? ""));
return false;
}
catch (PermissionSetFileReadException e)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PermissionSetAttributeFileReadError, Location.None, e.FileName, e.PropertyName, e.Message));
return false;
}
// translate metadata errors.
if (!FilterAndAppendAndFreeDiagnostics(diagnostics, ref metadataDiagnostics, cancellationToken))
{
return false;
}
return
emitPeStream.Complete(StrongNameKeys, MessageProvider, diagnostics) &&
(emitMetadataStream?.Complete(StrongNameKeys, MessageProvider, diagnostics) ?? true);
}
finally
{
nativePdbWriter?.Dispose();
emitPeStream?.Close();
emitMetadataStream?.Close();
pdbBag?.Free();
metadataDiagnostics?.Free();
}
}
private static Stream? ConditionalGetOrCreateStream(EmitStreamProvider metadataPEStreamProvider, DiagnosticBag metadataDiagnostics)
{
if (metadataDiagnostics.HasAnyErrors())
{
return null;
}
var auxStream = metadataPEStreamProvider.GetOrCreateStream(metadataDiagnostics);
Debug.Assert(auxStream != null || metadataDiagnostics.HasAnyErrors());
return auxStream;
}
internal static bool SerializePeToStream(
CommonPEModuleBuilder moduleBeingBuilt,
DiagnosticBag metadataDiagnostics,
CommonMessageProvider messageProvider,
Func<Stream?> getPeStream,
Func<Stream?>? getMetadataPeStreamOpt,
Func<Stream?>? getPortablePdbStreamOpt,
Cci.PdbWriter? nativePdbWriterOpt,
string? pdbPathOpt,
bool metadataOnly,
bool includePrivateMembers,
bool isDeterministic,
bool emitTestCoverageData,
RSAParameters? privateKeyOpt,
CancellationToken cancellationToken)
{
bool emitSecondaryAssembly = getMetadataPeStreamOpt != null;
bool includePrivateMembersOnPrimaryOutput = metadataOnly ? includePrivateMembers : true;
bool deterministicPrimaryOutput = (metadataOnly && !includePrivateMembers) || isDeterministic;
if (!Cci.PeWriter.WritePeToStream(
new EmitContext(moduleBeingBuilt, null, metadataDiagnostics, metadataOnly, includePrivateMembersOnPrimaryOutput),
messageProvider,
getPeStream,
getPortablePdbStreamOpt,
nativePdbWriterOpt,
pdbPathOpt,
metadataOnly,
deterministicPrimaryOutput,
emitTestCoverageData,
privateKeyOpt,
cancellationToken))
{
return false;
}
// produce the secondary output (ref assembly) if needed
if (emitSecondaryAssembly)
{
Debug.Assert(!metadataOnly);
Debug.Assert(!includePrivateMembers);
if (!Cci.PeWriter.WritePeToStream(
new EmitContext(moduleBeingBuilt, null, metadataDiagnostics, metadataOnly: true, includePrivateMembers: false),
messageProvider,
getMetadataPeStreamOpt,
getPortablePdbStreamOpt: null,
nativePdbWriterOpt: null,
pdbPathOpt: null,
metadataOnly: true,
isDeterministic: true,
emitTestCoverageData: false,
privateKeyOpt: privateKeyOpt,
cancellationToken: cancellationToken))
{
return false;
}
}
return true;
}
internal EmitBaseline? SerializeToDeltaStreams(
CommonPEModuleBuilder moduleBeingBuilt,
EmitBaseline baseline,
DefinitionMap definitionMap,
SymbolChanges changes,
Stream metadataStream,
Stream ilStream,
Stream pdbStream,
ICollection<MethodDefinitionHandle> updatedMethods,
DiagnosticBag diagnostics,
Func<ISymWriterMetadataProvider, SymUnmanagedWriter> testSymWriterFactory,
string pdbFilePath,
CancellationToken cancellationToken)
{
var nativePdbWriterOpt = (moduleBeingBuilt.DebugInformationFormat != DebugInformationFormat.Pdb) ? null :
new Cci.PdbWriter(
pdbFilePath ?? FileNameUtilities.ChangeExtension(SourceModule.Name, "pdb"),
testSymWriterFactory,
hashAlgorithmNameOpt: default);
using (nativePdbWriterOpt)
{
var context = new EmitContext(moduleBeingBuilt, null, diagnostics, metadataOnly: false, includePrivateMembers: true);
var encId = Guid.NewGuid();
try
{
var writer = new DeltaMetadataWriter(
context,
MessageProvider,
baseline,
encId,
definitionMap,
changes,
cancellationToken);
writer.WriteMetadataAndIL(
nativePdbWriterOpt,
metadataStream,
ilStream,
(nativePdbWriterOpt == null) ? pdbStream : null,
out MetadataSizes metadataSizes);
writer.GetMethodTokens(updatedMethods);
nativePdbWriterOpt?.WriteTo(pdbStream);
return diagnostics.HasAnyErrors() ? null : writer.GetDelta(baseline, this, encId, metadataSizes);
}
catch (SymUnmanagedWriterException e)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PdbWritingFailed, Location.None, e.Message));
return null;
}
catch (Cci.PeWritingException e)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PeWritingFailure, Location.None, e.InnerException?.ToString() ?? ""));
return null;
}
catch (PermissionSetFileReadException e)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PermissionSetAttributeFileReadError, Location.None, e.FileName, e.PropertyName, e.Message));
return null;
}
}
}
internal string? Feature(string p)
{
string? v;
return _features.TryGetValue(p, out v) ? v : null;
}
#endregion
private ConcurrentDictionary<SyntaxTree, SmallConcurrentSetOfInts>? _lazyTreeToUsedImportDirectivesMap;
private static readonly Func<SyntaxTree, SmallConcurrentSetOfInts> s_createSetCallback = t => new SmallConcurrentSetOfInts();
private ConcurrentDictionary<SyntaxTree, SmallConcurrentSetOfInts> TreeToUsedImportDirectivesMap
{
get
{
return RoslynLazyInitializer.EnsureInitialized(ref _lazyTreeToUsedImportDirectivesMap);
}
}
internal void MarkImportDirectiveAsUsed(SyntaxNode node)
{
MarkImportDirectiveAsUsed(node.SyntaxTree, node.Span.Start);
}
internal void MarkImportDirectiveAsUsed(SyntaxTree? syntaxTree, int position)
{
// Optimization: Don't initialize TreeToUsedImportDirectivesMap in submissions.
if (!IsSubmission && syntaxTree != null)
{
var set = TreeToUsedImportDirectivesMap.GetOrAdd(syntaxTree, s_createSetCallback);
set.Add(position);
}
}
internal bool IsImportDirectiveUsed(SyntaxTree syntaxTree, int position)
{
if (IsSubmission)
{
// Since usings apply to subsequent submissions, we have to assume they are used.
return true;
}
SmallConcurrentSetOfInts? usedImports;
return syntaxTree != null &&
TreeToUsedImportDirectivesMap.TryGetValue(syntaxTree, out usedImports) &&
usedImports.Contains(position);
}
/// <summary>
/// The compiler needs to define an ordering among different partial class in different syntax trees
/// in some cases, because emit order for fields in structures, for example, is semantically important.
/// This function defines an ordering among syntax trees in this compilation.
/// </summary>
internal int CompareSyntaxTreeOrdering(SyntaxTree tree1, SyntaxTree tree2)
{
if (tree1 == tree2)
{
return 0;
}
Debug.Assert(this.ContainsSyntaxTree(tree1));
Debug.Assert(this.ContainsSyntaxTree(tree2));
return this.GetSyntaxTreeOrdinal(tree1) - this.GetSyntaxTreeOrdinal(tree2);
}
internal abstract int GetSyntaxTreeOrdinal(SyntaxTree tree);
/// <summary>
/// Compare two source locations, using their containing trees, and then by Span.First within a tree.
/// Can be used to get a total ordering on declarations, for example.
/// </summary>
internal abstract int CompareSourceLocations(Location loc1, Location loc2);
/// <summary>
/// Compare two source locations, using their containing trees, and then by Span.First within a tree.
/// Can be used to get a total ordering on declarations, for example.
/// </summary>
internal abstract int CompareSourceLocations(SyntaxReference loc1, SyntaxReference loc2);
/// <summary>
/// Return the lexically first of two locations.
/// </summary>
internal TLocation FirstSourceLocation<TLocation>(TLocation first, TLocation second)
where TLocation : Location
{
if (CompareSourceLocations(first, second) <= 0)
{
return first;
}
else
{
return second;
}
}
/// <summary>
/// Return the lexically first of multiple locations.
/// </summary>
internal TLocation? FirstSourceLocation<TLocation>(ImmutableArray<TLocation> locations)
where TLocation : Location
{
if (locations.IsEmpty)
{
return null;
}
var result = locations[0];
for (int i = 1; i < locations.Length; i++)
{
result = FirstSourceLocation(result, locations[i]);
}
return result;
}
#region Logging Helpers
// Following helpers are used when logging ETW events. These helpers are invoked only if we are running
// under an ETW listener that has requested 'verbose' logging. In other words, these helpers will never
// be invoked in the 'normal' case (i.e. when the code is running on user's machine and no ETW listener
// is involved).
// Note: Most of the below helpers are unused at the moment - but we would like to keep them around in
// case we decide we need more verbose logging in certain cases for debugging.
internal string GetMessage(CompilationStage stage)
{
return string.Format("{0} ({1})", this.AssemblyName, stage.ToString());
}
internal string GetMessage(ITypeSymbol source, ITypeSymbol destination)
{
if (source == null || destination == null) return this.AssemblyName ?? "";
return string.Format("{0}: {1} {2} -> {3} {4}", this.AssemblyName, source.TypeKind.ToString(), source.Name, destination.TypeKind.ToString(), destination.Name);
}
#endregion
#region Declaration Name Queries
/// <summary>
/// Return true if there is a source declaration symbol name that meets given predicate.
/// </summary>
public abstract bool ContainsSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return source declaration symbols whose name meets given predicate.
/// </summary>
public abstract IEnumerable<ISymbol> GetSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken));
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
/// <summary>
/// Return true if there is a source declaration symbol name that matches the provided name.
/// This may be faster than <see cref="ContainsSymbolsWithName(Func{string, bool},
/// SymbolFilter, CancellationToken)"/> when predicate is just a simple string check.
/// <paramref name="name"/> is case sensitive or not depending on the target language.
/// </summary>
public abstract bool ContainsSymbolsWithName(string name, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return source declaration symbols whose name matches the provided name. This may be
/// faster than <see cref="GetSymbolsWithName(Func{string, bool}, SymbolFilter,
/// CancellationToken)"/> when predicate is just a simple string check. <paramref
/// name="name"/> is case sensitive or not depending on the target language.
/// </summary>
public abstract IEnumerable<ISymbol> GetSymbolsWithName(string name, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken));
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
#endregion
internal void MakeMemberMissing(WellKnownMember member)
{
MakeMemberMissing((int)member);
}
internal void MakeMemberMissing(SpecialMember member)
{
MakeMemberMissing(-(int)member - 1);
}
internal bool IsMemberMissing(WellKnownMember member)
{
return IsMemberMissing((int)member);
}
internal bool IsMemberMissing(SpecialMember member)
{
return IsMemberMissing(-(int)member - 1);
}
private void MakeMemberMissing(int member)
{
if (_lazyMakeMemberMissingMap == null)
{
_lazyMakeMemberMissingMap = new SmallDictionary<int, bool>();
}
_lazyMakeMemberMissingMap[member] = true;
}
private bool IsMemberMissing(int member)
{
return _lazyMakeMemberMissingMap != null && _lazyMakeMemberMissingMap.ContainsKey(member);
}
internal void MakeTypeMissing(SpecialType type)
{
MakeTypeMissing((int)type);
}
internal void MakeTypeMissing(WellKnownType type)
{
MakeTypeMissing((int)type);
}
private void MakeTypeMissing(int type)
{
if (_lazyMakeWellKnownTypeMissingMap == null)
{
_lazyMakeWellKnownTypeMissingMap = new SmallDictionary<int, bool>();
}
_lazyMakeWellKnownTypeMissingMap[(int)type] = true;
}
internal bool IsTypeMissing(SpecialType type)
{
return IsTypeMissing((int)type);
}
internal bool IsTypeMissing(WellKnownType type)
{
return IsTypeMissing((int)type);
}
private bool IsTypeMissing(int type)
{
return _lazyMakeWellKnownTypeMissingMap != null && _lazyMakeWellKnownTypeMissingMap.ContainsKey((int)type);
}
/// <summary>
/// Given a <see cref="Diagnostic"/> reporting unreferenced <see cref="AssemblyIdentity"/>s, returns
/// the actual <see cref="AssemblyIdentity"/> instances that were not referenced.
/// </summary>
public ImmutableArray<AssemblyIdentity> GetUnreferencedAssemblyIdentities(Diagnostic diagnostic)
{
if (diagnostic == null)
{
throw new ArgumentNullException(nameof(diagnostic));
}
if (!IsUnreferencedAssemblyIdentityDiagnosticCode(diagnostic.Code))
{
return ImmutableArray<AssemblyIdentity>.Empty;
}
var builder = ArrayBuilder<AssemblyIdentity>.GetInstance();
foreach (var argument in diagnostic.Arguments)
{
if (argument is AssemblyIdentity id)
{
builder.Add(id);
}
}
return builder.ToImmutableAndFree();
}
internal abstract bool IsUnreferencedAssemblyIdentityDiagnosticCode(int code);
/// <summary>
/// Returns the required language version found in a <see cref="Diagnostic"/>, if any is found.
/// Returns null if none is found.
/// </summary>
public static string? GetRequiredLanguageVersion(Diagnostic diagnostic)
{
if (diagnostic == null)
{
throw new ArgumentNullException(nameof(diagnostic));
}
bool found = false;
string? foundVersion = null;
if (diagnostic.Arguments != null)
{
foreach (var argument in diagnostic.Arguments)
{
if (argument is RequiredLanguageVersion versionDiagnostic)
{
Debug.Assert(!found); // only one required language version in a given diagnostic
found = true;
foundVersion = versionDiagnostic.ToString();
}
}
}
return foundVersion;
}
}
}
| ErikSchierboom/roslyn | src/Compilers/Core/Portable/Compilation/Compilation.cs | C# | apache-2.0 | 144,929 |
/**
*
* Copyright 2015 Florian Schmaus
*
* 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.
*/
/**
* Providers for XEP-0033: Extended Stanza Addressing.
*/
package org.jivesoftware.smackx.address.provider;
| igniterealtime/Smack | smack-extensions/src/main/java/org/jivesoftware/smackx/address/provider/package-info.java | Java | apache-2.0 | 717 |
'use strict';
var assert = require('assert');
var fixtures = require('../fixtures');
var sharp = require('../../index');
var defaultConcurrency = sharp.concurrency();
describe('Utilities', function() {
describe('Cache', function() {
it('Can be disabled', function() {
var cache = sharp.cache(0, 0);
assert.strictEqual(0, cache.memory);
assert.strictEqual(0, cache.items);
});
it('Can be set to a maximum of 50MB and 500 items', function() {
var cache = sharp.cache(50, 500);
assert.strictEqual(50, cache.memory);
assert.strictEqual(500, cache.items);
});
it('Ignores invalid values', function() {
sharp.cache(50, 500);
var cache = sharp.cache('spoons');
assert.strictEqual(50, cache.memory);
assert.strictEqual(500, cache.items);
});
});
describe('Concurrency', function() {
it('Can be set to use 16 threads', function() {
sharp.concurrency(16);
assert.strictEqual(16, sharp.concurrency());
});
it('Can be reset to default', function() {
sharp.concurrency(0);
assert.strictEqual(defaultConcurrency, sharp.concurrency());
});
it('Ignores invalid values', function() {
sharp.concurrency(0);
sharp.concurrency('spoons');
assert.strictEqual(defaultConcurrency, sharp.concurrency());
});
});
describe('Counters', function() {
it('Have zero value at rest', function() {
var counters = sharp.counters();
assert.strictEqual(0, counters.queue);
assert.strictEqual(0, counters.process);
});
});
describe('Format', function() {
it('Contains expected attributes', function() {
assert.strictEqual('object', typeof sharp.format);
Object.keys(sharp.format).forEach(function(format) {
assert.strictEqual(true, 'id' in sharp.format[format]);
assert.strictEqual(format, sharp.format[format].id);
['input', 'output'].forEach(function(direction) {
assert.strictEqual(true, direction in sharp.format[format]);
assert.strictEqual('object', typeof sharp.format[format][direction]);
assert.strictEqual(3, Object.keys(sharp.format[format][direction]).length);
assert.strictEqual(true, 'file' in sharp.format[format][direction]);
assert.strictEqual(true, 'buffer' in sharp.format[format][direction]);
assert.strictEqual(true, 'stream' in sharp.format[format][direction]);
assert.strictEqual('boolean', typeof sharp.format[format][direction].file);
assert.strictEqual('boolean', typeof sharp.format[format][direction].buffer);
assert.strictEqual('boolean', typeof sharp.format[format][direction].stream);
});
});
});
});
});
| mcanthony/sharp | test/unit/util.js | JavaScript | apache-2.0 | 2,746 |
package org.edx.mobile.view.custom;
import org.edx.mobile.R;
import org.edx.mobile.logger.Logger;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class ETextView extends TextView {
private final Logger logger = new Logger(getClass().getName());
public ETextView(Context context) {
super(context);
}
public ETextView(Context context, AttributeSet attrs) {
super(context, attrs);
processAttrs(context, attrs);
}
public ETextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
processAttrs(context, attrs);
}
private void processAttrs(Context context, AttributeSet attrs) {
if(isInEditMode())
return;
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.custom_view, 0, 0);
try {
// check for the font attribute and setup font
String fontFileName = a.getString(R.styleable.custom_view_font);
if(fontFileName==null){
//If font is not set for ETextView, set default font
fontFileName = "OpenSans-Regular.ttf";
}
Typeface font = FontFactory.getInstance().getFont(context,fontFileName);
setTypeface(font);
} catch (Exception ex) {
logger.error(ex);
} finally {
// a.recycle();
}
}
}
| miptliot/edx-app-android | VideoLocker/src/main/java/org/edx/mobile/view/custom/ETextView.java | Java | apache-2.0 | 1,539 |
/**
* Copyright 2015 Netflix, 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.netflix.spectator.api;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicLong;
/** Counter implementation for the default registry. */
final class DefaultCounter implements Counter {
private final Clock clock;
private final Id id;
private final AtomicLong count;
/** Create a new instance. */
DefaultCounter(Clock clock, Id id) {
this.clock = clock;
this.id = id;
this.count = new AtomicLong(0L);
}
@Override public Id id() {
return id;
}
@Override public boolean hasExpired() {
return false;
}
@Override public Iterable<Measurement> measure() {
long now = clock.wallTime();
long v = count.get();
return Collections.singleton(new Measurement(id, now, v));
}
@Override public void increment() {
count.incrementAndGet();
}
@Override public void increment(long amount) {
count.addAndGet(amount);
}
@Override public long count() {
return count.get();
}
}
| pstout/spectator | spectator-api/src/main/java/com/netflix/spectator/api/DefaultCounter.java | Java | apache-2.0 | 1,572 |
/*
* Copyright (C) 2008 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.uzaygezen.core;
import java.math.BigInteger;
import java.util.BitSet;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import com.google.common.base.Preconditions;
/**
* BitVector implementation for vectors of length 64 or less.
*
* @author Mehmet Akin
* @author Daniel Aioanei
*/
public final class LongBitVector implements BitVector, Cloneable {
private static final long WORD_MASK = -1L;
private static final int BITS_PER_WORD = 64;
private final int size;
// used to clear excess bits after operations.
// Equal to WORD_MASK >>> BITS_PER_WORD - size
private final long mask;
private long data;
public LongBitVector(int size) {
this(size, 0);
Preconditions.checkArgument(size >= 0 && size <= BITS_PER_WORD,
"Size must be positive and <= {1} size: {2}", BITS_PER_WORD, size);
}
/**
* Unsafe constructor. Keep it private.
*/
private LongBitVector(int size, long data) {
assert 64 - Long.numberOfLeadingZeros(data) <= size;
this.size = size;
this.data = data;
mask = size == 0 ? 0 : WORD_MASK >>> BITS_PER_WORD - size;
}
private void checkSize(BitVector other) {
if (size != other.size()) {
throw new IllegalArgumentException(
"Sizes must be equal. " + this.size + " : " + other.size());
}
}
private void checkIndex(int bitIndex) {
if (bitIndex < 0 | bitIndex >= size) {
throw new IndexOutOfBoundsException("Bit index out of range: " + bitIndex);
}
}
private void checkBounds(int fromIndex, int toIndex) {
if (fromIndex < 0 | toIndex > size | fromIndex > toIndex) {
throw new IndexOutOfBoundsException(
"Range [" + fromIndex + ", " + toIndex + ") is invalid for this bit vector");
}
}
@Override
public void and(BitVector o) {
checkSize(o);
data &= o.toExactLong();
}
@Override
public void andNot(BitVector o) {
checkSize(o);
data &= ~o.toExactLong();
}
@Override
public int cardinality() {
return Long.bitCount(data);
}
@Override
public void clear() {
data = 0;
}
@Override
public void clear(int bitIndex) {
checkIndex(bitIndex);
data &= ~(1L << bitIndex);
}
@Override
public void clear(int fromIndex, int toIndex) {
checkBounds(fromIndex, toIndex);
if (fromIndex != toIndex) {
unsafeClearNonEmptySection(fromIndex, toIndex);
}
}
private void unsafeClearNonEmptySection(int fromIndex, int toIndex) {
data &= ~((WORD_MASK << fromIndex) & (WORD_MASK >>> -toIndex));
}
@Override
public void copyFrom(BitVector from) {
checkSize(from);
data = from.toExactLong();
}
@Override
public void flip(int bitIndex) {
checkIndex(bitIndex);
data ^= (1L << bitIndex);
}
@Override
public void flip(int fromIndex, int toIndex) {
checkBounds(fromIndex, toIndex);
if (fromIndex != toIndex) {
data ^= ((WORD_MASK << fromIndex) & (WORD_MASK >>> -toIndex));
}
}
@Override
public boolean get(int bitIndex) {
checkIndex(bitIndex);
return unsafeGet(bitIndex);
}
private boolean unsafeGet(int bitIndex) {
return (data & (1L << bitIndex)) != 0;
}
@Override
public void grayCode() {
data ^= (data >>> 1);
}
@Override
public void grayCodeInverse() {
long localData = data;
localData ^= localData >>> 1;
localData ^= localData >>> 2;
localData ^= localData >>> 4;
localData ^= localData >>> 8;
localData ^= localData >>> 16;
localData ^= localData >>> 32;
data = localData;
}
@Override
public boolean increment() {
// Check for overflow
if (data == mask) {
return false;
}
data++;
return true;
}
@Override
public boolean intersects(BitVector o) {
checkSize(o);
return (data & o.toExactLong()) != 0;
}
@Override
public int length() {
return BITS_PER_WORD - Long.numberOfLeadingZeros(data);
}
@Override
public int size() {
return size;
}
@Override
public int nextClearBit(int fromIndex) {
Preconditions.checkArgument(fromIndex >= 0);
if (fromIndex >= size) {
return -1;
}
long w = ~data & (WORD_MASK << fromIndex);
int tcb = Long.numberOfTrailingZeros(w);
return tcb == size ? -1 : tcb;
}
@Override
public int nextSetBit(int fromIndex) {
Preconditions.checkArgument(fromIndex >= 0);
if (fromIndex >= size) {
return -1;
}
long w = data & (WORD_MASK << fromIndex);
int tcb = Long.numberOfTrailingZeros(w);
return tcb == 64 ? -1 : tcb;
}
@Override
public void or(BitVector o) {
checkSize(o);
this.data |= o.toExactLong();
}
@Override
public void rotate(int count) {
final int localSize = size;
count %= localSize;
final long localData = data;
if (count > 0) {
data = ((localData >>> count) | (localData << localSize - count)) & mask;
} else {
data = ((localData >>> localSize + count) | (localData << -count)) & mask;
}
}
@Override
public void set(int bitIndex) {
checkIndex(bitIndex);
data |= (1L << bitIndex);
}
public void set(int bitIndex, boolean value) {
if (value) {
set(bitIndex);
} else {
clear(bitIndex);
}
}
@Override
public void set(int fromIndex, int toIndex) {
checkBounds(fromIndex, toIndex);
if (fromIndex != toIndex) {
data |= ((WORD_MASK << fromIndex) & (WORD_MASK >>> -toIndex));
}
}
@Override
public void set(int fromIndex, int toIndex, boolean value) {
if (value) {
set(fromIndex, toIndex);
} else {
clear(fromIndex, toIndex);
}
}
@Override
public void xor(BitVector o) {
checkSize(o);
this.data ^= o.toExactLong();
}
@Override
public boolean isEmpty() {
return data == 0;
}
@Override
public LongBitVector clone() {
try {
return (LongBitVector) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError("Cloning error. ");
}
}
@Override
public boolean equals(Object obj) {
if (obj instanceof BitVector) {
BitVector other = (BitVector) obj;
// optimisation
if (size <= 64) {
return size == other.size() && data == other.toExactLong();
} else {
return size == other.size() && toBitSet().equals(other.toBitSet());
}
} else {
return false;
}
}
@Override
public int hashCode() {
// We imitate BitSet's hashcode implementation
long h = 1234 ^ data;
int bitSetHashCode = (int) ((h >> 32) ^ h);
return size + 31 * bitSetHashCode;
}
@Override
public String toString() {
return StringUtils.leftPad(Long.toBinaryString(data), size, '0');
}
@Override
public BitSet toBitSet() {
BitSet b = new BitSet(size);
for (int i = 0; i < size; i++) {
if (unsafeGet(i)) {
b.set(i);
}
}
return b;
}
@Override
public long toLong() {
return data;
}
@Override
public BigInteger toBigInteger() {
final BigInteger result;
if (data >= 0) {
result = BigInteger.valueOf(data);
} else {
BigInteger missingLowestBit = BigInteger.valueOf(data >>> 1).shiftLeft(1);
if ((data & 1) == 1) {
result = missingLowestBit.setBit(0);
} else {
result = missingLowestBit;
}
}
return result;
}
public void copyFrom(long value) {
Preconditions.checkArgument(64 - Long.numberOfLeadingZeros(value) <= size, "value doesn't fit");
data = value;
}
@Override
public int compareTo(BitVector o) {
checkSize(o);
final int cmp;
// optimisation
if (o.size() <= 64) {
// 0, positives, Long.MAX_VALUE, Long.MIN_VALUE, negatives, -1
long x = data + Long.MIN_VALUE;
long y = o.toExactLong() + Long.MIN_VALUE;
cmp = Long.compare(x, y);
assert Integer.signum(cmp) == Integer.signum(
BitSetComparator.INSTANCE.compare(toBitSet(), o.toBitSet()));
} else {
cmp = BitSetComparator.INSTANCE.compare(toBitSet(), o.toBitSet());
}
return cmp;
}
@Override
public void copyFrom(BitSet from) {
int localSize = size;
long value = 0;
for (int i = from.nextSetBit(0); i != -1; i = from.nextSetBit(i + 1)) {
Preconditions.checkArgument(i < localSize, "bit set too large");
value |= 1L << i;
}
data = value;
}
@Override
public void copyFromSection(BitVector src, int fromIndex) {
Preconditions.checkArgument(fromIndex >= 0, "fromIndex must be non-negative");
int srcSize = src.size();
int toIndex = fromIndex + size;
Preconditions.checkArgument(toIndex <= srcSize, "not enough bits in src");
long value;
if (toIndex <= 64) {
long srcData = src.toLong();
value = (srcData >>> fromIndex) & mask;
} else {
value = 0;
for (int i = src.nextSetBit(fromIndex); i < toIndex && i != -1; i = src.nextSetBit(i + 1)) {
value |= 1L << (i - fromIndex);
}
}
data = value;
}
@Override
public long toExactLong() {
return data;
}
@Override
public void smallerEvenAndGrayCode() {
long localData = data;
if ((localData & 0x1) == 1) {
assert size > 0;
data = localData ^ (localData >>> 1) ^ 0x1;
} else {
if (localData != 0) {
long dataMinusTwo = localData - 2;
data = dataMinusTwo ^ (dataMinusTwo >>> 1);
}
}
}
@Override
public void grayCodeRank(BitVector mu, BitVector w) {
grayCodeRank(mu, w, true);
}
/**
* Visible for testing.
*/
void grayCodeRank(BitVector mu, BitVector w, boolean optimiseIfPossible) {
int theirSize = mu.size();
Preconditions.checkArgument(theirSize == w.size(), "mu/w size mismatch");
int muLen = mu.length();
long pow2pos = 1L;
long value = 0;
if (optimiseIfPossible & muLen <= 64) {
// mu doesn't have any set bits over index 63
long muLong = mu.toExactLong();
// w might have some set bits over index 63, but they don't matter anyway
long wLong = w.toLong();
long pow2i = 1L;
for (int i = 0; i < muLen; ++i) {
if ((muLong & pow2i) != 0) {
if ((wLong & pow2i) != 0) {
value |= pow2pos;
}
pow2pos <<= 1;
}
pow2i <<= 1;
}
} else {
for (int j = theirSize == 0 ? -1 : mu.nextSetBit(0); j != -1;
j = j == theirSize - 1 ? -1 : mu.nextSetBit(j + 1)) {
if (w.get(j)) {
value |= pow2pos;
}
pow2pos <<= 1;
}
}
assert pow2pos == 1L << mu.cardinality();
Preconditions.checkArgument(1L << size == pow2pos, "wrong size");
data = value;
}
@Override
public int lowestDifferentBit() {
long localData = data;
final int value;
if ((localData & 0x1L) == 0) {
if (localData == 0) {
value = 0;
} else {
value = Long.numberOfTrailingZeros(localData);
}
} else {
if (localData == mask) {
value = 0;
} else {
value = Long.numberOfTrailingZeros(~localData);
}
}
assert value == 0 || (0 < value & value < size);
return value;
}
@Override
public void grayCodeRankInverse(BitVector mu, BitVector known, BitVector r) {
int muSize = mu.size();
Preconditions.checkArgument(size == muSize, "i/mu size mismatch");
// Will fail if the sizes are different.
Preconditions.checkArgument(!known.intersects(mu), "known and mu must not intersect");
long muLong = mu.toExactLong();
long knownLong = known.toExactLong();
// Will check r.size() against mu.cardinality later.
int rSize = r.size();
Preconditions.checkArgument(rSize <= muSize, "r is too large");
long rLong = r.toExactLong();
long value = 0;
int pos = 0;
int muLength = mu.length();
long pow2k = 1L;
for (int k = 0; k < muLength; ++k) {
if ((muLong & pow2k) != 0) {
if ((rLong >> pos & 1L) != 0) {
value |= pow2k;
}
++pos;
}
pow2k <<= 1;
}
assert pos == mu.cardinality();
Preconditions.checkArgument(pos == rSize, "r.size()/mu.cardinality() mismatch");
int knownLength = known.length();
for (int k = Math.max(muLength - 1, knownLength); --k >= 0; ) {
pow2k = 1L << k;
if ((muLong & pow2k) == 0) {
assert (value & pow2k) == 0;
if (((knownLong & pow2k) ^ (value >> 1 & pow2k)) != 0) {
value |= pow2k;
}
}
}
data = value;
}
@Override
public void copySectionFrom(int offset, BitVector src) {
int srcSize = src.size();
int toIndex = offset + srcSize;
if (offset < 0 | toIndex > size) {
throw new IndexOutOfBoundsException(
"invalid range: offset=" + offset + " src.size()=" + src.size());
}
if (offset != toIndex) {
unsafeClearNonEmptySection(offset, toIndex);
long srcData = src.toExactLong();
data |= srcData << offset;
}
}
@Override
public long[] toLongArray() {
return size == 0 ? ArrayUtils.EMPTY_LONG_ARRAY : new long[] {data};
}
@Override
public byte[] toBigEndianByteArray() {
int n = MathUtils.bitCountToByteCount(size);
byte[] a = new byte[n];
long x = data;
for (int i = 0; i < n; ) {
a[n - ++i] = (byte) (x & 0xFF);
x >>>= 8;
}
assert x == 0;
return a;
}
@Override
public void copyFrom(long[] array) {
if (size == 0) {
Preconditions.checkArgument(array.length == 0, "Array must be empty.");
} else {
Preconditions.checkArgument(array.length == 1, "Array length must be 1.");
copyFrom(array[0]);
}
}
@Override
public void copyFromBigEndian(byte[] array) {
int n = MathUtils.bitCountToByteCount(size);
Preconditions.checkArgument(array.length == n, "Array length must be %s.", n);
long x = 0;
for (int i = 0; i < n - 1; ) {
x |= (array[i++] & 0xFF);
x <<= 8;
}
if (n != 0) {
x |= (array[n - 1] & 0xFF);
}
copyFrom(x);
}
@Override
public boolean areAllLowestBitsClear(int bitCount) {
Preconditions.checkArgument(0 <= bitCount & bitCount <= size, "bitCount is out of range");
// Only bitCount == 64 is affected by xoring with (bitCount >> 6).
return (data & (((1L << bitCount) ^ (bitCount >> 6)) - 1)) == 0;
}
@Override
public void copyFrom(BigInteger s) {
Preconditions.checkArgument(s.signum() >= 0, s);
Preconditions.checkArgument(s.bitLength() <= size());
// Note that the long value will be negative iff bitLength == 644 and bit 63
// is set.
copyFrom(s.longValue());
}
}
| GrammarViz2/Uzaygezen | uzaygezen-core/src/main/java/com/google/uzaygezen/core/LongBitVector.java | Java | apache-2.0 | 15,293 |
/*
Copyright 2016 Goldman Sachs.
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.gs.fw.common.mithra.util.fileparser;
import java.io.IOException;
import java.io.StreamTokenizer;
import java.text.ParseException;
public class ClassReaderState extends ParserState
{
public ClassReaderState(AbstractMithraDataFileParser parser)
{
super(parser);
}
public ParserState parse(StreamTokenizer st) throws IOException, ParseException
{
int token = st.ttype;
if (token != StreamTokenizer.TT_WORD || !st.sval.equals(AbstractMithraDataFileParser.CLASS_IDENTIFIER))
{
throw new ParseException("expected line " + st.lineno() + " to begin with class", st.lineno());
}
token = st.nextToken();
if (token != StreamTokenizer.TT_WORD)
{
throw new ParseException("expected a class name on line "+st.lineno(), st.lineno());
}
this.getParser().addNewMithraParsedData();
String className = st.sval;
try
{
this.getParser().getCurrentParsedData().setParsedClassName(className);
}
catch (Exception e)
{
ParseException parseException = new ParseException("no such class (or finder): "+className+" on line "+st.lineno(), st.lineno());
parseException.initCause(e);
throw parseException;
}
this.getParser().getDataReaderState().setClass(className, st.lineno());
token = st.nextToken();
if (token != StreamTokenizer.TT_EOL)
{
throw new ParseException("invalid data after the class name on line "+st.lineno(), st.lineno());
}
return this.getParser().getAttributeReaderState();
}
}
| goldmansachs/reladomo | reladomo/src/main/java/com/gs/fw/common/mithra/util/fileparser/ClassReaderState.java | Java | apache-2.0 | 2,312 |
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* 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 org.pentaho.di.trans;
import java.util.concurrent.TimeUnit;
import junit.framework.TestCase;
import org.pentaho.di.core.RowSet;
import org.pentaho.di.core.row.RowMetaInterface;
/**
* Tests for RowProducer
*
*/
public class RowProducerIT extends TestCase {
/**
* Verify that putting a row into a RowProducer does not block if the underlying rowSet is not full.
*/
public void testPutRow_not_full() {
final int attempts = 1;
MockBlockingRowSet rs = new MockBlockingRowSet( attempts );
RowProducer rp = new RowProducer( null, rs );
rp.putRow( null, null );
assertEquals( "Total attempts to putRow() exceeded expected amount", attempts, rs.getTotalAttempts() );
}
/**
* Verify that putting a row into a RowProducer blocks until the row is successfully added instead of returning
* immediately.
*/
public void testPutRow_full() {
final int attempts = 10;
MockBlockingRowSet rs = new MockBlockingRowSet( attempts );
RowProducer rp = new RowProducer( null, rs );
rp.putRow( null, null );
assertEquals( "Total attempts to putRow() exceeded expected amount", attempts, rs.getTotalAttempts() );
}
class MockBlockingRowSet implements RowSet {
// The number of calls to putRowWait() that it requires to actually put a row.
private final int reqdAttempts;
// Number of times putRowWait() has been called.
private int totalAttempts;
/**
* Create a blocking row set that requires {@code attempts} calls to
* {@link #putRowWait(RowMetaInterface, Object[], long, TimeUnit)} before actually adding the row.
*
* @param attempts
* Number of calls required to actually put a row.
*/
public MockBlockingRowSet( int attempts ) {
this.reqdAttempts = attempts;
totalAttempts = 0;
}
public int getTotalAttempts() {
return totalAttempts;
}
public boolean putRow( RowMetaInterface rowMeta, Object[] rowData ) {
throw new UnsupportedOperationException();
}
public boolean putRowWait( RowMetaInterface rowMeta, Object[] rowData, long time, TimeUnit tu ) {
totalAttempts++;
if ( totalAttempts % reqdAttempts == 0 ) {
return true;
}
try {
Thread.sleep( 10 ); // Simulate overhead of blocking
} catch ( Exception ex ) {
throw new RuntimeException( ex );
}
return false;
}
public Object[] getRow() {
throw new UnsupportedOperationException();
}
public Object[] getRowImmediate() {
throw new UnsupportedOperationException();
}
public Object[] getRowWait( long timeout, TimeUnit tu ) {
throw new UnsupportedOperationException();
}
public void setDone() {
throw new UnsupportedOperationException();
}
public boolean isDone() {
throw new UnsupportedOperationException();
}
public String getOriginStepName() {
throw new UnsupportedOperationException();
}
public int getOriginStepCopy() {
throw new UnsupportedOperationException();
}
public String getDestinationStepName() {
throw new UnsupportedOperationException();
}
public int getDestinationStepCopy() {
throw new UnsupportedOperationException();
}
public String getName() {
throw new UnsupportedOperationException();
}
public int size() {
throw new UnsupportedOperationException();
}
public void setThreadNameFromToCopy( String from, int from_copy, String to, int to_copy ) {
throw new UnsupportedOperationException();
}
public RowMetaInterface getRowMeta() {
throw new UnsupportedOperationException();
}
public void setRowMeta( RowMetaInterface rowMeta ) {
throw new UnsupportedOperationException();
}
public String getRemoteSlaveServerName() {
throw new UnsupportedOperationException();
}
public void setRemoteSlaveServerName( String remoteSlaveServerName ) {
throw new UnsupportedOperationException();
}
public boolean isBlocking() {
return true;
}
public void clear() {
throw new UnsupportedOperationException();
}
}
}
| TatsianaKasiankova/pentaho-kettle | integration/src/it/java/org/pentaho/di/trans/RowProducerIT.java | Java | apache-2.0 | 5,094 |
//// [inferTypes1.ts]
type Unpacked<T> =
T extends (infer U)[] ? U :
T extends (...args: any[]) => infer U ? U :
T extends Promise<infer U> ? U :
T;
type T00 = Unpacked<string>; // string
type T01 = Unpacked<string[]>; // string
type T02 = Unpacked<() => string>; // string
type T03 = Unpacked<Promise<string>>; // string
type T04 = Unpacked<Unpacked<Promise<string>[]>>; // string
type T05 = Unpacked<any>; // any
type T06 = Unpacked<never>; // never
function f1(s: string) {
return { a: 1, b: s };
}
class C {
x = 0;
y = 0;
}
type T10 = ReturnType<() => string>; // string
type T11 = ReturnType<(s: string) => void>; // void
type T12 = ReturnType<(<T>() => T)>; // {}
type T13 = ReturnType<(<T extends U, U extends number[]>() => T)>; // number[]
type T14 = ReturnType<typeof f1>; // { a: number, b: string }
type T15 = ReturnType<any>; // any
type T16 = ReturnType<never>; // never
type T17 = ReturnType<string>; // Error
type T18 = ReturnType<Function>; // Error
type U10 = InstanceType<typeof C>; // C
type U11 = InstanceType<any>; // any
type U12 = InstanceType<never>; // never
type U13 = InstanceType<string>; // Error
type U14 = InstanceType<Function>; // Error
type ArgumentType<T extends (x: any) => any> = T extends (a: infer A) => any ? A : any;
type T20 = ArgumentType<() => void>; // {}
type T21 = ArgumentType<(x: string) => number>; // string
type T22 = ArgumentType<(x?: string) => number>; // string | undefined
type T23 = ArgumentType<(...args: string[]) => number>; // string
type T24 = ArgumentType<(x: string, y: string) => number>; // Error
type T25 = ArgumentType<Function>; // Error
type T26 = ArgumentType<any>; // any
type T27 = ArgumentType<never>; // never
type X1<T extends { x: any, y: any }> = T extends { x: infer X, y: infer Y } ? [X, Y] : any;
type T30 = X1<{ x: any, y: any }>; // [any, any]
type T31 = X1<{ x: number, y: string }>; // [number, string]
type T32 = X1<{ x: number, y: string, z: boolean }>; // [number, string]
type X2<T> = T extends { a: infer U, b: infer U } ? U : never;
type T40 = X2<{}>; // never
type T41 = X2<{ a: string }>; // never
type T42 = X2<{ a: string, b: string }>; // string
type T43 = X2<{ a: number, b: string }>; // string | number
type T44 = X2<{ a: number, b: string, c: boolean }>; // string | number
type X3<T> = T extends { a: (x: infer U) => void, b: (x: infer U) => void } ? U : never;
type T50 = X3<{}>; // never
type T51 = X3<{ a: (x: string) => void }>; // never
type T52 = X3<{ a: (x: string) => void, b: (x: string) => void }>; // string
type T53 = X3<{ a: (x: number) => void, b: (x: string) => void }>; // string & number
type T54 = X3<{ a: (x: number) => void, b: () => void }>; // number
type T60 = infer U; // Error
type T61<T> = infer A extends infer B ? infer C : infer D; // Error
type T62<T> = U extends (infer U)[] ? U : U; // Error
type T63<T> = T extends (infer A extends infer B ? infer C : infer D) ? string : number;
type T70<T extends string> = { x: T };
type T71<T> = T extends T70<infer U> ? T70<U> : never;
type T72<T extends number> = { y: T };
type T73<T> = T extends T72<infer U> ? T70<U> : never; // Error
type T74<T extends number, U extends string> = { x: T, y: U };
type T75<T> = T extends T74<infer U, infer U> ? T70<U> | T72<U> | T74<U, U> : never;
type T76<T extends T[], U extends T> = { x: T };
type T77<T> = T extends T76<infer X, infer Y> ? T76<X, Y> : never;
type T78<T> = T extends T76<infer X, infer X> ? T76<X, X> : never;
type Foo<T extends string, U extends T> = [T, U];
type Bar<T> = T extends Foo<infer X, infer Y> ? Foo<X, Y> : never;
type T90 = Bar<[string, string]>; // [string, string]
type T91 = Bar<[string, "a"]>; // [string, "a"]
type T92 = Bar<[string, "a"] & { x: string }>; // [string, "a"]
type T93 = Bar<["a", string]>; // never
type T94 = Bar<[number, number]>; // never
// Example from #21496
type JsonifiedObject<T extends object> = { [K in keyof T]: Jsonified<T[K]> };
type Jsonified<T> =
T extends string | number | boolean | null ? T
: T extends undefined | Function ? never // undefined and functions are removed
: T extends { toJSON(): infer R } ? R // toJSON is called if it exists (e.g. Date)
: T extends object ? JsonifiedObject<T>
: "what is this";
type Example = {
str: "literalstring",
fn: () => void,
date: Date,
customClass: MyClass,
obj: {
prop: "property",
clz: MyClass,
nested: { attr: Date }
},
}
declare class MyClass {
toJSON(): "correct";
}
type JsonifiedExample = Jsonified<Example>;
declare let ex: JsonifiedExample;
const z1: "correct" = ex.customClass;
const z2: string = ex.obj.nested.attr;
// Repros from #21631
type A1<T, U extends A1<any, any>> = [T, U];
type B1<S> = S extends A1<infer T, infer U> ? [T, U] : never;
type A2<T, U extends void> = [T, U];
type B2<S> = S extends A2<infer T, infer U> ? [T, U] : never;
type C2<S, U extends void> = S extends A2<infer T, U> ? [T, U] : never;
// Repro from #21735
type A<T> = T extends string ? { [P in T]: void; } : T;
type B<T> = string extends T ? { [P in T]: void; } : T; // Error
// Repro from #22302
type MatchingKeys<T, U, K extends keyof T = keyof T> =
K extends keyof T ? T[K] extends U ? K : never : never;
type VoidKeys<T> = MatchingKeys<T, void>;
interface test {
a: 1,
b: void
}
type T80 = MatchingKeys<test, void>;
type T81 = VoidKeys<test>;
// Repro from #22221
type MustBeString<T extends string> = T;
type EnsureIsString<T> = T extends MustBeString<infer U> ? U : never;
type Test1 = EnsureIsString<"hello">; // "hello"
type Test2 = EnsureIsString<42>; // never
//// [inferTypes1.js]
"use strict";
function f1(s) {
return { a: 1, b: s };
}
var C = /** @class */ (function () {
function C() {
this.x = 0;
this.y = 0;
}
return C;
}());
var z1 = ex.customClass;
var z2 = ex.obj.nested.attr;
| domchen/typescript-plus | tests/baselines/reference/inferTypes1.js | JavaScript | apache-2.0 | 5,975 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.structuralsearch.impl.matcher;
import com.intellij.structuralsearch.impl.matcher.strategies.XmlMatchingStrategy;
/**
* @author Eugene.Kudelevsky
*/
public class XmlCompiledPattern extends CompiledPattern {
private static final String XML_TYPED_VAR_PREFIX = "__";
public XmlCompiledPattern() {
setStrategy(XmlMatchingStrategy.getInstance());
}
@Override
public String[] getTypedVarPrefixes() {
return new String[] {XML_TYPED_VAR_PREFIX};
}
@Override
public boolean isTypedVar(final String str) {
return str.trim().startsWith(XML_TYPED_VAR_PREFIX);
}
}
| goodwinnk/intellij-community | platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/XmlCompiledPattern.java | Java | apache-2.0 | 748 |
/*
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.batik.ext.awt.image.rendered;
import java.awt.image.Raster;
/**
* This the generic interface for a source of tiles. This is used
* when the cache has a miss.
*
* @version $Id$
*/
public interface TileGenerator {
Raster genTile(int x, int y);
}
| Squeegee/batik | sources/org/apache/batik/ext/awt/image/rendered/TileGenerator.java | Java | apache-2.0 | 1,080 |
/*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.worker.block;
import alluxio.Configuration;
import alluxio.PropertyKey;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import javax.annotation.concurrent.ThreadSafe;
/**
* Read/write lock associated with clients rather than threads. Either its read lock or write lock
* can be released by a thread different from the one acquiring them (but supposed to be requested
* by the same client).
*/
@ThreadSafe
public final class ClientRWLock implements ReadWriteLock {
/** Total number of permits. This value decides the max number of concurrent readers. */
private static final int MAX_AVAILABLE =
Configuration.getInt(PropertyKey.WORKER_TIERED_STORE_BLOCK_LOCK_READERS);
/**
* Uses the unfair lock to prevent a read lock that fails to release from locking the block
* forever and thus blocking all the subsequent write access.
* See https://alluxio.atlassian.net/browse/ALLUXIO-2636.
*/
private final Semaphore mAvailable = new Semaphore(MAX_AVAILABLE, false);
/** Reference count. */
private AtomicInteger mReferences = new AtomicInteger();
/**
* Constructs a new {@link ClientRWLock}.
*/
public ClientRWLock() {}
@Override
public Lock readLock() {
return new SessionLock(1);
}
@Override
public Lock writeLock() {
return new SessionLock(MAX_AVAILABLE);
}
/**
* @return the reference count
*/
public int getReferenceCount() {
return mReferences.get();
}
/**
* Increments the reference count.
*/
public void addReference() {
mReferences.incrementAndGet();
}
/**
* Decrements the reference count.
*
* @return the new reference count
*/
public int dropReference() {
return mReferences.decrementAndGet();
}
private final class SessionLock implements Lock {
private final int mPermits;
private SessionLock(int permits) {
mPermits = permits;
}
@Override
public void lock() {
mAvailable.acquireUninterruptibly(mPermits);
}
@Override
public void lockInterruptibly() throws InterruptedException {
mAvailable.acquire(mPermits);
}
@Override
public boolean tryLock() {
return mAvailable.tryAcquire(mPermits);
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return mAvailable.tryAcquire(mPermits, time, unit);
}
@Override
public void unlock() {
mAvailable.release(mPermits);
}
@Override
public Condition newCondition() {
throw new UnsupportedOperationException("newCondition() is not supported");
}
}
}
| PasaLab/tachyon | core/server/worker/src/main/java/alluxio/worker/block/ClientRWLock.java | Java | apache-2.0 | 3,343 |
/* eslint-disable no-unused-vars */
// This helps ember-browserify find npm modules in ember-cli addons
import md5 from 'npm:js-md5';
import config from 'ember-get-config';
import _get from 'npm:lodash/get';
import Cookie from 'npm:js-cookie';
import keenTracking from 'npm:keen-tracking';
export {default} from 'ember-osf/mixins/keen-tracker';
| binoculars/ember-osf | app/mixins/keen-tracker.js | JavaScript | apache-2.0 | 347 |
/*
* 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.
*/
import java.rmi.RemoteException;
import java.security.Permission;
import java.util.Collections;
import net.jini.core.constraint.MethodConstraints;
import net.jini.security.BasicProxyPreparer;
import net.jini.security.Security;
/**
* A basic proxy preparer that uses this class's class loader when verifying
* trust in proxies.
*/
public class LocalClassLoaderVerifyProxyPreparer extends BasicProxyPreparer {
public LocalClassLoaderVerifyProxyPreparer(boolean verify,
Permission[] permissions)
{
super(verify, permissions);
}
public LocalClassLoaderVerifyProxyPreparer(
boolean verify,
MethodConstraints methodConstraints,
Permission[] permissions)
{
super(verify, methodConstraints, permissions);
}
protected void verify(Object proxy) throws RemoteException {
if (proxy == null) {
throw new NullPointerException("Proxy cannot be null");
} else if (verify) {
MethodConstraints mc = getMethodConstraints(proxy);
Security.verifyObjectTrust(
proxy, getClass().getClassLoader(),
mc == null ? Collections.EMPTY_SET : Collections.singleton(mc));
}
}
}
| pfirmstone/JGDMS | qa/jtreg/net/jini/security/ProxyPreparer/LocalClassLoaderVerifyProxyPreparer.java | Java | apache-2.0 | 1,930 |
#!/usr/bin/python
#
# Copyright 2017 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.
"""All sorts of properties for every field.
Generated by ./generate-onetime-js-widget-data.py
AMD-style module definition.
Note: No leading, internal path before the [], since we'd have to hardwire it
to data/whatever-fns.js which is inflexible.
"""
# TODO: Clean up the description fields that actually contain data
# extracted from the comments of dbroot_v2.proto.
# The META_INFO contains already vetted snippets.
META_INFO = r"""
{
"end_snippet.bbs_server_info.base_url:value": {
"abstract_fieldpath": "end_snippet.bbs_server_info.base_url:value",
"default_value": null,
"description": "URL of the server including protocol, domain and port. Can be translated if we use different servers for different languages.",
"empty_concrete_fieldpath": "end_snippet.bbs_server_info.base_url:value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "base_url:value",
"presence": "optional",
"short_label": "base_url",
"typ": "string"
},
"end_snippet.bbs_server_info.file_submit_path:value": {
"abstract_fieldpath": "end_snippet.bbs_server_info.file_submit_path:value",
"default_value": null,
"description": "Path on server where files can be submitted.",
"empty_concrete_fieldpath": "end_snippet.bbs_server_info.file_submit_path:value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "file_submit_path:value",
"presence": "optional",
"short_label": "file_submit_path",
"typ": "string"
},
"end_snippet.bbs_server_info.name:value": {
"abstract_fieldpath": "end_snippet.bbs_server_info.name:value",
"default_value": null,
"description": "Name that will be displayed in context menu to user. Must be translated.",
"empty_concrete_fieldpath": "end_snippet.bbs_server_info.name:value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "name:value",
"presence": "optional",
"short_label": "name",
"typ": "string"
},
"end_snippet.bbs_server_info.post_wizard_path:value": {
"abstract_fieldpath": "end_snippet.bbs_server_info.post_wizard_path:value",
"default_value": null,
"description": "Path on server where wizard can be found.",
"empty_concrete_fieldpath": "end_snippet.bbs_server_info.post_wizard_path:value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "post_wizard_path:value",
"presence": "optional",
"short_label": "post_wizard_path",
"typ": "string"
},
"end_snippet.client_options.disable_disk_cache": {
"abstract_fieldpath": "end_snippet.client_options.disable_disk_cache",
"default_value": null,
"description": "If true, no data will be cached on disk for this database. It will not be accessible offline.",
"empty_concrete_fieldpath": "end_snippet.client_options.disable_disk_cache",
"enum_vals": null,
"js_validation_rule": {
"required": false
},
"name": "disable_disk_cache",
"presence": "optional",
"short_label": "disable_disk_cache",
"typ": "bool"
},
"end_snippet.cobrand_info.logo_url": {
"abstract_fieldpath": "end_snippet.cobrand_info.logo_url",
"default_value": null,
"description": "URL of image to use as logo. Can be remote or local. However, using local URLs depends on the installation of the client and should be used carefully.",
"empty_concrete_fieldpath": "end_snippet.cobrand_info.[].logo_url",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "logo_url",
"presence": "required",
"short_label": "logo_url",
"typ": "string"
},
"end_snippet.cobrand_info.screen_size": {
"abstract_fieldpath": "end_snippet.cobrand_info.screen_size",
"default_value": "0.0",
"description": "If specified and strictly positive but <= 1.0, makes logo scalable with screen by forcing its width to occupy a fixed fraction of the screeen. For instance, a value of .25 makes the given logo occupy 25% of the screen.",
"empty_concrete_fieldpath": "end_snippet.cobrand_info.[].screen_size",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "screen_size",
"presence": "optional",
"short_label": "screen_size",
"typ": "double"
},
"end_snippet.cobrand_info.tie_point": {
"abstract_fieldpath": "end_snippet.cobrand_info.tie_point",
"default_value": "BOTTOM_LEFT",
"description": "Controls reference point in overlay.",
"empty_concrete_fieldpath": "end_snippet.cobrand_info.[].tie_point",
"enum_vals": {
"BOTTOM_CENTER": 7,
"BOTTOM_LEFT": 6,
"BOTTOM_RIGHT": 8,
"MID_CENTER": 4,
"MID_LEFT": 3,
"MID_RIGHT": 5,
"TOP_CENTER": 1,
"TOP_LEFT": 0,
"TOP_RIGHT": 2
},
"js_validation_rule": {
"required": true
},
"name": "tie_point",
"presence": "optional",
"short_label": "tie_point",
"typ": "TiePoint"
},
"end_snippet.cobrand_info.x_coord.is_relative": {
"abstract_fieldpath": "end_snippet.cobrand_info.x_coord.is_relative",
"default_value": "false",
"description": "If true, the coordinate is relative to the screen.",
"empty_concrete_fieldpath": "end_snippet.cobrand_info.[].x_coord.is_relative",
"enum_vals": null,
"js_validation_rule": {
"required": false
},
"name": "is_relative",
"presence": "optional",
"short_label": "is_relative",
"typ": "bool"
},
"end_snippet.cobrand_info.x_coord.value": {
"abstract_fieldpath": "end_snippet.cobrand_info.x_coord.value",
"default_value": "0.0",
"description": "Coordinate value. Interpretation depends on is_relative (absolute or",
"empty_concrete_fieldpath": "end_snippet.cobrand_info.[].x_coord.value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "value",
"presence": "required",
"short_label": "value",
"typ": "double"
},
"end_snippet.cobrand_info.y_coord.is_relative": {
"abstract_fieldpath": "end_snippet.cobrand_info.y_coord.is_relative",
"default_value": "false",
"description": "If true, the coordinate is relative to the screen.",
"empty_concrete_fieldpath": "end_snippet.cobrand_info.[].y_coord.is_relative",
"enum_vals": null,
"js_validation_rule": {
"required": false
},
"name": "is_relative",
"presence": "optional",
"short_label": "is_relative",
"typ": "bool"
},
"end_snippet.cobrand_info.y_coord.value": {
"abstract_fieldpath": "end_snippet.cobrand_info.y_coord.value",
"default_value": "0.0",
"description": "Coordinate value. Interpretation depends on is_relative (absolute or",
"empty_concrete_fieldpath": "end_snippet.cobrand_info.[].y_coord.value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "value",
"presence": "required",
"short_label": "value",
"typ": "double"
},
"end_snippet.default_web_page_intl_url:value": {
"abstract_fieldpath": "end_snippet.default_web_page_intl_url:value",
"default_value": null,
"description": "Default location of web page.",
"empty_concrete_fieldpath": "end_snippet.default_web_page_intl_url:value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "default_web_page_intl_url:value",
"presence": "optional",
"short_label": "default_web_page_intl_url",
"typ": "string"
},
"end_snippet.earth_intl_url:value": {
"abstract_fieldpath": "end_snippet.earth_intl_url:value",
"default_value": null,
"description": "Location of international page for earth.",
"empty_concrete_fieldpath": "end_snippet.earth_intl_url:value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "earth_intl_url:value",
"presence": "optional",
"short_label": "earth_intl_url",
"typ": "string"
},
"end_snippet.elevation_service_base_url": {
"abstract_fieldpath": "end_snippet.elevation_service_base_url",
"default_value": "",
"description": "Terrain elevation service URL. If empty, service will be unavailable.",
"empty_concrete_fieldpath": "end_snippet.elevation_service_base_url",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "elevation_service_base_url",
"presence": "optional",
"short_label": "elevation_service_base_url",
"typ": "string"
},
"end_snippet.hide_user_data": {
"abstract_fieldpath": "end_snippet.hide_user_data",
"default_value": "false",
"description": "If true, hides user license key in about dialog. Useful for Pro only, allows information to not be visible for shared license keys.",
"empty_concrete_fieldpath": "end_snippet.hide_user_data",
"enum_vals": null,
"js_validation_rule": {
"required": false
},
"name": "hide_user_data",
"presence": "optional",
"short_label": "hide_user_data",
"typ": "bool"
},
"end_snippet.keyboard_shortcuts_url:value": {
"abstract_fieldpath": "end_snippet.keyboard_shortcuts_url:value",
"default_value": null,
"description": "URL for keyboard shortcuts page. If not specified, this URL is built from user_guide_intl_url as user_guide_intl_url + \"ug_keyboard.html\".",
"empty_concrete_fieldpath": "end_snippet.keyboard_shortcuts_url:value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "keyboard_shortcuts_url:value",
"presence": "optional",
"short_label": "keyboard_shortcuts_url",
"typ": "string"
},
"end_snippet.model.compressed_negative_altitude_threshold": {
"abstract_fieldpath": "end_snippet.model.compressed_negative_altitude_threshold",
"default_value": null,
"description": "Threshold below which negative altitudes are compressed",
"empty_concrete_fieldpath": "end_snippet.model.compressed_negative_altitude_threshold",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "compressed_negative_altitude_threshold",
"presence": "optional",
"short_label": "compressed_negative_altitude_threshold",
"typ": "double"
},
"end_snippet.model.elevation_bias": {
"abstract_fieldpath": "end_snippet.model.elevation_bias",
"default_value": null,
"description": "Elevation bias",
"empty_concrete_fieldpath": "end_snippet.model.elevation_bias",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "elevation_bias",
"presence": "optional",
"short_label": "elevation_bias",
"typ": "double"
},
"end_snippet.model.flattening": {
"abstract_fieldpath": "end_snippet.model.flattening",
"default_value": "0.00335281066474748",
"description": "Planet flattening. Default value is 1.0/298.257223563 (from WGS84).",
"empty_concrete_fieldpath": "end_snippet.model.flattening",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "flattening",
"presence": "optional",
"short_label": "flattening",
"typ": "double"
},
"end_snippet.model.negative_altitude_exponent_bias": {
"abstract_fieldpath": "end_snippet.model.negative_altitude_exponent_bias",
"default_value": null,
"description": "Bias for negative altitude so that ocean tiles can be streamed to older clients",
"empty_concrete_fieldpath": "end_snippet.model.negative_altitude_exponent_bias",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "negative_altitude_exponent_bias",
"presence": "optional",
"short_label": "negative_altitude_exponent_bias",
"typ": "int32"
},
"end_snippet.model.radius": {
"abstract_fieldpath": "end_snippet.model.radius",
"default_value": "6378.13700",
"description": "Mean planet radius. Default value is the WGS84 model for earth.",
"empty_concrete_fieldpath": "end_snippet.model.radius",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "radius",
"presence": "optional",
"short_label": "radius",
"typ": "double"
},
"end_snippet.privacy_policy_url:value": {
"abstract_fieldpath": "end_snippet.privacy_policy_url:value",
"default_value": null,
"description": "URL for the privacy policy.",
"empty_concrete_fieldpath": "end_snippet.privacy_policy_url:value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "privacy_policy_url:value",
"presence": "optional",
"short_label": "privacy_policy_url",
"typ": "string"
},
"end_snippet.release_notes_url:value": {
"abstract_fieldpath": "end_snippet.release_notes_url:value",
"default_value": null,
"description": "URL for release notes page.",
"empty_concrete_fieldpath": "end_snippet.release_notes_url:value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "release_notes_url:value",
"presence": "optional",
"short_label": "release_notes_url",
"typ": "string"
},
"end_snippet.reverse_geocoder_protocol_version": {
"abstract_fieldpath": "end_snippet.reverse_geocoder_protocol_version",
"default_value": "3",
"description": "Reverse geocoder protocol version. Default is 3 which is the protocol supported by newer clients.",
"empty_concrete_fieldpath": "end_snippet.reverse_geocoder_protocol_version",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "reverse_geocoder_protocol_version",
"presence": "optional",
"short_label": "reverse_geocoder_protocol_version",
"typ": "int32"
},
"end_snippet.reverse_geocoder_url:value": {
"abstract_fieldpath": "end_snippet.reverse_geocoder_url:value",
"default_value": null,
"description": "Reverse geocoder server URL",
"empty_concrete_fieldpath": "end_snippet.reverse_geocoder_url:value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "reverse_geocoder_url:value",
"presence": "optional",
"short_label": "reverse_geocoder_url",
"typ": "string"
},
"end_snippet.show_signin_button": {
"abstract_fieldpath": "end_snippet.show_signin_button",
"default_value": null,
"description": "If true, shows the signin button in the upper right corner.",
"empty_concrete_fieldpath": "end_snippet.show_signin_button",
"enum_vals": null,
"js_validation_rule": {
"required": false
},
"name": "show_signin_button",
"presence": "optional",
"short_label": "show_signin_button",
"typ": "bool"
},
"end_snippet.startup_tips_intl_url:value": {
"abstract_fieldpath": "end_snippet.startup_tips_intl_url:value",
"default_value": null,
"description": "URL from which to load startup tips in Earth 7.0 and higher.",
"empty_concrete_fieldpath": "end_snippet.startup_tips_intl_url:value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "startup_tips_intl_url:value",
"presence": "optional",
"short_label": "startup_tips_intl_url",
"typ": "string"
},
"end_snippet.support_answer_intl_url:value": {
"abstract_fieldpath": "end_snippet.support_answer_intl_url:value",
"default_value": null,
"description": "Url to support answer.",
"empty_concrete_fieldpath": "end_snippet.support_answer_intl_url:value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "support_answer_intl_url:value",
"presence": "optional",
"short_label": "support_answer_intl_url",
"typ": "string"
},
"end_snippet.support_center_intl_url:value": {
"abstract_fieldpath": "end_snippet.support_center_intl_url:value",
"default_value": null,
"description": "Url to support center.",
"empty_concrete_fieldpath": "end_snippet.support_center_intl_url:value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "support_center_intl_url:value",
"presence": "optional",
"short_label": "support_center_intl_url",
"typ": "string"
},
"end_snippet.support_request_intl_url:value": {
"abstract_fieldpath": "end_snippet.support_request_intl_url:value",
"default_value": null,
"description": "Url to support pages.",
"empty_concrete_fieldpath": "end_snippet.support_request_intl_url:value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "support_request_intl_url:value",
"presence": "optional",
"short_label": "support_request_intl_url",
"typ": "string"
},
"end_snippet.support_topic_intl_url:value": {
"abstract_fieldpath": "end_snippet.support_topic_intl_url:value",
"default_value": null,
"description": "Url to support topics used by certain diagnostic messages.",
"empty_concrete_fieldpath": "end_snippet.support_topic_intl_url:value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "support_topic_intl_url:value",
"presence": "optional",
"short_label": "support_topic_intl_url",
"typ": "string"
},
"end_snippet.swoop_parameters.start_dist_in_meters": {
"abstract_fieldpath": "end_snippet.swoop_parameters.start_dist_in_meters",
"default_value": null,
"description": "Controls how far from a target swooping should start.",
"empty_concrete_fieldpath": "end_snippet.swoop_parameters.start_dist_in_meters",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "start_dist_in_meters",
"presence": "optional",
"short_label": "start_dist_in_meters",
"typ": "double"
},
"end_snippet.tutorial_url:value": {
"abstract_fieldpath": "end_snippet.tutorial_url:value",
"default_value": null,
"description": "URL for tutorial page. If not specified, this URL is built from user_guide_intl_url as user_guide_intl_url + \"tutorials/index.html\".",
"empty_concrete_fieldpath": "end_snippet.tutorial_url:value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "tutorial_url:value",
"presence": "optional",
"short_label": "tutorial_url",
"typ": "string"
},
"end_snippet.use_ge_logo": {
"abstract_fieldpath": "end_snippet.use_ge_logo",
"default_value": "true",
"description": "If false, hides the Google logo.",
"empty_concrete_fieldpath": "end_snippet.use_ge_logo",
"enum_vals": null,
"js_validation_rule": {
"required": false
},
"name": "use_ge_logo",
"presence": "optional",
"short_label": "use_ge_logo",
"typ": "bool"
},
"end_snippet.user_guide_intl_url:value": {
"abstract_fieldpath": "end_snippet.user_guide_intl_url:value",
"default_value": null,
"description": "Url to user guide.",
"empty_concrete_fieldpath": "end_snippet.user_guide_intl_url:value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "user_guide_intl_url:value",
"presence": "optional",
"short_label": "user_guide_intl_url",
"typ": "string"
},
"end_snippet.valid_database.database_name:value": {
"abstract_fieldpath": "end_snippet.valid_database.database_name:value",
"default_value": null,
"description": "Human-readable name of database (such as \"Primary Database\" or \"Digital Globe Database\")",
"empty_concrete_fieldpath": "end_snippet.valid_database.[].database_name:value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "database_name:value",
"presence": "optional",
"short_label": "database_name",
"typ": "string"
},
"end_snippet.valid_database.database_url": {
"abstract_fieldpath": "end_snippet.valid_database.database_url",
"default_value": null,
"description": "URL of server. This can include a path and query, and must be a well-formed, absolute URL.",
"empty_concrete_fieldpath": "end_snippet.valid_database.[].database_url",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "database_url",
"presence": "required",
"short_label": "database_url",
"typ": "string"
},
"end_snippet.search_config.error_page_url:value": {
"abstract_fieldpath": "end_snippet.search_config.error_page_url:value",
"default_value": "about:blank",
"description": "URL of a page that will be displayed if a network error or other local error occurs while performing a search. This might be an error for a local geocode while in offline mode, a connection error while trying to connect to MFE, or some other error where we can't get an error message from the server. (Obviously this page should be cached locally, or it's not terribly useful.) The URL should be fully encoded, and can use $[hl] and friends if necessary.",
"empty_concrete_fieldpath": "end_snippet.search_config.error_page_url:value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "error_page_url:value",
"presence": "optional",
"short_label": "error_page_url",
"typ": "string"
},
"end_snippet.search_config.kml_render_url:value": {
"abstract_fieldpath": "end_snippet.search_config.kml_render_url:value",
"default_value": "/earth/client/kmlrender/index_$[hl].html",
"description": "URL of a page that will be shown when KML is rendered in the search panel. This page should have JavaScript that reads the KML from the environment and renders it as HTML, but should NOT perform onebox or searchlet searches. The URL should be fully encoded, and can use $[hl] and friends if necessary.",
"empty_concrete_fieldpath": "end_snippet.search_config.kml_render_url:value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "kml_render_url:value",
"presence": "optional",
"short_label": "kml_render_url",
"typ": "string"
},
"end_snippet.search_config.kml_search_url:value": {
"abstract_fieldpath": "end_snippet.search_config.kml_search_url:value",
"default_value": "/earth/client/kmlrender/index_$[hl].html",
"description": "URL of a page that will be shown when a KML search is performed. This page should have JavaScript that reads the KML from the environment and renders it as HTML, and also performs onebox and searchlet searches if applicable. The URL should be fully encoded, and can use $[hl] and friends if necessary.",
"empty_concrete_fieldpath": "end_snippet.search_config.kml_search_url:value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "kml_search_url:value",
"presence": "optional",
"short_label": "kml_search_url",
"typ": "string"
},
"end_snippet.search_config.search_history_url:value": {
"abstract_fieldpath": "end_snippet.search_config.search_history_url:value",
"default_value": "http://www.google.com/earth/client/search/history_$[hl].html",
"description": "URL of a page that will be shown when the search history is requested. This page should have JavaScript that reads the search history from the client and renders it as HTML.",
"empty_concrete_fieldpath": "end_snippet.search_config.search_history_url:value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "search_history_url:value",
"presence": "optional",
"short_label": "search_history_url",
"typ": "string"
},
"end_snippet.google_maps_url:value": {
"abstract_fieldpath": "end_snippet.google_maps_url:value",
"default_value": "",
"description": "URL for Google Maps, for features like 'View in Maps'.",
"empty_concrete_fieldpath": "end_snippet.google_maps_url:value",
"enum_vals": null,
"js_validation_rule": {
"required": true
},
"name": "google_maps_url:value",
"presence": "optional",
"short_label": "google_maps_url",
"typ": "string"
}
}
"""
| tst-ahernandez/earthenterprise | earth_enterprise/src/server/wsgi/serve/snippets/data/metainfo_by_fieldpath.py | Python | apache-2.0 | 24,676 |
/*
* Copyright 2005-2007 WSO2, Inc. (http://wso2.com)
*
* 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 org.wso2.carbon.identity.sso.saml.admin;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.opensaml.saml1.core.NameIdentifier;
import org.wso2.carbon.identity.base.IdentityException;
import org.wso2.carbon.identity.core.model.SAMLSSOServiceProviderDO;
import org.wso2.carbon.identity.core.persistence.IdentityPersistenceManager;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import org.wso2.carbon.identity.sso.saml.dto.SAMLSSOServiceProviderDTO;
import org.wso2.carbon.identity.sso.saml.dto.SAMLSSOServiceProviderInfoDTO;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.session.UserRegistry;
/**
* This class is used for managing SAML SSO providers. Adding, retrieving and removing service
* providers are supported here.
* In addition to that logic for generating key pairs for tenants except for tenant 0, is included
* here.
*/
public class SAMLSSOConfigAdmin {
private static Log log = LogFactory.getLog(SAMLSSOConfigAdmin.class);
private UserRegistry registry;
public SAMLSSOConfigAdmin(Registry userRegistry) {
registry = (UserRegistry) userRegistry;
}
/**
* Add a new service provider
*
* @param serviceProviderDTO service Provider DTO
* @return true if successful, false otherwise
* @throws IdentityException if fails to load the identity persistence manager
*/
public boolean addRelyingPartyServiceProvider(SAMLSSOServiceProviderDTO serviceProviderDTO) throws IdentityException {
SAMLSSOServiceProviderDO serviceProviderDO = new SAMLSSOServiceProviderDO();
if (serviceProviderDTO.getIssuer() == null || serviceProviderDTO.getIssuer().equals("")) {
String message = "A value for the Issuer is mandatory";
log.error(message);
throw new IdentityException(message);
}
if (serviceProviderDTO.getIssuer().contains("@")) {
String message = "\'@\' is a reserved character. Cannot be used for Service Provider Entity ID";
log.error(message);
throw new IdentityException(message);
}
serviceProviderDO.setIssuer(serviceProviderDTO.getIssuer());
serviceProviderDO.setAssertionConsumerUrl(serviceProviderDTO.getAssertionConsumerUrl());
serviceProviderDO.setCertAlias(serviceProviderDTO.getCertAlias());
serviceProviderDO.setUseFullyQualifiedUsername(serviceProviderDTO.isUseFullyQualifiedUsername());
serviceProviderDO.setDoSingleLogout(serviceProviderDTO.isDoSingleLogout());
serviceProviderDO.setLoginPageURL(serviceProviderDTO.getLoginPageURL());
serviceProviderDO.setLogoutURL(serviceProviderDTO.getLogoutURL());
serviceProviderDO.setDoSignResponse(serviceProviderDTO.isDoSignResponse());
serviceProviderDO.setDoSignAssertions(serviceProviderDTO.isDoSignAssertions());
serviceProviderDO.setNameIdClaimUri(serviceProviderDTO.getNameIdClaimUri());
serviceProviderDO.setEnableAttributesByDefault(serviceProviderDTO.isEnableAttributesByDefault());
if (serviceProviderDTO.getNameIDFormat() == null) {
serviceProviderDTO.setNameIDFormat(NameIdentifier.EMAIL);
} else {
serviceProviderDTO.setNameIDFormat(serviceProviderDTO.getNameIDFormat().replace("/",
":"));
}
serviceProviderDO.setNameIDFormat(serviceProviderDTO.getNameIDFormat());
if (serviceProviderDTO.getRequestedClaims() != null && serviceProviderDTO.getRequestedClaims().length != 0) {
if (serviceProviderDTO.getAttributeConsumingServiceIndex() != null &&
!serviceProviderDTO.getAttributeConsumingServiceIndex().equals("")) {
serviceProviderDO.setAttributeConsumingServiceIndex(serviceProviderDTO.getAttributeConsumingServiceIndex());
} else {
serviceProviderDO.setAttributeConsumingServiceIndex(Integer.toString(IdentityUtil.getRandomInteger()));
}
serviceProviderDO.setRequestedClaims(serviceProviderDTO.getRequestedClaims());
} else {
if (serviceProviderDTO.getAttributeConsumingServiceIndex() == null ||
serviceProviderDTO.getAttributeConsumingServiceIndex().isEmpty()) {
serviceProviderDO.setAttributeConsumingServiceIndex(Integer.toString(IdentityUtil.getRandomInteger()));
} else {
serviceProviderDO.setAttributeConsumingServiceIndex(serviceProviderDTO.getAttributeConsumingServiceIndex());
}
}
if (serviceProviderDTO.getRequestedAudiences() != null && serviceProviderDTO.getRequestedAudiences().length != 0) {
serviceProviderDO.setRequestedAudiences(serviceProviderDTO.getRequestedAudiences());
}
if (serviceProviderDTO.getRequestedRecipients() != null && serviceProviderDTO.getRequestedRecipients().length != 0) {
serviceProviderDO.setRequestedRecipients(serviceProviderDTO.getRequestedRecipients());
}
serviceProviderDO.setIdPInitSSOEnabled(serviceProviderDTO.isIdPInitSSOEnabled());
serviceProviderDO.setDoEnableEncryptedAssertion(serviceProviderDTO.isDoEnableEncryptedAssertion());
serviceProviderDO.setDoValidateSignatureInRequests(serviceProviderDTO.isDoValidateSignatureInRequests());
IdentityPersistenceManager persistenceManager = IdentityPersistenceManager
.getPersistanceManager();
try {
return persistenceManager.addServiceProvider(registry, serviceProviderDO);
} catch (IdentityException e) {
log.error("Error obtaining a registry for adding a new service provider", e);
throw new IdentityException("Error obtaining a registry for adding a new service provider", e);
}
}
/**
* Retrieve all the relying party service providers
*
* @return set of RP Service Providers + file path of pub. key of generated key pair
*/
public SAMLSSOServiceProviderInfoDTO getServiceProviders() throws IdentityException {
SAMLSSOServiceProviderDTO[] serviceProviders = null;
try {
IdentityPersistenceManager persistenceManager = IdentityPersistenceManager
.getPersistanceManager();
SAMLSSOServiceProviderDO[] providersSet = persistenceManager.
getServiceProviders(registry);
serviceProviders = new SAMLSSOServiceProviderDTO[providersSet.length];
for (int i = 0; i < providersSet.length; i++) {
SAMLSSOServiceProviderDO providerDO = providersSet[i];
SAMLSSOServiceProviderDTO providerDTO = new SAMLSSOServiceProviderDTO();
providerDTO.setIssuer(providerDO.getIssuer());
providerDTO.setAssertionConsumerUrl(providerDO.getAssertionConsumerUrl());
providerDTO.setCertAlias(providerDO.getCertAlias());
providerDTO.setAttributeConsumingServiceIndex(providerDO.getAttributeConsumingServiceIndex());
providerDTO.setUseFullyQualifiedUsername(providerDO.isUseFullyQualifiedUsername());
providerDTO.setDoSignResponse(providerDO.isDoSignResponse());
providerDTO.setDoSignAssertions(providerDO.isDoSignAssertions());
providerDTO.setDoSingleLogout(providerDO.isDoSingleLogout());
if (providerDO.getLoginPageURL() == null || "null".equals(providerDO.getLoginPageURL())) {
providerDTO.setLoginPageURL("");
} else {
providerDTO.setLoginPageURL(providerDO.getLoginPageURL());
}
if (providerDO.getLogoutURL() == null || "null".equals(providerDO.getLogoutURL())) {
providerDTO.setLogoutURL("");
} else {
providerDTO.setLogoutURL(providerDO.getLogoutURL());
}
providerDTO.setRequestedClaims(providerDO.getRequestedClaims());
providerDTO.setRequestedAudiences(providerDO.getRequestedAudiences());
providerDTO.setRequestedRecipients(providerDO.getRequestedRecipients());
providerDTO.setEnableAttributesByDefault(providerDO.isEnableAttributesByDefault());
providerDTO.setNameIdClaimUri(providerDO.getNameIdClaimUri());
providerDTO.setNameIDFormat(providerDO.getNameIDFormat());
if (providerDTO.getNameIDFormat() == null) {
providerDTO.setNameIDFormat(NameIdentifier.EMAIL);
}
providerDTO.setNameIDFormat(providerDTO.getNameIDFormat().replace(":", "/"));
providerDTO.setIdPInitSSOEnabled(providerDO.isIdPInitSSOEnabled());
providerDTO.setDoEnableEncryptedAssertion(providerDO.isDoEnableEncryptedAssertion());
providerDTO.setDoValidateSignatureInRequests(providerDO.isDoValidateSignatureInRequests());
serviceProviders[i] = providerDTO;
}
} catch (IdentityException e) {
log.error("Error obtaining a registry intance for reading service provider list", e);
throw new IdentityException("Error obtaining a registry intance for reading service provider list", e);
}
SAMLSSOServiceProviderInfoDTO serviceProviderInfoDTO = new SAMLSSOServiceProviderInfoDTO();
serviceProviderInfoDTO.setServiceProviders(serviceProviders);
//if it is tenant zero
if (registry.getTenantId() == 0) {
serviceProviderInfoDTO.setTenantZero(true);
}
return serviceProviderInfoDTO;
}
/**
* Remove an existing service provider.
*
* @param issuer issuer name
* @return true is successful
* @throws IdentityException
*/
public boolean removeServiceProvider(String issuer) throws IdentityException {
try {
IdentityPersistenceManager persistenceManager = IdentityPersistenceManager.getPersistanceManager();
return persistenceManager.removeServiceProvider(registry, issuer);
} catch (IdentityException e) {
log.error("Error removing a Service Provider");
throw new IdentityException("Error removing a Service Provider", e);
}
}
}
| rswijesena/carbon-identity | components/sso-saml/org.wso2.carbon.identity.sso.saml/src/main/java/org/wso2/carbon/identity/sso/saml/admin/SAMLSSOConfigAdmin.java | Java | apache-2.0 | 11,010 |
/*
* Copyright 2014 JBoss, by Red Hat, 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 org.drools.workbench.screens.guided.dtree.backend.server.indexing.classes;
public class Applicant {
private int age;
public int getAge() {
return age;
}
}
| cristianonicolai/drools-wb | drools-wb-screens/drools-wb-guided-dtree-editor/drools-wb-guided-dtree-editor-backend/src/test/java/org/drools/workbench/screens/guided/dtree/backend/server/indexing/classes/Applicant.java | Java | apache-2.0 | 795 |
class AddCompactNameIndexToMissions < ActiveRecord::Migration
def change
add_index(:missions, [:compact_name])
end
end
| nmckahd/AHDBurundi | db/migrate/20120822161441_add_compact_name_index_to_missions.rb | Ruby | apache-2.0 | 127 |
/*
* Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*
* Copyright 1999-2002,2004 The Apache Software Foundation.
*
* 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.sun.org.apache.xerces.internal.impl.dv.util;
/**
* format validation
*
* This class encodes/decodes hexadecimal data
*
* @xerces.internal
*
* @author Jeffrey Rodriguez
*/
public final class HexBin {
static private final int BASELENGTH = 128;
static private final int LOOKUPLENGTH = 16;
static final private byte [] hexNumberTable = new byte[BASELENGTH];
static final private char [] lookUpHexAlphabet = new char[LOOKUPLENGTH];
static {
for (int i = 0; i < BASELENGTH; i++ ) {
hexNumberTable[i] = -1;
}
for ( int i = '9'; i >= '0'; i--) {
hexNumberTable[i] = (byte) (i-'0');
}
for ( int i = 'F'; i>= 'A'; i--) {
hexNumberTable[i] = (byte) ( i-'A' + 10 );
}
for ( int i = 'f'; i>= 'a'; i--) {
hexNumberTable[i] = (byte) ( i-'a' + 10 );
}
for(int i = 0; i<10; i++ ) {
lookUpHexAlphabet[i] = (char)('0'+i);
}
for(int i = 10; i<=15; i++ ) {
lookUpHexAlphabet[i] = (char)('A'+i -10);
}
}
/**
* Encode a byte array to hex string
*
* @param binaryData array of byte to encode
* @return return encoded string
*/
static public String encode(byte[] binaryData) {
if (binaryData == null)
return null;
int lengthData = binaryData.length;
int lengthEncode = lengthData * 2;
char[] encodedData = new char[lengthEncode];
int temp;
for (int i = 0; i < lengthData; i++) {
temp = binaryData[i];
if (temp < 0)
temp += 256;
encodedData[i*2] = lookUpHexAlphabet[temp >> 4];
encodedData[i*2+1] = lookUpHexAlphabet[temp & 0xf];
}
return new String(encodedData);
}
/**
* Decode hex string to a byte array
*
* @param encoded encoded string
* @return return array of byte to encode
*/
static public byte[] decode(String encoded) {
if (encoded == null)
return null;
int lengthData = encoded.length();
if (lengthData % 2 != 0)
return null;
char[] binaryData = encoded.toCharArray();
int lengthDecode = lengthData / 2;
byte[] decodedData = new byte[lengthDecode];
byte temp1, temp2;
char tempChar;
for( int i = 0; i<lengthDecode; i++ ){
tempChar = binaryData[i*2];
temp1 = (tempChar < BASELENGTH) ? hexNumberTable[tempChar] : -1;
if (temp1 == -1)
return null;
tempChar = binaryData[i*2+1];
temp2 = (tempChar < BASELENGTH) ? hexNumberTable[tempChar] : -1;
if (temp2 == -1)
return null;
decodedData[i] = (byte)((temp1 << 4) | temp2);
}
return decodedData;
}
}
| shun634501730/java_source_cn | src_en/com/sun/org/apache/xerces/internal/impl/dv/util/HexBin.java | Java | apache-2.0 | 3,681 |
/*
* 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.hive.common.io;
import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicBoolean;
import java.io.IOException;
import java.io.InputStream;
import org.apache.hadoop.hive.common.io.encoded.MemoryBufferOrBuffers;
public interface FileMetadataCache {
/**
* @return Metadata for a given file (ORC or Parquet footer).
* The caller must decref this buffer when done.
*/
MemoryBufferOrBuffers getFileMetadata(Object fileKey);
@Deprecated
MemoryBufferOrBuffers putFileMetadata(
Object fileKey, int length, InputStream is) throws IOException;
@Deprecated
MemoryBufferOrBuffers putFileMetadata(Object fileKey, ByteBuffer tailBuffer);
@Deprecated
MemoryBufferOrBuffers putFileMetadata(
Object fileKey, int length, InputStream is, CacheTag tag) throws IOException;
@Deprecated
MemoryBufferOrBuffers putFileMetadata(Object fileKey, ByteBuffer tailBuffer, CacheTag tag);
/**
* Releases the buffer returned from getFileMetadata or putFileMetadata method.
* @param buffer The buffer to release.
*/
void decRefBuffer(MemoryBufferOrBuffers buffer);
/**
* Puts the metadata for a given file (e.g. a footer buffer into cache).
* @param fileKey The file key.
* @return The buffer or buffers representing the cached footer.
* The caller must decref this buffer when done.
*/
MemoryBufferOrBuffers putFileMetadata(Object fileKey, ByteBuffer tailBuffer,
CacheTag tag, AtomicBoolean isStopped);
MemoryBufferOrBuffers putFileMetadata(Object fileKey, int length,
InputStream is, CacheTag tag, AtomicBoolean isStopped) throws IOException;
}
| vineetgarg02/hive | storage-api/src/java/org/apache/hadoop/hive/common/io/FileMetadataCache.java | Java | apache-2.0 | 2,471 |
/**************************************************************************
** **
** QCustomPlot, an easy to use, modern plotting widget for Qt **
** Copyright (C) 2011, 2012, 2013 Emanuel Eichhammer **
* 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: Emanuel Eichhammer **
** Website/Contact: http://www.qcustomplot.com/ **
** Date: 09.12.13 **
** Version: 1.1.1 **
****************************************************************************/
/* Including QCustomPlot qcustomplot.cpp under GPLv2 license within NetAnim,
* as a special exception,
* with permission from the copyright holder: Emanuel Eichhammer */
#include "qcustomplot.h"
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPPainter
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPPainter
\brief QPainter subclass used internally
This internal class is used to provide some extended functionality e.g. for tweaking position
consistency between antialiased and non-antialiased painting. Further it provides workarounds
for QPainter quirks.
\warning This class intentionally hides non-virtual functions of QPainter, e.g. setPen, save and
restore. So while it is possible to pass a QCPPainter instance to a function that expects a
QPainter pointer, some of the workarounds and tweaks will be unavailable to the function (because
it will call the base class implementations of the functions actually hidden by QCPPainter).
*/
/*!
Creates a new QCPPainter instance and sets default values
*/
QCPPainter::QCPPainter() :
QPainter(),
mModes(pmDefault),
mIsAntialiasing(false)
{
// don't setRenderHint(QPainter::NonCosmeticDefautPen) here, because painter isn't active yet and
// a call to begin() will follow
}
/*!
Creates a new QCPPainter instance on the specified paint \a device and sets default values. Just
like the analogous QPainter constructor, begins painting on \a device immediately.
Like \ref begin, this method sets QPainter::NonCosmeticDefaultPen in Qt versions before Qt5.
*/
QCPPainter::QCPPainter(QPaintDevice *device) :
QPainter(device),
mModes(pmDefault),
mIsAntialiasing(false)
{
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions.
if (isActive())
setRenderHint(QPainter::NonCosmeticDefaultPen);
#endif
}
QCPPainter::~QCPPainter()
{
}
/*!
Sets the pen of the painter and applies certain fixes to it, depending on the mode of this
QCPPainter.
\note this function hides the non-virtual base class implementation.
*/
void QCPPainter::setPen(const QPen &pen)
{
QPainter::setPen(pen);
if (mModes.testFlag(pmNonCosmetic))
makeNonCosmetic();
}
/*! \overload
Sets the pen (by color) of the painter and applies certain fixes to it, depending on the mode of
this QCPPainter.
\note this function hides the non-virtual base class implementation.
*/
void QCPPainter::setPen(const QColor &color)
{
QPainter::setPen(color);
if (mModes.testFlag(pmNonCosmetic))
makeNonCosmetic();
}
/*! \overload
Sets the pen (by style) of the painter and applies certain fixes to it, depending on the mode of
this QCPPainter.
\note this function hides the non-virtual base class implementation.
*/
void QCPPainter::setPen(Qt::PenStyle penStyle)
{
QPainter::setPen(penStyle);
if (mModes.testFlag(pmNonCosmetic))
makeNonCosmetic();
}
/*! \overload
Works around a Qt bug introduced with Qt 4.8 which makes drawing QLineF unpredictable when
antialiasing is disabled. Thus when antialiasing is disabled, it rounds the \a line to
integer coordinates and then passes it to the original drawLine.
\note this function hides the non-virtual base class implementation.
*/
void QCPPainter::drawLine(const QLineF &line)
{
if (mIsAntialiasing || mModes.testFlag(pmVectorized))
QPainter::drawLine(line);
else
QPainter::drawLine(line.toLine());
}
/*!
Sets whether painting uses antialiasing or not. Use this method instead of using setRenderHint
with QPainter::Antialiasing directly, as it allows QCPPainter to regain pixel exactness between
antialiased and non-antialiased painting (Since Qt < 5.0 uses slightly different coordinate systems for
AA/Non-AA painting).
*/
void QCPPainter::setAntialiasing(bool enabled)
{
setRenderHint(QPainter::Antialiasing, enabled);
if (mIsAntialiasing != enabled)
{
mIsAntialiasing = enabled;
if (!mModes.testFlag(pmVectorized)) // antialiasing half-pixel shift only needed for rasterized outputs
{
if (mIsAntialiasing)
translate(0.5, 0.5);
else
translate(-0.5, -0.5);
}
}
}
/*!
Sets the mode of the painter. This controls whether the painter shall adjust its
fixes/workarounds optimized for certain output devices.
*/
void QCPPainter::setModes(QCPPainter::PainterModes modes)
{
mModes = modes;
}
/*!
Sets the QPainter::NonCosmeticDefaultPen in Qt versions before Qt5 after beginning painting on \a
device. This is necessary to get cosmetic pen consistency across Qt versions, because since Qt5,
all pens are non-cosmetic by default, and in Qt4 this render hint must be set to get that
behaviour.
The Constructor \ref QCPPainter(QPaintDevice *device) which directly starts painting also sets
the render hint as appropriate.
\note this function hides the non-virtual base class implementation.
*/
bool QCPPainter::begin(QPaintDevice *device)
{
bool result = QPainter::begin(device);
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions.
if (result)
setRenderHint(QPainter::NonCosmeticDefaultPen);
#endif
return result;
}
/*! \overload
Sets the mode of the painter. This controls whether the painter shall adjust its
fixes/workarounds optimized for certain output devices.
*/
void QCPPainter::setMode(QCPPainter::PainterMode mode, bool enabled)
{
if (!enabled && mModes.testFlag(mode))
mModes &= ~mode;
else if (enabled && !mModes.testFlag(mode))
mModes |= mode;
}
/*!
Saves the painter (see QPainter::save). Since QCPPainter adds some new internal state to
QPainter, the save/restore functions are reimplemented to also save/restore those members.
\note this function hides the non-virtual base class implementation.
\see restore
*/
void QCPPainter::save()
{
mAntialiasingStack.push(mIsAntialiasing);
QPainter::save();
}
/*!
Restores the painter (see QPainter::restore). Since QCPPainter adds some new internal state to
QPainter, the save/restore functions are reimplemented to also save/restore those members.
\note this function hides the non-virtual base class implementation.
\see save
*/
void QCPPainter::restore()
{
if (!mAntialiasingStack.isEmpty())
mIsAntialiasing = mAntialiasingStack.pop();
else
qDebug() << Q_FUNC_INFO << "Unbalanced save/restore";
QPainter::restore();
}
/*!
Changes the pen width to 1 if it currently is 0. This function is called in the \ref setPen
overrides when the \ref pmNonCosmetic mode is set.
*/
void QCPPainter::makeNonCosmetic()
{
if (qFuzzyIsNull(pen().widthF()))
{
QPen p = pen();
p.setWidth(1);
QPainter::setPen(p);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPScatterStyle
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPScatterStyle
\brief Represents the visual appearance of scatter points
This class holds information about shape, color and size of scatter points. In plottables like
QCPGraph it is used to store how scatter points shall be drawn. For example, \ref
QCPGraph::setScatterStyle takes a QCPScatterStyle instance.
A scatter style consists of a shape (\ref setShape), a line color (\ref setPen) and possibly a
fill (\ref setBrush), if the shape provides a fillable area. Further, the size of the shape can
be controlled with \ref setSize.
\section QCPScatterStyle-defining Specifying a scatter style
You can set all these configurations either by calling the respective functions on an instance:
\code
QCPScatterStyle myScatter;
myScatter.setShape(QCPScatterStyle::ssCircle);
myScatter.setPen(Qt::blue);
myScatter.setBrush(Qt::white);
myScatter.setSize(5);
customPlot->graph(0)->setScatterStyle(myScatter);
\endcode
Or you can use one of the various constructors that take different parameter combinations, making
it easy to specify a scatter style in a single call, like so:
\code
customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::blue, Qt::white, 5));
\endcode
\section QCPScatterStyle-undefinedpen Leaving the color/pen up to the plottable
There are two constructors which leave the pen undefined: \ref QCPScatterStyle() and \ref
QCPScatterStyle(ScatterShape shape, double size). If those constructors are used, a call to \ref
isPenDefined will return false. It leads to scatter points that inherit the pen from the
plottable that uses the scatter style. Thus, if such a scatter style is passed to QCPGraph, the line
color of the graph (\ref QCPGraph::setPen) will be used by the scatter points. This makes
it very convenient to set up typical scatter settings:
\code
customPlot->graph(0)->setScatterStyle(QCPScatterStyle::ssPlus);
\endcode
Notice that it wasn't even necessary to explicitly call a QCPScatterStyle constructor. This works
because QCPScatterStyle provides a constructor that can transform a \ref ScatterShape directly
into a QCPScatterStyle instance (that's the \ref QCPScatterStyle(ScatterShape shape, double size)
constructor with a default for \a size). In those cases, C++ allows directly supplying a \ref
ScatterShape, where actually a QCPScatterStyle is expected.
\section QCPScatterStyle-custompath-and-pixmap Custom shapes and pixmaps
QCPScatterStyle supports drawing custom shapes and arbitrary pixmaps as scatter points.
For custom shapes, you can provide a QPainterPath with the desired shape to the \ref
setCustomPath function or call the constructor that takes a painter path. The scatter shape will
automatically be set to \ref ssCustom.
For pixmaps, you call \ref setPixmap with the desired QPixmap. Alternatively you can use the
constructor that takes a QPixmap. The scatter shape will automatically be set to \ref ssPixmap.
Note that \ref setSize does not influence the appearance of the pixmap.
*/
/* start documentation of inline functions */
/*! \fn bool QCPScatterStyle::isNone() const
Returns whether the scatter shape is \ref ssNone.
\see setShape
*/
/*! \fn bool QCPScatterStyle::isPenDefined() const
Returns whether a pen has been defined for this scatter style.
The pen is undefined if a constructor is called that does not carry \a pen as parameter. Those are
\ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If the pen is
left undefined, the scatter color will be inherited from the plottable that uses this scatter
style.
\see setPen
*/
/* end documentation of inline functions */
/*!
Creates a new QCPScatterStyle instance with size set to 6. No shape, pen or brush is defined.
Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
from the plottable that uses this scatter style.
*/
QCPScatterStyle::QCPScatterStyle() :
mSize(6),
mShape(ssNone),
mPen(Qt::NoPen),
mBrush(Qt::NoBrush),
mPenDefined(false)
{
}
/*!
Creates a new QCPScatterStyle instance with shape set to \a shape and size to \a size. No pen or
brush is defined.
Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
from the plottable that uses this scatter style.
*/
QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) :
mSize(size),
mShape(shape),
mPen(Qt::NoPen),
mBrush(Qt::NoBrush),
mPenDefined(false)
{
}
/*!
Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
and size to \a size. No brush is defined, i.e. the scatter point will not be filled.
*/
QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double size) :
mSize(size),
mShape(shape),
mPen(QPen(color)),
mBrush(Qt::NoBrush),
mPenDefined(true)
{
}
/*!
Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
the brush color to \a fill (with a solid pattern), and size to \a size.
*/
QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) :
mSize(size),
mShape(shape),
mPen(QPen(color)),
mBrush(QBrush(fill)),
mPenDefined(true)
{
}
/*!
Creates a new QCPScatterStyle instance with shape set to \a shape, the pen set to \a pen, the
brush to \a brush, and size to \a size.
\warning In some cases it might be tempting to directly use a pen style like <tt>Qt::NoPen</tt> as \a pen
and a color like <tt>Qt::blue</tt> as \a brush. Notice however, that the corresponding call\n
<tt>QCPScatterStyle(QCPScatterShape::ssCircle, Qt::NoPen, Qt::blue, 5)</tt>\n
doesn't necessarily lead C++ to use this constructor in some cases, but might mistake
<tt>Qt::NoPen</tt> for a QColor and use the
\ref QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size)
constructor instead (which will lead to an unexpected look of the scatter points). To prevent
this, be more explicit with the parameter types. For example, use <tt>QBrush(Qt::blue)</tt>
instead of just <tt>Qt::blue</tt>, to clearly point out to the compiler that this constructor is
wanted.
*/
QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size) :
mSize(size),
mShape(shape),
mPen(pen),
mBrush(brush),
mPenDefined(pen.style() != Qt::NoPen)
{
}
/*!
Creates a new QCPScatterStyle instance which will show the specified \a pixmap. The scatter shape
is set to \ref ssPixmap.
*/
QCPScatterStyle::QCPScatterStyle(const QPixmap &pixmap) :
mSize(5),
mShape(ssPixmap),
mPen(Qt::NoPen),
mBrush(Qt::NoBrush),
mPixmap(pixmap),
mPenDefined(false)
{
}
/*!
Creates a new QCPScatterStyle instance with a custom shape that is defined via \a customPath. The
scatter shape is set to \ref ssCustom.
The custom shape line will be drawn with \a pen and filled with \a brush. The size has a slightly
different meaning than for built-in scatter points: The custom path will be drawn scaled by a
factor of \a size/6.0. Since the default \a size is 6, the custom path will appear at a its
natural size by default. To double the size of the path for example, set \a size to 12.
*/
QCPScatterStyle::QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush, double size) :
mSize(size),
mShape(ssCustom),
mPen(pen),
mBrush(brush),
mCustomPath(customPath),
mPenDefined(false)
{
}
/*!
Sets the size (pixel diameter) of the drawn scatter points to \a size.
\see setShape
*/
void QCPScatterStyle::setSize(double size)
{
mSize = size;
}
/*!
Sets the shape to \a shape.
Note that the calls \ref setPixmap and \ref setCustomPath automatically set the shape to \ref
ssPixmap and \ref ssCustom, respectively.
\see setSize
*/
void QCPScatterStyle::setShape(QCPScatterStyle::ScatterShape shape)
{
mShape = shape;
}
/*!
Sets the pen that will be used to draw scatter points to \a pen.
If the pen was previously undefined (see \ref isPenDefined), the pen is considered defined after
a call to this function, even if \a pen is <tt>Qt::NoPen</tt>.
\see setBrush
*/
void QCPScatterStyle::setPen(const QPen &pen)
{
mPenDefined = true;
mPen = pen;
}
/*!
Sets the brush that will be used to fill scatter points to \a brush. Note that not all scatter
shapes have fillable areas. For example, \ref ssPlus does not while \ref ssCircle does.
\see setPen
*/
void QCPScatterStyle::setBrush(const QBrush &brush)
{
mBrush = brush;
}
/*!
Sets the pixmap that will be drawn as scatter point to \a pixmap.
Note that \ref setSize does not influence the appearance of the pixmap.
The scatter shape is automatically set to \ref ssPixmap.
*/
void QCPScatterStyle::setPixmap(const QPixmap &pixmap)
{
setShape(ssPixmap);
mPixmap = pixmap;
}
/*!
Sets the custom shape that will be drawn as scatter point to \a customPath.
The scatter shape is automatically set to \ref ssCustom.
*/
void QCPScatterStyle::setCustomPath(const QPainterPath &customPath)
{
setShape(ssCustom);
mCustomPath = customPath;
}
/*!
Applies the pen and the brush of this scatter style to \a painter. If this scatter style has an
undefined pen (\ref isPenDefined), sets the pen of \a painter to \a defaultPen instead.
This function is used by plottables (or any class that wants to draw scatters) just before a
number of scatters with this style shall be drawn with the \a painter.
\see drawShape
*/
void QCPScatterStyle::applyTo(QCPPainter *painter, const QPen &defaultPen) const
{
painter->setPen(mPenDefined ? mPen : defaultPen);
painter->setBrush(mBrush);
}
/*!
Draws the scatter shape with \a painter at position \a pos.
This function does not modify the pen or the brush on the painter, as \ref applyTo is meant to be
called before scatter points are drawn with \ref drawShape.
\see applyTo
*/
void QCPScatterStyle::drawShape(QCPPainter *painter, QPointF pos) const
{
drawShape(painter, pos.x(), pos.y());
}
/*! \overload
Draws the scatter shape with \a painter at position \a x and \a y.
*/
void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const
{
double w = mSize/2.0;
switch (mShape)
{
case ssNone: break;
case ssDot:
{
painter->drawLine(QPointF(x, y), QPointF(x+0.0001, y));
break;
}
case ssCross:
{
painter->drawLine(QLineF(x-w, y-w, x+w, y+w));
painter->drawLine(QLineF(x-w, y+w, x+w, y-w));
break;
}
case ssPlus:
{
painter->drawLine(QLineF(x-w, y, x+w, y));
painter->drawLine(QLineF( x, y+w, x, y-w));
break;
}
case ssCircle:
{
painter->drawEllipse(QPointF(x , y), w, w);
break;
}
case ssDisc:
{
QBrush b = painter->brush();
painter->setBrush(painter->pen().color());
painter->drawEllipse(QPointF(x , y), w, w);
painter->setBrush(b);
break;
}
case ssSquare:
{
painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
break;
}
case ssDiamond:
{
painter->drawLine(QLineF(x-w, y, x, y-w));
painter->drawLine(QLineF( x, y-w, x+w, y));
painter->drawLine(QLineF(x+w, y, x, y+w));
painter->drawLine(QLineF( x, y+w, x-w, y));
break;
}
case ssStar:
{
painter->drawLine(QLineF(x-w, y, x+w, y));
painter->drawLine(QLineF( x, y+w, x, y-w));
painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.707, y+w*0.707));
painter->drawLine(QLineF(x-w*0.707, y+w*0.707, x+w*0.707, y-w*0.707));
break;
}
case ssTriangle:
{
painter->drawLine(QLineF(x-w, y+0.755*w, x+w, y+0.755*w));
painter->drawLine(QLineF(x+w, y+0.755*w, x, y-0.977*w));
painter->drawLine(QLineF( x, y-0.977*w, x-w, y+0.755*w));
break;
}
case ssTriangleInverted:
{
painter->drawLine(QLineF(x-w, y-0.755*w, x+w, y-0.755*w));
painter->drawLine(QLineF(x+w, y-0.755*w, x, y+0.977*w));
painter->drawLine(QLineF( x, y+0.977*w, x-w, y-0.755*w));
break;
}
case ssCrossSquare:
{
painter->drawLine(QLineF(x-w, y-w, x+w*0.95, y+w*0.95));
painter->drawLine(QLineF(x-w, y+w*0.95, x+w*0.95, y-w));
painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
break;
}
case ssPlusSquare:
{
painter->drawLine(QLineF(x-w, y, x+w*0.95, y));
painter->drawLine(QLineF( x, y+w, x, y-w));
painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
break;
}
case ssCrossCircle:
{
painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.670, y+w*0.670));
painter->drawLine(QLineF(x-w*0.707, y+w*0.670, x+w*0.670, y-w*0.707));
painter->drawEllipse(QPointF(x, y), w, w);
break;
}
case ssPlusCircle:
{
painter->drawLine(QLineF(x-w, y, x+w, y));
painter->drawLine(QLineF( x, y+w, x, y-w));
painter->drawEllipse(QPointF(x, y), w, w);
break;
}
case ssPeace:
{
painter->drawLine(QLineF(x, y-w, x, y+w));
painter->drawLine(QLineF(x, y, x-w*0.707, y+w*0.707));
painter->drawLine(QLineF(x, y, x+w*0.707, y+w*0.707));
painter->drawEllipse(QPointF(x, y), w, w);
break;
}
case ssPixmap:
{
painter->drawPixmap(x-mPixmap.width()*0.5, y-mPixmap.height()*0.5, mPixmap);
break;
}
case ssCustom:
{
QTransform oldTransform = painter->transform();
painter->translate(x, y);
painter->scale(mSize/6.0, mSize/6.0);
painter->drawPath(mCustomPath);
painter->setTransform(oldTransform);
break;
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLayer
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPLayer
\brief A layer that may contain objects, to control the rendering order
The Layering system of QCustomPlot is the mechanism to control the rendering order of the
elements inside the plot.
It is based on the two classes QCPLayer and QCPLayerable. QCustomPlot holds an ordered list of
one or more instances of QCPLayer (see QCustomPlot::addLayer, QCustomPlot::layer,
QCustomPlot::moveLayer, etc.). When replotting, QCustomPlot goes through the list of layers
bottom to top and successively draws the layerables of the layers.
A QCPLayer contains an ordered list of QCPLayerable instances. QCPLayerable is an abstract base
class from which almost all visible objects derive, like axes, grids, graphs, items, etc.
Initially, QCustomPlot has five layers: "background", "grid", "main", "axes" and "legend" (in
that order). The top two layers "axes" and "legend" contain the default axes and legend, so they
will be drawn on top. In the middle, there is the "main" layer. It is initially empty and set as
the current layer (see QCustomPlot::setCurrentLayer). This means, all new plottables, items etc.
are created on this layer by default. Then comes the "grid" layer which contains the QCPGrid
instances (which belong tightly to QCPAxis, see \ref QCPAxis::grid). The Axis rect background
shall be drawn behind everything else, thus the default QCPAxisRect instance is placed on the
"background" layer. Of course, the layer affiliation of the individual objects can be changed as
required (\ref QCPLayerable::setLayer).
Controlling the ordering of objects is easy: Create a new layer in the position you want it to
be, e.g. above "main", with QCustomPlot::addLayer. Then set the current layer with
QCustomPlot::setCurrentLayer to that new layer and finally create the objects normally. They will
be placed on the new layer automatically, due to the current layer setting. Alternatively you
could have also ignored the current layer setting and just moved the objects with
QCPLayerable::setLayer to the desired layer after creating them.
It is also possible to move whole layers. For example, If you want the grid to be shown in front
of all plottables/items on the "main" layer, just move it above "main" with
QCustomPlot::moveLayer.
The rendering order within one layer is simply by order of creation or insertion. The item
created last (or added last to the layer), is drawn on top of all other objects on that layer.
When a layer is deleted, the objects on it are not deleted with it, but fall on the layer below
the deleted layer, see QCustomPlot::removeLayer.
*/
/* start documentation of inline functions */
/*! \fn QList<QCPLayerable*> QCPLayer::children() const
Returns a list of all layerables on this layer. The order corresponds to the rendering order:
layerables with higher indices are drawn above layerables with lower indices.
*/
/*! \fn int QCPLayer::index() const
Returns the index this layer has in the QCustomPlot. The index is the integer number by which this layer can be
accessed via \ref QCustomPlot::layer.
Layers with higher indices will be drawn above layers with lower indices.
*/
/* end documentation of inline functions */
/*!
Creates a new QCPLayer instance.
Normally you shouldn't directly instantiate layers, use \ref QCustomPlot::addLayer instead.
\warning It is not checked that \a layerName is actually a unique layer name in \a parentPlot.
This check is only performed by \ref QCustomPlot::addLayer.
*/
QCPLayer::QCPLayer(QCustomPlot *parentPlot, const QString &layerName) :
QObject(parentPlot),
mParentPlot(parentPlot),
mName(layerName),
mIndex(-1) // will be set to a proper value by the QCustomPlot layer creation function
{
// Note: no need to make sure layerName is unique, because layer
// management is done with QCustomPlot functions.
}
QCPLayer::~QCPLayer()
{
// If child layerables are still on this layer, detach them, so they don't try to reach back to this
// then invalid layer once they get deleted/moved themselves. This only happens when layers are deleted
// directly, like in the QCustomPlot destructor. (The regular layer removal procedure for the user is to
// call QCustomPlot::removeLayer, which moves all layerables off this layer before deleting it.)
while (!mChildren.isEmpty())
mChildren.last()->setLayer(0); // removes itself from mChildren via removeChild()
if (mParentPlot->currentLayer() == this)
qDebug() << Q_FUNC_INFO << "The parent plot's mCurrentLayer will be a dangling pointer. Should have been set to a valid layer or 0 beforehand.";
}
/*! \internal
Adds the \a layerable to the list of this layer. If \a prepend is set to true, the layerable will
be prepended to the list, i.e. be drawn beneath the other layerables already in the list.
This function does not change the \a mLayer member of \a layerable to this layer. (Use
QCPLayerable::setLayer to change the layer of an object, not this function.)
\see removeChild
*/
void QCPLayer::addChild(QCPLayerable *layerable, bool prepend)
{
if (!mChildren.contains(layerable))
{
if (prepend)
mChildren.prepend(layerable);
else
mChildren.append(layerable);
} else
qDebug() << Q_FUNC_INFO << "layerable is already child of this layer" << reinterpret_cast<quintptr>(layerable);
}
/*! \internal
Removes the \a layerable from the list of this layer.
This function does not change the \a mLayer member of \a layerable. (Use QCPLayerable::setLayer
to change the layer of an object, not this function.)
\see addChild
*/
void QCPLayer::removeChild(QCPLayerable *layerable)
{
if (!mChildren.removeOne(layerable))
qDebug() << Q_FUNC_INFO << "layerable is not child of this layer" << reinterpret_cast<quintptr>(layerable);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLayerable
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPLayerable
\brief Base class for all drawable objects
This is the abstract base class most visible objects derive from, e.g. plottables, axes, grid
etc.
Every layerable is on a layer (QCPLayer) which allows controlling the rendering order by stacking
the layers accordingly.
For details about the layering mechanism, see the QCPLayer documentation.
*/
/* start documentation of inline functions */
/*! \fn QCPLayerable *QCPLayerable::parentLayerable() const
Returns the parent layerable of this layerable. The parent layerable is used to provide
visibility hierarchies in conjunction with the method \ref realVisibility. This way, layerables
only get drawn if their parent layerables are visible, too.
Note that a parent layerable is not necessarily also the QObject parent for memory management.
Further, a layerable doesn't always have a parent layerable, so this function may return 0.
A parent layerable is set implicitly with when placed inside layout elements and doesn't need to be
set manually by the user.
*/
/* end documentation of inline functions */
/* start documentation of pure virtual functions */
/*! \fn virtual void QCPLayerable::applyDefaultAntialiasingHint(QCPPainter *painter) const = 0
\internal
This function applies the default antialiasing setting to the specified \a painter, using the
function \ref applyAntialiasingHint. It is the antialiasing state the painter is put in, when
\ref draw is called on the layerable. If the layerable has multiple entities whose antialiasing
setting may be specified individually, this function should set the antialiasing state of the
most prominent entity. In this case however, the \ref draw function usually calls the specialized
versions of this function before drawing each entity, effectively overriding the setting of the
default antialiasing hint.
<b>First example:</b> QCPGraph has multiple entities that have an antialiasing setting: The graph
line, fills, scatters and error bars. Those can be configured via QCPGraph::setAntialiased,
QCPGraph::setAntialiasedFill, QCPGraph::setAntialiasedScatters etc. Consequently, there isn't
only the QCPGraph::applyDefaultAntialiasingHint function (which corresponds to the graph line's
antialiasing), but specialized ones like QCPGraph::applyFillAntialiasingHint and
QCPGraph::applyScattersAntialiasingHint. So before drawing one of those entities, QCPGraph::draw
calls the respective specialized applyAntialiasingHint function.
<b>Second example:</b> QCPItemLine consists only of a line so there is only one antialiasing
setting which can be controlled with QCPItemLine::setAntialiased. (This function is inherited by
all layerables. The specialized functions, as seen on QCPGraph, must be added explicitly to the
respective layerable subclass.) Consequently it only has the normal
QCPItemLine::applyDefaultAntialiasingHint. The \ref QCPItemLine::draw function doesn't need to
care about setting any antialiasing states, because the default antialiasing hint is already set
on the painter when the \ref draw function is called, and that's the state it wants to draw the
line with.
*/
/*! \fn virtual void QCPLayerable::draw(QCPPainter *painter) const = 0
\internal
This function draws the layerable with the specified \a painter. It is only called by
QCustomPlot, if the layerable is visible (\ref setVisible).
Before this function is called, the painter's antialiasing state is set via \ref
applyDefaultAntialiasingHint, see the documentation there. Further, the clipping rectangle was
set to \ref clipRect.
*/
/* end documentation of pure virtual functions */
/*!
Creates a new QCPLayerable instance.
Since QCPLayerable is an abstract base class, it can't be instantiated directly. Use one of the
derived classes.
If \a plot is provided, it automatically places itself on the layer named \a targetLayer. If \a
targetLayer is an empty string, it places itself on the current layer of the plot (see \ref
QCustomPlot::setCurrentLayer).
It is possible to provide 0 as \a plot. In that case, you should assign a parent plot at a later
time with \ref initializeParentPlot.
The layerable's parent layerable is set to \a parentLayerable, if provided. Direct layerable parents
are mainly used to control visibility in a hierarchy of layerables. This means a layerable is
only drawn, if all its ancestor layerables are also visible. Note that \a parentLayerable does
not become the QObject-parent (for memory management) of this layerable, \a plot does.
*/
QCPLayerable::QCPLayerable(QCustomPlot *plot, QString targetLayer, QCPLayerable *parentLayerable) :
QObject(plot),
mVisible(true),
mParentPlot(plot),
mParentLayerable(parentLayerable),
mLayer(0),
mAntialiased(true)
{
if (mParentPlot)
{
if (targetLayer.isEmpty())
setLayer(mParentPlot->currentLayer());
else if (!setLayer(targetLayer))
qDebug() << Q_FUNC_INFO << "setting QCPlayerable initial layer to" << targetLayer << "failed.";
}
}
QCPLayerable::~QCPLayerable()
{
if (mLayer)
{
mLayer->removeChild(this);
mLayer = 0;
}
}
/*!
Sets the visibility of this layerable object. If an object is not visible, it will not be drawn
on the QCustomPlot surface, and user interaction with it (e.g. click and selection) is not
possible.
*/
void QCPLayerable::setVisible(bool on)
{
mVisible = on;
}
/*!
Sets the \a layer of this layerable object. The object will be placed on top of the other objects
already on \a layer.
Returns true on success, i.e. if \a layer is a valid layer.
*/
bool QCPLayerable::setLayer(QCPLayer *layer)
{
return moveToLayer(layer, false);
}
/*! \overload
Sets the layer of this layerable object by name
Returns true on success, i.e. if \a layerName is a valid layer name.
*/
bool QCPLayerable::setLayer(const QString &layerName)
{
if (!mParentPlot)
{
qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set";
return false;
}
if (QCPLayer *layer = mParentPlot->layer(layerName))
{
return setLayer(layer);
} else
{
qDebug() << Q_FUNC_INFO << "there is no layer with name" << layerName;
return false;
}
}
/*!
Sets whether this object will be drawn antialiased or not.
Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and
QCustomPlot::setNotAntialiasedElements.
*/
void QCPLayerable::setAntialiased(bool enabled)
{
mAntialiased = enabled;
}
/*!
Returns whether this layerable is visible, taking possible direct layerable parent visibility
into account. This is the method that is consulted to decide whether a layerable shall be drawn
or not.
If this layerable has a direct layerable parent (usually set via hierarchies implemented in
subclasses, like in the case of QCPLayoutElement), this function returns true only if this
layerable has its visibility set to true and the parent layerable's \ref realVisibility returns
true.
If this layerable doesn't have a direct layerable parent, returns the state of this layerable's
visibility.
*/
bool QCPLayerable::realVisibility() const
{
return mVisible && (!mParentLayerable || mParentLayerable.data()->realVisibility());
}
/*!
This function is used to decide whether a click hits a layerable object or not.
\a pos is a point in pixel coordinates on the QCustomPlot surface. This function returns the
shortest pixel distance of this point to the object. If the object is either invisible or the
distance couldn't be determined, -1.0 is returned. Further, if \a onlySelectable is true and the
object is not selectable, -1.0 is returned, too.
If the item is represented not by single lines but by an area like QCPItemRect or QCPItemText, a
click inside the area returns a constant value greater zero (typically the selectionTolerance of
the parent QCustomPlot multiplied by 0.99). If the click lies outside the area, this function
returns -1.0.
Providing a constant value for area objects allows selecting line objects even when they are
obscured by such area objects, by clicking close to the lines (i.e. closer than
0.99*selectionTolerance).
The actual setting of the selection state is not done by this function. This is handled by the
parent QCustomPlot when the mouseReleaseEvent occurs, and the finally selected object is notified
via the selectEvent/deselectEvent methods.
\a details is an optional output parameter. Every layerable subclass may place any information
in \a details. This information will be passed to \ref selectEvent when the parent QCustomPlot
decides on the basis of this selectTest call, that the object was successfully selected. The
subsequent call to \ref selectEvent will carry the \a details. This is useful for multi-part
objects (like QCPAxis). This way, a possibly complex calculation to decide which part was clicked
is only done once in \ref selectTest. The result (i.e. the actually clicked part) can then be
placed in \a details. So in the subsequent \ref selectEvent, the decision which part was
selected doesn't have to be done a second time for a single selection operation.
You may pass 0 as \a details to indicate that you are not interested in those selection details.
\see selectEvent, deselectEvent, QCustomPlot::setInteractions
*/
double QCPLayerable::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(pos)
Q_UNUSED(onlySelectable)
Q_UNUSED(details)
return -1.0;
}
/*! \internal
Sets the parent plot of this layerable. Use this function once to set the parent plot if you have
passed 0 in the constructor. It can not be used to move a layerable from one QCustomPlot to
another one.
Note that, unlike when passing a non-null parent plot in the constructor, this function does not
make \a parentPlot the QObject-parent of this layerable. If you want this, call
QObject::setParent(\a parentPlot) in addition to this function.
Further, you will probably want to set a layer (\ref setLayer) after calling this function, to
make the layerable appear on the QCustomPlot.
The parent plot change will be propagated to subclasses via a call to \ref parentPlotInitialized
so they can react accordingly (e.g. also initialize the parent plot of child layerables, like
QCPLayout does).
*/
void QCPLayerable::initializeParentPlot(QCustomPlot *parentPlot)
{
if (mParentPlot)
{
qDebug() << Q_FUNC_INFO << "called with mParentPlot already initialized";
return;
}
if (!parentPlot)
qDebug() << Q_FUNC_INFO << "called with parentPlot zero";
mParentPlot = parentPlot;
parentPlotInitialized(mParentPlot);
}
/*! \internal
Sets the parent layerable of this layerable to \a parentLayerable. Note that \a parentLayerable does not
become the QObject-parent (for memory management) of this layerable.
The parent layerable has influence on the return value of the \ref realVisibility method. Only
layerables with a fully visible parent tree will return true for \ref realVisibility, and thus be
drawn.
\see realVisibility
*/
void QCPLayerable::setParentLayerable(QCPLayerable *parentLayerable)
{
mParentLayerable = parentLayerable;
}
/*! \internal
Moves this layerable object to \a layer. If \a prepend is true, this object will be prepended to
the new layer's list, i.e. it will be drawn below the objects already on the layer. If it is
false, the object will be appended.
Returns true on success, i.e. if \a layer is a valid layer.
*/
bool QCPLayerable::moveToLayer(QCPLayer *layer, bool prepend)
{
if (layer && !mParentPlot)
{
qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set";
return false;
}
if (layer && layer->parentPlot() != mParentPlot)
{
qDebug() << Q_FUNC_INFO << "layer" << layer->name() << "is not in same QCustomPlot as this layerable";
return false;
}
if (mLayer)
mLayer->removeChild(this);
mLayer = layer;
if (mLayer)
mLayer->addChild(this, prepend);
return true;
}
/*! \internal
Sets the QCPainter::setAntialiasing state on the provided \a painter, depending on the \a
localAntialiased value as well as the overrides \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements. Which override enum this function takes into account is
controlled via \a overrideElement.
*/
void QCPLayerable::applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const
{
if (mParentPlot && mParentPlot->notAntialiasedElements().testFlag(overrideElement))
painter->setAntialiasing(false);
else if (mParentPlot && mParentPlot->antialiasedElements().testFlag(overrideElement))
painter->setAntialiasing(true);
else
painter->setAntialiasing(localAntialiased);
}
/*! \internal
This function is called by \ref initializeParentPlot, to allow subclasses to react on the setting
of a parent plot. This is the case when 0 was passed as parent plot in the constructor, and the
parent plot is set at a later time.
For example, QCPLayoutElement/QCPLayout hierarchies may be created independently of any
QCustomPlot at first. When they are then added to a layout inside the QCustomPlot, the top level
element of the hierarchy gets its parent plot initialized with \ref initializeParentPlot. To
propagate the parent plot to all the children of the hierarchy, the top level element then uses
this function to pass the parent plot on to its child elements.
The default implementation does nothing.
\see initializeParentPlot
*/
void QCPLayerable::parentPlotInitialized(QCustomPlot *parentPlot)
{
Q_UNUSED(parentPlot)
}
/*! \internal
Returns the selection category this layerable shall belong to. The selection category is used in
conjunction with \ref QCustomPlot::setInteractions to control which objects are selectable and
which aren't.
Subclasses that don't fit any of the normal \ref QCP::Interaction values can use \ref
QCP::iSelectOther. This is what the default implementation returns.
\see QCustomPlot::setInteractions
*/
QCP::Interaction QCPLayerable::selectionCategory() const
{
return QCP::iSelectOther;
}
/*! \internal
Returns the clipping rectangle of this layerable object. By default, this is the viewport of the
parent QCustomPlot. Specific subclasses may reimplement this function to provide different
clipping rects.
The returned clipping rect is set on the painter before the draw function of the respective
object is called.
*/
QRect QCPLayerable::clipRect() const
{
if (mParentPlot)
return mParentPlot->viewport();
else
return QRect();
}
/*! \internal
This event is called when the layerable shall be selected, as a consequence of a click by the
user. Subclasses should react to it by setting their selection state appropriately. The default
implementation does nothing.
\a event is the mouse event that caused the selection. \a additive indicates, whether the user
was holding the multi-select-modifier while performing the selection (see \ref
QCustomPlot::setMultiSelectModifier). if \a additive is true, the selection state must be toggled
(i.e. become selected when unselected and unselected when selected).
Every selectEvent is preceded by a call to \ref selectTest, which has returned positively (i.e.
returned a value greater than 0 and less than the selection tolerance of the parent QCustomPlot).
The \a details data you output from \ref selectTest is fed back via \a details here. You may
use it to transport any kind of information from the selectTest to the possibly subsequent
selectEvent. Usually \a details is used to transfer which part was clicked, if it is a layerable
that has multiple individually selectable parts (like QCPAxis). This way selectEvent doesn't need
to do the calculation again to find out which part was actually clicked.
\a selectionStateChanged is an output parameter. If the pointer is non-null, this function must
set the value either to true or false, depending on whether the selection state of this layerable
was actually changed. For layerables that only are selectable as a whole and not in parts, this
is simple: if \a additive is true, \a selectionStateChanged must also be set to true, because the
selection toggles. If \a additive is false, \a selectionStateChanged is only set to true, if the
layerable was previously unselected and now is switched to the selected state.
\see selectTest, deselectEvent
*/
void QCPLayerable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
Q_UNUSED(event)
Q_UNUSED(additive)
Q_UNUSED(details)
Q_UNUSED(selectionStateChanged)
}
/*! \internal
This event is called when the layerable shall be deselected, either as consequence of a user
interaction or a call to \ref QCustomPlot::deselectAll. Subclasses should react to it by
unsetting their selection appropriately.
just as in \ref selectEvent, the output parameter \a selectionStateChanged (if non-null), must
return true or false when the selection state of this layerable has changed or not changed,
respectively.
\see selectTest, selectEvent
*/
void QCPLayerable::deselectEvent(bool *selectionStateChanged)
{
Q_UNUSED(selectionStateChanged)
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPRange
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPRange
\brief Represents the range an axis is encompassing.
contains a \a lower and \a upper double value and provides convenience input, output and
modification functions.
\see QCPAxis::setRange
*/
/*!
Minimum range size (\a upper - \a lower) the range changing functions will accept. Smaller
intervals would cause errors due to the 11-bit exponent of double precision numbers,
corresponding to a minimum magnitude of roughly 1e-308.
\see validRange, maxRange
*/
const double QCPRange::minRange = 1e-280;
/*!
Maximum values (negative and positive) the range will accept in range-changing functions.
Larger absolute values would cause errors due to the 11-bit exponent of double precision numbers,
corresponding to a maximum magnitude of roughly 1e308.
Since the number of planck-volumes in the entire visible universe is only ~1e183, this should
be enough.
\see validRange, minRange
*/
const double QCPRange::maxRange = 1e250;
/*!
Constructs a range with \a lower and \a upper set to zero.
*/
QCPRange::QCPRange() :
lower(0),
upper(0)
{
}
/*! \overload
Constructs a range with the specified \a lower and \a upper values.
*/
QCPRange::QCPRange(double lower, double upper) :
lower(lower),
upper(upper)
{
normalize();
}
/*!
Returns the size of the range, i.e. \a upper-\a lower
*/
double QCPRange::size() const
{
return upper-lower;
}
/*!
Returns the center of the range, i.e. (\a upper+\a lower)*0.5
*/
double QCPRange::center() const
{
return (upper+lower)*0.5;
}
/*!
Makes sure \a lower is numerically smaller than \a upper. If this is not the case, the values
are swapped.
*/
void QCPRange::normalize()
{
if (lower > upper)
qSwap(lower, upper);
}
/*!
Expands this range such that \a otherRange is contained in the new range. It is assumed that both
this range and \a otherRange are normalized (see \ref normalize).
If \a otherRange is already inside the current range, this function does nothing.
\see expanded
*/
void QCPRange::expand(const QCPRange &otherRange)
{
if (lower > otherRange.lower)
lower = otherRange.lower;
if (upper < otherRange.upper)
upper = otherRange.upper;
}
/*!
Returns an expanded range that contains this and \a otherRange. It is assumed that both this
range and \a otherRange are normalized (see \ref normalize).
\see expand
*/
QCPRange QCPRange::expanded(const QCPRange &otherRange) const
{
QCPRange result = *this;
result.expand(otherRange);
return result;
}
/*!
Returns a sanitized version of the range. Sanitized means for logarithmic scales, that
the range won't span the positive and negative sign domain, i.e. contain zero. Further
\a lower will always be numerically smaller (or equal) to \a upper.
If the original range does span positive and negative sign domains or contains zero,
the returned range will try to approximate the original range as good as possible.
If the positive interval of the original range is wider than the negative interval, the
returned range will only contain the positive interval, with lower bound set to \a rangeFac or
\a rangeFac *\a upper, whichever is closer to zero. Same procedure is used if the negative interval
is wider than the positive interval, this time by changing the \a upper bound.
*/
QCPRange QCPRange::sanitizedForLogScale() const
{
double rangeFac = 1e-3;
QCPRange sanitizedRange(lower, upper);
sanitizedRange.normalize();
// can't have range spanning negative and positive values in log plot, so change range to fix it
//if (qFuzzyCompare(sanitizedRange.lower+1, 1) && !qFuzzyCompare(sanitizedRange.upper+1, 1))
if (sanitizedRange.lower == 0.0 && sanitizedRange.upper != 0.0)
{
// case lower is 0
if (rangeFac < sanitizedRange.upper*rangeFac)
sanitizedRange.lower = rangeFac;
else
sanitizedRange.lower = sanitizedRange.upper*rangeFac;
} //else if (!qFuzzyCompare(lower+1, 1) && qFuzzyCompare(upper+1, 1))
else if (sanitizedRange.lower != 0.0 && sanitizedRange.upper == 0.0)
{
// case upper is 0
if (-rangeFac > sanitizedRange.lower*rangeFac)
sanitizedRange.upper = -rangeFac;
else
sanitizedRange.upper = sanitizedRange.lower*rangeFac;
} else if (sanitizedRange.lower < 0 && sanitizedRange.upper > 0)
{
// find out whether negative or positive interval is wider to decide which sign domain will be chosen
if (-sanitizedRange.lower > sanitizedRange.upper)
{
// negative is wider, do same as in case upper is 0
if (-rangeFac > sanitizedRange.lower*rangeFac)
sanitizedRange.upper = -rangeFac;
else
sanitizedRange.upper = sanitizedRange.lower*rangeFac;
} else
{
// positive is wider, do same as in case lower is 0
if (rangeFac < sanitizedRange.upper*rangeFac)
sanitizedRange.lower = rangeFac;
else
sanitizedRange.lower = sanitizedRange.upper*rangeFac;
}
}
// due to normalization, case lower>0 && upper<0 should never occur, because that implies upper<lower
return sanitizedRange;
}
/*!
Returns a sanitized version of the range. Sanitized means for linear scales, that
\a lower will always be numerically smaller (or equal) to \a upper.
*/
QCPRange QCPRange::sanitizedForLinScale() const
{
QCPRange sanitizedRange(lower, upper);
sanitizedRange.normalize();
return sanitizedRange;
}
/*!
Returns true when \a value lies within or exactly on the borders of the range.
*/
bool QCPRange::contains(double value) const
{
return value >= lower && value <= upper;
}
/*!
Checks, whether the specified range is within valid bounds, which are defined
as QCPRange::maxRange and QCPRange::minRange.
A valid range means:
\li range bounds within -maxRange and maxRange
\li range size above minRange
\li range size below maxRange
*/
bool QCPRange::validRange(double lower, double upper)
{
/*
return (lower > -maxRange &&
upper < maxRange &&
qAbs(lower-upper) > minRange &&
(lower < -minRange || lower > minRange) &&
(upper < -minRange || upper > minRange));
*/
return (lower > -maxRange &&
upper < maxRange &&
qAbs(lower-upper) > minRange &&
qAbs(lower-upper) < maxRange);
}
/*!
\overload
Checks, whether the specified range is within valid bounds, which are defined
as QCPRange::maxRange and QCPRange::minRange.
A valid range means:
\li range bounds within -maxRange and maxRange
\li range size above minRange
\li range size below maxRange
*/
bool QCPRange::validRange(const QCPRange &range)
{
/*
return (range.lower > -maxRange &&
range.upper < maxRange &&
qAbs(range.lower-range.upper) > minRange &&
qAbs(range.lower-range.upper) < maxRange &&
(range.lower < -minRange || range.lower > minRange) &&
(range.upper < -minRange || range.upper > minRange));
*/
return (range.lower > -maxRange &&
range.upper < maxRange &&
qAbs(range.lower-range.upper) > minRange &&
qAbs(range.lower-range.upper) < maxRange);
}
/*! \page thelayoutsystem The Layout System
The layout system is responsible for positioning and scaling layout elements such as axis rects,
legends and plot titles in a QCustomPlot.
\section layoutsystem-classesandmechanisms Classes and mechanisms
The layout system is based on the abstract base class \ref QCPLayoutElement. All objects that
take part in the layout system derive from this class, either directly or indirectly.
Since QCPLayoutElement itself derives from \ref QCPLayerable, a layout element may draw its own
content. However, it is perfectly possible for a layout element to only serve as a structuring
and/or positioning element, not drawing anything on its own.
\subsection layoutsystem-rects Rects of a layout element
A layout element is a rectangular object described by two rects: the inner rect (\ref
QCPLayoutElement::rect) and the outer rect (\ref QCPLayoutElement::setOuterRect). The inner rect
is calculated automatically by applying the margin (\ref QCPLayoutElement::setMargins) inward
from the outer rect. The inner rect is meant for main content while the margin area may either be
left blank or serve for displaying peripheral graphics. For example, \ref QCPAxisRect positions
the four main axes at the sides of the inner rect, so graphs end up inside it and the axis labels
and tick labels are in the margin area.
\subsection layoutsystem-margins Margins
Each layout element may provide a mechanism to automatically determine its margins. Internally,
this is realized with the \ref QCPLayoutElement::calculateAutoMargin function which takes a \ref
QCP::MarginSide and returns an integer value which represents the ideal margin for the specified
side. The automatic margin will be used on the sides specified in \ref
QCPLayoutElement::setAutoMargins. By default, it is set to \ref QCP::msAll meaning automatic
margin calculation is enabled for all four sides. In this case, a minimum margin may be set with
\ref QCPLayoutElement::setMinimumMargins, to prevent the automatic margin mechanism from setting
margins smaller than desired for a specific situation. If automatic margin calculation is unset
for a specific side, the margin of that side can be controlled directy via \ref
QCPLayoutElement::setMargins.
If multiple layout ements are arranged next to or beneath each other, it may be desirable to
align their inner rects on certain sides. Since they all might have different automatic margins,
this usually isn't the case. The class \ref QCPMarginGroup and \ref
QCPLayoutElement::setMarginGroup fix this by allowing to synchronize multiple margins. See the
documentation there for details.
\subsection layoutsystem-layout Layouts
As mentioned, a QCPLayoutElement may have an arbitrary number of child layout elements and in
princple can have the only purpose to manage/arrange those child elements. This is what the
subclass \ref QCPLayout specializes on. It is a QCPLayoutElement itself but has no visual
representation. It defines an interface to add, remove and manage child layout elements.
QCPLayout isn't a usable layout though, it's an abstract base class that concrete layouts derive
from, like \ref QCPLayoutGrid which arranges its child elements in a grid and \ref QCPLayoutInset
which allows placing child elements freely inside its rect.
Since a QCPLayout is a layout element itself, it may be placed inside other layouts. This way,
complex hierarchies may be created, offering very flexible arrangements.
<div style="text-align:center">
<div style="display:inline-block; margin-left:auto; margin-right:auto">\image html LayoutsystemSketch0.png ""</div>
<div style="display:inline-block; margin-left:auto; margin-right:auto">\image html LayoutsystemSketch1.png ""</div>
<div style="clear:both"></div>
<div style="display:inline-block; max-width:1000px; text-align:justify">
Sketch of the default QCPLayoutGrid accessible via \ref QCustomPlot::plotLayout. The left image
shows the outer and inner rect of the grid layout itself while the right image shows how two
child layout elements are placed inside the grid layout next to each other in cells (0, 0) and
(0, 1).
</div>
</div>
\subsection layoutsystem-plotlayout The top level plot layout
Every QCustomPlot has one top level layout of type \ref QCPLayoutGrid. It is accessible via \ref
QCustomPlot::plotLayout and contains (directly or indirectly via other sub-layouts) all layout
elements in the QCustomPlot. By default, this top level grid layout contains a single cell which
holds the main axis rect.
\subsection layoutsystem-examples Examples
<b>Adding a plot title</b> is a typical and simple case to demonstrate basic workings of the layout system.
\code
// first we create and prepare a plot title layout element:
QCPPlotTitle *title = new QCPPlotTitle(customPlot);
title->setText("Plot Title Example");
title->setFont(QFont("sans", 12, QFont::Bold));
// then we add it to the main plot layout:
customPlot->plotLayout()->insertRow(0); // insert an empty row above the axis rect
customPlot->plotLayout()->addElement(0, 0, title); // insert the title in the empty cell we just created
\endcode
\image html layoutsystem-addingplottitle.png
<b>Arranging multiple axis rects</b> actually is the central purpose of the layout system.
\code
customPlot->plotLayout()->clear(); // let's start from scratch and remove the default axis rect
// add the first axis rect in second row (row index 1):
customPlot->plotLayout()->addElement(1, 0, new QCPAxisRect(customPlot));
// create a sub layout that we'll place in first row:
QCPLayoutGrid *subLayout = new QCPLayoutGrid;
customPlot->plotLayout()->addElement(0, 0, subLayout);
// add two axis rects in the sub layout next to eachother:
subLayout->addElement(0, 0, new QCPAxisRect(customPlot));
subLayout->addElement(0, 1, new QCPAxisRect(customPlot));
subLayout->setColumnStretchFactor(0, 3); // left axis rect shall have 60% of width
subLayout->setColumnStretchFactor(1, 2); // right one only 40% (3:2 = 60:40)
\endcode
\image html layoutsystem-multipleaxisrects.png
*/
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPMarginGroup
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPMarginGroup
\brief A margin group allows synchronization of margin sides if working with multiple layout elements.
QCPMarginGroup allows you to tie a margin side of two or more layout elements together, such that
they will all have the same size, based on the largest required margin in the group.
\n
\image html QCPMarginGroup.png "Demonstration of QCPMarginGroup"
\n
In certain situations it is desirable that margins at specific sides are synchronized across
layout elements. For example, if one QCPAxisRect is below another one in a grid layout, it will
provide a cleaner look to the user if the left and right margins of the two axis rects are of the
same size. The left axis of the top axis rect will then be at the same horizontal position as the
left axis of the lower axis rect, making them appear aligned. The same applies for the right
axes. This is what QCPMarginGroup makes possible.
To add/remove a specific side of a layout element to/from a margin group, use the \ref
QCPLayoutElement::setMarginGroup method. To completely break apart the margin group, either call
\ref clear, or just delete the margin group.
\section QCPMarginGroup-example Example
First create a margin group:
\code
QCPMarginGroup *group = new QCPMarginGroup(customPlot);
\endcode
Then set this group on the layout element sides:
\code
customPlot->axisRect(0)->setMarginGroup(QCP::msLeft|QCP::msRight, group);
customPlot->axisRect(1)->setMarginGroup(QCP::msLeft|QCP::msRight, group);
\endcode
Here, we've used the first two axis rects of the plot and synchronized their left margins with
each other and their right margins with each other.
*/
/* start documentation of inline functions */
/*! \fn QList<QCPLayoutElement*> QCPMarginGroup::elements(QCP::MarginSide side) const
Returns a list of all layout elements that have their margin \a side associated with this margin
group.
*/
/* end documentation of inline functions */
/*!
Creates a new QCPMarginGroup instance in \a parentPlot.
*/
QCPMarginGroup::QCPMarginGroup(QCustomPlot *parentPlot) :
QObject(parentPlot),
mParentPlot(parentPlot)
{
mChildren.insert(QCP::msLeft, QList<QCPLayoutElement*>());
mChildren.insert(QCP::msRight, QList<QCPLayoutElement*>());
mChildren.insert(QCP::msTop, QList<QCPLayoutElement*>());
mChildren.insert(QCP::msBottom, QList<QCPLayoutElement*>());
}
QCPMarginGroup::~QCPMarginGroup()
{
clear();
}
/*!
Returns whether this margin group is empty. If this function returns true, no layout elements use
this margin group to synchronize margin sides.
*/
bool QCPMarginGroup::isEmpty() const
{
QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*> > it(mChildren);
while (it.hasNext())
{
it.next();
if (!it.value().isEmpty())
return false;
}
return true;
}
/*!
Clears this margin group. The synchronization of the margin sides that use this margin group is
lifted and they will use their individual margin sizes again.
*/
void QCPMarginGroup::clear()
{
// make all children remove themselves from this margin group:
QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*> > it(mChildren);
while (it.hasNext())
{
it.next();
const QList<QCPLayoutElement*> elements = it.value();
for (int i=elements.size()-1; i>=0; --i)
elements.at(i)->setMarginGroup(it.key(), 0); // removes itself from mChildren via removeChild
}
}
/*! \internal
Returns the synchronized common margin for \a side. This is the margin value that will be used by
the layout element on the respective side, if it is part of this margin group.
The common margin is calculated by requesting the automatic margin (\ref
QCPLayoutElement::calculateAutoMargin) of each element associated with \a side in this margin
group, and choosing the largest returned value. (QCPLayoutElement::minimumMargins is taken into
account, too.)
*/
int QCPMarginGroup::commonMargin(QCP::MarginSide side) const
{
// query all automatic margins of the layout elements in this margin group side and find maximum:
int result = 0;
const QList<QCPLayoutElement*> elements = mChildren.value(side);
for (int i=0; i<elements.size(); ++i)
{
if (!elements.at(i)->autoMargins().testFlag(side))
continue;
int m = qMax(elements.at(i)->calculateAutoMargin(side), QCP::getMarginValue(elements.at(i)->minimumMargins(), side));
if (m > result)
result = m;
}
return result;
}
/*! \internal
Adds \a element to the internal list of child elements, for the margin \a side.
This function does not modify the margin group property of \a element.
*/
void QCPMarginGroup::addChild(QCP::MarginSide side, QCPLayoutElement *element)
{
if (!mChildren[side].contains(element))
mChildren[side].append(element);
else
qDebug() << Q_FUNC_INFO << "element is already child of this margin group side" << reinterpret_cast<quintptr>(element);
}
/*! \internal
Removes \a element from the internal list of child elements, for the margin \a side.
This function does not modify the margin group property of \a element.
*/
void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element)
{
if (!mChildren[side].removeOne(element))
qDebug() << Q_FUNC_INFO << "element is not child of this margin group side" << reinterpret_cast<quintptr>(element);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLayoutElement
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPLayoutElement
\brief The abstract base class for all objects that form \ref thelayoutsystem "the layout system".
This is an abstract base class. As such, it can't be instantiated directly, rather use one of its subclasses.
A Layout element is a rectangular object which can be placed in layouts. It has an outer rect
(QCPLayoutElement::outerRect) and an inner rect (\ref QCPLayoutElement::rect). The difference
between outer and inner rect is called its margin. The margin can either be set to automatic or
manual (\ref setAutoMargins) on a per-side basis. If a side is set to manual, that margin can be
set explicitly with \ref setMargins and will stay fixed at that value. If it's set to automatic,
the layout element subclass will control the value itself (via \ref calculateAutoMargin).
Layout elements can be placed in layouts (base class QCPLayout) like QCPLayoutGrid. The top level
layout is reachable via \ref QCustomPlot::plotLayout, and is a \ref QCPLayoutGrid. Since \ref
QCPLayout itself derives from \ref QCPLayoutElement, layouts can be nested.
Thus in QCustomPlot one can divide layout elements into two categories: The ones that are
invisible by themselves, because they don't draw anything. Their only purpose is to manage the
position and size of other layout elements. This category of layout elements usually use
QCPLayout as base class. Then there is the category of layout elements which actually draw
something. For example, QCPAxisRect, QCPLegend and QCPPlotTitle are of this category. This does
not necessarily mean that the latter category can't have child layout elements. QCPLegend for
instance, actually derives from QCPLayoutGrid and the individual legend items are child layout
elements in the grid layout.
*/
/* start documentation of inline functions */
/*! \fn QCPLayout *QCPLayoutElement::layout() const
Returns the parent layout of this layout element.
*/
/*! \fn QRect QCPLayoutElement::rect() const
Returns the inner rect of this layout element. The inner rect is the outer rect (\ref
setOuterRect) shrinked by the margins (\ref setMargins, \ref setAutoMargins).
In some cases, the area between outer and inner rect is left blank. In other cases the margin
area is used to display peripheral graphics while the main content is in the inner rect. This is
where automatic margin calculation becomes interesting because it allows the layout element to
adapt the margins to the peripheral graphics it wants to draw. For example, \ref QCPAxisRect
draws the axis labels and tick labels in the margin area, thus needs to adjust the margins (if
\ref setAutoMargins is enabled) according to the space required by the labels of the axes.
*/
/*! \fn virtual void QCPLayoutElement::mousePressEvent(QMouseEvent *event)
This event is called, if the mouse was pressed while being inside the outer rect of this layout
element.
*/
/*! \fn virtual void QCPLayoutElement::mouseMoveEvent(QMouseEvent *event)
This event is called, if the mouse is moved inside the outer rect of this layout element.
*/
/*! \fn virtual void QCPLayoutElement::mouseReleaseEvent(QMouseEvent *event)
This event is called, if the mouse was previously pressed inside the outer rect of this layout
element and is now released.
*/
/*! \fn virtual void QCPLayoutElement::mouseDoubleClickEvent(QMouseEvent *event)
This event is called, if the mouse is double-clicked inside the outer rect of this layout
element.
*/
/*! \fn virtual void QCPLayoutElement::wheelEvent(QWheelEvent *event)
This event is called, if the mouse wheel is scrolled while the cursor is inside the rect of this
layout element.
*/
/* end documentation of inline functions */
/*!
Creates an instance of QCPLayoutElement and sets default values.
*/
QCPLayoutElement::QCPLayoutElement(QCustomPlot *parentPlot) :
QCPLayerable(parentPlot), // parenthood is changed as soon as layout element gets inserted into a layout (except for top level layout)
mParentLayout(0),
mMinimumSize(),
mMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX),
mRect(0, 0, 0, 0),
mOuterRect(0, 0, 0, 0),
mMargins(0, 0, 0, 0),
mMinimumMargins(0, 0, 0, 0),
mAutoMargins(QCP::msAll)
{
}
QCPLayoutElement::~QCPLayoutElement()
{
setMarginGroup(QCP::msAll, 0); // unregister at margin groups, if there are any
// unregister at layout:
if (qobject_cast<QCPLayout*>(mParentLayout)) // the qobject_cast is just a safeguard in case the layout forgets to call clear() in its dtor and this dtor is called by QObject dtor
mParentLayout->take(this);
}
/*!
Sets the outer rect of this layout element. If the layout element is inside a layout, the layout
sets the position and size of this layout element using this function.
Calling this function externally has no effect, since the layout will overwrite any changes to
the outer rect upon the next replot.
The layout element will adapt its inner \ref rect by applying the margins inward to the outer rect.
\see rect
*/
void QCPLayoutElement::setOuterRect(const QRect &rect)
{
if (mOuterRect != rect)
{
mOuterRect = rect;
mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom());
}
}
/*!
Sets the margins of this layout element. If \ref setAutoMargins is disabled for some or all
sides, this function is used to manually set the margin on those sides. Sides that are still set
to be handled automatically are ignored and may have any value in \a margins.
The margin is the distance between the outer rect (controlled by the parent layout via \ref
setOuterRect) and the inner \ref rect (which usually contains the main content of this layout
element).
\see setAutoMargins
*/
void QCPLayoutElement::setMargins(const QMargins &margins)
{
if (mMargins != margins)
{
mMargins = margins;
mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom());
}
}
/*!
If \ref setAutoMargins is enabled on some or all margins, this function is used to provide
minimum values for those margins.
The minimum values are not enforced on margin sides that were set to be under manual control via
\ref setAutoMargins.
\see setAutoMargins
*/
void QCPLayoutElement::setMinimumMargins(const QMargins &margins)
{
if (mMinimumMargins != margins)
{
mMinimumMargins = margins;
}
}
/*!
Sets on which sides the margin shall be calculated automatically. If a side is calculated
automatically, a minimum margin value may be provided with \ref setMinimumMargins. If a side is
set to be controlled manually, the value may be specified with \ref setMargins.
Margin sides that are under automatic control may participate in a \ref QCPMarginGroup (see \ref
setMarginGroup), to synchronize (align) it with other layout elements in the plot.
\see setMinimumMargins, setMargins
*/
void QCPLayoutElement::setAutoMargins(QCP::MarginSides sides)
{
mAutoMargins = sides;
}
/*!
Sets the minimum size for the inner \ref rect of this layout element. A parent layout tries to
respect the \a size here by changing row/column sizes in the layout accordingly.
If the parent layout size is not sufficient to satisfy all minimum size constraints of its child
layout elements, the layout may set a size that is actually smaller than \a size. QCustomPlot
propagates the layout's size constraints to the outside by setting its own minimum QWidget size
accordingly, so violations of \a size should be exceptions.
*/
void QCPLayoutElement::setMinimumSize(const QSize &size)
{
if (mMinimumSize != size)
{
mMinimumSize = size;
if (mParentLayout)
mParentLayout->sizeConstraintsChanged();
}
}
/*! \overload
Sets the minimum size for the inner \ref rect of this layout element.
*/
void QCPLayoutElement::setMinimumSize(int width, int height)
{
setMinimumSize(QSize(width, height));
}
/*!
Sets the maximum size for the inner \ref rect of this layout element. A parent layout tries to
respect the \a size here by changing row/column sizes in the layout accordingly.
*/
void QCPLayoutElement::setMaximumSize(const QSize &size)
{
if (mMaximumSize != size)
{
mMaximumSize = size;
if (mParentLayout)
mParentLayout->sizeConstraintsChanged();
}
}
/*! \overload
Sets the maximum size for the inner \ref rect of this layout element.
*/
void QCPLayoutElement::setMaximumSize(int width, int height)
{
setMaximumSize(QSize(width, height));
}
/*!
Sets the margin \a group of the specified margin \a sides.
Margin groups allow synchronizing specified margins across layout elements, see the documentation
of \ref QCPMarginGroup.
To unset the margin group of \a sides, set \a group to 0.
Note that margin groups only work for margin sides that are set to automatic (\ref
setAutoMargins).
*/
void QCPLayoutElement::setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group)
{
QVector<QCP::MarginSide> sideVector;
if (sides.testFlag(QCP::msLeft)) sideVector.append(QCP::msLeft);
if (sides.testFlag(QCP::msRight)) sideVector.append(QCP::msRight);
if (sides.testFlag(QCP::msTop)) sideVector.append(QCP::msTop);
if (sides.testFlag(QCP::msBottom)) sideVector.append(QCP::msBottom);
for (int i=0; i<sideVector.size(); ++i)
{
QCP::MarginSide side = sideVector.at(i);
if (marginGroup(side) != group)
{
QCPMarginGroup *oldGroup = marginGroup(side);
if (oldGroup) // unregister at old group
oldGroup->removeChild(side, this);
if (!group) // if setting to 0, remove hash entry. Else set hash entry to new group and register there
{
mMarginGroups.remove(side);
} else // setting to a new group
{
mMarginGroups[side] = group;
group->addChild(side, this);
}
}
}
}
/*!
Updates the layout element and sub-elements. This function is automatically called upon replot by
the parent layout element.
Layout elements that have child elements should call the \ref update method of their child
elements.
The default implementation executes the automatic margin mechanism, so subclasses should make
sure to call the base class implementation.
*/
void QCPLayoutElement::update()
{
if (mAutoMargins != QCP::msNone)
{
// set the margins of this layout element according to automatic margin calculation, either directly or via a margin group:
QMargins newMargins = mMargins;
QVector<QCP::MarginSide> marginSides = QVector<QCP::MarginSide>() << QCP::msLeft << QCP::msRight << QCP::msTop << QCP::msBottom;
for (int i=0; i<marginSides.size(); ++i)
{
QCP::MarginSide side = marginSides.at(i);
if (mAutoMargins.testFlag(side)) // this side's margin shall be calculated automatically
{
if (mMarginGroups.contains(side))
QCP::setMarginValue(newMargins, side, mMarginGroups[side]->commonMargin(side)); // this side is part of a margin group, so get the margin value from that group
else
QCP::setMarginValue(newMargins, side, calculateAutoMargin(side)); // this side is not part of a group, so calculate the value directly
// apply minimum margin restrictions:
if (QCP::getMarginValue(newMargins, side) < QCP::getMarginValue(mMinimumMargins, side))
QCP::setMarginValue(newMargins, side, QCP::getMarginValue(mMinimumMargins, side));
}
}
setMargins(newMargins);
}
}
/*!
Returns the minimum size this layout element (the inner \ref rect) may be compressed to.
if a minimum size (\ref setMinimumSize) was not set manually, parent layouts consult this
function to determine the minimum allowed size of this layout element. (A manual minimum size is
considered set if it is non-zero.)
*/
QSize QCPLayoutElement::minimumSizeHint() const
{
return mMinimumSize;
}
/*!
Returns the maximum size this layout element (the inner \ref rect) may be expanded to.
if a maximum size (\ref setMaximumSize) was not set manually, parent layouts consult this
function to determine the maximum allowed size of this layout element. (A manual maximum size is
considered set if it is smaller than Qt's QWIDGETSIZE_MAX.)
*/
QSize QCPLayoutElement::maximumSizeHint() const
{
return mMaximumSize;
}
/*!
Returns a list of all child elements in this layout element. If \a recursive is true, all
sub-child elements are included in the list, too.
Note that there may be entries with value 0 in the returned list. (For example, QCPLayoutGrid may have
empty cells which yield 0 at the respective index.)
*/
QList<QCPLayoutElement*> QCPLayoutElement::elements(bool recursive) const
{
Q_UNUSED(recursive)
return QList<QCPLayoutElement*>();
}
/*!
Layout elements are sensitive to events inside their outer rect. If \a pos is within the outer
rect, this method returns a value corresponding to 0.99 times the parent plot's selection
tolerance. However, layout elements are not selectable by default. So if \a onlySelectable is
true, -1.0 is returned.
See \ref QCPLayerable::selectTest for a general explanation of this virtual method.
QCPLayoutElement subclasses may reimplement this method to provide more specific selection test
behaviour.
*/
double QCPLayoutElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable)
return -1;
if (QRectF(mOuterRect).contains(pos))
{
if (mParentPlot)
return mParentPlot->selectionTolerance()*0.99;
else
{
qDebug() << Q_FUNC_INFO << "parent plot not defined";
return -1;
}
} else
return -1;
}
/*! \internal
propagates the parent plot initialization to all child elements, by calling \ref
QCPLayerable::initializeParentPlot on them.
*/
void QCPLayoutElement::parentPlotInitialized(QCustomPlot *parentPlot)
{
QList<QCPLayoutElement*> els = elements(false);
for (int i=0; i<els.size(); ++i)
{
if (!els.at(i)->parentPlot())
els.at(i)->initializeParentPlot(parentPlot);
}
}
/*! \internal
Returns the margin size for this \a side. It is used if automatic margins is enabled for this \a
side (see \ref setAutoMargins). If a minimum margin was set with \ref setMinimumMargins, the
returned value will not be smaller than the specified minimum margin.
The default implementation just returns the respective manual margin (\ref setMargins) or the
minimum margin, whichever is larger.
*/
int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side)
{
return qMax(QCP::getMarginValue(mMargins, side), QCP::getMarginValue(mMinimumMargins, side));
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLayout
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPLayout
\brief The abstract base class for layouts
This is an abstract base class for layout elements whose main purpose is to define the position
and size of other child layout elements. In most cases, layouts don't draw anything themselves
(but there are exceptions to this, e.g. QCPLegend).
QCPLayout derives from QCPLayoutElement, and thus can itself be nested in other layouts.
QCPLayout introduces a common interface for accessing and manipulating the child elements. Those
functions are most notably \ref elementCount, \ref elementAt, \ref takeAt, \ref take, \ref
simplify, \ref removeAt, \ref remove and \ref clear. Individual subclasses may add more functions
to this interface which are more specialized to the form of the layout. For example, \ref
QCPLayoutGrid adds functions that take row and column indices to access cells of the layout grid
more conveniently.
Since this is an abstract base class, you can't instantiate it directly. Rather use one of its
subclasses like QCPLayoutGrid or QCPLayoutInset.
For a general introduction to the layout system, see the dedicated documentation page \ref
thelayoutsystem "The Layout System".
*/
/* start documentation of pure virtual functions */
/*! \fn virtual int QCPLayout::elementCount() const = 0
Returns the number of elements/cells in the layout.
\see elements, elementAt
*/
/*! \fn virtual QCPLayoutElement* QCPLayout::elementAt(int index) const = 0
Returns the element in the cell with the given \a index. If \a index is invalid, returns 0.
Note that even if \a index is valid, the respective cell may be empty in some layouts (e.g.
QCPLayoutGrid), so this function may return 0 in those cases. You may use this function to check
whether a cell is empty or not.
\see elements, elementCount, takeAt
*/
/*! \fn virtual QCPLayoutElement* QCPLayout::takeAt(int index) = 0
Removes the element with the given \a index from the layout and returns it.
If the \a index is invalid or the cell with that index is empty, returns 0.
Note that some layouts don't remove the respective cell right away but leave an empty cell after
successful removal of the layout element. To collapse empty cells, use \ref simplify.
\see elementAt, take
*/
/*! \fn virtual bool QCPLayout::take(QCPLayoutElement* element) = 0
Removes the specified \a element from the layout and returns true on success.
If the \a element isn't in this layout, returns false.
Note that some layouts don't remove the respective cell right away but leave an empty cell after
successful removal of the layout element. To collapse empty cells, use \ref simplify.
\see takeAt
*/
/* end documentation of pure virtual functions */
/*!
Creates an instance of QCPLayout and sets default values. Note that since QCPLayout
is an abstract base class, it can't be instantiated directly.
*/
QCPLayout::QCPLayout()
{
}
/*!
First calls the QCPLayoutElement::update base class implementation to update the margins on this
layout.
Then calls \ref updateLayout which subclasses reimplement to reposition and resize their cells.
Finally, \ref update is called on all child elements.
*/
void QCPLayout::update()
{
QCPLayoutElement::update(); // recalculates (auto-)margins
// set child element rects according to layout:
updateLayout();
// propagate update call to child elements:
for (int i=0; i<elementCount(); ++i)
{
if (QCPLayoutElement *el = elementAt(i))
el->update();
}
}
/* inherits documentation from base class */
QList<QCPLayoutElement*> QCPLayout::elements(bool recursive) const
{
int c = elementCount();
QList<QCPLayoutElement*> result;
#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
result.reserve(c);
#endif
for (int i=0; i<c; ++i)
result.append(elementAt(i));
if (recursive)
{
for (int i=0; i<c; ++i)
{
if (result.at(i))
result << result.at(i)->elements(recursive);
}
}
return result;
}
/*!
Simplifies the layout by collapsing empty cells. The exact behavior depends on subclasses, the
default implementation does nothing.
Not all layouts need simplification. For example, QCPLayoutInset doesn't use explicit
simplification while QCPLayoutGrid does.
*/
void QCPLayout::simplify()
{
}
/*!
Removes and deletes the element at the provided \a index. Returns true on success. If \a index is
invalid or points to an empty cell, returns false.
This function internally uses \ref takeAt to remove the element from the layout and then deletes
the returned element.
\see remove, takeAt
*/
bool QCPLayout::removeAt(int index)
{
if (QCPLayoutElement *el = takeAt(index))
{
delete el;
return true;
} else
return false;
}
/*!
Removes and deletes the provided \a element. Returns true on success. If \a element is not in the
layout, returns false.
This function internally uses \ref takeAt to remove the element from the layout and then deletes
the element.
\see removeAt, take
*/
bool QCPLayout::remove(QCPLayoutElement *element)
{
if (take(element))
{
delete element;
return true;
} else
return false;
}
/*!
Removes and deletes all layout elements in this layout.
\see remove, removeAt
*/
void QCPLayout::clear()
{
for (int i=elementCount()-1; i>=0; --i)
{
if (elementAt(i))
removeAt(i);
}
simplify();
}
/*!
Subclasses call this method to report changed (minimum/maximum) size constraints.
If the parent of this layout is again a QCPLayout, forwards the call to the parent's \ref
sizeConstraintsChanged. If the parent is a QWidget (i.e. is the \ref QCustomPlot::plotLayout of
QCustomPlot), calls QWidget::updateGeometry, so if the QCustomPlot widget is inside a Qt QLayout,
it may update itself and resize cells accordingly.
*/
void QCPLayout::sizeConstraintsChanged() const
{
if (QWidget *w = qobject_cast<QWidget*>(parent()))
w->updateGeometry();
else if (QCPLayout *l = qobject_cast<QCPLayout*>(parent()))
l->sizeConstraintsChanged();
}
/*! \internal
Subclasses reimplement this method to update the position and sizes of the child elements/cells
via calling their \ref QCPLayoutElement::setOuterRect. The default implementation does nothing.
The geometry used as a reference is the inner \ref rect of this layout. Child elements should stay
within that rect.
\ref getSectionSizes may help with the reimplementation of this function.
\see update
*/
void QCPLayout::updateLayout()
{
}
/*! \internal
Associates \a el with this layout. This is done by setting the \ref QCPLayoutElement::layout, the
\ref QCPLayerable::parentLayerable and the QObject parent to this layout.
Further, if \a el didn't previously have a parent plot, calls \ref
QCPLayerable::initializeParentPlot on \a el to set the paret plot.
This method is used by subclass specific methods that add elements to the layout. Note that this
method only changes properties in \a el. The removal from the old layout and the insertion into
the new layout must be done additionally.
*/
void QCPLayout::adoptElement(QCPLayoutElement *el)
{
if (el)
{
el->mParentLayout = this;
el->setParentLayerable(this);
el->setParent(this);
if (!el->parentPlot())
el->initializeParentPlot(mParentPlot);
} else
qDebug() << Q_FUNC_INFO << "Null element passed";
}
/*! \internal
Disassociates \a el from this layout. This is done by setting the \ref QCPLayoutElement::layout
and the \ref QCPLayerable::parentLayerable to zero. The QObject parent is set to the parent
QCustomPlot.
This method is used by subclass specific methods that remove elements from the layout (e.g. \ref
take or \ref takeAt). Note that this method only changes properties in \a el. The removal from
the old layout must be done additionally.
*/
void QCPLayout::releaseElement(QCPLayoutElement *el)
{
if (el)
{
el->mParentLayout = 0;
el->setParentLayerable(0);
el->setParent(mParentPlot);
// Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent plot
} else
qDebug() << Q_FUNC_INFO << "Null element passed";
}
/*! \internal
This is a helper function for the implementation of \ref updateLayout in subclasses.
It calculates the sizes of one-dimensional sections with provided constraints on maximum section
sizes, minimum section sizes, relative stretch factors and the final total size of all sections.
The QVector entries refer to the sections. Thus all QVectors must have the same size.
\a maxSizes gives the maximum allowed size of each section. If there shall be no maximum size
imposed, set all vector values to Qt's QWIDGETSIZE_MAX.
\a minSizes gives the minimum allowed size of each section. If there shall be no minimum size
imposed, set all vector values to zero. If the \a minSizes entries add up to a value greater than
\a totalSize, sections will be scaled smaller than the proposed minimum sizes. (In other words,
not exceeding the allowed total size is taken to be more important than not going below minimum
section sizes.)
\a stretchFactors give the relative proportions of the sections to each other. If all sections
shall be scaled equally, set all values equal. If the first section shall be double the size of
each individual other section, set the first number of \a stretchFactors to double the value of
the other individual values (e.g. {2, 1, 1, 1}).
\a totalSize is the value that the final section sizes will add up to. Due to rounding, the
actual sum may differ slightly. If you want the section sizes to sum up to exactly that value,
you could distribute the remaining difference on the sections.
The return value is a QVector containing the section sizes.
*/
QVector<int> QCPLayout::getSectionSizes(QVector<int> maxSizes, QVector<int> minSizes, QVector<double> stretchFactors, int totalSize) const
{
if (maxSizes.size() != minSizes.size() || minSizes.size() != stretchFactors.size())
{
qDebug() << Q_FUNC_INFO << "Passed vector sizes aren't equal:" << maxSizes << minSizes << stretchFactors;
return QVector<int>();
}
if (stretchFactors.isEmpty())
return QVector<int>();
int sectionCount = stretchFactors.size();
QVector<double> sectionSizes(sectionCount);
// if provided total size is forced smaller than total minimum size, ignore minimum sizes (squeeze sections):
int minSizeSum = 0;
for (int i=0; i<sectionCount; ++i)
minSizeSum += minSizes.at(i);
if (totalSize < minSizeSum)
{
// new stretch factors are minimum sizes and minimum sizes are set to zero:
for (int i=0; i<sectionCount; ++i)
{
stretchFactors[i] = minSizes.at(i);
minSizes[i] = 0;
}
}
QList<int> minimumLockedSections;
QList<int> unfinishedSections;
for (int i=0; i<sectionCount; ++i)
unfinishedSections.append(i);
double freeSize = totalSize;
int outerIterations = 0;
while (!unfinishedSections.isEmpty() && outerIterations < sectionCount*2) // the iteration check ist just a failsafe in case something really strange happens
{
++outerIterations;
int innerIterations = 0;
while (!unfinishedSections.isEmpty() && innerIterations < sectionCount*2) // the iteration check ist just a failsafe in case something really strange happens
{
++innerIterations;
// find section that hits its maximum next:
int nextId = -1;
double nextMax = 1e12;
for (int i=0; i<unfinishedSections.size(); ++i)
{
int secId = unfinishedSections.at(i);
double hitsMaxAt = (maxSizes.at(secId)-sectionSizes.at(secId))/stretchFactors.at(secId);
if (hitsMaxAt < nextMax)
{
nextMax = hitsMaxAt;
nextId = secId;
}
}
// check if that maximum is actually within the bounds of the total size (i.e. can we stretch all remaining sections so far that the found section
// actually hits its maximum, without exceeding the total size when we add up all sections)
double stretchFactorSum = 0;
for (int i=0; i<unfinishedSections.size(); ++i)
stretchFactorSum += stretchFactors.at(unfinishedSections.at(i));
double nextMaxLimit = freeSize/stretchFactorSum;
if (nextMax < nextMaxLimit) // next maximum is actually hit, move forward to that point and fix the size of that section
{
for (int i=0; i<unfinishedSections.size(); ++i)
{
sectionSizes[unfinishedSections.at(i)] += nextMax*stretchFactors.at(unfinishedSections.at(i)); // increment all sections
freeSize -= nextMax*stretchFactors.at(unfinishedSections.at(i));
}
unfinishedSections.removeOne(nextId); // exclude the section that is now at maximum from further changes
} else // next maximum isn't hit, just distribute rest of free space on remaining sections
{
for (int i=0; i<unfinishedSections.size(); ++i)
sectionSizes[unfinishedSections.at(i)] += nextMaxLimit*stretchFactors.at(unfinishedSections.at(i)); // increment all sections
unfinishedSections.clear();
}
}
if (innerIterations == sectionCount*2)
qDebug() << Q_FUNC_INFO << "Exceeded maximum expected inner iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize;
// now check whether the resulting section sizes violate minimum restrictions:
bool foundMinimumViolation = false;
for (int i=0; i<sectionSizes.size(); ++i)
{
if (minimumLockedSections.contains(i))
continue;
if (sectionSizes.at(i) < minSizes.at(i)) // section violates minimum
{
sectionSizes[i] = minSizes.at(i); // set it to minimum
foundMinimumViolation = true; // make sure we repeat the whole optimization process
minimumLockedSections.append(i);
}
}
if (foundMinimumViolation)
{
freeSize = totalSize;
for (int i=0; i<sectionCount; ++i)
{
if (!minimumLockedSections.contains(i)) // only put sections that haven't hit their minimum back into the pool
unfinishedSections.append(i);
else
freeSize -= sectionSizes.at(i); // remove size of minimum locked sections from available space in next round
}
// reset all section sizes to zero that are in unfinished sections (all others have been set to their minimum):
for (int i=0; i<unfinishedSections.size(); ++i)
sectionSizes[unfinishedSections.at(i)] = 0;
}
}
if (outerIterations == sectionCount*2)
qDebug() << Q_FUNC_INFO << "Exceeded maximum expected outer iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize;
QVector<int> result(sectionCount);
for (int i=0; i<sectionCount; ++i)
result[i] = qRound(sectionSizes.at(i));
return result;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLayoutGrid
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPLayoutGrid
\brief A layout that arranges child elements in a grid
Elements are laid out in a grid with configurable stretch factors (\ref setColumnStretchFactor,
\ref setRowStretchFactor) and spacing (\ref setColumnSpacing, \ref setRowSpacing).
Elements can be added to cells via \ref addElement. The grid is expanded if the specified row or
column doesn't exist yet. Whether a cell contains a valid layout element can be checked with \ref
hasElement, that element can be retrieved with \ref element. If rows and columns that only have
empty cells shall be removed, call \ref simplify. Removal of elements is either done by just
adding the element to a different layout or by using the QCPLayout interface \ref take or \ref
remove.
Row and column insertion can be performed with \ref insertRow and \ref insertColumn.
*/
/*!
Creates an instance of QCPLayoutGrid and sets default values.
*/
QCPLayoutGrid::QCPLayoutGrid() :
mColumnSpacing(5),
mRowSpacing(5)
{
}
QCPLayoutGrid::~QCPLayoutGrid()
{
// clear all child layout elements. This is important because only the specific layouts know how
// to handle removing elements (clear calls virtual removeAt method to do that).
clear();
}
/*!
Returns the element in the cell in \a row and \a column.
Returns 0 if either the row/column is invalid or if the cell is empty. In those cases, a qDebug
message is printed. To check whether a cell exists and isn't empty, use \ref hasElement.
\see addElement, hasElement
*/
QCPLayoutElement *QCPLayoutGrid::element(int row, int column) const
{
if (row >= 0 && row < mElements.size())
{
if (column >= 0 && column < mElements.first().size())
{
if (QCPLayoutElement *result = mElements.at(row).at(column))
return result;
else
qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row << "Column:" << column;
} else
qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column;
} else
qDebug() << Q_FUNC_INFO << "Invalid row. Row:" << row << "Column:" << column;
return 0;
}
/*!
Returns the number of rows in the layout.
\see columnCount
*/
int QCPLayoutGrid::rowCount() const
{
return mElements.size();
}
/*!
Returns the number of columns in the layout.
\see rowCount
*/
int QCPLayoutGrid::columnCount() const
{
if (mElements.size() > 0)
return mElements.first().size();
else
return 0;
}
/*!
Adds the \a element to cell with \a row and \a column. If \a element is already in a layout, it
is first removed from there. If \a row or \a column don't exist yet, the layout is expanded
accordingly.
Returns true if the element was added successfully, i.e. if the cell at \a row and \a column
didn't already have an element.
\see element, hasElement, take, remove
*/
bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement *element)
{
if (element)
{
if (!hasElement(row, column))
{
if (element->layout()) // remove from old layout first
element->layout()->take(element);
expandTo(row+1, column+1);
mElements[row][column] = element;
adoptElement(element);
return true;
} else
qDebug() << Q_FUNC_INFO << "There is already an element in the specified row/column:" << row << column;
} else
qDebug() << Q_FUNC_INFO << "Can't add null element to row/column:" << row << column;
return false;
}
/*!
Returns whether the cell at \a row and \a column exists and contains a valid element, i.e. isn't
empty.
\see element
*/
bool QCPLayoutGrid::hasElement(int row, int column)
{
if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount())
return mElements.at(row).at(column);
else
return false;
}
/*!
Sets the stretch \a factor of \a column.
Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref
QCPLayoutElement::setMaximumSize), regardless of the stretch factor.
The default stretch factor of newly created rows/columns is 1.
\see setColumnStretchFactors, setRowStretchFactor
*/
void QCPLayoutGrid::setColumnStretchFactor(int column, double factor)
{
if (column >= 0 && column < columnCount())
{
if (factor > 0)
mColumnStretchFactors[column] = factor;
else
qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor;
} else
qDebug() << Q_FUNC_INFO << "Invalid column:" << column;
}
/*!
Sets the stretch \a factors of all columns. \a factors must have the size \ref columnCount.
Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref
QCPLayoutElement::setMaximumSize), regardless of the stretch factor.
The default stretch factor of newly created rows/columns is 1.
\see setColumnStretchFactor, setRowStretchFactors
*/
void QCPLayoutGrid::setColumnStretchFactors(const QList<double> &factors)
{
if (factors.size() == mColumnStretchFactors.size())
{
mColumnStretchFactors = factors;
for (int i=0; i<mColumnStretchFactors.size(); ++i)
{
if (mColumnStretchFactors.at(i) <= 0)
{
qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mColumnStretchFactors.at(i);
mColumnStretchFactors[i] = 1;
}
}
} else
qDebug() << Q_FUNC_INFO << "Column count not equal to passed stretch factor count:" << factors;
}
/*!
Sets the stretch \a factor of \a row.
Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref
QCPLayoutElement::setMaximumSize), regardless of the stretch factor.
The default stretch factor of newly created rows/columns is 1.
\see setColumnStretchFactors, setRowStretchFactor
*/
void QCPLayoutGrid::setRowStretchFactor(int row, double factor)
{
if (row >= 0 && row < rowCount())
{
if (factor > 0)
mRowStretchFactors[row] = factor;
else
qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor;
} else
qDebug() << Q_FUNC_INFO << "Invalid row:" << row;
}
/*!
Sets the stretch \a factors of all rows. \a factors must have the size \ref rowCount.
Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref
QCPLayoutElement::setMaximumSize), regardless of the stretch factor.
The default stretch factor of newly created rows/columns is 1.
\see setRowStretchFactor, setColumnStretchFactors
*/
void QCPLayoutGrid::setRowStretchFactors(const QList<double> &factors)
{
if (factors.size() == mRowStretchFactors.size())
{
mRowStretchFactors = factors;
for (int i=0; i<mRowStretchFactors.size(); ++i)
{
if (mRowStretchFactors.at(i) <= 0)
{
qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mRowStretchFactors.at(i);
mRowStretchFactors[i] = 1;
}
}
} else
qDebug() << Q_FUNC_INFO << "Row count not equal to passed stretch factor count:" << factors;
}
/*!
Sets the gap that is left blank between columns to \a pixels.
\see setRowSpacing
*/
void QCPLayoutGrid::setColumnSpacing(int pixels)
{
mColumnSpacing = pixels;
}
/*!
Sets the gap that is left blank between rows to \a pixels.
\see setColumnSpacing
*/
void QCPLayoutGrid::setRowSpacing(int pixels)
{
mRowSpacing = pixels;
}
/*!
Expands the layout to have \a newRowCount rows and \a newColumnCount columns. So the last valid
row index will be \a newRowCount-1, the last valid column index will be \a newColumnCount-1.
If the current column/row count is already larger or equal to \a newColumnCount/\a newRowCount,
this function does nothing in that dimension.
Newly created cells are empty, new rows and columns have the stretch factor 1.
Note that upon a call to \ref addElement, the layout is expanded automatically to contain the
specified row and column, using this function.
\see simplify
*/
void QCPLayoutGrid::expandTo(int newRowCount, int newColumnCount)
{
// add rows as necessary:
while (rowCount() < newRowCount)
{
mElements.append(QList<QCPLayoutElement*>());
mRowStretchFactors.append(1);
}
// go through rows and expand columns as necessary:
int newColCount = qMax(columnCount(), newColumnCount);
for (int i=0; i<rowCount(); ++i)
{
while (mElements.at(i).size() < newColCount)
mElements[i].append(0);
}
while (mColumnStretchFactors.size() < newColCount)
mColumnStretchFactors.append(1);
}
/*!
Inserts a new row with empty cells at the row index \a newIndex. Valid values for \a newIndex
range from 0 (inserts a row at the top) to \a rowCount (appends a row at the bottom).
\see insertColumn
*/
void QCPLayoutGrid::insertRow(int newIndex)
{
if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell
{
expandTo(1, 1);
return;
}
if (newIndex < 0)
newIndex = 0;
if (newIndex > rowCount())
newIndex = rowCount();
mRowStretchFactors.insert(newIndex, 1);
QList<QCPLayoutElement*> newRow;
for (int col=0; col<columnCount(); ++col)
newRow.append((QCPLayoutElement*)0);
mElements.insert(newIndex, newRow);
}
/*!
Inserts a new column with empty cells at the column index \a newIndex. Valid values for \a
newIndex range from 0 (inserts a row at the left) to \a rowCount (appends a row at the right).
\see insertRow
*/
void QCPLayoutGrid::insertColumn(int newIndex)
{
if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell
{
expandTo(1, 1);
return;
}
if (newIndex < 0)
newIndex = 0;
if (newIndex > columnCount())
newIndex = columnCount();
mColumnStretchFactors.insert(newIndex, 1);
for (int row=0; row<rowCount(); ++row)
mElements[row].insert(newIndex, (QCPLayoutElement*)0);
}
/* inherits documentation from base class */
void QCPLayoutGrid::updateLayout()
{
QVector<int> minColWidths, minRowHeights, maxColWidths, maxRowHeights;
getMinimumRowColSizes(&minColWidths, &minRowHeights);
getMaximumRowColSizes(&maxColWidths, &maxRowHeights);
int totalRowSpacing = (rowCount()-1) * mRowSpacing;
int totalColSpacing = (columnCount()-1) * mColumnSpacing;
QVector<int> colWidths = getSectionSizes(maxColWidths, minColWidths, mColumnStretchFactors.toVector(), mRect.width()-totalColSpacing);
QVector<int> rowHeights = getSectionSizes(maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), mRect.height()-totalRowSpacing);
// go through cells and set rects accordingly:
int yOffset = mRect.top();
for (int row=0; row<rowCount(); ++row)
{
if (row > 0)
yOffset += rowHeights.at(row-1)+mRowSpacing;
int xOffset = mRect.left();
for (int col=0; col<columnCount(); ++col)
{
if (col > 0)
xOffset += colWidths.at(col-1)+mColumnSpacing;
if (mElements.at(row).at(col))
mElements.at(row).at(col)->setOuterRect(QRect(xOffset, yOffset, colWidths.at(col), rowHeights.at(row)));
}
}
}
/* inherits documentation from base class */
int QCPLayoutGrid::elementCount() const
{
return rowCount()*columnCount();
}
/* inherits documentation from base class */
QCPLayoutElement *QCPLayoutGrid::elementAt(int index) const
{
if (index >= 0 && index < elementCount())
return mElements.at(index / columnCount()).at(index % columnCount());
else
return 0;
}
/* inherits documentation from base class */
QCPLayoutElement *QCPLayoutGrid::takeAt(int index)
{
if (QCPLayoutElement *el = elementAt(index))
{
releaseElement(el);
mElements[index / columnCount()][index % columnCount()] = 0;
return el;
} else
{
qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index;
return 0;
}
}
/* inherits documentation from base class */
bool QCPLayoutGrid::take(QCPLayoutElement *element)
{
if (element)
{
for (int i=0; i<elementCount(); ++i)
{
if (elementAt(i) == element)
{
takeAt(i);
return true;
}
}
qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take";
} else
qDebug() << Q_FUNC_INFO << "Can't take null element";
return false;
}
/* inherits documentation from base class */
QList<QCPLayoutElement*> QCPLayoutGrid::elements(bool recursive) const
{
QList<QCPLayoutElement*> result;
int colC = columnCount();
int rowC = rowCount();
#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
result.reserve(colC*rowC);
#endif
for (int row=0; row<rowC; ++row)
{
for (int col=0; col<colC; ++col)
{
result.append(mElements.at(row).at(col));
}
}
if (recursive)
{
int c = result.size();
for (int i=0; i<c; ++i)
{
if (result.at(i))
result << result.at(i)->elements(recursive);
}
}
return result;
}
/*!
Simplifies the layout by collapsing rows and columns which only contain empty cells.
*/
void QCPLayoutGrid::simplify()
{
// remove rows with only empty cells:
for (int row=rowCount()-1; row>=0; --row)
{
bool hasElements = false;
for (int col=0; col<columnCount(); ++col)
{
if (mElements.at(row).at(col))
{
hasElements = true;
break;
}
}
if (!hasElements)
{
mRowStretchFactors.removeAt(row);
mElements.removeAt(row);
if (mElements.isEmpty()) // removed last element, also remove stretch factor (wouldn't happen below because also columnCount changed to 0 now)
mColumnStretchFactors.clear();
}
}
// remove columns with only empty cells:
for (int col=columnCount()-1; col>=0; --col)
{
bool hasElements = false;
for (int row=0; row<rowCount(); ++row)
{
if (mElements.at(row).at(col))
{
hasElements = true;
break;
}
}
if (!hasElements)
{
mColumnStretchFactors.removeAt(col);
for (int row=0; row<rowCount(); ++row)
mElements[row].removeAt(col);
}
}
}
/* inherits documentation from base class */
QSize QCPLayoutGrid::minimumSizeHint() const
{
QVector<int> minColWidths, minRowHeights;
getMinimumRowColSizes(&minColWidths, &minRowHeights);
QSize result(0, 0);
for (int i=0; i<minColWidths.size(); ++i)
result.rwidth() += minColWidths.at(i);
for (int i=0; i<minRowHeights.size(); ++i)
result.rheight() += minRowHeights.at(i);
result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing + mMargins.left() + mMargins.right();
result.rheight() += qMax(0, rowCount()-1) * mRowSpacing + mMargins.top() + mMargins.bottom();
return result;
}
/* inherits documentation from base class */
QSize QCPLayoutGrid::maximumSizeHint() const
{
QVector<int> maxColWidths, maxRowHeights;
getMaximumRowColSizes(&maxColWidths, &maxRowHeights);
QSize result(0, 0);
for (int i=0; i<maxColWidths.size(); ++i)
result.setWidth(qMin(result.width()+maxColWidths.at(i), QWIDGETSIZE_MAX));
for (int i=0; i<maxRowHeights.size(); ++i)
result.setHeight(qMin(result.height()+maxRowHeights.at(i), QWIDGETSIZE_MAX));
result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing + mMargins.left() + mMargins.right();
result.rheight() += qMax(0, rowCount()-1) * mRowSpacing + mMargins.top() + mMargins.bottom();
return result;
}
/*! \internal
Places the minimum column widths and row heights into \a minColWidths and \a minRowHeights
respectively.
The minimum height of a row is the largest minimum height of any element in that row. The minimum
width of a column is the largest minimum width of any element in that column.
This is a helper function for \ref updateLayout.
\see getMaximumRowColSizes
*/
void QCPLayoutGrid::getMinimumRowColSizes(QVector<int> *minColWidths, QVector<int> *minRowHeights) const
{
*minColWidths = QVector<int>(columnCount(), 0);
*minRowHeights = QVector<int>(rowCount(), 0);
for (int row=0; row<rowCount(); ++row)
{
for (int col=0; col<columnCount(); ++col)
{
if (mElements.at(row).at(col))
{
QSize minHint = mElements.at(row).at(col)->minimumSizeHint();
QSize min = mElements.at(row).at(col)->minimumSize();
QSize final(min.width() > 0 ? min.width() : minHint.width(), min.height() > 0 ? min.height() : minHint.height());
if (minColWidths->at(col) < final.width())
(*minColWidths)[col] = final.width();
if (minRowHeights->at(row) < final.height())
(*minRowHeights)[row] = final.height();
}
}
}
}
/*! \internal
Places the maximum column widths and row heights into \a maxColWidths and \a maxRowHeights
respectively.
The maximum height of a row is the smallest maximum height of any element in that row. The
maximum width of a column is the smallest maximum width of any element in that column.
This is a helper function for \ref updateLayout.
\see getMinimumRowColSizes
*/
void QCPLayoutGrid::getMaximumRowColSizes(QVector<int> *maxColWidths, QVector<int> *maxRowHeights) const
{
*maxColWidths = QVector<int>(columnCount(), QWIDGETSIZE_MAX);
*maxRowHeights = QVector<int>(rowCount(), QWIDGETSIZE_MAX);
for (int row=0; row<rowCount(); ++row)
{
for (int col=0; col<columnCount(); ++col)
{
if (mElements.at(row).at(col))
{
QSize maxHint = mElements.at(row).at(col)->maximumSizeHint();
QSize max = mElements.at(row).at(col)->maximumSize();
QSize final(max.width() < QWIDGETSIZE_MAX ? max.width() : maxHint.width(), max.height() < QWIDGETSIZE_MAX ? max.height() : maxHint.height());
if (maxColWidths->at(col) > final.width())
(*maxColWidths)[col] = final.width();
if (maxRowHeights->at(row) > final.height())
(*maxRowHeights)[row] = final.height();
}
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLayoutInset
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPLayoutInset
\brief A layout that places child elements aligned to the border or arbitrarily positioned
Elements are placed either aligned to the border or at arbitrary position in the area of the
layout. Which placement applies is controlled with the \ref InsetPlacement (\ref
setInsetPlacement).
Elements are added via \ref addElement(QCPLayoutElement *element, Qt::Alignment alignment) or
addElement(QCPLayoutElement *element, const QRectF &rect). If the first method is used, the inset
placement will default to \ref ipBorderAligned and the element will be aligned according to the
\a alignment parameter. The second method defaults to \ref ipFree and allows placing elements at
arbitrary position and size, defined by \a rect.
The alignment or rect can be set via \ref setInsetAlignment or \ref setInsetRect, respectively.
This is the layout that every QCPAxisRect has as \ref QCPAxisRect::insetLayout.
*/
/* start documentation of inline functions */
/*! \fn virtual void QCPLayoutInset::simplify()
The QCPInsetLayout does not need simplification since it can never have empty cells due to its
linear index structure. This method does nothing.
*/
/* end documentation of inline functions */
/*!
Creates an instance of QCPLayoutInset and sets default values.
*/
QCPLayoutInset::QCPLayoutInset()
{
}
QCPLayoutInset::~QCPLayoutInset()
{
// clear all child layout elements. This is important because only the specific layouts know how
// to handle removing elements (clear calls virtual removeAt method to do that).
clear();
}
/*!
Returns the placement type of the element with the specified \a index.
*/
QCPLayoutInset::InsetPlacement QCPLayoutInset::insetPlacement(int index) const
{
if (elementAt(index))
return mInsetPlacement.at(index);
else
{
qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
return ipFree;
}
}
/*!
Returns the alignment of the element with the specified \a index. The alignment only has a
meaning, if the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned.
*/
Qt::Alignment QCPLayoutInset::insetAlignment(int index) const
{
if (elementAt(index))
return mInsetAlignment.at(index);
else
{
qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
return 0;
}
}
/*!
Returns the rect of the element with the specified \a index. The rect only has a
meaning, if the inset placement (\ref setInsetPlacement) is \ref ipFree.
*/
QRectF QCPLayoutInset::insetRect(int index) const
{
if (elementAt(index))
return mInsetRect.at(index);
else
{
qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
return QRectF();
}
}
/*!
Sets the inset placement type of the element with the specified \a index to \a placement.
\see InsetPlacement
*/
void QCPLayoutInset::setInsetPlacement(int index, QCPLayoutInset::InsetPlacement placement)
{
if (elementAt(index))
mInsetPlacement[index] = placement;
else
qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
}
/*!
If the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned, this function
is used to set the alignment of the element with the specified \a index to \a alignment.
\a alignment is an or combination of the following alignment flags: Qt::AlignLeft,
Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other
alignment flags will be ignored.
*/
void QCPLayoutInset::setInsetAlignment(int index, Qt::Alignment alignment)
{
if (elementAt(index))
mInsetAlignment[index] = alignment;
else
qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
}
/*!
If the inset placement (\ref setInsetPlacement) is \ref ipFree, this function is used to set the
position and size of the element with the specified \a index to \a rect.
\a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1)
will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right
corner of the layout, with 35% width and height of the parent layout.
Note that the minimum and maximum sizes of the embedded element (\ref
QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize) are enforced.
*/
void QCPLayoutInset::setInsetRect(int index, const QRectF &rect)
{
if (elementAt(index))
mInsetRect[index] = rect;
else
qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
}
/* inherits documentation from base class */
void QCPLayoutInset::updateLayout()
{
for (int i=0; i<mElements.size(); ++i)
{
QRect insetRect;
QSize finalMinSize, finalMaxSize;
QSize minSizeHint = mElements.at(i)->minimumSizeHint();
QSize maxSizeHint = mElements.at(i)->maximumSizeHint();
finalMinSize.setWidth(mElements.at(i)->minimumSize().width() > 0 ? mElements.at(i)->minimumSize().width() : minSizeHint.width());
finalMinSize.setHeight(mElements.at(i)->minimumSize().height() > 0 ? mElements.at(i)->minimumSize().height() : minSizeHint.height());
finalMaxSize.setWidth(mElements.at(i)->maximumSize().width() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().width() : maxSizeHint.width());
finalMaxSize.setHeight(mElements.at(i)->maximumSize().height() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().height() : maxSizeHint.height());
if (mInsetPlacement.at(i) == ipFree)
{
insetRect = QRect(rect().x()+rect().width()*mInsetRect.at(i).x(),
rect().y()+rect().height()*mInsetRect.at(i).y(),
rect().width()*mInsetRect.at(i).width(),
rect().height()*mInsetRect.at(i).height());
if (insetRect.size().width() < finalMinSize.width())
insetRect.setWidth(finalMinSize.width());
if (insetRect.size().height() < finalMinSize.height())
insetRect.setHeight(finalMinSize.height());
if (insetRect.size().width() > finalMaxSize.width())
insetRect.setWidth(finalMaxSize.width());
if (insetRect.size().height() > finalMaxSize.height())
insetRect.setHeight(finalMaxSize.height());
} else if (mInsetPlacement.at(i) == ipBorderAligned)
{
insetRect.setSize(finalMinSize);
Qt::Alignment al = mInsetAlignment.at(i);
if (al.testFlag(Qt::AlignLeft)) insetRect.moveLeft(rect().x());
else if (al.testFlag(Qt::AlignRight)) insetRect.moveRight(rect().x()+rect().width());
else insetRect.moveLeft(rect().x()+rect().width()*0.5-finalMinSize.width()*0.5); // default to Qt::AlignHCenter
if (al.testFlag(Qt::AlignTop)) insetRect.moveTop(rect().y());
else if (al.testFlag(Qt::AlignBottom)) insetRect.moveBottom(rect().y()+rect().height());
else insetRect.moveTop(rect().y()+rect().height()*0.5-finalMinSize.height()*0.5); // default to Qt::AlignVCenter
}
mElements.at(i)->setOuterRect(insetRect);
}
}
/* inherits documentation from base class */
int QCPLayoutInset::elementCount() const
{
return mElements.size();
}
/* inherits documentation from base class */
QCPLayoutElement *QCPLayoutInset::elementAt(int index) const
{
if (index >= 0 && index < mElements.size())
return mElements.at(index);
else
return 0;
}
/* inherits documentation from base class */
QCPLayoutElement *QCPLayoutInset::takeAt(int index)
{
if (QCPLayoutElement *el = elementAt(index))
{
releaseElement(el);
mElements.removeAt(index);
mInsetPlacement.removeAt(index);
mInsetAlignment.removeAt(index);
mInsetRect.removeAt(index);
return el;
} else
{
qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index;
return 0;
}
}
/* inherits documentation from base class */
bool QCPLayoutInset::take(QCPLayoutElement *element)
{
if (element)
{
for (int i=0; i<elementCount(); ++i)
{
if (elementAt(i) == element)
{
takeAt(i);
return true;
}
}
qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take";
} else
qDebug() << Q_FUNC_INFO << "Can't take null element";
return false;
}
/*!
The inset layout is sensitive to events only at areas where its (visible) child elements are
sensitive. If the selectTest method of any of the child elements returns a positive number for \a
pos, this method returns a value corresponding to 0.99 times the parent plot's selection
tolerance. The inset layout is not selectable itself by default. So if \a onlySelectable is true,
-1.0 is returned.
See \ref QCPLayerable::selectTest for a general explanation of this virtual method.
*/
double QCPLayoutInset::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable)
return -1;
for (int i=0; i<mElements.size(); ++i)
{
// inset layout shall only return positive selectTest, if actually an inset object is at pos
// else it would block the entire underlying QCPAxisRect with its surface.
if (mElements.at(i)->realVisibility() && mElements.at(i)->selectTest(pos, onlySelectable) >= 0)
return mParentPlot->selectionTolerance()*0.99;
}
return -1;
}
/*!
Adds the specified \a element to the layout as an inset aligned at the border (\ref
setInsetAlignment is initialized with \ref ipBorderAligned). The alignment is set to \a
alignment.
\a alignment is an or combination of the following alignment flags: Qt::AlignLeft,
Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other
alignment flags will be ignored.
\see addElement(QCPLayoutElement *element, const QRectF &rect)
*/
void QCPLayoutInset::addElement(QCPLayoutElement *element, Qt::Alignment alignment)
{
if (element)
{
if (element->layout()) // remove from old layout first
element->layout()->take(element);
mElements.append(element);
mInsetPlacement.append(ipBorderAligned);
mInsetAlignment.append(alignment);
mInsetRect.append(QRectF(0.6, 0.6, 0.4, 0.4));
adoptElement(element);
} else
qDebug() << Q_FUNC_INFO << "Can't add null element";
}
/*!
Adds the specified \a element to the layout as an inset with free positioning/sizing (\ref
setInsetAlignment is initialized with \ref ipFree). The position and size is set to \a
rect.
\a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1)
will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right
corner of the layout, with 35% width and height of the parent layout.
\see addElement(QCPLayoutElement *element, Qt::Alignment alignment)
*/
void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect)
{
if (element)
{
if (element->layout()) // remove from old layout first
element->layout()->take(element);
mElements.append(element);
mInsetPlacement.append(ipFree);
mInsetAlignment.append(Qt::AlignRight|Qt::AlignTop);
mInsetRect.append(rect);
adoptElement(element);
} else
qDebug() << Q_FUNC_INFO << "Can't add null element";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLineEnding
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPLineEnding
\brief Handles the different ending decorations for line-like items
\image html QCPLineEnding.png "The various ending styles currently supported"
For every ending a line-like item has, an instance of this class exists. For example, QCPItemLine
has two endings which can be set with QCPItemLine::setHead and QCPItemLine::setTail.
The styles themselves are defined via the enum QCPLineEnding::EndingStyle. Most decorations can
be modified regarding width and length, see \ref setWidth and \ref setLength. The direction of
the ending decoration (e.g. direction an arrow is pointing) is controlled by the line-like item.
For example, when both endings of a QCPItemLine are set to be arrows, they will point to opposite
directions, e.g. "outward". This can be changed by \ref setInverted, which would make the
respective arrow point inward.
Note that due to the overloaded QCPLineEnding constructor, you may directly specify a
QCPLineEnding::EndingStyle where actually a QCPLineEnding is expected, e.g. \code
myItemLine->setHead(QCPLineEnding::esSpikeArrow) \endcode
*/
/*!
Creates a QCPLineEnding instance with default values (style \ref esNone).
*/
QCPLineEnding::QCPLineEnding() :
mStyle(esNone),
mWidth(8),
mLength(10),
mInverted(false)
{
}
/*!
Creates a QCPLineEnding instance with the specified values.
*/
QCPLineEnding::QCPLineEnding(QCPLineEnding::EndingStyle style, double width, double length, bool inverted) :
mStyle(style),
mWidth(width),
mLength(length),
mInverted(inverted)
{
}
/*!
Sets the style of the ending decoration.
*/
void QCPLineEnding::setStyle(QCPLineEnding::EndingStyle style)
{
mStyle = style;
}
/*!
Sets the width of the ending decoration, if the style supports it. On arrows, for example, the
width defines the size perpendicular to the arrow's pointing direction.
\see setLength
*/
void QCPLineEnding::setWidth(double width)
{
mWidth = width;
}
/*!
Sets the length of the ending decoration, if the style supports it. On arrows, for example, the
length defines the size in pointing direction.
\see setWidth
*/
void QCPLineEnding::setLength(double length)
{
mLength = length;
}
/*!
Sets whether the ending decoration shall be inverted. For example, an arrow decoration will point
inward when \a inverted is set to true.
Note that also the \a width direction is inverted. For symmetrical ending styles like arrows or
discs, this doesn't make a difference. However, asymmetric styles like \ref esHalfBar are
affected by it, which can be used to control to which side the half bar points to.
*/
void QCPLineEnding::setInverted(bool inverted)
{
mInverted = inverted;
}
/*! \internal
Returns the maximum pixel radius the ending decoration might cover, starting from the position
the decoration is drawn at (typically a line ending/\ref QCPItemPosition of an item).
This is relevant for clipping. Only omit painting of the decoration when the position where the
decoration is supposed to be drawn is farther away from the clipping rect than the returned
distance.
*/
double QCPLineEnding::boundingDistance() const
{
switch (mStyle)
{
case esNone:
return 0;
case esFlatArrow:
case esSpikeArrow:
case esLineArrow:
case esSkewedBar:
return qSqrt(mWidth*mWidth+mLength*mLength); // items that have width and length
case esDisc:
case esSquare:
case esDiamond:
case esBar:
case esHalfBar:
return mWidth*1.42; // items that only have a width -> width*sqrt(2)
}
return 0;
}
/*!
Starting from the origin of this line ending (which is style specific), returns the length
covered by the line ending symbol, in backward direction.
For example, the \ref esSpikeArrow has a shorter real length than a \ref esFlatArrow, even if
both have the same \ref setLength value, because the spike arrow has an inward curved back, which
reduces the length along its center axis (the drawing origin for arrows is at the tip).
This function is used for precise, style specific placement of line endings, for example in
QCPAxes.
*/
double QCPLineEnding::realLength() const
{
switch (mStyle)
{
case esNone:
case esLineArrow:
case esSkewedBar:
case esBar:
case esHalfBar:
return 0;
case esFlatArrow:
return mLength;
case esDisc:
case esSquare:
case esDiamond:
return mWidth*0.5;
case esSpikeArrow:
return mLength*0.8;
}
return 0;
}
/*! \internal
Draws the line ending with the specified \a painter at the position \a pos. The direction of the
line ending is controlled with \a dir.
*/
void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, const QVector2D &dir) const
{
if (mStyle == esNone)
return;
QVector2D lengthVec(dir.normalized());
if (lengthVec.isNull())
lengthVec = QVector2D(1, 0);
QVector2D widthVec(-lengthVec.y(), lengthVec.x());
lengthVec *= mLength*(mInverted ? -1 : 1);
widthVec *= mWidth*0.5*(mInverted ? -1 : 1);
QPen penBackup = painter->pen();
QBrush brushBackup = painter->brush();
QPen miterPen = penBackup;
miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey
QBrush brush(painter->pen().color(), Qt::SolidPattern);
switch (mStyle)
{
case esNone: break;
case esFlatArrow:
{
QPointF points[3] = {pos.toPointF(),
(pos-lengthVec+widthVec).toPointF(),
(pos-lengthVec-widthVec).toPointF()
};
painter->setPen(miterPen);
painter->setBrush(brush);
painter->drawConvexPolygon(points, 3);
painter->setBrush(brushBackup);
painter->setPen(penBackup);
break;
}
case esSpikeArrow:
{
QPointF points[4] = {pos.toPointF(),
(pos-lengthVec+widthVec).toPointF(),
(pos-lengthVec*0.8).toPointF(),
(pos-lengthVec-widthVec).toPointF()
};
painter->setPen(miterPen);
painter->setBrush(brush);
painter->drawConvexPolygon(points, 4);
painter->setBrush(brushBackup);
painter->setPen(penBackup);
break;
}
case esLineArrow:
{
QPointF points[3] = {(pos-lengthVec+widthVec).toPointF(),
pos.toPointF(),
(pos-lengthVec-widthVec).toPointF()
};
painter->setPen(miterPen);
painter->drawPolyline(points, 3);
painter->setPen(penBackup);
break;
}
case esDisc:
{
painter->setBrush(brush);
painter->drawEllipse(pos.toPointF(), mWidth*0.5, mWidth*0.5);
painter->setBrush(brushBackup);
break;
}
case esSquare:
{
QVector2D widthVecPerp(-widthVec.y(), widthVec.x());
QPointF points[4] = {(pos-widthVecPerp+widthVec).toPointF(),
(pos-widthVecPerp-widthVec).toPointF(),
(pos+widthVecPerp-widthVec).toPointF(),
(pos+widthVecPerp+widthVec).toPointF()
};
painter->setPen(miterPen);
painter->setBrush(brush);
painter->drawConvexPolygon(points, 4);
painter->setBrush(brushBackup);
painter->setPen(penBackup);
break;
}
case esDiamond:
{
QVector2D widthVecPerp(-widthVec.y(), widthVec.x());
QPointF points[4] = {(pos-widthVecPerp).toPointF(),
(pos-widthVec).toPointF(),
(pos+widthVecPerp).toPointF(),
(pos+widthVec).toPointF()
};
painter->setPen(miterPen);
painter->setBrush(brush);
painter->drawConvexPolygon(points, 4);
painter->setBrush(brushBackup);
painter->setPen(penBackup);
break;
}
case esBar:
{
painter->drawLine((pos+widthVec).toPointF(), (pos-widthVec).toPointF());
break;
}
case esHalfBar:
{
painter->drawLine((pos+widthVec).toPointF(), pos.toPointF());
break;
}
case esSkewedBar:
{
if (qFuzzyIsNull(painter->pen().widthF()) && !painter->modes().testFlag(QCPPainter::pmNonCosmetic))
{
// if drawing with cosmetic pen (perfectly thin stroke, happens only in vector exports), draw bar exactly on tip of line
painter->drawLine((pos+widthVec+lengthVec*0.2*(mInverted?-1:1)).toPointF(),
(pos-widthVec-lengthVec*0.2*(mInverted?-1:1)).toPointF());
} else
{
// if drawing with thick (non-cosmetic) pen, shift bar a little in line direction to prevent line from sticking through bar slightly
painter->drawLine((pos+widthVec+lengthVec*0.2*(mInverted?-1:1)+dir.normalized()*qMax(1.0, (double)painter->pen().widthF())*0.5).toPointF(),
(pos-widthVec-lengthVec*0.2*(mInverted?-1:1)+dir.normalized()*qMax(1.0, (double)painter->pen().widthF())*0.5).toPointF());
}
break;
}
}
}
/*! \internal
\overload
Draws the line ending. The direction is controlled with the \a angle parameter in radians.
*/
void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, double angle) const
{
draw(painter, pos, QVector2D(qCos(angle), qSin(angle)));
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPGrid
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPGrid
\brief Responsible for drawing the grid of a QCPAxis.
This class is tightly bound to QCPAxis. Every axis owns a grid instance and uses it to draw the
grid lines, sub grid lines and zero-line. You can interact with the grid of an axis via \ref
QCPAxis::grid. Normally, you don't need to create an instance of QCPGrid yourself.
The axis and grid drawing was split into two classes to allow them to be placed on different
layers (both QCPAxis and QCPGrid inherit from QCPLayerable). Thus it is possible to have the grid
in the background and the axes in the foreground, and any plottables/items in between. This
described situation is the default setup, see the QCPLayer documentation.
*/
/*!
Creates a QCPGrid instance and sets default values.
You shouldn't instantiate grids on their own, since every QCPAxis brings its own QCPGrid.
*/
QCPGrid::QCPGrid(QCPAxis *parentAxis) :
QCPLayerable(parentAxis->parentPlot(), "", parentAxis),
mParentAxis(parentAxis)
{
// warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called
setParent(parentAxis);
setPen(QPen(QColor(200,200,200), 0, Qt::DotLine));
setSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine));
setZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine));
setSubGridVisible(false);
setAntialiased(false);
setAntialiasedSubGrid(false);
setAntialiasedZeroLine(false);
}
/*!
Sets whether grid lines at sub tick marks are drawn.
\see setSubGridPen
*/
void QCPGrid::setSubGridVisible(bool visible)
{
mSubGridVisible = visible;
}
/*!
Sets whether sub grid lines are drawn antialiased.
*/
void QCPGrid::setAntialiasedSubGrid(bool enabled)
{
mAntialiasedSubGrid = enabled;
}
/*!
Sets whether zero lines are drawn antialiased.
*/
void QCPGrid::setAntialiasedZeroLine(bool enabled)
{
mAntialiasedZeroLine = enabled;
}
/*!
Sets the pen with which (major) grid lines are drawn.
*/
void QCPGrid::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen with which sub grid lines are drawn.
*/
void QCPGrid::setSubGridPen(const QPen &pen)
{
mSubGridPen = pen;
}
/*!
Sets the pen with which zero lines are drawn.
Zero lines are lines at value coordinate 0 which may be drawn with a different pen than other grid
lines. To disable zero lines and just draw normal grid lines at zero, set \a pen to Qt::NoPen.
*/
void QCPGrid::setZeroLinePen(const QPen &pen)
{
mZeroLinePen = pen;
}
/*! \internal
A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
before drawing the major grid lines.
This is the antialiasing state the painter passed to the \ref draw method is in by default.
This function takes into account the local setting of the antialiasing flag as well as the
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
\see setAntialiased
*/
void QCPGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid);
}
/*! \internal
Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning
over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen).
*/
void QCPGrid::draw(QCPPainter *painter)
{
if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
if (mSubGridVisible)
drawSubGridLines(painter);
drawGridLines(painter);
}
/*! \internal
Draws the main grid lines and possibly a zero line with the specified painter.
This is a helper function called by \ref draw.
*/
void QCPGrid::drawGridLines(QCPPainter *painter) const
{
if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
int lowTick = mParentAxis->mLowestVisibleTick;
int highTick = mParentAxis->mHighestVisibleTick;
double t; // helper variable, result of coordinate-to-pixel transforms
if (mParentAxis->orientation() == Qt::Horizontal)
{
// draw zeroline:
int zeroLineIndex = -1;
if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0)
{
applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
painter->setPen(mZeroLinePen);
double epsilon = mParentAxis->range().size()*1E-6; // for comparing double to zero
for (int i=lowTick; i <= highTick; ++i)
{
if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
{
zeroLineIndex = i;
t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
break;
}
}
}
// draw grid lines:
applyDefaultAntialiasingHint(painter);
painter->setPen(mPen);
for (int i=lowTick; i <= highTick; ++i)
{
if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
}
} else
{
// draw zeroline:
int zeroLineIndex = -1;
if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0)
{
applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
painter->setPen(mZeroLinePen);
double epsilon = mParentAxis->mRange.size()*1E-6; // for comparing double to zero
for (int i=lowTick; i <= highTick; ++i)
{
if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
{
zeroLineIndex = i;
t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
break;
}
}
}
// draw grid lines:
applyDefaultAntialiasingHint(painter);
painter->setPen(mPen);
for (int i=lowTick; i <= highTick; ++i)
{
if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
}
}
}
/*! \internal
Draws the sub grid lines with the specified painter.
This is a helper function called by \ref draw.
*/
void QCPGrid::drawSubGridLines(QCPPainter *painter) const
{
if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid);
double t; // helper variable, result of coordinate-to-pixel transforms
painter->setPen(mSubGridPen);
if (mParentAxis->orientation() == Qt::Horizontal)
{
for (int i=0; i<mParentAxis->mSubTickVector.size(); ++i)
{
t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // x
painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
}
} else
{
for (int i=0; i<mParentAxis->mSubTickVector.size(); ++i)
{
t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // y
painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAxis
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAxis
\brief Manages a single axis inside a QCustomPlot.
Usually doesn't need to be instantiated externally. Access %QCustomPlot's default four axes via
QCustomPlot::xAxis (bottom), QCustomPlot::yAxis (left), QCustomPlot::xAxis2 (top) and
QCustomPlot::yAxis2 (right).
Axes are always part of an axis rect, see QCPAxisRect.
\image html AxisNamesOverview.png
<center>Naming convention of axis parts</center>
\n
\image html AxisRectSpacingOverview.png
<center>Overview of the spacings and paddings that define the geometry of an axis. The dashed gray line
on the left represents the QCustomPlot widget border.</center>
*/
/* start of documentation of inline functions */
/*! \fn Qt::Orientation QCPAxis::orientation() const
Returns the orientation of the axis. The axis orientation (horizontal or vertical) is deduced
from the axis type (left, top, right or bottom).
*/
/*! \fn QCPGrid *QCPAxis::grid() const
Returns the \ref QCPGrid instance belonging to this axis. Access it to set details about the way the
grid is displayed.
*/
/* end of documentation of inline functions */
/* start of documentation of signals */
/*! \fn void QCPAxis::ticksRequest()
This signal is emitted when \ref setAutoTicks is false and the axis is about to generate tick
labels for a replot.
Modifying the tick positions can be done with \ref setTickVector. If you also want to control the
tick labels, set \ref setAutoTickLabels to false and also provide the labels with \ref
setTickVectorLabels.
If you only want static ticks you probably don't need this signal, since you can just set the
tick vector (and possibly tick label vector) once. However, if you want to provide ticks (and
maybe labels) dynamically, e.g. depending on the current axis range, connect a slot to this
signal and set the vector/vectors there.
*/
/*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange)
This signal is emitted when the range of this axis has changed. You can connect it to the \ref
setRange slot of another axis to communicate the new range to the other axis, in order for it to
be synchronized.
*/
/*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange)
\overload
Additionally to the new range, this signal also provides the previous range held by the axis as
\a oldRange.
*/
/*! \fn void QCPAxis::selectionChanged(QCPAxis::SelectableParts selection)
This signal is emitted when the selection state of this axis has changed, either by user interaction
or by a direct call to \ref setSelectedParts.
*/
/* end of documentation of signals */
/*!
Constructs an Axis instance of Type \a type for the axis rect \a parent.
You shouldn't instantiate axes directly, rather use \ref QCPAxisRect::addAxis.
*/
QCPAxis::QCPAxis(QCPAxisRect *parent, AxisType type) :
QCPLayerable(parent->parentPlot(), "", parent),
// axis base:
mAxisType(type),
mAxisRect(parent),
mOffset(0),
mPadding(5),
mOrientation((type == atBottom || type == atTop) ? Qt::Horizontal : Qt::Vertical),
mSelectableParts(spAxis | spTickLabels | spAxisLabel),
mSelectedParts(spNone),
mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
mSelectedBasePen(QPen(Qt::blue, 2)),
mLowerEnding(QCPLineEnding::esNone),
mUpperEnding(QCPLineEnding::esNone),
// axis label:
mLabelPadding(0),
mLabel(""),
mLabelFont(mParentPlot->font()),
mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)),
mLabelColor(Qt::black),
mSelectedLabelColor(Qt::blue),
// tick labels:
mTickLabelPadding(0),
mTickLabels(true),
mAutoTickLabels(true),
mTickLabelRotation(0),
mTickLabelType(ltNumber),
mTickLabelFont(mParentPlot->font()),
mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)),
mTickLabelColor(Qt::black),
mSelectedTickLabelColor(Qt::blue),
mDateTimeFormat("hh:mm:ss\ndd.MM.yy"),
mDateTimeSpec(Qt::LocalTime),
mNumberPrecision(6),
mNumberFormatChar('g'),
mNumberBeautifulPowers(true),
mNumberMultiplyCross(false),
// ticks and subticks:
mTicks(true),
mTickStep(1),
mSubTickCount(4),
mAutoTickCount(6),
mAutoTicks(true),
mAutoTickStep(true),
mAutoSubTicks(true),
mTickLengthIn(5),
mTickLengthOut(0),
mSubTickLengthIn(2),
mSubTickLengthOut(0),
mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
mSelectedTickPen(QPen(Qt::blue, 2)),
mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
mSelectedSubTickPen(QPen(Qt::blue, 2)),
// scale and range:
mRange(0, 5),
mRangeReversed(false),
mScaleType(stLinear),
mScaleLogBase(10),
mScaleLogBaseLogInv(1.0/qLn(mScaleLogBase)),
// internal members:
mGrid(new QCPGrid(this)),
mLabelCache(16), // cache at most 16 (tick) labels
mLowestVisibleTick(0),
mHighestVisibleTick(-1),
mExponentialChar('e'), // will be updated with locale sensitive values in setupTickVector
mPositiveSignChar('+'), // will be updated with locale sensitive values in setupTickVector
mCachedMarginValid(false),
mCachedMargin(0)
{
mGrid->setVisible(false);
setAntialiased(false);
setLayer(mParentPlot->currentLayer()); // it's actually on that layer already, but we want it in front of the grid, so we place it on there again
if (type == atTop)
{
setTickLabelPadding(3);
setLabelPadding(6);
} else if (type == atRight)
{
setTickLabelPadding(7);
setLabelPadding(12);
} else if (type == atBottom)
{
setTickLabelPadding(3);
setLabelPadding(3);
} else if (type == atLeft)
{
setTickLabelPadding(5);
setLabelPadding(10);
}
}
/* No documentation as it is a property getter */
QString QCPAxis::numberFormat() const
{
QString result;
result.append(mNumberFormatChar);
if (mNumberBeautifulPowers)
{
result.append("b");
if (mNumberMultiplyCross)
result.append("c");
}
return result;
}
/*!
Sets whether the axis uses a linear scale or a logarithmic scale. If \a type is set to \ref
stLogarithmic, the logarithm base can be set with \ref setScaleLogBase. In logarithmic axis
scaling, major tick marks appear at all powers of the logarithm base. Properties like tick step
(\ref setTickStep) don't apply in logarithmic scaling. If you wish a decimal base but less major
ticks, consider choosing a logarithm base of 100, 1000 or even higher.
If \a type is \ref stLogarithmic and the number format (\ref setNumberFormat) uses the 'b' option
(beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10
[superscript] n", which looks unnatural for logarithmic scaling (the "1 [multiplication sign]"
part). To only display the decimal power, set the number precision to zero with
\ref setNumberPrecision.
*/
void QCPAxis::setScaleType(ScaleType type)
{
if (mScaleType != type)
{
mScaleType = type;
if (mScaleType == stLogarithmic)
mRange = mRange.sanitizedForLogScale();
mCachedMarginValid = false;
}
}
/*!
If \ref setScaleType is set to \ref stLogarithmic, \a base will be the logarithm base of the
scaling. In logarithmic axis scaling, major tick marks appear at all powers of \a base.
Properties like tick step (\ref setTickStep) don't apply in logarithmic scaling. If you wish a decimal base but
less major ticks, consider choosing \a base 100, 1000 or even higher.
*/
void QCPAxis::setScaleLogBase(double base)
{
if (base > 1)
{
mScaleLogBase = base;
mScaleLogBaseLogInv = 1.0/qLn(mScaleLogBase); // buffer for faster baseLog() calculation
mCachedMarginValid = false;
} else
qDebug() << Q_FUNC_INFO << "Invalid logarithmic scale base (must be greater 1):" << base;
}
/*!
Sets the range of the axis.
This slot may be connected with the \ref rangeChanged signal of another axis so this axis
is always synchronized with the other axis range, when it changes.
To invert the direction of an axis, use \ref setRangeReversed.
*/
void QCPAxis::setRange(const QCPRange &range)
{
if (range.lower == mRange.lower && range.upper == mRange.upper)
return;
if (!QCPRange::validRange(range)) return;
QCPRange oldRange = mRange;
if (mScaleType == stLogarithmic)
{
mRange = range.sanitizedForLogScale();
} else
{
mRange = range.sanitizedForLinScale();
}
mCachedMarginValid = false;
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
(When \ref QCustomPlot::setInteractions contains iSelectAxes.)
However, even when \a selectable is set to a value not allowing the selection of a specific part,
it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
directly.
\see SelectablePart, setSelectedParts
*/
void QCPAxis::setSelectableParts(const SelectableParts &selectable)
{
mSelectableParts = selectable;
}
/*!
Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part
is selected, it uses a different pen/font.
The entire selection mechanism for axes is handled automatically when \ref
QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you
wish to change the selection state manually.
This function can change the selection state of a part, independent of the \ref setSelectableParts setting.
emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
\see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen,
setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor
*/
void QCPAxis::setSelectedParts(const SelectableParts &selected)
{
if (mSelectedParts != selected)
{
if (mSelectedParts.testFlag(spTickLabels) != selected.testFlag(spTickLabels))
mLabelCache.clear();
mSelectedParts = selected;
emit selectionChanged(mSelectedParts);
}
}
/*!
\overload
Sets the lower and upper bound of the axis range.
To invert the direction of an axis, use \ref setRangeReversed.
There is also a slot to set a range, see \ref setRange(const QCPRange &range).
*/
void QCPAxis::setRange(double lower, double upper)
{
if (lower == mRange.lower && upper == mRange.upper)
return;
if (!QCPRange::validRange(lower, upper)) return;
QCPRange oldRange = mRange;
mRange.lower = lower;
mRange.upper = upper;
if (mScaleType == stLogarithmic)
{
mRange = mRange.sanitizedForLogScale();
} else
{
mRange = mRange.sanitizedForLinScale();
}
mCachedMarginValid = false;
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
\overload
Sets the range of the axis.
The \a position coordinate indicates together with the \a alignment parameter, where the new
range will be positioned. \a size defines the size of the new axis range. \a alignment may be
Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border,
or center of the range to be aligned with \a position. Any other values of \a alignment will
default to Qt::AlignCenter.
*/
void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment)
{
if (alignment == Qt::AlignLeft)
setRange(position, position+size);
else if (alignment == Qt::AlignRight)
setRange(position-size, position);
else // alignment == Qt::AlignCenter
setRange(position-size/2.0, position+size/2.0);
}
/*!
Sets the lower bound of the axis range. The upper bound is not changed.
\see setRange
*/
void QCPAxis::setRangeLower(double lower)
{
if (mRange.lower == lower)
return;
QCPRange oldRange = mRange;
mRange.lower = lower;
if (mScaleType == stLogarithmic)
{
mRange = mRange.sanitizedForLogScale();
} else
{
mRange = mRange.sanitizedForLinScale();
}
mCachedMarginValid = false;
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
Sets the upper bound of the axis range. The lower bound is not changed.
\see setRange
*/
void QCPAxis::setRangeUpper(double upper)
{
if (mRange.upper == upper)
return;
QCPRange oldRange = mRange;
mRange.upper = upper;
if (mScaleType == stLogarithmic)
{
mRange = mRange.sanitizedForLogScale();
} else
{
mRange = mRange.sanitizedForLinScale();
}
mCachedMarginValid = false;
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal
axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the
direction of increasing values is inverted.
Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part
of the \ref setRange interface will still reference the mathematically smaller number than the \a
upper part.
*/
void QCPAxis::setRangeReversed(bool reversed)
{
if (mRangeReversed != reversed)
{
mRangeReversed = reversed;
mCachedMarginValid = false;
}
}
/*!
Sets whether the tick positions should be calculated automatically (either from an automatically
generated tick step or a tick step provided manually via \ref setTickStep, see \ref setAutoTickStep).
If \a on is set to false, you must provide the tick positions manually via \ref setTickVector.
For these manual ticks you may let QCPAxis generate the appropriate labels automatically by
leaving \ref setAutoTickLabels set to true. If you also wish to control the displayed labels
manually, set \ref setAutoTickLabels to false and provide the label strings with \ref
setTickVectorLabels.
If you need dynamically calculated tick vectors (and possibly tick label vectors), set the
vectors in a slot connected to the \ref ticksRequest signal.
\see setAutoTickLabels, setAutoSubTicks, setAutoTickCount, setAutoTickStep
*/
void QCPAxis::setAutoTicks(bool on)
{
if (mAutoTicks != on)
{
mAutoTicks = on;
mCachedMarginValid = false;
}
}
/*!
When \ref setAutoTickStep is true, \a approximateCount determines how many ticks should be
generated in the visible range, approximately.
It's not guaranteed that this number of ticks is met exactly, but approximately within a
tolerance of about two.
Only values greater than zero are accepted as \a approximateCount.
\see setAutoTickStep, setAutoTicks, setAutoSubTicks
*/
void QCPAxis::setAutoTickCount(int approximateCount)
{
if (mAutoTickCount != approximateCount)
{
if (approximateCount > 0)
{
mAutoTickCount = approximateCount;
mCachedMarginValid = false;
} else
qDebug() << Q_FUNC_INFO << "approximateCount must be greater than zero:" << approximateCount;
}
}
/*!
Sets whether the tick labels are generated automatically. Depending on the tick label type (\ref
ltNumber or \ref ltDateTime), the labels will either show the coordinate as floating point
number (\ref setNumberFormat), or a date/time formatted according to \ref setDateTimeFormat.
If \a on is set to false, you should provide the tick labels via \ref setTickVectorLabels. This
is usually used in a combination with \ref setAutoTicks set to false for complete control over
tick positions and labels, e.g. when the ticks should be at multiples of pi and show "2pi", "3pi"
etc. as tick labels.
If you need dynamically calculated tick vectors (and possibly tick label vectors), set the
vectors in a slot connected to the \ref ticksRequest signal.
\see setAutoTicks
*/
void QCPAxis::setAutoTickLabels(bool on)
{
if (mAutoTickLabels != on)
{
mAutoTickLabels = on;
mCachedMarginValid = false;
}
}
/*!
Sets whether the tick step, i.e. the interval between two (major) ticks, is calculated
automatically. If \a on is set to true, the axis finds a tick step that is reasonable for human
readable plots.
The number of ticks the algorithm aims for within the visible range can be specified with \ref
setAutoTickCount.
If \a on is set to false, you may set the tick step manually with \ref setTickStep.
\see setAutoTicks, setAutoSubTicks, setAutoTickCount
*/
void QCPAxis::setAutoTickStep(bool on)
{
if (mAutoTickStep != on)
{
mAutoTickStep = on;
mCachedMarginValid = false;
}
}
/*!
Sets whether the number of sub ticks in one tick interval is determined automatically. This
works, as long as the tick step mantissa is a multiple of 0.5. When \ref setAutoTickStep is
enabled, this is always the case.
When \a on is set to false, you may set the sub tick count with \ref setSubTickCount manually.
\see setAutoTickCount, setAutoTicks, setAutoTickStep
*/
void QCPAxis::setAutoSubTicks(bool on)
{
if (mAutoSubTicks != on)
{
mAutoSubTicks = on;
mCachedMarginValid = false;
}
}
/*!
Sets whether tick marks are displayed.
Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
that, see \ref setTickLabels.
*/
void QCPAxis::setTicks(bool show)
{
if (mTicks != show)
{
mTicks = show;
mCachedMarginValid = false;
}
}
/*!
Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks.
*/
void QCPAxis::setTickLabels(bool show)
{
if (mTickLabels != show)
{
mTickLabels = show;
mCachedMarginValid = false;
}
}
/*!
Sets the distance between the axis base line (including any outward ticks) and the tick labels.
\see setLabelPadding, setPadding
*/
void QCPAxis::setTickLabelPadding(int padding)
{
if (mTickLabelPadding != padding)
{
mTickLabelPadding = padding;
mCachedMarginValid = false;
}
}
/*!
Sets whether the tick labels display numbers or dates/times.
If \a type is set to \ref ltNumber, the format specifications of \ref setNumberFormat apply.
If \a type is set to \ref ltDateTime, the format specifications of \ref setDateTimeFormat apply.
In QCustomPlot, date/time coordinates are <tt>double</tt> numbers representing the seconds since
1970-01-01T00:00:00 UTC. This format can be retrieved from QDateTime objects with the
QDateTime::toTime_t() function. Since this only gives a resolution of one second, there is also
the QDateTime::toMSecsSinceEpoch() function which returns the timespan described above in
milliseconds. Divide its return value by 1000.0 to get a value with the format needed for
date/time plotting, with a resolution of one millisecond.
Using the toMSecsSinceEpoch function allows dates that go back to 2nd January 4713 B.C.
(represented by a negative number), unlike the toTime_t function, which works with unsigned
integers and thus only goes back to 1st January 1970. So both for range and accuracy, use of
toMSecsSinceEpoch()/1000.0 should be preferred as key coordinate for date/time axes.
\see setTickLabels
*/
void QCPAxis::setTickLabelType(LabelType type)
{
if (mTickLabelType != type)
{
mTickLabelType = type;
mCachedMarginValid = false;
}
}
/*!
Sets the font of the tick labels.
\see setTickLabels, setTickLabelColor
*/
void QCPAxis::setTickLabelFont(const QFont &font)
{
if (font != mTickLabelFont)
{
mTickLabelFont = font;
mCachedMarginValid = false;
mLabelCache.clear();
}
}
/*!
Sets the color of the tick labels.
\see setTickLabels, setTickLabelFont
*/
void QCPAxis::setTickLabelColor(const QColor &color)
{
if (color != mTickLabelColor)
{
mTickLabelColor = color;
mCachedMarginValid = false;
mLabelCache.clear();
}
}
/*!
Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else,
the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values
from -90 to 90 degrees.
If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For
other angles, the label is drawn with an offset such that it seems to point toward or away from
the tick mark.
*/
void QCPAxis::setTickLabelRotation(double degrees)
{
if (!qFuzzyIsNull(degrees-mTickLabelRotation))
{
mTickLabelRotation = qBound(-90.0, degrees, 90.0);
mCachedMarginValid = false;
mLabelCache.clear();
}
}
/*!
Sets the format in which dates and times are displayed as tick labels, if \ref setTickLabelType is \ref ltDateTime.
for details about the \a format string, see the documentation of QDateTime::toString().
Newlines can be inserted with "\n".
\see setDateTimeSpec
*/
void QCPAxis::setDateTimeFormat(const QString &format)
{
if (mDateTimeFormat != format)
{
mDateTimeFormat = format;
mCachedMarginValid = false;
mLabelCache.clear();
}
}
/*!
Sets the time spec that is used for the date time values when \ref setTickLabelType is \ref
ltDateTime.
The default value of QDateTime objects (and also QCustomPlot) is <tt>Qt::LocalTime</tt>. However,
if the date time values passed to QCustomPlot are given in the UTC spec, set \a
timeSpec to <tt>Qt::UTC</tt> to get the correct axis labels.
\see setDateTimeFormat
*/
void QCPAxis::setDateTimeSpec(const Qt::TimeSpec &timeSpec)
{
mDateTimeSpec = timeSpec;
}
/*!
Sets the number format for the numbers drawn as tick labels (if tick label type is \ref
ltNumber). This \a formatCode is an extended version of the format code used e.g. by
QString::number() and QLocale::toString(). For reference about that, see the "Argument Formats"
section in the detailed description of the QString class. \a formatCode is a string of one, two
or three characters. The first character is identical to the normal format code used by Qt. In
short, this means: 'e'/'E' scientific format, 'f' fixed format, 'g'/'G' scientific or fixed,
whichever is shorter.
The second and third characters are optional and specific to QCustomPlot:\n
If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g.
"5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for
"beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5
[multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot.
If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can
be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
cross and 183 (0xB7) for the dot.
If the scale type (\ref setScaleType) is \ref stLogarithmic and the \a formatCode uses the 'b'
option (beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10
[superscript] n", which looks unnatural for logarithmic scaling (the "1 [multiplication sign]"
part). To only display the decimal power, set the number precision to zero with \ref
setNumberPrecision.
Examples for \a formatCode:
\li \c g normal format code behaviour. If number is small, fixed format is used, if number is large,
normal scientific format is used
\li \c gb If number is small, fixed format is used, if number is large, scientific format is used with
beautifully typeset decimal powers and a dot as multiplication sign
\li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as
multiplication sign
\li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal
powers. Format code will be reduced to 'f'.
\li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format
code will not be changed.
*/
void QCPAxis::setNumberFormat(const QString &formatCode)
{
if (formatCode.isEmpty())
{
qDebug() << Q_FUNC_INFO << "Passed formatCode is empty";
return;
}
mLabelCache.clear();
mCachedMarginValid = false;
// interpret first char as number format char:
QString allowedFormatChars = "eEfgG";
if (allowedFormatChars.contains(formatCode.at(0)))
{
mNumberFormatChar = formatCode.at(0).toLatin1();
} else
{
qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode;
return;
}
if (formatCode.length() < 2)
{
mNumberBeautifulPowers = false;
mNumberMultiplyCross = false;
return;
}
// interpret second char as indicator for beautiful decimal powers:
if (formatCode.at(1) == 'b' && (mNumberFormatChar == 'e' || mNumberFormatChar == 'g'))
{
mNumberBeautifulPowers = true;
} else
{
qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode;
return;
}
if (formatCode.length() < 3)
{
mNumberMultiplyCross = false;
return;
}
// interpret third char as indicator for dot or cross multiplication symbol:
if (formatCode.at(2) == 'c')
{
mNumberMultiplyCross = true;
} else if (formatCode.at(2) == 'd')
{
mNumberMultiplyCross = false;
} else
{
qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode;
return;
}
}
/*!
Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
for details. The effect of precisions are most notably for number Formats starting with 'e', see
\ref setNumberFormat
If the scale type (\ref setScaleType) is \ref stLogarithmic and the number format (\ref
setNumberFormat) uses the 'b' format code (beautifully typeset decimal powers), the display
usually is "1 [multiplication sign] 10 [superscript] n", which looks unnatural for logarithmic
scaling (the redundant "1 [multiplication sign]" part). To only display the decimal power "10
[superscript] n", set \a precision to zero.
*/
void QCPAxis::setNumberPrecision(int precision)
{
if (mNumberPrecision != precision)
{
mNumberPrecision = precision;
mCachedMarginValid = false;
}
}
/*!
If \ref setAutoTickStep is set to false, use this function to set the tick step manually.
The tick step is the interval between (major) ticks, in plot coordinates.
\see setSubTickCount
*/
void QCPAxis::setTickStep(double step)
{
if (mTickStep != step)
{
mTickStep = step;
mCachedMarginValid = false;
}
}
/*!
If you want full control over what ticks (and possibly labels) the axes show, this function is
used to set the coordinates at which ticks will appear.\ref setAutoTicks must be disabled, else
the provided tick vector will be overwritten with automatically generated tick coordinates upon
replot. The labels of the ticks can be generated automatically when \ref setAutoTickLabels is
left enabled. If it is disabled, you can set the labels manually with \ref setTickVectorLabels.
\a vec is a vector containing the positions of the ticks, in plot coordinates.
\warning \a vec must be sorted in ascending order, no additional checks are made to ensure this.
\see setTickVectorLabels
*/
void QCPAxis::setTickVector(const QVector<double> &vec)
{
// don't check whether mTickVector != vec here, because it takes longer than we would save
mTickVector = vec;
mCachedMarginValid = false;
}
/*!
If you want full control over what ticks and labels the axes show, this function is used to set a
number of QStrings that will be displayed at the tick positions which you need to provide with
\ref setTickVector. These two vectors should have the same size. (Note that you need to disable
\ref setAutoTicks and \ref setAutoTickLabels first.)
\a vec is a vector containing the labels of the ticks. The entries correspond to the respective
indices in the tick vector, passed via \ref setTickVector.
\see setTickVector
*/
void QCPAxis::setTickVectorLabels(const QVector<QString> &vec)
{
// don't check whether mTickVectorLabels != vec here, because it takes longer than we would save
mTickVectorLabels = vec;
mCachedMarginValid = false;
}
/*!
Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
zero, the tick labels and axis label will increase their distance to the axis accordingly, so
they won't collide with the ticks.
\see setSubTickLength
*/
void QCPAxis::setTickLength(int inside, int outside)
{
if (mTickLengthIn != inside)
{
mTickLengthIn = inside;
}
if (mTickLengthOut != outside)
{
mTickLengthOut = outside;
mCachedMarginValid = false; // only outside tick length can change margin
}
}
/*!
Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach
inside the plot.
\see setTickLengthOut, setSubTickLength
*/
void QCPAxis::setTickLengthIn(int inside)
{
if (mTickLengthIn != inside)
{
mTickLengthIn = inside;
}
}
/*!
Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach
outside the plot. If \a outside is greater than zero, the tick labels and axis label will
increase their distance to the axis accordingly, so they won't collide with the ticks.
\see setTickLengthIn, setSubTickLength
*/
void QCPAxis::setTickLengthOut(int outside)
{
if (mTickLengthOut != outside)
{
mTickLengthOut = outside;
mCachedMarginValid = false; // only outside tick length can change margin
}
}
/*!
Sets the number of sub ticks in one (major) tick step. A sub tick count of three for example,
divides the tick intervals in four sub intervals.
By default, the number of sub ticks is chosen automatically in a reasonable manner as long as the
mantissa of the tick step is a multiple of 0.5. When \ref setAutoTickStep is enabled, this is
always the case.
If you want to disable automatic sub tick count and use this function to set the count manually,
see \ref setAutoSubTicks.
*/
void QCPAxis::setSubTickCount(int count)
{
mSubTickCount = count;
}
/*!
Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside
the plot and \a outside is the length they will reach outside the plot. If \a outside is greater
than zero, the tick labels and axis label will increase their distance to the axis accordingly,
so they won't collide with the ticks.
*/
void QCPAxis::setSubTickLength(int inside, int outside)
{
if (mSubTickLengthIn != inside)
{
mSubTickLengthIn = inside;
}
if (mSubTickLengthOut != outside)
{
mSubTickLengthOut = outside;
mCachedMarginValid = false; // only outside tick length can change margin
}
}
/*!
Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside
the plot.
\see setSubTickLengthOut, setTickLength
*/
void QCPAxis::setSubTickLengthIn(int inside)
{
if (mSubTickLengthIn != inside)
{
mSubTickLengthIn = inside;
}
}
/*!
Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach
outside the plot. If \a outside is greater than zero, the tick labels will increase their
distance to the axis accordingly, so they won't collide with the ticks.
\see setSubTickLengthIn, setTickLength
*/
void QCPAxis::setSubTickLengthOut(int outside)
{
if (mSubTickLengthOut != outside)
{
mSubTickLengthOut = outside;
mCachedMarginValid = false; // only outside tick length can change margin
}
}
/*!
Sets the pen, the axis base line is drawn with.
\see setTickPen, setSubTickPen
*/
void QCPAxis::setBasePen(const QPen &pen)
{
mBasePen = pen;
}
/*!
Sets the pen, tick marks will be drawn with.
\see setTickLength, setBasePen
*/
void QCPAxis::setTickPen(const QPen &pen)
{
mTickPen = pen;
}
/*!
Sets the pen, subtick marks will be drawn with.
\see setSubTickCount, setSubTickLength, setBasePen
*/
void QCPAxis::setSubTickPen(const QPen &pen)
{
mSubTickPen = pen;
}
/*!
Sets the font of the axis label.
\see setLabelColor
*/
void QCPAxis::setLabelFont(const QFont &font)
{
if (mLabelFont != font)
{
mLabelFont = font;
mCachedMarginValid = false;
}
}
/*!
Sets the color of the axis label.
\see setLabelFont
*/
void QCPAxis::setLabelColor(const QColor &color)
{
mLabelColor = color;
}
/*!
Sets the text of the axis label that will be shown below/above or next to the axis, depending on
its orientation. To disable axis labels, pass an empty string as \a str.
*/
void QCPAxis::setLabel(const QString &str)
{
if (mLabel != str)
{
mLabel = str;
mCachedMarginValid = false;
}
}
/*!
Sets the distance between the tick labels and the axis label.
\see setTickLabelPadding, setPadding
*/
void QCPAxis::setLabelPadding(int padding)
{
if (mLabelPadding != padding)
{
mLabelPadding = padding;
mCachedMarginValid = false;
}
}
/*!
Sets the padding of the axis.
When \ref QCPAxisRect::setAutoMargins is enabled, the padding is the additional outer most space,
that is left blank.
The axis padding has no meaning if \ref QCPAxisRect::setAutoMargins is disabled.
\see setLabelPadding, setTickLabelPadding
*/
void QCPAxis::setPadding(int padding)
{
if (mPadding != padding)
{
mPadding = padding;
mCachedMarginValid = false;
}
}
/*!
Sets the offset the axis has to its axis rect side.
If an axis rect side has multiple axes, only the offset of the inner most axis has meaning. The offset of the other axes
is controlled automatically, to place the axes at appropriate positions to prevent them from overlapping.
*/
void QCPAxis::setOffset(int offset)
{
mOffset = offset;
}
/*!
Sets the font that is used for tick labels when they are selected.
\see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPAxis::setSelectedTickLabelFont(const QFont &font)
{
if (font != mSelectedTickLabelFont)
{
mSelectedTickLabelFont = font;
mLabelCache.clear();
// don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
}
}
/*!
Sets the font that is used for the axis label when it is selected.
\see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPAxis::setSelectedLabelFont(const QFont &font)
{
mSelectedLabelFont = font;
// don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
}
/*!
Sets the color that is used for tick labels when they are selected.
\see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPAxis::setSelectedTickLabelColor(const QColor &color)
{
if (color != mSelectedTickLabelColor)
{
mSelectedTickLabelColor = color;
mLabelCache.clear();
}
}
/*!
Sets the color that is used for the axis label when it is selected.
\see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPAxis::setSelectedLabelColor(const QColor &color)
{
mSelectedLabelColor = color;
}
/*!
Sets the pen that is used to draw the axis base line when selected.
\see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPAxis::setSelectedBasePen(const QPen &pen)
{
mSelectedBasePen = pen;
}
/*!
Sets the pen that is used to draw the (major) ticks when selected.
\see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPAxis::setSelectedTickPen(const QPen &pen)
{
mSelectedTickPen = pen;
}
/*!
Sets the pen that is used to draw the subticks when selected.
\see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
*/
void QCPAxis::setSelectedSubTickPen(const QPen &pen)
{
mSelectedSubTickPen = pen;
}
/*!
Sets the style for the lower axis ending. See the documentation of QCPLineEnding for available
styles.
For horizontal axes, this method refers to the left ending, for vertical axes the bottom ending.
Note that this meaning does not change when the axis range is reversed with \ref
setRangeReversed.
\see setUpperEnding
*/
void QCPAxis::setLowerEnding(const QCPLineEnding &ending)
{
mLowerEnding = ending;
}
/*!
Sets the style for the upper axis ending. See the documentation of QCPLineEnding for available
styles.
For horizontal axes, this method refers to the right ending, for vertical axes the top ending.
Note that this meaning does not change when the axis range is reversed with \ref
setRangeReversed.
\see setLowerEnding
*/
void QCPAxis::setUpperEnding(const QCPLineEnding &ending)
{
mUpperEnding = ending;
}
/*!
If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper
bounds of the range. The range is simply moved by \a diff.
If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This
corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff).
*/
void QCPAxis::moveRange(double diff)
{
QCPRange oldRange = mRange;
if (mScaleType == stLinear)
{
mRange.lower += diff;
mRange.upper += diff;
} else // mScaleType == stLogarithmic
{
mRange.lower *= diff;
mRange.upper *= diff;
}
mCachedMarginValid = false;
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
around 1.0 will have moved symmetrically closer to 1.0).
*/
void QCPAxis::scaleRange(double factor, double center)
{
QCPRange oldRange = mRange;
if (mScaleType == stLinear)
{
QCPRange newRange;
newRange.lower = (mRange.lower-center)*factor + center;
newRange.upper = (mRange.upper-center)*factor + center;
if (QCPRange::validRange(newRange))
mRange = newRange.sanitizedForLinScale();
} else // mScaleType == stLogarithmic
{
if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range
{
QCPRange newRange;
newRange.lower = pow(mRange.lower/center, factor)*center;
newRange.upper = pow(mRange.upper/center, factor)*center;
if (QCPRange::validRange(newRange))
mRange = newRange.sanitizedForLogScale();
} else
qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center;
}
mCachedMarginValid = false;
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
Scales the range of this axis to have a certain scale \a ratio to \a otherAxis. The scaling will
be done around the center of the current axis range.
For example, if \a ratio is 1, this axis is the \a yAxis and \a otherAxis is \a xAxis, graphs
plotted with those axes will appear in a 1:1 aspect ratio, independent of the aspect ratio the
axis rect has.
This is an operation that changes the range of this axis once, it doesn't fix the scale ratio
indefinitely. Note that calling this function in the constructor of the QCustomPlot's parent
won't have the desired effect, since the widget dimensions aren't defined yet, and a resizeEvent
will follow.
*/
void QCPAxis::setScaleRatio(const QCPAxis *otherAxis, double ratio)
{
int otherPixelSize, ownPixelSize;
if (otherAxis->orientation() == Qt::Horizontal)
otherPixelSize = otherAxis->axisRect()->width();
else
otherPixelSize = otherAxis->axisRect()->height();
if (orientation() == Qt::Horizontal)
ownPixelSize = axisRect()->width();
else
ownPixelSize = axisRect()->height();
double newRangeSize = ratio*otherAxis->range().size()*ownPixelSize/(double)otherPixelSize;
setRange(range().center(), newRangeSize, Qt::AlignCenter);
}
/*!
Changes the axis range such that all plottables associated with this axis are fully visible in
that dimension.
\see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
*/
void QCPAxis::rescale(bool onlyVisiblePlottables)
{
QList<QCPAbstractPlottable*> p = plottables();
QCPRange newRange;
bool haveRange = false;
for (int i=0; i<p.size(); ++i)
{
if (!p.at(i)->realVisibility() && onlyVisiblePlottables)
continue;
QCPRange plottableRange;
bool validRange;
QCPAbstractPlottable::SignDomain signDomain = QCPAbstractPlottable::sdBoth;
if (mScaleType == stLogarithmic)
signDomain = (mRange.upper < 0 ? QCPAbstractPlottable::sdNegative : QCPAbstractPlottable::sdPositive);
if (p.at(i)->keyAxis() == this)
plottableRange = p.at(i)->getKeyRange(validRange, signDomain);
else
plottableRange = p.at(i)->getValueRange(validRange, signDomain);
if (validRange)
{
if (!haveRange)
newRange = plottableRange;
else
newRange.expand(plottableRange);
haveRange = true;
}
}
if (haveRange)
{
if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
{
double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
if (mScaleType == stLinear)
{
newRange.lower = center-mRange.size()/2.0;
newRange.upper = center+mRange.size()/2.0;
} else // mScaleType == stLogarithmic
{
newRange.lower = center/qSqrt(mRange.upper/mRange.lower);
newRange.upper = center*qSqrt(mRange.upper/mRange.lower);
}
}
setRange(newRange);
}
}
/*!
Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates.
*/
double QCPAxis::pixelToCoord(double value) const
{
if (orientation() == Qt::Horizontal)
{
if (mScaleType == stLinear)
{
if (!mRangeReversed)
return (value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.lower;
else
return -(value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.upper;
} else // mScaleType == stLogarithmic
{
if (!mRangeReversed)
return pow(mRange.upper/mRange.lower, (value-mAxisRect->left())/(double)mAxisRect->width())*mRange.lower;
else
return pow(mRange.upper/mRange.lower, (mAxisRect->left()-value)/(double)mAxisRect->width())*mRange.upper;
}
} else // orientation() == Qt::Vertical
{
if (mScaleType == stLinear)
{
if (!mRangeReversed)
return (mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.lower;
else
return -(mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.upper;
} else // mScaleType == stLogarithmic
{
if (!mRangeReversed)
return pow(mRange.upper/mRange.lower, (mAxisRect->bottom()-value)/(double)mAxisRect->height())*mRange.lower;
else
return pow(mRange.upper/mRange.lower, (value-mAxisRect->bottom())/(double)mAxisRect->height())*mRange.upper;
}
}
}
/*!
Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget.
*/
double QCPAxis::coordToPixel(double value) const
{
if (orientation() == Qt::Horizontal)
{
if (mScaleType == stLinear)
{
if (!mRangeReversed)
return (value-mRange.lower)/mRange.size()*mAxisRect->width()+mAxisRect->left();
else
return (mRange.upper-value)/mRange.size()*mAxisRect->width()+mAxisRect->left();
} else // mScaleType == stLogarithmic
{
if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it outside visible range
return !mRangeReversed ? mAxisRect->right()+200 : mAxisRect->left()-200;
else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just draw it outside visible range
return !mRangeReversed ? mAxisRect->left()-200 : mAxisRect->right()+200;
else
{
if (!mRangeReversed)
return baseLog(value/mRange.lower)/baseLog(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
else
return baseLog(mRange.upper/value)/baseLog(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
}
}
} else // orientation() == Qt::Vertical
{
if (mScaleType == stLinear)
{
if (!mRangeReversed)
return mAxisRect->bottom()-(value-mRange.lower)/mRange.size()*mAxisRect->height();
else
return mAxisRect->bottom()-(mRange.upper-value)/mRange.size()*mAxisRect->height();
} else // mScaleType == stLogarithmic
{
if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it outside visible range
return !mRangeReversed ? mAxisRect->top()-200 : mAxisRect->bottom()+200;
else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just draw it outside visible range
return !mRangeReversed ? mAxisRect->bottom()+200 : mAxisRect->top()-200;
else
{
if (!mRangeReversed)
return mAxisRect->bottom()-baseLog(value/mRange.lower)/baseLog(mRange.upper/mRange.lower)*mAxisRect->height();
else
return mAxisRect->bottom()-baseLog(mRange.upper/value)/baseLog(mRange.upper/mRange.lower)*mAxisRect->height();
}
}
}
}
/*!
Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function
is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this
function does not change the current selection state of the axis.
If the axis is not visible (\ref setVisible), this function always returns \ref spNone.
\see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions
*/
QCPAxis::SelectablePart QCPAxis::getPartAt(const QPointF &pos) const
{
if (!mVisible)
return spNone;
if (mAxisSelectionBox.contains(pos.toPoint()))
return spAxis;
else if (mTickLabelsSelectionBox.contains(pos.toPoint()))
return spTickLabels;
else if (mLabelSelectionBox.contains(pos.toPoint()))
return spAxisLabel;
else
return spNone;
}
/* inherits documentation from base class */
double QCPAxis::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
if (!mParentPlot) return -1;
SelectablePart part = getPartAt(pos);
if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone)
return -1;
if (details)
details->setValue(part);
return mParentPlot->selectionTolerance()*0.99;
}
/*!
Returns a list of all the plottables that have this axis as key or value axis.
If you are only interested in plottables of type QCPGraph, see \ref graphs.
\see graphs, items
*/
QList<QCPAbstractPlottable*> QCPAxis::plottables() const
{
QList<QCPAbstractPlottable*> result;
if (!mParentPlot) return result;
for (int i=0; i<mParentPlot->mPlottables.size(); ++i)
{
if (mParentPlot->mPlottables.at(i)->keyAxis() == this ||mParentPlot->mPlottables.at(i)->valueAxis() == this)
result.append(mParentPlot->mPlottables.at(i));
}
return result;
}
/*!
Returns a list of all the graphs that have this axis as key or value axis.
\see plottables, items
*/
QList<QCPGraph*> QCPAxis::graphs() const
{
QList<QCPGraph*> result;
if (!mParentPlot) return result;
for (int i=0; i<mParentPlot->mGraphs.size(); ++i)
{
if (mParentPlot->mGraphs.at(i)->keyAxis() == this || mParentPlot->mGraphs.at(i)->valueAxis() == this)
result.append(mParentPlot->mGraphs.at(i));
}
return result;
}
/*!
Returns a list of all the items that are associated with this axis. An item is considered
associated with an axis if at least one of its positions uses the axis as key or value axis.
\see plottables, graphs
*/
QList<QCPAbstractItem*> QCPAxis::items() const
{
QList<QCPAbstractItem*> result;
if (!mParentPlot) return result;
for (int itemId=0; itemId<mParentPlot->mItems.size(); ++itemId)
{
QList<QCPItemPosition*> positions = mParentPlot->mItems.at(itemId)->positions();
for (int posId=0; posId<positions.size(); ++posId)
{
if (positions.at(posId)->keyAxis() == this || positions.at(posId)->valueAxis() == this)
{
result.append(mParentPlot->mItems.at(itemId));
break;
}
}
}
return result;
}
/*!
Transforms a margin side to the logically corresponding axis type. (QCP::msLeft to
QCPAxis::atLeft, QCP::msRight to QCPAxis::atRight, etc.)
*/
QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side)
{
switch (side)
{
case QCP::msLeft: return atLeft;
case QCP::msRight: return atRight;
case QCP::msTop: return atTop;
case QCP::msBottom: return atBottom;
default: break;
}
qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << (int)side;
return atLeft;
}
/*! \internal
This function is called to prepare the tick vector, sub tick vector and tick label vector. If
\ref setAutoTicks is set to true, appropriate tick values are determined automatically via \ref
generateAutoTicks. If it's set to false, the signal ticksRequest is emitted, which can be used to
provide external tick positions. Then the sub tick vectors and tick label vectors are created.
*/
void QCPAxis::setupTickVectors()
{
if (!mParentPlot) return;
if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return;
// fill tick vectors, either by auto generating or by notifying user to fill the vectors himself
if (mAutoTicks)
{
generateAutoTicks();
} else
{
emit ticksRequest();
}
visibleTickBounds(mLowestVisibleTick, mHighestVisibleTick);
if (mTickVector.isEmpty())
{
mSubTickVector.clear();
return;
}
// generate subticks between ticks:
mSubTickVector.resize((mTickVector.size()-1)*mSubTickCount);
if (mSubTickCount > 0)
{
double subTickStep = 0;
double subTickPosition = 0;
int subTickIndex = 0;
bool done = false;
int lowTick = mLowestVisibleTick > 0 ? mLowestVisibleTick-1 : mLowestVisibleTick;
int highTick = mHighestVisibleTick < mTickVector.size()-1 ? mHighestVisibleTick+1 : mHighestVisibleTick;
for (int i=lowTick+1; i<=highTick; ++i)
{
subTickStep = (mTickVector.at(i)-mTickVector.at(i-1))/(double)(mSubTickCount+1);
for (int k=1; k<=mSubTickCount; ++k)
{
subTickPosition = mTickVector.at(i-1) + k*subTickStep;
if (subTickPosition < mRange.lower)
continue;
if (subTickPosition > mRange.upper)
{
done = true;
break;
}
mSubTickVector[subTickIndex] = subTickPosition;
subTickIndex++;
}
if (done) break;
}
mSubTickVector.resize(subTickIndex);
}
// generate tick labels according to tick positions:
mExponentialChar = mParentPlot->locale().exponential(); // will be needed when drawing the numbers generated here, in getTickLabelData()
mPositiveSignChar = mParentPlot->locale().positiveSign(); // will be needed when drawing the numbers generated here, in getTickLabelData()
if (mAutoTickLabels)
{
int vecsize = mTickVector.size();
mTickVectorLabels.resize(vecsize);
if (mTickLabelType == ltNumber)
{
for (int i=mLowestVisibleTick; i<=mHighestVisibleTick; ++i)
mTickVectorLabels[i] = mParentPlot->locale().toString(mTickVector.at(i), mNumberFormatChar, mNumberPrecision);
} else if (mTickLabelType == ltDateTime)
{
for (int i=mLowestVisibleTick; i<=mHighestVisibleTick; ++i)
{
#if QT_VERSION < QT_VERSION_CHECK(4, 7, 0) // use fromMSecsSinceEpoch function if available, to gain sub-second accuracy on tick labels (e.g. for format "hh:mm:ss:zzz")
mTickVectorLabels[i] = mParentPlot->locale().toString(QDateTime::fromTime_t(mTickVector.at(i)).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
#else
mTickVectorLabels[i] = mParentPlot->locale().toString(QDateTime::fromMSecsSinceEpoch(mTickVector.at(i)*1000).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
#endif
}
}
} else // mAutoTickLabels == false
{
if (mAutoTicks) // ticks generated automatically, but not ticklabels, so emit ticksRequest here for labels
{
emit ticksRequest();
}
// make sure provided tick label vector has correct (minimal) length:
if (mTickVectorLabels.size() < mTickVector.size())
mTickVectorLabels.resize(mTickVector.size());
}
}
/*! \internal
If \ref setAutoTicks is set to true, this function is called by \ref setupTickVectors to
generate reasonable tick positions (and subtick count). The algorithm tries to create
approximately <tt>mAutoTickCount</tt> ticks (set via \ref setAutoTickCount).
If the scale is logarithmic, \ref setAutoTickCount is ignored, and one tick is generated at every
power of the current logarithm base, set via \ref setScaleLogBase.
*/
void QCPAxis::generateAutoTicks()
{
if (mScaleType == stLinear)
{
if (mAutoTickStep)
{
// Generate tick positions according to linear scaling:
mTickStep = mRange.size()/(double)(mAutoTickCount+1e-10); // mAutoTickCount ticks on average, the small addition is to prevent jitter on exact integers
double magnitudeFactor = qPow(10.0, qFloor(qLn(mTickStep)/qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc.
double tickStepMantissa = mTickStep/magnitudeFactor;
if (tickStepMantissa < 5)
{
// round digit after decimal point to 0.5
mTickStep = (int)(tickStepMantissa*2)/2.0*magnitudeFactor;
} else
{
// round to first digit in multiples of 2
mTickStep = (int)(tickStepMantissa/2.0)*2.0*magnitudeFactor;
}
}
if (mAutoSubTicks)
mSubTickCount = calculateAutoSubTickCount(mTickStep);
// Generate tick positions according to mTickStep:
qint64 firstStep = floor(mRange.lower/mTickStep);
qint64 lastStep = ceil(mRange.upper/mTickStep);
int tickcount = lastStep-firstStep+1;
if (tickcount < 0) tickcount = 0;
mTickVector.resize(tickcount);
for (int i=0; i<tickcount; ++i)
mTickVector[i] = (firstStep+i)*mTickStep;
} else // mScaleType == stLogarithmic
{
// Generate tick positions according to logbase scaling:
if (mRange.lower > 0 && mRange.upper > 0) // positive range
{
double lowerMag = basePow((int)floor(baseLog(mRange.lower)));
double currentMag = lowerMag;
mTickVector.clear();
mTickVector.append(currentMag);
while (currentMag < mRange.upper && currentMag > 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
{
currentMag *= mScaleLogBase;
mTickVector.append(currentMag);
}
} else if (mRange.lower < 0 && mRange.upper < 0) // negative range
{
double lowerMag = -basePow((int)ceil(baseLog(-mRange.lower)));
double currentMag = lowerMag;
mTickVector.clear();
mTickVector.append(currentMag);
while (currentMag < mRange.upper && currentMag < 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
{
currentMag /= mScaleLogBase;
mTickVector.append(currentMag);
}
} else // invalid range for logarithmic scale, because lower and upper have different sign
{
mTickVector.clear();
qDebug() << Q_FUNC_INFO << "Invalid range for logarithmic plot: " << mRange.lower << "-" << mRange.upper;
}
}
}
/*! \internal
Called by generateAutoTicks when \ref setAutoSubTicks is set to true. Depending on the \a
tickStep between two major ticks on the axis, a different number of sub ticks is appropriate. For
Example taking 4 sub ticks for a \a tickStep of 1 makes more sense than taking 5 sub ticks,
because this corresponds to a sub tick step of 0.2, instead of the less intuitive 0.16667. Note
that a subtick count of 4 means dividing the major tick step into 5 sections.
This is implemented by a hand made lookup for integer tick steps as well as fractional tick steps
with a fractional part of (approximately) 0.5. If a tick step is different (i.e. has no
fractional part close to 0.5), the currently set sub tick count (\ref setSubTickCount) is
returned.
*/
int QCPAxis::calculateAutoSubTickCount(double tickStep) const
{
int result = mSubTickCount; // default to current setting, if no proper value can be found
// get mantissa of tickstep:
double magnitudeFactor = qPow(10.0, qFloor(qLn(tickStep)/qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc.
double tickStepMantissa = tickStep/magnitudeFactor;
// separate integer and fractional part of mantissa:
double epsilon = 0.01;
double intPartf;
int intPart;
double fracPart = modf(tickStepMantissa, &intPartf);
intPart = intPartf;
// handle cases with (almost) integer mantissa:
if (fracPart < epsilon || 1.0-fracPart < epsilon)
{
if (1.0-fracPart < epsilon)
++intPart;
switch (intPart)
{
case 1: result = 4; break; // 1.0 -> 0.2 substep
case 2: result = 3; break; // 2.0 -> 0.5 substep
case 3: result = 2; break; // 3.0 -> 1.0 substep
case 4: result = 3; break; // 4.0 -> 1.0 substep
case 5: result = 4; break; // 5.0 -> 1.0 substep
case 6: result = 2; break; // 6.0 -> 2.0 substep
case 7: result = 6; break; // 7.0 -> 1.0 substep
case 8: result = 3; break; // 8.0 -> 2.0 substep
case 9: result = 2; break; // 9.0 -> 3.0 substep
}
} else
{
// handle cases with significantly fractional mantissa:
if (qAbs(fracPart-0.5) < epsilon) // *.5 mantissa
{
switch (intPart)
{
case 1: result = 2; break; // 1.5 -> 0.5 substep
case 2: result = 4; break; // 2.5 -> 0.5 substep
case 3: result = 4; break; // 3.5 -> 0.7 substep
case 4: result = 2; break; // 4.5 -> 1.5 substep
case 5: result = 4; break; // 5.5 -> 1.1 substep (won't occur with autoTickStep from here on)
case 6: result = 4; break; // 6.5 -> 1.3 substep
case 7: result = 2; break; // 7.5 -> 2.5 substep
case 8: result = 4; break; // 8.5 -> 1.7 substep
case 9: result = 4; break; // 9.5 -> 1.9 substep
}
}
// if mantissa fraction isnt 0.0 or 0.5, don't bother finding good sub tick marks, leave default
}
return result;
}
/*! \internal
Draws the axis with the specified \a painter.
The selection boxes (mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox) are set
here, too.
*/
void QCPAxis::draw(QCPPainter *painter)
{
if (!mParentPlot) return;
QPoint origin;
if (mAxisType == atLeft)
origin = mAxisRect->bottomLeft()+QPoint(-mOffset, 0);
else if (mAxisType == atRight)
origin = mAxisRect->bottomRight()+QPoint(+mOffset, 0);
else if (mAxisType == atTop)
origin = mAxisRect->topLeft()+QPoint(0, -mOffset);
else if (mAxisType == atBottom)
origin = mAxisRect->bottomLeft()+QPoint(0, +mOffset);
double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes)
switch (mAxisType)
{
case atTop: yCor = -1; break;
case atRight: xCor = 1; break;
default: break;
}
int margin = 0;
int lowTick = mLowestVisibleTick;
int highTick = mHighestVisibleTick;
double t; // helper variable, result of coordinate-to-pixel transforms
// draw baseline:
QLineF baseLine;
painter->setPen(getBasePen());
if (orientation() == Qt::Horizontal)
baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(mAxisRect->width()+xCor, yCor));
else
baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(xCor, -mAxisRect->height()+yCor));
if (mRangeReversed)
baseLine = QLineF(baseLine.p2(), baseLine.p1()); // won't make a difference for line itself, but for line endings later
painter->drawLine(baseLine);
// draw ticks:
if (mTicks)
{
painter->setPen(getTickPen());
// direction of ticks ("inward" is right for left axis and left for right axis)
int tickDir = (mAxisType == atBottom || mAxisType == atRight) ? -1 : 1;
if (orientation() == Qt::Horizontal)
{
for (int i=lowTick; i <= highTick; ++i)
{
t = coordToPixel(mTickVector.at(i)); // x
painter->drawLine(QLineF(t+xCor, origin.y()-mTickLengthOut*tickDir+yCor, t+xCor, origin.y()+mTickLengthIn*tickDir+yCor));
}
} else
{
for (int i=lowTick; i <= highTick; ++i)
{
t = coordToPixel(mTickVector.at(i)); // y
painter->drawLine(QLineF(origin.x()-mTickLengthOut*tickDir+xCor, t+yCor, origin.x()+mTickLengthIn*tickDir+xCor, t+yCor));
}
}
}
// draw subticks:
if (mTicks && mSubTickCount > 0)
{
painter->setPen(getSubTickPen());
// direction of ticks ("inward" is right for left axis and left for right axis)
int tickDir = (mAxisType == atBottom || mAxisType == atRight) ? -1 : 1;
if (orientation() == Qt::Horizontal)
{
for (int i=0; i<mSubTickVector.size(); ++i) // no need to check bounds because subticks are always only created inside current mRange
{
t = coordToPixel(mSubTickVector.at(i));
painter->drawLine(QLineF(t+xCor, origin.y()-mSubTickLengthOut*tickDir+yCor, t+xCor, origin.y()+mSubTickLengthIn*tickDir+yCor));
}
} else
{
for (int i=0; i<mSubTickVector.size(); ++i)
{
t = coordToPixel(mSubTickVector.at(i));
painter->drawLine(QLineF(origin.x()-mSubTickLengthOut*tickDir+xCor, t+yCor, origin.x()+mSubTickLengthIn*tickDir+xCor, t+yCor));
}
}
}
margin += qMax(0, qMax(mTickLengthOut, mSubTickLengthOut));
// draw axis base endings:
bool antialiasingBackup = painter->antialiasing();
painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't
painter->setBrush(QBrush(basePen().color()));
QVector2D baseLineVector(baseLine.dx(), baseLine.dy());
if (mLowerEnding.style() != QCPLineEnding::esNone)
mLowerEnding.draw(painter, QVector2D(baseLine.p1())-baseLineVector.normalized()*mLowerEnding.realLength()*(mLowerEnding.inverted()?-1:1), -baseLineVector);
if (mUpperEnding.style() != QCPLineEnding::esNone)
mUpperEnding.draw(painter, QVector2D(baseLine.p2())+baseLineVector.normalized()*mUpperEnding.realLength()*(mUpperEnding.inverted()?-1:1), baseLineVector);
painter->setAntialiasing(antialiasingBackup);
// tick labels:
QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label
if (mTickLabels)
{
margin += mTickLabelPadding;
painter->setFont(getTickLabelFont());
painter->setPen(QPen(getTickLabelColor()));
for (int i=lowTick; i <= highTick; ++i)
{
t = coordToPixel(mTickVector.at(i));
placeTickLabel(painter, t, margin, mTickVectorLabels.at(i), &tickLabelsSize);
}
}
if (orientation() == Qt::Horizontal)
margin += tickLabelsSize.height();
else
margin += tickLabelsSize.width();
// axis label:
QRect labelBounds;
if (!mLabel.isEmpty())
{
margin += mLabelPadding;
painter->setFont(getLabelFont());
painter->setPen(QPen(getLabelColor()));
labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, mLabel);
if (mAxisType == atLeft)
{
QTransform oldTransform = painter->transform();
painter->translate((origin.x()-margin-labelBounds.height()), origin.y());
painter->rotate(-90);
painter->drawText(0, 0, mAxisRect->height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, mLabel);
painter->setTransform(oldTransform);
}
else if (mAxisType == atRight)
{
QTransform oldTransform = painter->transform();
painter->translate((origin.x()+margin+labelBounds.height()), origin.y()-mAxisRect->height());
painter->rotate(90);
painter->drawText(0, 0, mAxisRect->height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, mLabel);
painter->setTransform(oldTransform);
}
else if (mAxisType == atTop)
painter->drawText(origin.x(), origin.y()-margin-labelBounds.height(), mAxisRect->width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, mLabel);
else if (mAxisType == atBottom)
painter->drawText(origin.x(), origin.y()+margin, mAxisRect->width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, mLabel);
}
// set selection boxes:
int selAxisOutSize = qMax(qMax(mTickLengthOut, mSubTickLengthOut), mParentPlot->selectionTolerance());
int selAxisInSize = mParentPlot->selectionTolerance();
int selTickLabelSize = (orientation()==Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width());
int selTickLabelOffset = qMax(mTickLengthOut, mSubTickLengthOut)+mTickLabelPadding;
int selLabelSize = labelBounds.height();
int selLabelOffset = selTickLabelOffset+selTickLabelSize+mLabelPadding;
if (mAxisType == atLeft)
{
mAxisSelectionBox.setCoords(origin.x()-selAxisOutSize, mAxisRect->top(), origin.x()+selAxisInSize, mAxisRect->bottom());
mTickLabelsSelectionBox.setCoords(origin.x()-selTickLabelOffset-selTickLabelSize, mAxisRect->top(), origin.x()-selTickLabelOffset, mAxisRect->bottom());
mLabelSelectionBox.setCoords(origin.x()-selLabelOffset-selLabelSize, mAxisRect->top(), origin.x()-selLabelOffset, mAxisRect->bottom());
} else if (mAxisType == atRight)
{
mAxisSelectionBox.setCoords(origin.x()-selAxisInSize, mAxisRect->top(), origin.x()+selAxisOutSize, mAxisRect->bottom());
mTickLabelsSelectionBox.setCoords(origin.x()+selTickLabelOffset+selTickLabelSize, mAxisRect->top(), origin.x()+selTickLabelOffset, mAxisRect->bottom());
mLabelSelectionBox.setCoords(origin.x()+selLabelOffset+selLabelSize, mAxisRect->top(), origin.x()+selLabelOffset, mAxisRect->bottom());
} else if (mAxisType == atTop)
{
mAxisSelectionBox.setCoords(mAxisRect->left(), origin.y()-selAxisOutSize, mAxisRect->right(), origin.y()+selAxisInSize);
mTickLabelsSelectionBox.setCoords(mAxisRect->left(), origin.y()-selTickLabelOffset-selTickLabelSize, mAxisRect->right(), origin.y()-selTickLabelOffset);
mLabelSelectionBox.setCoords(mAxisRect->left(), origin.y()-selLabelOffset-selLabelSize, mAxisRect->right(), origin.y()-selLabelOffset);
} else if (mAxisType == atBottom)
{
mAxisSelectionBox.setCoords(mAxisRect->left(), origin.y()-selAxisInSize, mAxisRect->right(), origin.y()+selAxisOutSize);
mTickLabelsSelectionBox.setCoords(mAxisRect->left(), origin.y()+selTickLabelOffset+selTickLabelSize, mAxisRect->right(), origin.y()+selTickLabelOffset);
mLabelSelectionBox.setCoords(mAxisRect->left(), origin.y()+selLabelOffset+selLabelSize, mAxisRect->right(), origin.y()+selLabelOffset);
}
// draw hitboxes for debug purposes:
//painter->setBrush(Qt::NoBrush);
//painter->drawRects(QVector<QRect>() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox);
}
/*! \internal
Draws a single tick label with the provided \a painter, utilizing the internal label cache to
significantly speed up drawing of labels that were drawn in previous calls. The tick label is
always bound to an axis, the distance to the axis is controllable via \a distanceToAxis in
pixels. The pixel position in the axis direction is passed in the \a position parameter. Hence
for the bottom axis, \a position would indicate the horizontal pixel position (not coordinate),
at which the label should be drawn.
In order to later draw the axis label in a place that doesn't overlap with the tick labels, the
largest tick label size is needed. This is acquired by passing a \a tickLabelsSize to the \ref
drawTickLabel calls during the process of drawing all tick labels of one axis. In every call, \a
tickLabelsSize is expanded, if the drawn label exceeds the value \a tickLabelsSize currently
holds.
The label is drawn with the font and pen that are currently set on the \a painter. To draw
superscripted powers, the font is temporarily made smaller by a fixed factor (see \ref
getTickLabelData).
*/
void QCPAxis::placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize)
{
// warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly!
if (!mParentPlot) return;
if (text.isEmpty()) return;
QSize finalSize;
QPointF labelAnchor;
switch (mAxisType)
{
case atLeft: labelAnchor = QPointF(mAxisRect->left()-distanceToAxis-mOffset, position); break;
case atRight: labelAnchor = QPointF(mAxisRect->right()+distanceToAxis+mOffset, position); break;
case atTop: labelAnchor = QPointF(position, mAxisRect->top()-distanceToAxis-mOffset); break;
case atBottom: labelAnchor = QPointF(position, mAxisRect->bottom()+distanceToAxis+mOffset); break;
}
if (parentPlot()->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled
{
if (!mLabelCache.contains(text)) // no cached label exists, create it
{
CachedLabel *newCachedLabel = new CachedLabel;
TickLabelData labelData = getTickLabelData(painter->font(), text);
QPointF drawOffset = getTickLabelDrawOffset(labelData);
newCachedLabel->offset = drawOffset+labelData.rotatedTotalBounds.topLeft();
newCachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size());
newCachedLabel->pixmap.fill(Qt::transparent);
QCPPainter cachePainter(&newCachedLabel->pixmap);
cachePainter.setPen(painter->pen());
drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData);
mLabelCache.insert(text, newCachedLabel, 1);
}
// draw cached label:
const CachedLabel *cachedLabel = mLabelCache.object(text);
// if label would be partly clipped by widget border on sides, don't draw it:
if (orientation() == Qt::Horizontal)
{
if (labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width() > mParentPlot->viewport().right() ||
labelAnchor.x()+cachedLabel->offset.x() < mParentPlot->viewport().left())
return;
} else
{
if (labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height() > mParentPlot->viewport().bottom() ||
labelAnchor.y()+cachedLabel->offset.y() < mParentPlot->viewport().top())
return;
}
painter->drawPixmap(labelAnchor+cachedLabel->offset, cachedLabel->pixmap);
finalSize = cachedLabel->pixmap.size();
} else // label caching disabled, draw text directly on surface:
{
TickLabelData labelData = getTickLabelData(painter->font(), text);
QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData);
// if label would be partly clipped by widget border on sides, don't draw it:
if (orientation() == Qt::Horizontal)
{
if (finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > mParentPlot->viewport().right() ||
finalPosition.x()+labelData.rotatedTotalBounds.left() < mParentPlot->viewport().left())
return;
} else
{
if (finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > mParentPlot->viewport().bottom() ||
finalPosition.y()+labelData.rotatedTotalBounds.top() < mParentPlot->viewport().top())
return;
}
drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData);
finalSize = labelData.rotatedTotalBounds.size();
}
// expand passed tickLabelsSize if current tick label is larger:
if (finalSize.width() > tickLabelsSize->width())
tickLabelsSize->setWidth(finalSize.width());
if (finalSize.height() > tickLabelsSize->height())
tickLabelsSize->setHeight(finalSize.height());
}
/*! \internal
This is a \ref placeTickLabel helper function.
Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a
y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to
directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when
QCP::phCacheLabels plotting hint is not set.
*/
void QCPAxis::drawTickLabel(QCPPainter *painter, double x, double y, const QCPAxis::TickLabelData &labelData) const
{
// backup painter settings that we're about to change:
QTransform oldTransform = painter->transform();
QFont oldFont = painter->font();
// transform painter to position/rotation:
painter->translate(x, y);
if (!qFuzzyIsNull(mTickLabelRotation))
painter->rotate(mTickLabelRotation);
// draw text:
if (!labelData.expPart.isEmpty()) // indicator that beautiful powers must be used
{
painter->setFont(labelData.baseFont);
painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart);
painter->setFont(labelData.expFont);
painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart);
} else
{
painter->setFont(labelData.baseFont);
painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart);
}
// reset painter settings to what it was before:
painter->setTransform(oldTransform);
painter->setFont(oldFont);
}
/*! \internal
This is a \ref placeTickLabel helper function.
Transforms the passed \a text and \a font to a tickLabelData structure that can then be further
processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and
exponent if necessary (see \ref setNumberFormat) and calculates appropriate bounding boxes.
*/
QCPAxis::TickLabelData QCPAxis::getTickLabelData(const QFont &font, const QString &text) const
{
TickLabelData result;
// determine whether beautiful decimal powers should be used
bool useBeautifulPowers = false;
int ePos = -1;
if (mAutoTickLabels && mNumberBeautifulPowers && mTickLabelType == ltNumber)
{
ePos = text.indexOf('e');
if (ePos > -1)
useBeautifulPowers = true;
}
// calculate text bounding rects and do string preparation for beautiful decimal powers:
result.baseFont = font;
result.baseFont.setPointSizeF(result.baseFont.pointSizeF()+0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the results oscillate due to internal rounding
if (useBeautifulPowers)
{
// split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent:
result.basePart = text.left(ePos);
// in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base:
if (mScaleType == stLogarithmic && result.basePart == "1")
result.basePart = "10";
else
result.basePart += (mNumberMultiplyCross ? QString(QChar(215)) : QString(QChar(183))) + "10";
result.expPart = text.mid(ePos+1);
// clip "+" and leading zeros off expPart:
while (result.expPart.at(1) == '0' && result.expPart.length() > 2) // length > 2 so we leave one zero when numberFormatChar is 'e'
result.expPart.remove(1, 1);
if (result.expPart.at(0) == mPositiveSignChar)
result.expPart.remove(0, 1);
// prepare smaller font for exponent:
result.expFont = font;
result.expFont.setPointSize(result.expFont.pointSize()*0.75);
// calculate bounding rects of base part, exponent part and total one:
result.baseBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart);
result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart);
result.totalBounds = result.baseBounds.adjusted(0, 0, result.expBounds.width()+2, 0); // +2 consists of the 1 pixel spacing between base and exponent (see drawTickLabel) and an extra pixel to include AA
} else // useBeautifulPowers == false
{
result.basePart = text;
result.totalBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart);
}
result.totalBounds.moveTopLeft(QPoint(0, 0)); // want bounding box aligned top left at origin, independent of how it was created, to make further processing simpler
// calculate possibly different bounding rect after rotation:
result.rotatedTotalBounds = result.totalBounds;
if (!qFuzzyIsNull(mTickLabelRotation))
{
QTransform transform;
transform.rotate(mTickLabelRotation);
result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds);
}
return result;
}
/*! \internal
This is a \ref placeTickLabel helper function.
Calculates the offset at which the top left corner of the specified tick label shall be drawn.
The offset is relative to a point right next to the tick the label belongs to.
This function is thus responsible for e.g. centering tick labels under ticks and positioning them
appropriately when they are rotated.
*/
QPointF QCPAxis::getTickLabelDrawOffset(const QCPAxis::TickLabelData &labelData) const
{
/*
calculate label offset from base point at tick (non-trivial, for best visual appearance): short
explanation for bottom axis: The anchor, i.e. the point in the label that is placed
horizontally under the corresponding tick is always on the label side that is closer to the
axis (e.g. the left side of the text when we're rotating clockwise). On that side, the height
is halved and the resulting point is defined the anchor. This way, a 90 degree rotated text
will be centered under the tick (i.e. displaced horizontally by half its height). At the same
time, a 45 degree rotated text will "point toward" its tick, as is typical for rotated tick
labels.
*/
bool doRotation = !qFuzzyIsNull(mTickLabelRotation);
bool flip = qFuzzyCompare(qAbs(mTickLabelRotation), 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes.
double radians = mTickLabelRotation/180.0*M_PI;
int x=0, y=0;
if (mAxisType == atLeft)
{
if (doRotation)
{
if (mTickLabelRotation > 0)
{
x = -qCos(radians)*labelData.totalBounds.width();
y = flip ? -labelData.totalBounds.width()/2.0 : -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height()/2.0;
} else
{
x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height();
y = flip ? +labelData.totalBounds.width()/2.0 : +qSin(-radians)*labelData.totalBounds.width()-qCos(-radians)*labelData.totalBounds.height()/2.0;
}
} else
{
x = -labelData.totalBounds.width();
y = -labelData.totalBounds.height()/2.0;
}
} else if (mAxisType == atRight)
{
if (doRotation)
{
if (mTickLabelRotation > 0)
{
x = +qSin(radians)*labelData.totalBounds.height();
y = flip ? -labelData.totalBounds.width()/2.0 : -qCos(radians)*labelData.totalBounds.height()/2.0;
} else
{
x = 0;
y = flip ? +labelData.totalBounds.width()/2.0 : -qCos(-radians)*labelData.totalBounds.height()/2.0;
}
} else
{
x = 0;
y = -labelData.totalBounds.height()/2.0;
}
} else if (mAxisType == atTop)
{
if (doRotation)
{
if (mTickLabelRotation > 0)
{
x = -qCos(radians)*labelData.totalBounds.width()+qSin(radians)*labelData.totalBounds.height()/2.0;
y = -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height();
} else
{
x = -qSin(-radians)*labelData.totalBounds.height()/2.0;
y = -qCos(-radians)*labelData.totalBounds.height();
}
} else
{
x = -labelData.totalBounds.width()/2.0;
y = -labelData.totalBounds.height();
}
} else if (mAxisType == atBottom)
{
if (doRotation)
{
if (mTickLabelRotation > 0)
{
x = +qSin(radians)*labelData.totalBounds.height()/2.0;
y = 0;
} else
{
x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height()/2.0;
y = +qSin(-radians)*labelData.totalBounds.width();
}
} else
{
x = -labelData.totalBounds.width()/2.0;
y = 0;
}
}
return QPointF(x, y);
}
/*! \internal
Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label
to be drawn, depending on number format etc. Since only the largest tick label is wanted for the
margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a
smaller width/height.
*/
void QCPAxis::getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const
{
// note: this function must return the same tick label sizes as the placeTickLabel function.
QSize finalSize;
if (parentPlot()->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label
{
const CachedLabel *cachedLabel = mLabelCache.object(text);
finalSize = cachedLabel->pixmap.size();
} else // label caching disabled or no label with this text cached:
{
TickLabelData labelData = getTickLabelData(font, text);
finalSize = labelData.rotatedTotalBounds.size();
}
// expand passed tickLabelsSize if current tick label is larger:
if (finalSize.width() > tickLabelsSize->width())
tickLabelsSize->setWidth(finalSize.width());
if (finalSize.height() > tickLabelsSize->height())
tickLabelsSize->setHeight(finalSize.height());
}
/* inherits documentation from base class */
void QCPAxis::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
Q_UNUSED(event)
SelectablePart part = details.value<SelectablePart>();
if (mSelectableParts.testFlag(part))
{
SelectableParts selBefore = mSelectedParts;
setSelectedParts(additive ? mSelectedParts^part : part);
if (selectionStateChanged)
*selectionStateChanged = mSelectedParts != selBefore;
}
}
/* inherits documentation from base class */
void QCPAxis::deselectEvent(bool *selectionStateChanged)
{
SelectableParts selBefore = mSelectedParts;
setSelectedParts(mSelectedParts & ~mSelectableParts);
if (selectionStateChanged)
*selectionStateChanged = mSelectedParts != selBefore;
}
/*! \internal
A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
before drawing axis lines.
This is the antialiasing state the painter passed to the \ref draw method is in by default.
This function takes into account the local setting of the antialiasing flag as well as the
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
\see setAntialiased
*/
void QCPAxis::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes);
}
/*! \internal
Returns via \a lowIndex and \a highIndex, which ticks in the current tick vector are visible in
the current range. The return values are indices of the tick vector, not the positions of the
ticks themselves.
The actual use of this function is when an external tick vector is provided, since it might
exceed far beyond the currently displayed range, and would cause unnecessary calculations e.g. of
subticks.
If all ticks are outside the axis range, an inverted range is returned, i.e. highIndex will be
smaller than lowIndex. There is one case, where this function returns indices that are not really
visible in the current axis range: When the tick spacing is larger than the axis range size and
one tick is below the axis range and the next tick is already above the axis range. Because in
such cases it is usually desirable to know the tick pair, to draw proper subticks.
*/
void QCPAxis::visibleTickBounds(int &lowIndex, int &highIndex) const
{
bool lowFound = false;
bool highFound = false;
lowIndex = 0;
highIndex = -1;
for (int i=0; i < mTickVector.size(); ++i)
{
if (mTickVector.at(i) >= mRange.lower)
{
lowFound = true;
lowIndex = i;
break;
}
}
for (int i=mTickVector.size()-1; i >= 0; --i)
{
if (mTickVector.at(i) <= mRange.upper)
{
highFound = true;
highIndex = i;
break;
}
}
if (!lowFound && highFound)
lowIndex = highIndex+1;
else if (lowFound && !highFound)
highIndex = lowIndex-1;
}
/*! \internal
A log function with the base mScaleLogBase, used mostly for coordinate transforms in logarithmic
scales with arbitrary log base. Uses the buffered mScaleLogBaseLogInv for faster calculation.
This is set to <tt>1.0/qLn(mScaleLogBase)</tt> in \ref setScaleLogBase.
\see basePow, setScaleLogBase, setScaleType
*/
double QCPAxis::baseLog(double value) const
{
return qLn(value)*mScaleLogBaseLogInv;
}
/*! \internal
A power function with the base mScaleLogBase, used mostly for coordinate transforms in
logarithmic scales with arbitrary log base.
\see baseLog, setScaleLogBase, setScaleType
*/
double QCPAxis::basePow(double value) const
{
return qPow(mScaleLogBase, value);
}
/*! \internal
Returns the pen that is used to draw the axis base line. Depending on the selection state, this
is either mSelectedBasePen or mBasePen.
*/
QPen QCPAxis::getBasePen() const
{
return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen;
}
/*! \internal
Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this
is either mSelectedTickPen or mTickPen.
*/
QPen QCPAxis::getTickPen() const
{
return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen;
}
/*! \internal
Returns the pen that is used to draw the subticks. Depending on the selection state, this
is either mSelectedSubTickPen or mSubTickPen.
*/
QPen QCPAxis::getSubTickPen() const
{
return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen;
}
/*! \internal
Returns the font that is used to draw the tick labels. Depending on the selection state, this
is either mSelectedTickLabelFont or mTickLabelFont.
*/
QFont QCPAxis::getTickLabelFont() const
{
return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont;
}
/*! \internal
Returns the font that is used to draw the axis label. Depending on the selection state, this
is either mSelectedLabelFont or mLabelFont.
*/
QFont QCPAxis::getLabelFont() const
{
return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont;
}
/*! \internal
Returns the color that is used to draw the tick labels. Depending on the selection state, this
is either mSelectedTickLabelColor or mTickLabelColor.
*/
QColor QCPAxis::getTickLabelColor() const
{
return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor;
}
/*! \internal
Returns the color that is used to draw the axis label. Depending on the selection state, this
is either mSelectedLabelColor or mLabelColor.
*/
QColor QCPAxis::getLabelColor() const
{
return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor;
}
/*! \internal
Returns the appropriate outward margin for this axis. It is needed if \ref
QCPAxisRect::setAutoMargins is set to true on the parent axis rect. An axis with axis type \ref
atLeft will return an appropriate left margin, \ref atBottom will return an appropriate bottom
margin and so forth. For the calculation, this function goes through similar steps as \ref draw,
so changing one function likely requires the modification of the other one as well.
The margin consists of the outward tick length, tick label padding, tick label size, label
padding, label size, and padding.
The margin is cached internally, so repeated calls while leaving the axis range, fonts, etc.
unchanged are very fast.
*/
int QCPAxis::calculateMargin()
{
if (mCachedMarginValid)
return mCachedMargin;
// run through similar steps as QCPAxis::draw, and caluclate margin needed to fit axis and its labels
int margin = 0;
if (mVisible)
{
int lowTick, highTick;
visibleTickBounds(lowTick, highTick);
// get length of tick marks pointing outwards:
if (mTicks)
margin += qMax(0, qMax(mTickLengthOut, mSubTickLengthOut));
// calculate size of tick labels:
QSize tickLabelsSize(0, 0);
if (mTickLabels)
{
for (int i=lowTick; i<=highTick; ++i)
getMaxTickLabelSize(mTickLabelFont, mTickVectorLabels.at(i), &tickLabelsSize); // don't use getTickLabelFont() because we don't want margin to possibly change on selection
margin += orientation() == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width();
margin += mTickLabelPadding;
}
// calculate size of axis label (only height needed, because left/right labels are rotated by 90 degrees):
if (!mLabel.isEmpty())
{
QFontMetrics fontMetrics(mLabelFont); // don't use getLabelFont() because we don't want margin to possibly change on selection
QRect bounds;
bounds = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter | Qt::AlignVCenter, mLabel);
margin += bounds.height() + mLabelPadding;
}
}
margin += mPadding;
mCachedMargin = margin;
mCachedMarginValid = true;
return margin;
}
/* inherits documentation from base class */
QCP::Interaction QCPAxis::selectionCategory() const
{
return QCP::iSelectAxes;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAbstractPlottable
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAbstractPlottable
\brief The abstract base class for all data representing objects in a plot.
It defines a very basic interface like name, pen, brush, visibility etc. Since this class is
abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to
create new ways of displaying data (see "Creating own plottables" below).
All further specifics are in the subclasses, for example:
\li A normal graph with possibly a line, scatter points and error bars is displayed by \ref QCPGraph
(typically created with \ref QCustomPlot::addGraph).
\li A parametric curve can be displayed with \ref QCPCurve.
\li A stackable bar chart can be achieved with \ref QCPBars.
\li A box of a statistical box plot is created with \ref QCPStatisticalBox.
\section plottables-subclassing Creating own plottables
To create an own plottable, you implement a subclass of QCPAbstractPlottable. These are the pure
virtual functions, you must implement:
\li \ref clearData
\li \ref selectTest
\li \ref draw
\li \ref drawLegendIcon
\li \ref getKeyRange
\li \ref getValueRange
See the documentation of those functions for what they need to do.
For drawing your plot, you can use the \ref coordsToPixels functions to translate a point in plot
coordinates to pixel coordinates. This function is quite convenient, because it takes the
orientation of the key and value axes into account for you (x and y are swapped when the key axis
is vertical and the value axis horizontal). If you are worried about performance (i.e. you need
to translate many points in a loop like QCPGraph), you can directly use \ref
QCPAxis::coordToPixel. However, you must then take care about the orientation of the axis
yourself.
Here are some important members you inherit from QCPAbstractPlottable:
<table>
<tr>
<td>QCustomPlot *\b mParentPlot</td>
<td>A pointer to the parent QCustomPlot instance. The parent plot is inferred from the axes that are passed in the constructor.</td>
</tr><tr>
<td>QString \b mName</td>
<td>The name of the plottable.</td>
</tr><tr>
<td>QPen \b mPen</td>
<td>The generic pen of the plottable. You should use this pen for the most prominent data representing lines in the plottable (e.g QCPGraph uses this pen for its graph lines and scatters)</td>
</tr><tr>
<td>QPen \b mSelectedPen</td>
<td>The generic pen that should be used when the plottable is selected (hint: \ref mainPen gives you the right pen, depending on selection state).</td>
</tr><tr>
<td>QBrush \b mBrush</td>
<td>The generic brush of the plottable. You should use this brush for the most prominent fillable structures in the plottable (e.g. QCPGraph uses this brush to control filling under the graph)</td>
</tr><tr>
<td>QBrush \b mSelectedBrush</td>
<td>The generic brush that should be used when the plottable is selected (hint: \ref mainBrush gives you the right brush, depending on selection state).</td>
</tr><tr>
<td>QPointer<QCPAxis>\b mKeyAxis, \b mValueAxis</td>
<td>The key and value axes this plottable is attached to. Call their QCPAxis::coordToPixel functions to translate coordinates to pixels in either the key or value dimension.
Make sure to check whether the pointer is null before using it. If one of the axes is null, don't draw the plottable.</td>
</tr><tr>
<td>bool \b mSelected</td>
<td>indicates whether the plottable is selected or not.</td>
</tr>
</table>
*/
/* start of documentation of pure virtual functions */
/*! \fn void QCPAbstractPlottable::clearData() = 0
Clears all data in the plottable.
*/
/*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const QRect &rect) const = 0
\internal
called by QCPLegend::draw (via QCPPlottableLegendItem::draw) to create a graphical representation
of this plottable inside \a rect, next to the plottable name.
*/
/*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &validRange, SignDomain inSignDomain) const = 0
\internal
called by rescaleAxes functions to get the full data key bounds. For logarithmic plots, one can
set \a inSignDomain to either \ref sdNegative or \ref sdPositive in order to restrict the
returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain
to \ref sdNegative and all positive points will be ignored for range calculation. For no
restriction, just set \a inSignDomain to \ref sdBoth (default). \a validRange is an output
parameter that indicates whether a proper range could be found or not. If this is false, you
shouldn't use the returned range (e.g. no points in data).
\see rescaleAxes, getValueRange
*/
/*! \fn QCPRange QCPAbstractPlottable::getValueRange(bool &validRange, SignDomain inSignDomain) const = 0
\internal
called by rescaleAxes functions to get the full data value bounds. For logarithmic plots, one can
set \a inSignDomain to either \ref sdNegative or \ref sdPositive in order to restrict the
returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain
to \ref sdNegative and all positive points will be ignored for range calculation. For no
restriction, just set \a inSignDomain to \ref sdBoth (default). \a validRange is an output
parameter that indicates whether a proper range could be found or not. If this is false, you
shouldn't use the returned range (e.g. no points in data).
\see rescaleAxes, getKeyRange
*/
/* end of documentation of pure virtual functions */
/* start of documentation of signals */
/*! \fn void QCPAbstractPlottable::selectionChanged(bool selected)
This signal is emitted when the selection state of this plottable has changed to \a selected,
either by user interaction or by a direct call to \ref setSelected.
*/
/* end of documentation of signals */
/*!
Constructs an abstract plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as
its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance
and have perpendicular orientations. If either of these restrictions is violated, a corresponding
message is printed to the debug output (qDebug), the construction is not aborted, though.
Since QCPAbstractPlottable is an abstract class that defines the basic interface to plottables,
it can't be directly instantiated.
You probably want one of the subclasses like \ref QCPGraph or \ref QCPCurve instead.
*/
QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis) :
QCPLayerable(keyAxis->parentPlot(), "", keyAxis->axisRect()),
mName(""),
mAntialiasedFill(true),
mAntialiasedScatters(true),
mAntialiasedErrorBars(false),
mPen(Qt::black),
mSelectedPen(Qt::black),
mBrush(Qt::NoBrush),
mSelectedBrush(Qt::NoBrush),
mKeyAxis(keyAxis),
mValueAxis(valueAxis),
mSelectable(true),
mSelected(false)
{
if (keyAxis->parentPlot() != valueAxis->parentPlot())
qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis.";
if (keyAxis->orientation() == valueAxis->orientation())
qDebug() << Q_FUNC_INFO << "keyAxis and valueAxis must be orthogonal to each other.";
}
/*!
The name is the textual representation of this plottable as it is displayed in the legend
(\ref QCPLegend). It may contain any UTF-8 characters, including newlines.
*/
void QCPAbstractPlottable::setName(const QString &name)
{
mName = name;
}
/*!
Sets whether fills of this plottable is drawn antialiased or not.
Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
*/
void QCPAbstractPlottable::setAntialiasedFill(bool enabled)
{
mAntialiasedFill = enabled;
}
/*!
Sets whether the scatter symbols of this plottable are drawn antialiased or not.
Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
*/
void QCPAbstractPlottable::setAntialiasedScatters(bool enabled)
{
mAntialiasedScatters = enabled;
}
/*!
Sets whether the error bars of this plottable are drawn antialiased or not.
Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
*/
void QCPAbstractPlottable::setAntialiasedErrorBars(bool enabled)
{
mAntialiasedErrorBars = enabled;
}
/*!
The pen is used to draw basic lines that make up the plottable representation in the
plot.
For example, the \ref QCPGraph subclass draws its graph lines and scatter points
with this pen.
\see setBrush
*/
void QCPAbstractPlottable::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
When the plottable is selected, this pen is used to draw basic lines instead of the normal
pen set via \ref setPen.
\see setSelected, setSelectable, setSelectedBrush, selectTest
*/
void QCPAbstractPlottable::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/*!
The brush is used to draw basic fills of the plottable representation in the
plot. The Fill can be a color, gradient or texture, see the usage of QBrush.
For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when
it's not set to Qt::NoBrush.
\see setPen
*/
void QCPAbstractPlottable::setBrush(const QBrush &brush)
{
mBrush = brush;
}
/*!
When the plottable is selected, this brush is used to draw fills instead of the normal
brush set via \ref setBrush.
\see setSelected, setSelectable, setSelectedPen, selectTest
*/
void QCPAbstractPlottable::setSelectedBrush(const QBrush &brush)
{
mSelectedBrush = brush;
}
/*!
The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal
to the plottable's value axis. This function performs no checks to make sure this is the case.
The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the
y-axis (QCustomPlot::yAxis) as value axis.
Normally, the key and value axes are set in the constructor of the plottable (or \ref
QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
\see setValueAxis
*/
void QCPAbstractPlottable::setKeyAxis(QCPAxis *axis)
{
mKeyAxis = axis;
}
/*!
The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is
orthogonal to the plottable's key axis. This function performs no checks to make sure this is the
case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and
the y-axis (QCustomPlot::yAxis) as value axis.
Normally, the key and value axes are set in the constructor of the plottable (or \ref
QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
\see setKeyAxis
*/
void QCPAbstractPlottable::setValueAxis(QCPAxis *axis)
{
mValueAxis = axis;
}
/*!
Sets whether the user can (de-)select this plottable by clicking on the QCustomPlot surface.
(When \ref QCustomPlot::setInteractions contains iSelectPlottables.)
However, even when \a selectable was set to false, it is possible to set the selection manually,
by calling \ref setSelected directly.
\see setSelected
*/
void QCPAbstractPlottable::setSelectable(bool selectable)
{
mSelectable = selectable;
}
/*!
Sets whether this plottable is selected or not. When selected, it uses a different pen and brush
to draw its lines and fills, see \ref setSelectedPen and \ref setSelectedBrush.
The entire selection mechanism for plottables is handled automatically when \ref
QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when
you wish to change the selection state manually.
This function can change the selection state even when \ref setSelectable was set to false.
emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
\see setSelectable, selectTest
*/
void QCPAbstractPlottable::setSelected(bool selected)
{
if (mSelected != selected)
{
mSelected = selected;
emit selectionChanged(mSelected);
}
}
/*!
Rescales the key and value axes associated with this plottable to contain all displayed data, so
the whole plottable is visible. If the scaling of an axis is logarithmic, rescaleAxes will make
sure not to rescale to an illegal range i.e. a range containing different signs and/or zero.
Instead it will stay in the current sign domain and ignore all parts of the plottable that lie
outside of that domain.
\a onlyEnlarge makes sure the ranges are only expanded, never reduced. So it's possible to show
multiple plottables in their entirety by multiple calls to rescaleAxes where the first call has
\a onlyEnlarge set to false (the default), and all subsequent set to true.
\see rescaleKeyAxis, rescaleValueAxis, QCustomPlot::rescaleAxes, QCPAxis::rescale
*/
void QCPAbstractPlottable::rescaleAxes(bool onlyEnlarge) const
{
rescaleKeyAxis(onlyEnlarge);
rescaleValueAxis(onlyEnlarge);
}
/*!
Rescales the key axis of the plottable so the whole plottable is visible.
See \ref rescaleAxes for detailed behaviour.
*/
void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const
{
QCPAxis *keyAxis = mKeyAxis.data();
if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
SignDomain signDomain = sdBoth;
if (keyAxis->scaleType() == QCPAxis::stLogarithmic)
signDomain = (keyAxis->range().upper < 0 ? sdNegative : sdPositive);
bool rangeValid;
QCPRange newRange = getKeyRange(rangeValid, signDomain);
if (rangeValid)
{
if (onlyEnlarge)
newRange.expand(keyAxis->range());
if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
{
double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
if (keyAxis->scaleType() == QCPAxis::stLinear)
{
newRange.lower = center-keyAxis->range().size()/2.0;
newRange.upper = center+keyAxis->range().size()/2.0;
} else // scaleType() == stLogarithmic
{
newRange.lower = center/qSqrt(keyAxis->range().upper/keyAxis->range().lower);
newRange.upper = center*qSqrt(keyAxis->range().upper/keyAxis->range().lower);
}
}
keyAxis->setRange(newRange);
}
}
/*!
Rescales the value axis of the plottable so the whole plottable is visible.
Returns true if the axis was actually scaled. This might not be the case if this plottable has an
invalid range, e.g. because it has no data points.
See \ref rescaleAxes for detailed behaviour.
*/
void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge) const
{
QCPAxis *valueAxis = mValueAxis.data();
if (!valueAxis) { qDebug() << Q_FUNC_INFO << "invalid value axis"; return; }
SignDomain signDomain = sdBoth;
if (valueAxis->scaleType() == QCPAxis::stLogarithmic)
signDomain = (valueAxis->range().upper < 0 ? sdNegative : sdPositive);
bool rangeValid;
QCPRange newRange = getValueRange(rangeValid, signDomain);
if (rangeValid)
{
if (onlyEnlarge)
newRange.expand(valueAxis->range());
if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
{
double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
if (valueAxis->scaleType() == QCPAxis::stLinear)
{
newRange.lower = center-valueAxis->range().size()/2.0;
newRange.upper = center+valueAxis->range().size()/2.0;
} else // scaleType() == stLogarithmic
{
newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower);
newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower);
}
}
valueAxis->setRange(newRange);
}
}
/*!
Adds this plottable to the legend of the parent QCustomPlot (QCustomPlot::legend).
Normally, a QCPPlottableLegendItem is created and inserted into the legend. If the plottable
needs a more specialized representation in the legend, this function will take this into account
and instead create the specialized subclass of QCPAbstractLegendItem.
Returns true on success, i.e. when the legend exists and a legend item associated with this plottable isn't already in
the legend.
\see removeFromLegend, QCPLegend::addItem
*/
bool QCPAbstractPlottable::addToLegend()
{
if (!mParentPlot || !mParentPlot->legend)
return false;
if (!mParentPlot->legend->hasItemWithPlottable(this))
{
mParentPlot->legend->addItem(new QCPPlottableLegendItem(mParentPlot->legend, this));
return true;
} else
return false;
}
/*!
Removes the plottable from the legend of the parent QCustomPlot. This means the
QCPAbstractLegendItem (usually a QCPPlottableLegendItem) that is associated with this plottable
is removed.
Returns true on success, i.e. if the legend exists and a legend item associated with this
plottable was found and removed.
\see addToLegend, QCPLegend::removeItem
*/
bool QCPAbstractPlottable::removeFromLegend() const
{
if (!mParentPlot->legend)
return false;
if (QCPPlottableLegendItem *lip = mParentPlot->legend->itemWithPlottable(this))
return mParentPlot->legend->removeItem(lip);
else
return false;
}
/* inherits documentation from base class */
QRect QCPAbstractPlottable::clipRect() const
{
if (mKeyAxis && mValueAxis)
return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect();
else
return QRect();
}
/* inherits documentation from base class */
QCP::Interaction QCPAbstractPlottable::selectionCategory() const
{
return QCP::iSelectPlottables;
}
/*! \internal
Convenience function for transforming a key/value pair to pixels on the QCustomPlot surface,
taking the orientations of the axes associated with this plottable into account (e.g. whether key
represents x or y).
\a key and \a value are transformed to the coodinates in pixels and are written to \a x and \a y.
\see pixelsToCoords, QCPAxis::coordToPixel
*/
void QCPAbstractPlottable::coordsToPixels(double key, double value, double &x, double &y) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (keyAxis->orientation() == Qt::Horizontal)
{
x = keyAxis->coordToPixel(key);
y = valueAxis->coordToPixel(value);
} else
{
y = keyAxis->coordToPixel(key);
x = valueAxis->coordToPixel(value);
}
}
/*! \internal
\overload
Returns the input as pixel coordinates in a QPointF.
*/
const QPointF QCPAbstractPlottable::coordsToPixels(double key, double value) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
if (keyAxis->orientation() == Qt::Horizontal)
return QPointF(keyAxis->coordToPixel(key), valueAxis->coordToPixel(value));
else
return QPointF(valueAxis->coordToPixel(value), keyAxis->coordToPixel(key));
}
/*! \internal
Convenience function for transforming a x/y pixel pair on the QCustomPlot surface to plot coordinates,
taking the orientations of the axes associated with this plottable into account (e.g. whether key
represents x or y).
\a x and \a y are transformed to the plot coodinates and are written to \a key and \a value.
\see coordsToPixels, QCPAxis::coordToPixel
*/
void QCPAbstractPlottable::pixelsToCoords(double x, double y, double &key, double &value) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (keyAxis->orientation() == Qt::Horizontal)
{
key = keyAxis->pixelToCoord(x);
value = valueAxis->pixelToCoord(y);
} else
{
key = keyAxis->pixelToCoord(y);
value = valueAxis->pixelToCoord(x);
}
}
/*! \internal
\overload
Returns the pixel input \a pixelPos as plot coordinates \a key and \a value.
*/
void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const
{
pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value);
}
/*! \internal
Returns the pen that should be used for drawing lines of the plottable. Returns mPen when the
graph is not selected and mSelectedPen when it is.
*/
QPen QCPAbstractPlottable::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
/*! \internal
Returns the brush that should be used for drawing fills of the plottable. Returns mBrush when the
graph is not selected and mSelectedBrush when it is.
*/
QBrush QCPAbstractPlottable::mainBrush() const
{
return mSelected ? mSelectedBrush : mBrush;
}
/*! \internal
A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
before drawing plottable lines.
This is the antialiasing state the painter passed to the \ref draw method is in by default.
This function takes into account the local setting of the antialiasing flag as well as the
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
\see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint, applyErrorBarsAntialiasingHint
*/
void QCPAbstractPlottable::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables);
}
/*! \internal
A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
before drawing plottable fills.
This function takes into account the local setting of the antialiasing flag as well as the
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
\see setAntialiased, applyDefaultAntialiasingHint, applyScattersAntialiasingHint, applyErrorBarsAntialiasingHint
*/
void QCPAbstractPlottable::applyFillAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills);
}
/*! \internal
A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
before drawing plottable scatter points.
This function takes into account the local setting of the antialiasing flag as well as the
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
\see setAntialiased, applyFillAntialiasingHint, applyDefaultAntialiasingHint, applyErrorBarsAntialiasingHint
*/
void QCPAbstractPlottable::applyScattersAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters);
}
/*! \internal
A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
before drawing plottable error bars.
This function takes into account the local setting of the antialiasing flag as well as the
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
\see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint, applyDefaultAntialiasingHint
*/
void QCPAbstractPlottable::applyErrorBarsAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiasedErrorBars, QCP::aeErrorBars);
}
/*! \internal
Finds the shortest squared distance of \a point to the line segment defined by \a start and \a
end.
This function may be used to help with the implementation of the \ref selectTest function for
specific plottables.
\note This function is identical to QCPAbstractItem::distSqrToLine
*/
double QCPAbstractPlottable::distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const
{
QVector2D a(start);
QVector2D b(end);
QVector2D p(point);
QVector2D v(b-a);
double vLengthSqr = v.lengthSquared();
if (!qFuzzyIsNull(vLengthSqr))
{
double mu = QVector2D::dotProduct(p-a, v)/vLengthSqr;
if (mu < 0)
return (a-p).lengthSquared();
else if (mu > 1)
return (b-p).lengthSquared();
else
return ((a + mu*v)-p).lengthSquared();
} else
return (a-p).lengthSquared();
}
/* inherits documentation from base class */
void QCPAbstractPlottable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
Q_UNUSED(event)
Q_UNUSED(details)
if (mSelectable)
{
bool selBefore = mSelected;
setSelected(additive ? !mSelected : true);
if (selectionStateChanged)
*selectionStateChanged = mSelected != selBefore;
}
}
/* inherits documentation from base class */
void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged)
{
if (mSelectable)
{
bool selBefore = mSelected;
setSelected(false);
if (selectionStateChanged)
*selectionStateChanged = mSelected != selBefore;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemAnchor
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemAnchor
\brief An anchor of an item to which positions can be attached to.
An item (QCPAbstractItem) may have one or more anchors. Unlike QCPItemPosition, an anchor doesn't
control anything on its item, but provides a way to tie other items via their positions to the
anchor.
For example, a QCPItemRect is defined by its positions \a topLeft and \a bottomRight.
Additionally it has various anchors like \a top, \a topRight or \a bottomLeft etc. So you can
attach the \a start (which is a QCPItemPosition) of a QCPItemLine to one of the anchors by
calling QCPItemPosition::setParentAnchor on \a start, passing the wanted anchor of the
QCPItemRect. This way the start of the line will now always follow the respective anchor location
on the rect item.
Note that QCPItemPosition derives from QCPItemAnchor, so every position can also serve as an
anchor to other positions.
To learn how to provide anchors in your own item subclasses, see the subclassing section of the
QCPAbstractItem documentation.
*/
/* start documentation of inline functions */
/*! \fn virtual QCPItemPosition *QCPItemAnchor::toQCPItemPosition()
Returns 0 if this instance is merely a QCPItemAnchor, and a valid pointer of type QCPItemPosition* if
it actually is a QCPItemPosition (which is a subclass of QCPItemAnchor).
This safe downcast functionality could also be achieved with a dynamic_cast. However, QCustomPlot avoids
dynamic_cast to work with projects that don't have RTTI support enabled (e.g. -fno-rtti flag with
gcc compiler).
*/
/* end documentation of inline functions */
/*!
Creates a new QCPItemAnchor. You shouldn't create QCPItemAnchor instances directly, even if
you want to make a new item subclass. Use \ref QCPAbstractItem::createAnchor instead, as
explained in the subclassing section of the QCPAbstractItem documentation.
*/
QCPItemAnchor::QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name, int anchorId) :
mName(name),
mParentPlot(parentPlot),
mParentItem(parentItem),
mAnchorId(anchorId)
{
}
QCPItemAnchor::~QCPItemAnchor()
{
// unregister as parent at children:
QList<QCPItemPosition*> currentChildren(mChildren.toList());
for (int i=0; i<currentChildren.size(); ++i)
currentChildren.at(i)->setParentAnchor(0); // this acts back on this anchor and child removes itself from mChildren
}
/*!
Returns the final absolute pixel position of the QCPItemAnchor on the QCustomPlot surface.
The pixel information is internally retrieved via QCPAbstractItem::anchorPixelPosition of the
parent item, QCPItemAnchor is just an intermediary.
*/
QPointF QCPItemAnchor::pixelPoint() const
{
if (mParentItem)
{
if (mAnchorId > -1)
{
return mParentItem->anchorPixelPoint(mAnchorId);
} else
{
qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId;
return QPointF();
}
} else
{
qDebug() << Q_FUNC_INFO << "no parent item set";
return QPointF();
}
}
/*! \internal
Adds \a pos to the child list of this anchor. This is necessary to notify the children prior to
destruction of the anchor.
Note that this function does not change the parent setting in \a pos.
*/
void QCPItemAnchor::addChild(QCPItemPosition *pos)
{
if (!mChildren.contains(pos))
mChildren.insert(pos);
else
qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast<quintptr>(pos);
}
/*! \internal
Removes \a pos from the child list of this anchor.
Note that this function does not change the parent setting in \a pos.
*/
void QCPItemAnchor::removeChild(QCPItemPosition *pos)
{
if (!mChildren.remove(pos))
qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast<quintptr>(pos);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemPosition
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemPosition
\brief Manages the position of an item.
Every item has at least one public QCPItemPosition member pointer which provides ways to position the
item on the QCustomPlot surface. Some items have multiple positions, for example QCPItemRect has two:
\a topLeft and \a bottomRight.
QCPItemPosition has a type (\ref PositionType) that can be set with \ref setType. This type defines
how coordinates passed to \ref setCoords are to be interpreted, e.g. as absolute pixel coordinates, as
plot coordinates of certain axes, etc.
Further, QCPItemPosition may have a parent QCPItemAnchor, see \ref setParentAnchor. (Note that every
QCPItemPosition inherits from QCPItemAnchor and thus can itself be used as parent anchor for other
positions.) This way you can tie multiple items together. If the QCPItemPosition has a parent, the
coordinates set with \ref setCoords are considered to be absolute values in the reference frame of the
parent anchor, where (0, 0) means directly ontop of the parent anchor. For example, You could attach
the \a start position of a QCPItemLine to the \a bottom anchor of a QCPItemText to make the starting
point of the line always be centered under the text label, no matter where the text is moved to, or is
itself tied to.
To set the apparent pixel position on the QCustomPlot surface directly, use \ref setPixelPoint. This
works no matter what type this QCPItemPosition is or what parent-child situation it is in, as \ref
setPixelPoint transforms the coordinates appropriately, to make the position appear at the specified
pixel values.
*/
/*!
Creates a new QCPItemPosition. You shouldn't create QCPItemPosition instances directly, even if
you want to make a new item subclass. Use \ref QCPAbstractItem::createPosition instead, as
explained in the subclassing section of the QCPAbstractItem documentation.
*/
QCPItemPosition::QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name) :
QCPItemAnchor(parentPlot, parentItem, name),
mPositionType(ptAbsolute),
mKey(0),
mValue(0),
mParentAnchor(0)
{
}
QCPItemPosition::~QCPItemPosition()
{
// unregister as parent at children:
// Note: this is done in ~QCPItemAnchor again, but it's important QCPItemPosition does it itself, because only then
// the setParentAnchor(0) call the correct QCPItemPosition::pixelPoint function instead of QCPItemAnchor::pixelPoint
QList<QCPItemPosition*> currentChildren(mChildren.toList());
for (int i=0; i<currentChildren.size(); ++i)
currentChildren.at(i)->setParentAnchor(0); // this acts back on this anchor and child removes itself from mChildren
// unregister as child in parent:
if (mParentAnchor)
mParentAnchor->removeChild(this);
}
/* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */
QCPAxisRect *QCPItemPosition::axisRect() const
{
return mAxisRect.data();
}
/*!
Sets the type of the position. The type defines how the coordinates passed to \ref setCoords
should be handled and how the QCPItemPosition should behave in the plot.
The possible values for \a type can be separated in two main categories:
\li The position is regarded as a point in plot coordinates. This corresponds to \ref ptPlotCoords
and requires two axes that define the plot coordinate system. They can be specified with \ref setAxes.
By default, the QCustomPlot's x- and yAxis are used.
\li The position is fixed on the QCustomPlot surface, i.e. independent of axis ranges. This
corresponds to all other types, i.e. \ref ptAbsolute, \ref ptViewportRatio and \ref
ptAxisRectRatio. They differ only in the way the absolute position is described, see the
documentation of \ref PositionType for details. For \ref ptAxisRectRatio, note that you can specify
the axis rect with \ref setAxisRect. By default this is set to the main axis rect.
Note that the position type \ref ptPlotCoords is only available (and sensible) when the position
has no parent anchor (\ref setParentAnchor).
If the type is changed, the apparent pixel position on the plot is preserved. This means
the coordinates as retrieved with coords() and set with \ref setCoords may change in the process.
*/
void QCPItemPosition::setType(QCPItemPosition::PositionType type)
{
if (mPositionType != type)
{
// if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect
// were deleted), don't try to recover the pixelPoint() because it would output a qDebug warning.
bool recoverPixelPosition = true;
if ((mPositionType == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis))
recoverPixelPosition = false;
if ((mPositionType == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect))
recoverPixelPosition = false;
QPointF pixelP;
if (recoverPixelPosition)
pixelP = pixelPoint();
mPositionType = type;
if (recoverPixelPosition)
setPixelPoint(pixelP);
}
}
/*!
Sets the parent of this QCPItemPosition to \a parentAnchor. This means the position will now
follow any position changes of the anchor. The local coordinate system of positions with a parent
anchor always is absolute with (0, 0) being exactly on top of the parent anchor. (Hence the type
shouldn't be \ref ptPlotCoords for positions with parent anchors.)
if \a keepPixelPosition is true, the current pixel position of the QCPItemPosition is preserved
during reparenting. If it's set to false, the coordinates are set to (0, 0), i.e. the position
will be exactly on top of the parent anchor.
To remove this QCPItemPosition from any parent anchor, set \a parentAnchor to 0.
If the QCPItemPosition previously had no parent and the type is \ref ptPlotCoords, the type is
set to \ref ptAbsolute, to keep the position in a valid state.
*/
bool QCPItemPosition::setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
{
// make sure self is not assigned as parent:
if (parentAnchor == this)
{
qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast<quintptr>(parentAnchor);
return false;
}
// make sure no recursive parent-child-relationships are created:
QCPItemAnchor *currentParent = parentAnchor;
while (currentParent)
{
if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition())
{
// is a QCPItemPosition, might have further parent, so keep iterating
if (currentParentPos == this)
{
qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast<quintptr>(parentAnchor);
return false;
}
currentParent = currentParentPos->mParentAnchor;
} else
{
// is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the
// same, to prevent a position being child of an anchor which itself depends on the position,
// because they're both on the same item:
if (currentParent->mParentItem == mParentItem)
{
qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast<quintptr>(parentAnchor);
return false;
}
break;
}
}
// if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute:
if (!mParentAnchor && mPositionType == ptPlotCoords)
setType(ptAbsolute);
// save pixel position:
QPointF pixelP;
if (keepPixelPosition)
pixelP = pixelPoint();
// unregister at current parent anchor:
if (mParentAnchor)
mParentAnchor->removeChild(this);
// register at new parent anchor:
if (parentAnchor)
parentAnchor->addChild(this);
mParentAnchor = parentAnchor;
// restore pixel position under new parent:
if (keepPixelPosition)
setPixelPoint(pixelP);
else
setCoords(0, 0);
return true;
}
/*!
Sets the coordinates of this QCPItemPosition. What the coordinates mean, is defined by the type
(\ref setType).
For example, if the type is \ref ptAbsolute, \a key and \a value mean the x and y pixel position
on the QCustomPlot surface. In that case the origin (0, 0) is in the top left corner of the
QCustomPlot viewport. If the type is \ref ptPlotCoords, \a key and \a value mean a point in the
plot coordinate system defined by the axes set by \ref setAxes. By default those are the
QCustomPlot's xAxis and yAxis. See the documentation of \ref setType for other available
coordinate types and their meaning.
\see setPixelPoint
*/
void QCPItemPosition::setCoords(double key, double value)
{
mKey = key;
mValue = value;
}
/*! \overload
Sets the coordinates as a QPointF \a pos where pos.x has the meaning of \a key and pos.y the
meaning of \a value of the \ref setCoords(double key, double value) method.
*/
void QCPItemPosition::setCoords(const QPointF &pos)
{
setCoords(pos.x(), pos.y());
}
/*!
Returns the final absolute pixel position of the QCPItemPosition on the QCustomPlot surface. It
includes all effects of type (\ref setType) and possible parent anchors (\ref setParentAnchor).
\see setPixelPoint
*/
QPointF QCPItemPosition::pixelPoint() const
{
switch (mPositionType)
{
case ptAbsolute:
{
if (mParentAnchor)
return QPointF(mKey, mValue) + mParentAnchor->pixelPoint();
else
return QPointF(mKey, mValue);
}
case ptViewportRatio:
{
if (mParentAnchor)
{
return QPointF(mKey*mParentPlot->viewport().width(),
mValue*mParentPlot->viewport().height()) + mParentAnchor->pixelPoint();
} else
{
return QPointF(mKey*mParentPlot->viewport().width(),
mValue*mParentPlot->viewport().height()) + mParentPlot->viewport().topLeft();
}
}
case ptAxisRectRatio:
{
if (mAxisRect)
{
if (mParentAnchor)
{
return QPointF(mKey*mAxisRect.data()->width(),
mValue*mAxisRect.data()->height()) + mParentAnchor->pixelPoint();
} else
{
return QPointF(mKey*mAxisRect.data()->width(),
mValue*mAxisRect.data()->height()) + mAxisRect.data()->topLeft();
}
} else
{
qDebug() << Q_FUNC_INFO << "No axis rect defined";
return QPointF(mKey, mValue);
}
}
case ptPlotCoords:
{
double x, y;
if (mKeyAxis && mValueAxis)
{
// both key and value axis are given, translate key/value to x/y coordinates:
if (mKeyAxis.data()->orientation() == Qt::Horizontal)
{
x = mKeyAxis.data()->coordToPixel(mKey);
y = mValueAxis.data()->coordToPixel(mValue);
} else
{
y = mKeyAxis.data()->coordToPixel(mKey);
x = mValueAxis.data()->coordToPixel(mValue);
}
} else if (mKeyAxis)
{
// only key axis is given, depending on orientation only transform x or y to key coordinate, other stays pixel:
if (mKeyAxis.data()->orientation() == Qt::Horizontal)
{
x = mKeyAxis.data()->coordToPixel(mKey);
y = mValue;
} else
{
y = mKeyAxis.data()->coordToPixel(mKey);
x = mValue;
}
} else if (mValueAxis)
{
// only value axis is given, depending on orientation only transform x or y to value coordinate, other stays pixel:
if (mValueAxis.data()->orientation() == Qt::Horizontal)
{
x = mValueAxis.data()->coordToPixel(mValue);
y = mKey;
} else
{
y = mValueAxis.data()->coordToPixel(mValue);
x = mKey;
}
} else
{
// no axis given, basically the same as if mPositionType were ptAbsolute
qDebug() << Q_FUNC_INFO << "No axes defined";
x = mKey;
y = mValue;
}
return QPointF(x, y);
}
}
return QPointF();
}
/*!
When \ref setType is \ref ptPlotCoords, this function may be used to specify the axes the
coordinates set with \ref setCoords relate to. By default they are set to the initial xAxis and
yAxis of the QCustomPlot.
*/
void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis)
{
mKeyAxis = keyAxis;
mValueAxis = valueAxis;
}
/*!
When \ref setType is \ref ptAxisRectRatio, this function may be used to specify the axis rect the
coordinates set with \ref setCoords relate to. By default this is set to the main axis rect of
the QCustomPlot.
*/
void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect)
{
mAxisRect = axisRect;
}
/*!
Sets the apparent pixel position. This works no matter what type (\ref setType) this
QCPItemPosition is or what parent-child situation it is in, as coordinates are transformed
appropriately, to make the position finally appear at the specified pixel values.
Only if the type is \ref ptAbsolute and no parent anchor is set, this function's effect is
identical to that of \ref setCoords.
\see pixelPoint, setCoords
*/
void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint)
{
switch (mPositionType)
{
case ptAbsolute:
{
if (mParentAnchor)
setCoords(pixelPoint-mParentAnchor->pixelPoint());
else
setCoords(pixelPoint);
break;
}
case ptViewportRatio:
{
if (mParentAnchor)
{
QPointF p(pixelPoint-mParentAnchor->pixelPoint());
p.rx() /= (double)mParentPlot->viewport().width();
p.ry() /= (double)mParentPlot->viewport().height();
setCoords(p);
} else
{
QPointF p(pixelPoint-mParentPlot->viewport().topLeft());
p.rx() /= (double)mParentPlot->viewport().width();
p.ry() /= (double)mParentPlot->viewport().height();
setCoords(p);
}
break;
}
case ptAxisRectRatio:
{
if (mAxisRect)
{
if (mParentAnchor)
{
QPointF p(pixelPoint-mParentAnchor->pixelPoint());
p.rx() /= (double)mAxisRect.data()->width();
p.ry() /= (double)mAxisRect.data()->height();
setCoords(p);
} else
{
QPointF p(pixelPoint-mAxisRect.data()->topLeft());
p.rx() /= (double)mAxisRect.data()->width();
p.ry() /= (double)mAxisRect.data()->height();
setCoords(p);
}
} else
{
qDebug() << Q_FUNC_INFO << "No axis rect defined";
setCoords(pixelPoint);
}
break;
}
case ptPlotCoords:
{
double newKey, newValue;
if (mKeyAxis && mValueAxis)
{
// both key and value axis are given, translate point to key/value coordinates:
if (mKeyAxis.data()->orientation() == Qt::Horizontal)
{
newKey = mKeyAxis.data()->pixelToCoord(pixelPoint.x());
newValue = mValueAxis.data()->pixelToCoord(pixelPoint.y());
} else
{
newKey = mKeyAxis.data()->pixelToCoord(pixelPoint.y());
newValue = mValueAxis.data()->pixelToCoord(pixelPoint.x());
}
} else if (mKeyAxis)
{
// only key axis is given, depending on orientation only transform x or y to key coordinate, other stays pixel:
if (mKeyAxis.data()->orientation() == Qt::Horizontal)
{
newKey = mKeyAxis.data()->pixelToCoord(pixelPoint.x());
newValue = pixelPoint.y();
} else
{
newKey = mKeyAxis.data()->pixelToCoord(pixelPoint.y());
newValue = pixelPoint.x();
}
} else if (mValueAxis)
{
// only value axis is given, depending on orientation only transform x or y to value coordinate, other stays pixel:
if (mValueAxis.data()->orientation() == Qt::Horizontal)
{
newKey = pixelPoint.y();
newValue = mValueAxis.data()->pixelToCoord(pixelPoint.x());
} else
{
newKey = pixelPoint.x();
newValue = mValueAxis.data()->pixelToCoord(pixelPoint.y());
}
} else
{
// no axis given, basically the same as if mPositionType were ptAbsolute
qDebug() << Q_FUNC_INFO << "No axes defined";
newKey = pixelPoint.x();
newValue = pixelPoint.y();
}
setCoords(newKey, newValue);
break;
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAbstractItem
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAbstractItem
\brief The abstract base class for all items in a plot.
In QCustomPlot, items are supplemental graphical elements that are neither plottables
(QCPAbstractPlottable) nor axes (QCPAxis). While plottables are always tied to two axes and thus
plot coordinates, items can also be placed in absolute coordinates independent of any axes. Each
specific item has at least one QCPItemPosition member which controls the positioning. Some items
are defined by more than one coordinate and thus have two or more QCPItemPosition members (For
example, QCPItemRect has \a topLeft and \a bottomRight).
This abstract base class defines a very basic interface like visibility and clipping. Since this
class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass
yourself to create new items.
The built-in items are:
<table>
<tr><td>QCPItemLine</td><td>A line defined by a start and an end point. May have different ending styles on each side (e.g. arrows).</td></tr>
<tr><td>QCPItemStraightLine</td><td>A straight line defined by a start and a direction point. Unlike QCPItemLine, the straight line is infinitely long and has no endings.</td></tr>
<tr><td>QCPItemCurve</td><td>A curve defined by start, end and two intermediate control points. May have different ending styles on each side (e.g. arrows).</td></tr>
<tr><td>QCPItemRect</td><td>A rectangle</td></tr>
<tr><td>QCPItemEllipse</td><td>An ellipse</td></tr>
<tr><td>QCPItemPixmap</td><td>An arbitrary pixmap</td></tr>
<tr><td>QCPItemText</td><td>A text label</td></tr>
<tr><td>QCPItemBracket</td><td>A bracket which may be used to reference/highlight certain parts in the plot.</td></tr>
<tr><td>QCPItemTracer</td><td>An item that can be attached to a QCPGraph and sticks to its data points, given a key coordinate.</td></tr>
</table>
Items are by default clipped to the main axis rect. To make an item visible outside that axis
rect, disable clipping via \ref setClipToAxisRect.
\section items-using Using items
First you instantiate the item you want to use and add it to the plot:
\code
QCPItemLine *line = new QCPItemLine(customPlot);
customPlot->addItem(line);
\endcode
by default, the positions of the item are bound to the x- and y-Axis of the plot. So we can just
set the plot coordinates where the line should start/end:
\code
line->start->setCoords(-0.1, 0.8);
line->end->setCoords(1.1, 0.2);
\endcode
If we don't want the line to be positioned in plot coordinates but a different coordinate system,
e.g. absolute pixel positions on the QCustomPlot surface, we need to change the position type like this:
\code
line->start->setType(QCPItemPosition::ptAbsolute);
line->end->setType(QCPItemPosition::ptAbsolute);
\endcode
Then we can set the coordinates, this time in pixels:
\code
line->start->setCoords(100, 200);
line->end->setCoords(450, 320);
\endcode
\section items-subclassing Creating own items
To create an own item, you implement a subclass of QCPAbstractItem. These are the pure
virtual functions, you must implement:
\li \ref selectTest
\li \ref draw
See the documentation of those functions for what they need to do.
\subsection items-positioning Allowing the item to be positioned
As mentioned, item positions are represented by QCPItemPosition members. Let's assume the new item shall
have only one point as its position (as opposed to two like a rect or multiple like a polygon). You then add
a public member of type QCPItemPosition like so:
\code QCPItemPosition * const myPosition;\endcode
the const makes sure the pointer itself can't be modified from the user of your new item (the QCPItemPosition
instance it points to, can be modified, of course).
The initialization of this pointer is made easy with the \ref createPosition function. Just assign
the return value of this function to each QCPItemPosition in the constructor of your item. \ref createPosition
takes a string which is the name of the position, typically this is identical to the variable name.
For example, the constructor of QCPItemExample could look like this:
\code
QCPItemExample::QCPItemExample(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
myPosition(createPosition("myPosition"))
{
// other constructor code
}
\endcode
\subsection items-drawing The draw function
To give your item a visual representation, reimplement the \ref draw function and use the passed
QCPPainter to draw the item. You can retrieve the item position in pixel coordinates from the
position member(s) via \ref QCPItemPosition::pixelPoint.
To optimize performance you should calculate a bounding rect first (don't forget to take the pen
width into account), check whether it intersects the \ref clipRect, and only draw the item at all
if this is the case.
\subsection items-selection The selectTest function
Your implementation of the \ref selectTest function may use the helpers \ref distSqrToLine and
\ref rectSelectTest. With these, the implementation of the selection test becomes significantly
simpler for most items. See the documentation of \ref selectTest for what the function parameters
mean and what the function should return.
\subsection anchors Providing anchors
Providing anchors (QCPItemAnchor) starts off like adding a position. First you create a public
member, e.g.
\code QCPItemAnchor * const bottom;\endcode
and create it in the constructor with the \ref createAnchor function, assigning it a name and an
anchor id (an integer enumerating all anchors on the item, you may create an own enum for this).
Since anchors can be placed anywhere, relative to the item's position(s), your item needs to
provide the position of every anchor with the reimplementation of the \ref anchorPixelPoint(int
anchorId) function.
In essence the QCPItemAnchor is merely an intermediary that itself asks your item for the pixel
position when anything attached to the anchor needs to know the coordinates.
*/
/* start of documentation of inline functions */
/*! \fn QList<QCPItemPosition*> QCPAbstractItem::positions() const
Returns all positions of the item in a list.
\see anchors, position
*/
/*! \fn QList<QCPItemAnchor*> QCPAbstractItem::anchors() const
Returns all anchors of the item in a list. Note that since a position (QCPItemPosition) is always
also an anchor, the list will also contain the positions of this item.
\see positions, anchor
*/
/* end of documentation of inline functions */
/* start documentation of pure virtual functions */
/*! \fn void QCPAbstractItem::draw(QCPPainter *painter) = 0
\internal
Draws this item with the provided \a painter.
The cliprect of the provided painter is set to the rect returned by \ref clipRect before this
function is called. The clipRect depends on the clipping settings defined by \ref
setClipToAxisRect and \ref setClipAxisRect.
*/
/* end documentation of pure virtual functions */
/* start documentation of signals */
/*! \fn void QCPAbstractItem::selectionChanged(bool selected)
This signal is emitted when the selection state of this item has changed, either by user interaction
or by a direct call to \ref setSelected.
*/
/* end documentation of signals */
/*!
Base class constructor which initializes base class members.
*/
QCPAbstractItem::QCPAbstractItem(QCustomPlot *parentPlot) :
QCPLayerable(parentPlot),
mClipToAxisRect(false),
mSelectable(true),
mSelected(false)
{
QList<QCPAxisRect*> rects = parentPlot->axisRects();
if (rects.size() > 0)
{
setClipToAxisRect(true);
setClipAxisRect(rects.first());
}
}
QCPAbstractItem::~QCPAbstractItem()
{
// don't delete mPositions because every position is also an anchor and thus in mAnchors
qDeleteAll(mAnchors);
}
/* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */
QCPAxisRect *QCPAbstractItem::clipAxisRect() const
{
return mClipAxisRect.data();
}
/*!
Sets whether the item shall be clipped to an axis rect or whether it shall be visible on the
entire QCustomPlot. The axis rect can be set with \ref setClipAxisRect.
\see setClipAxisRect
*/
void QCPAbstractItem::setClipToAxisRect(bool clip)
{
mClipToAxisRect = clip;
if (mClipToAxisRect)
setParentLayerable(mClipAxisRect.data());
}
/*!
Sets the clip axis rect. It defines the rect that will be used to clip the item when \ref
setClipToAxisRect is set to true.
\see setClipToAxisRect
*/
void QCPAbstractItem::setClipAxisRect(QCPAxisRect *rect)
{
mClipAxisRect = rect;
if (mClipToAxisRect)
setParentLayerable(mClipAxisRect.data());
}
/*!
Sets whether the user can (de-)select this item by clicking on the QCustomPlot surface.
(When \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems.)
However, even when \a selectable was set to false, it is possible to set the selection manually,
by calling \ref setSelected.
\see QCustomPlot::setInteractions, setSelected
*/
void QCPAbstractItem::setSelectable(bool selectable)
{
mSelectable = selectable;
}
/*!
Sets whether this item is selected or not. When selected, it might use a different visual
appearance (e.g. pen and brush), this depends on the specific item though.
The entire selection mechanism for items is handled automatically when \ref
QCustomPlot::setInteractions contains QCustomPlot::iSelectItems. You only need to call this
function when you wish to change the selection state manually.
This function can change the selection state even when \ref setSelectable was set to false.
emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
\see setSelectable, selectTest
*/
void QCPAbstractItem::setSelected(bool selected)
{
if (mSelected != selected)
{
mSelected = selected;
emit selectionChanged(mSelected);
}
}
/*!
Returns the QCPItemPosition with the specified \a name. If this item doesn't have a position by
that name, returns 0.
This function provides an alternative way to access item positions. Normally, you access
positions direcly by their member pointers (which typically have the same variable name as \a
name).
\see positions, anchor
*/
QCPItemPosition *QCPAbstractItem::position(const QString &name) const
{
for (int i=0; i<mPositions.size(); ++i)
{
if (mPositions.at(i)->name() == name)
return mPositions.at(i);
}
qDebug() << Q_FUNC_INFO << "position with name not found:" << name;
return 0;
}
/*!
Returns the QCPItemAnchor with the specified \a name. If this item doesn't have an anchor by
that name, returns 0.
This function provides an alternative way to access item anchors. Normally, you access
anchors direcly by their member pointers (which typically have the same variable name as \a
name).
\see anchors, position
*/
QCPItemAnchor *QCPAbstractItem::anchor(const QString &name) const
{
for (int i=0; i<mAnchors.size(); ++i)
{
if (mAnchors.at(i)->name() == name)
return mAnchors.at(i);
}
qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name;
return 0;
}
/*!
Returns whether this item has an anchor with the specified \a name.
Note that you can check for positions with this function, too. This is because every position is
also an anchor (QCPItemPosition inherits from QCPItemAnchor).
\see anchor, position
*/
bool QCPAbstractItem::hasAnchor(const QString &name) const
{
for (int i=0; i<mAnchors.size(); ++i)
{
if (mAnchors.at(i)->name() == name)
return true;
}
return false;
}
/*! \internal
Returns the rect the visual representation of this item is clipped to. This depends on the
current setting of \ref setClipToAxisRect as well as the axis rect set with \ref setClipAxisRect.
If the item is not clipped to an axis rect, the \ref QCustomPlot::viewport rect is returned.
\see draw
*/
QRect QCPAbstractItem::clipRect() const
{
if (mClipToAxisRect && mClipAxisRect)
return mClipAxisRect.data()->rect();
else
return mParentPlot->viewport();
}
/*! \internal
A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
before drawing item lines.
This is the antialiasing state the painter passed to the \ref draw method is in by default.
This function takes into account the local setting of the antialiasing flag as well as the
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
\see setAntialiased
*/
void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aeItems);
}
/*! \internal
Finds the shortest squared distance of \a point to the line segment defined by \a start and \a
end.
This function may be used to help with the implementation of the \ref selectTest function for
specific items.
\note This function is identical to QCPAbstractPlottable::distSqrToLine
\see rectSelectTest
*/
double QCPAbstractItem::distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const
{
QVector2D a(start);
QVector2D b(end);
QVector2D p(point);
QVector2D v(b-a);
double vLengthSqr = v.lengthSquared();
if (!qFuzzyIsNull(vLengthSqr))
{
double mu = QVector2D::dotProduct(p-a, v)/vLengthSqr;
if (mu < 0)
return (a-p).lengthSquared();
else if (mu > 1)
return (b-p).lengthSquared();
else
return ((a + mu*v)-p).lengthSquared();
} else
return (a-p).lengthSquared();
}
/*! \internal
A convenience function which returns the selectTest value for a specified \a rect and a specified
click position \a pos. \a filledRect defines whether a click inside the rect should also be
considered a hit or whether only the rect border is sensitive to hits.
This function may be used to help with the implementation of the \ref selectTest function for
specific items.
For example, if your item consists of four rects, call this function four times, once for each
rect, in your \ref selectTest reimplementation. Finally, return the minimum of all four returned
values which were greater or equal to zero. (Because this function may return -1.0 when \a pos
doesn't hit \a rect at all). If all calls returned -1.0, return -1.0, too, because your item
wasn't hit.
\see distSqrToLine
*/
double QCPAbstractItem::rectSelectTest(const QRectF &rect, const QPointF &pos, bool filledRect) const
{
double result = -1;
// distance to border:
QList<QLineF> lines;
lines << QLineF(rect.topLeft(), rect.topRight()) << QLineF(rect.bottomLeft(), rect.bottomRight())
<< QLineF(rect.topLeft(), rect.bottomLeft()) << QLineF(rect.topRight(), rect.bottomRight());
double minDistSqr = std::numeric_limits<double>::max();
for (int i=0; i<lines.size(); ++i)
{
double distSqr = distSqrToLine(lines.at(i).p1(), lines.at(i).p2(), pos);
if (distSqr < minDistSqr)
minDistSqr = distSqr;
}
result = qSqrt(minDistSqr);
// filled rect, allow click inside to count as hit:
if (filledRect && result > mParentPlot->selectionTolerance()*0.99)
{
if (rect.contains(pos))
result = mParentPlot->selectionTolerance()*0.99;
}
return result;
}
/*! \internal
Returns the pixel position of the anchor with Id \a anchorId. This function must be reimplemented in
item subclasses if they want to provide anchors (QCPItemAnchor).
For example, if the item has two anchors with id 0 and 1, this function takes one of these anchor
ids and returns the respective pixel points of the specified anchor.
\see createAnchor
*/
QPointF QCPAbstractItem::anchorPixelPoint(int anchorId) const
{
qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId;
return QPointF();
}
/*! \internal
Creates a QCPItemPosition, registers it with this item and returns a pointer to it. The specified
\a name must be a unique string that is usually identical to the variable name of the position
member (This is needed to provide the name-based \ref position access to positions).
Don't delete positions created by this function manually, as the item will take care of it.
Use this function in the constructor (initialization list) of the specific item subclass to
create each position member. Don't create QCPItemPositions with \b new yourself, because they
won't be registered with the item properly.
\see createAnchor
*/
QCPItemPosition *QCPAbstractItem::createPosition(const QString &name)
{
if (hasAnchor(name))
qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
QCPItemPosition *newPosition = new QCPItemPosition(mParentPlot, this, name);
mPositions.append(newPosition);
mAnchors.append(newPosition); // every position is also an anchor
newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis);
newPosition->setType(QCPItemPosition::ptPlotCoords);
if (mParentPlot->axisRect())
newPosition->setAxisRect(mParentPlot->axisRect());
newPosition->setCoords(0, 0);
return newPosition;
}
/*! \internal
Creates a QCPItemAnchor, registers it with this item and returns a pointer to it. The specified
\a name must be a unique string that is usually identical to the variable name of the anchor
member (This is needed to provide the name based \ref anchor access to anchors).
The \a anchorId must be a number identifying the created anchor. It is recommended to create an
enum (e.g. "AnchorIndex") for this on each item that uses anchors. This id is used by the anchor
to identify itself when it calls QCPAbstractItem::anchorPixelPoint. That function then returns
the correct pixel coordinates for the passed anchor id.
Don't delete anchors created by this function manually, as the item will take care of it.
Use this function in the constructor (initialization list) of the specific item subclass to
create each anchor member. Don't create QCPItemAnchors with \b new yourself, because then they
won't be registered with the item properly.
\see createPosition
*/
QCPItemAnchor *QCPAbstractItem::createAnchor(const QString &name, int anchorId)
{
if (hasAnchor(name))
qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
QCPItemAnchor *newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId);
mAnchors.append(newAnchor);
return newAnchor;
}
/* inherits documentation from base class */
void QCPAbstractItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
Q_UNUSED(event)
Q_UNUSED(details)
if (mSelectable)
{
bool selBefore = mSelected;
setSelected(additive ? !mSelected : true);
if (selectionStateChanged)
*selectionStateChanged = mSelected != selBefore;
}
}
/* inherits documentation from base class */
void QCPAbstractItem::deselectEvent(bool *selectionStateChanged)
{
if (mSelectable)
{
bool selBefore = mSelected;
setSelected(false);
if (selectionStateChanged)
*selectionStateChanged = mSelected != selBefore;
}
}
/* inherits documentation from base class */
QCP::Interaction QCPAbstractItem::selectionCategory() const
{
return QCP::iSelectItems;
}
/*! \file */
/*! \mainpage %QCustomPlot 1.1.1 Documentation
\image html qcp-doc-logo.png
Below is a brief overview of and guide to the classes and their relations. If you are new to
QCustomPlot and just want to start using it, it's recommended to look at the tutorials and
examples at
http://www.qcustomplot.com/
This documentation is especially helpful as a reference, when you're familiar with the basic
concept of how to use %QCustomPlot and you wish to learn more about specific functionality.
See the \ref classoverview "class overview" for diagrams explaining the relationships between
the most important classes of the QCustomPlot library.
The central widget which displays the plottables and axes on its surface is QCustomPlot. Every
QCustomPlot contains four axes by default. They can be accessed via the members \ref
QCustomPlot::xAxis "xAxis", \ref QCustomPlot::yAxis "yAxis", \ref QCustomPlot::xAxis2 "xAxis2"
and \ref QCustomPlot::yAxis2 "yAxis2", and are of type QCPAxis. QCustomPlot supports an arbitrary
number of axes and axis rects, see the documentation of QCPAxisRect for details.
\section mainpage-plottables Plottables
\a Plottables are classes that display any kind of data inside the QCustomPlot. They all derive
from QCPAbstractPlottable. For example, the QCPGraph class is a plottable that displays a graph
inside the plot with different line styles, scatter styles, filling etc.
Since plotting graphs is such a dominant use case, QCustomPlot has a special interface for working
with QCPGraph plottables, that makes it very easy to handle them:\n
You create a new graph with QCustomPlot::addGraph and access them with QCustomPlot::graph.
For all other plottables, you need to use the normal plottable interface:\n
First, you create an instance of the plottable you want, e.g.
\code
QCPCurve *newCurve = new QCPCurve(customPlot->xAxis, customPlot->yAxis);\endcode
add it to the customPlot:
\code
customPlot->addPlottable(newCurve);\endcode
and then modify the properties of the newly created plottable via the <tt>newCurve</tt> pointer.
Plottables (including graphs) can be retrieved via QCustomPlot::plottable. Since the return type
of that function is the abstract base class of all plottables, QCPAbstractPlottable, you will
probably want to qobject_cast the returned pointer to the respective plottable subclass. (As
usual, if the cast returns zero, the plottable wasn't of that specific subclass.)
All further interfacing with plottables (e.g how to set data) is specific to the plottable type.
See the documentations of the subclasses: QCPGraph, QCPCurve, QCPBars, QCPStatisticalBox.
\section mainpage-axes Controlling the Axes
As mentioned, QCustomPlot has four axes by default: \a xAxis (bottom), \a yAxis (left), \a xAxis2
(top), \a yAxis2 (right).
Their range is handled by the simple QCPRange class. You can set the range with the
QCPAxis::setRange function. By default, the axes represent a linear scale. To set a logarithmic
scale, set \ref QCPAxis::setScaleType to \ref QCPAxis::stLogarithmic. The logarithm base can be set freely
with \ref QCPAxis::setScaleLogBase.
By default, an axis automatically creates and labels ticks in a sensible manner. See the
following functions for tick manipulation:\n QCPAxis::setTicks, QCPAxis::setAutoTicks,
QCPAxis::setAutoTickCount, QCPAxis::setAutoTickStep, QCPAxis::setTickLabels,
QCPAxis::setTickLabelType, QCPAxis::setTickLabelRotation, QCPAxis::setTickStep,
QCPAxis::setTickLength,...
Each axis can be given an axis label (e.g. "Voltage (mV)") with QCPAxis::setLabel.
The distance of an axis backbone to the respective viewport border is called its margin.
Normally, the margins are calculated automatically. To change this, set
\ref QCPAxisRect::setAutoMargins to exclude the respective margin sides, set the margins manually with
\ref QCPAxisRect::setMargins. The main axis rect can be reached with \ref QCustomPlot::axisRect().
\section mainpage-legend Plot Legend
Every QCustomPlot owns one QCPLegend (as \a legend) by default. A legend is a small layout
element inside the plot which lists the plottables with an icon of the plottable line/symbol and
a description. The Description is retrieved from the plottable name
(QCPAbstractPlottable::setName). Plottables can be added and removed from the legend via \ref
QCPAbstractPlottable::addToLegend and \ref QCPAbstractPlottable::removeFromLegend. By default,
adding a plottable to QCustomPlot automatically adds it to the legend, too. This behaviour can be
modified with the QCustomPlot::setAutoAddPlottableToLegend property.
The QCPLegend provides an interface to access, add and remove legend items directly, too. See
QCPLegend::item, QCPLegend::itemWithPlottable, QCPLegend::addItem, QCPLegend::removeItem for
example.
Multiple legends are supported via the layout system (as a QCPLegend simply is a normal layout
element).
\section mainpage-userinteraction User Interactions
QCustomPlot supports dragging axis ranges with the mouse (\ref
QCPAxisRect::setRangeDrag), zooming axis ranges with the mouse wheel (\ref
QCPAxisRect::setRangeZoom) and a complete selection mechanism.
The availability of these interactions is controlled with \ref QCustomPlot::setInteractions. For
details about the interaction system, see the documentation there.
Further, QCustomPlot always emits corresponding signals, when objects are clicked or
doubleClicked. See \ref QCustomPlot::plottableClick, \ref QCustomPlot::plottableDoubleClick
and \ref QCustomPlot::axisClick for example.
\section mainpage-items Items
Apart from plottables there is another category of plot objects that are important: Items. The
base class of all items is QCPAbstractItem. An item sets itself apart from plottables in that
it's not necessarily bound to any axes. This means it may also be positioned in absolute pixel
coordinates or placed at a relative position on an axis rect. Further, it usually doesn't
represent data directly, but acts as decoration, emphasis, description etc.
Multiple items can be arranged in a parent-child-hierarchy allowing for dynamical behaviour. For
example, you could place the head of an arrow at a fixed plot coordinate, so it always points to
some important area in the plot. The tail of the arrow can be anchored to a text item which
always resides in the top center of the axis rect, independent of where the user drags the axis
ranges. This way the arrow stretches and turns so it always points from the label to the
specified plot coordinate, without any further code necessary.
For a more detailed introduction, see the QCPAbstractItem documentation, and from there the
documentations of the individual built-in items, to find out how to use them.
\section mainpage-layoutelements Layout elements and layouts
QCustomPlot uses an internal layout system to provide dynamic sizing and positioning of objects like
the axis rect(s), legends and the plot title. They are all based on \ref QCPLayoutElement and are arranged by
placing them inside a \ref QCPLayout.
Details on this topic are given on the dedicated page about \link thelayoutsystem the layout system\endlink.
\section mainpage-performancetweaks Performance Tweaks
Although QCustomPlot is quite fast, some features like translucent fills, antialiasing and thick
lines can cause a significant slow down. If you notice this in your application, here are some
thoughts on how to increase performance. By far the most time is spent in the drawing functions,
specifically the drawing of graphs. For maximum performance, consider the following (most
recommended/effective measures first):
\li use Qt 4.8.0 and up. Performance has doubled or tripled with respect to Qt 4.7.4. However
QPainter was broken and drawing pixel precise things, e.g. scatters, isn't possible with Qt >=
4.8.0. So it's a performance vs. plot quality tradeoff when switching to Qt 4.8.
\li To increase responsiveness during dragging, consider setting \ref QCustomPlot::setNoAntialiasingOnDrag to true.
\li On X11 (GNU/Linux), avoid the slow native drawing system, use raster by supplying
"-graphicssystem raster" as command line argument or calling QApplication::setGraphicsSystem("raster")
before creating the QApplication object. (Only available for Qt versions before 5.0)
\li On all operating systems, use OpenGL hardware acceleration by supplying "-graphicssystem
opengl" as command line argument or calling QApplication::setGraphicsSystem("opengl") (Only
available for Qt versions before 5.0). If OpenGL is available, this will slightly decrease the
quality of antialiasing, but extremely increase performance especially with alpha
(semi-transparent) fills, much antialiasing and a large QCustomPlot drawing surface. Note
however, that the maximum frame rate might be constrained by the vertical sync frequency of your
monitor (VSync can be disabled in the graphics card driver configuration). So for simple plots
(where the potential framerate is far above 60 frames per second), OpenGL acceleration might
achieve numerically lower frame rates than the other graphics systems, because they are not
capped at the VSync frequency.
\li Avoid any kind of alpha (transparency), especially in fills
\li Avoid lines with a pen width greater than one
\li Avoid any kind of antialiasing, especially in graph lines (see \ref QCustomPlot::setNotAntialiasedElements)
\li Avoid repeatedly setting the complete data set with \ref QCPGraph::setData. Use \ref QCPGraph::addData instead, if most
data points stay unchanged, e.g. in a running measurement.
\li Set the \a copy parameter of the setData functions to false, so only pointers get
transferred. (Relevant only if preparing data maps with a large number of points, i.e. over 10000)
\section mainpage-flags Preprocessor Define Flags
QCustomPlot understands some preprocessor defines that are useful for debugging and compilation:
<dl>
<dt>\c QCUSTOMPLOT_COMPILE_LIBRARY
<dd>Define this flag when you compile QCustomPlot as a shared library (.so/.dll)
<dt>\c QCUSTOMPLOT_USE_LIBRARY
<dd>Define this flag before including the header, when using QCustomPlot as a shared library
<dt>\c QCUSTOMPLOT_CHECK_DATA
<dd>If this flag is defined, the QCustomPlot plottables will perform data validity checks on every redraw.
This means they will give qDebug output when you plot \e inf or \e nan values, they will not
fix your data.
</dl>
*/
/*! \page classoverview Class Overview
The following diagrams may help to gain a deeper understanding of the relationships between classes that make up
the QCustomPlot library. The diagrams are not exhaustive, so only the classes deemed most relevant are shown.
\section classoverview-relations Class Relationship Diagram
\image html RelationOverview.png "Overview of most important classes and their relations"
\section classoverview-inheritance Class Inheritance Tree
\image html InheritanceOverview.png "Inheritance tree of most important classes"
*/
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCustomPlot
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCustomPlot
\brief The central class of the library. This is the QWidget which displays the plot and
interacts with the user.
For tutorials on how to use QCustomPlot, see the website\n
http://www.qcustomplot.com/
*/
/* start of documentation of inline functions */
/*! \fn QRect QCustomPlot::viewport() const
Returns the viewport rect of this QCustomPlot instance. The viewport is the area the plot is
drawn in, all mechanisms, e.g. margin caluclation take the viewport to be the outer border of the
plot. The viewport normally is the rect() of the QCustomPlot widget, i.e. a rect with top left
(0, 0) and size of the QCustomPlot widget.
Don't confuse the viewport with the axis rect (QCustomPlot::axisRect). An axis rect is typically
an area enclosed by four axes, where the graphs/plottables are drawn in. The viewport is larger
and contains also the axes themselves, their tick numbers, their labels, the plot title etc.
Only when saving to a file (see \ref savePng, savePdf etc.) the viewport is temporarily modified
to allow saving plots with sizes independent of the current widget size.
*/
/*! \fn QCPLayoutGrid *QCustomPlot::plotLayout() const
Returns the top level layout of this QCustomPlot instance. It is a \ref QCPLayoutGrid, initially containing just
one cell with the main QCPAxisRect inside.
*/
/* end of documentation of inline functions */
/* start of documentation of signals */
/*! \fn void QCustomPlot::mouseDoubleClick(QMouseEvent *event)
This signal is emitted when the QCustomPlot receives a mouse double click event.
*/
/*! \fn void QCustomPlot::mousePress(QMouseEvent *event)
This signal is emitted when the QCustomPlot receives a mouse press event.
It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref
QCPAxisRect::setRangeDragAxes.
*/
/*! \fn void QCustomPlot::mouseMove(QMouseEvent *event)
This signal is emitted when the QCustomPlot receives a mouse move event.
It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref
QCPAxisRect::setRangeDragAxes.
\warning It is discouraged to change the drag-axes with \ref QCPAxisRect::setRangeDragAxes here,
because the dragging starting point was saved the moment the mouse was pressed. Thus it only has
a meaning for the range drag axes that were set at that moment. If you want to change the drag
axes, consider doing this in the \ref mousePress signal instead.
*/
/*! \fn void QCustomPlot::mouseRelease(QMouseEvent *event)
This signal is emitted when the QCustomPlot receives a mouse release event.
It is emitted before QCustomPlot handles any other mechanisms like object selection. So a
slot connected to this signal can still influence the behaviour e.g. with \ref setInteractions or
\ref QCPAbstractPlottable::setSelectable.
*/
/*! \fn void QCustomPlot::mouseWheel(QMouseEvent *event)
This signal is emitted when the QCustomPlot receives a mouse wheel event.
It is emitted before QCustomPlot handles any other mechanisms like range zooming. So a slot
connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeZoom, \ref
QCPAxisRect::setRangeZoomAxes or \ref QCPAxisRect::setRangeZoomFactor.
*/
/*! \fn void QCustomPlot::plottableClick(QCPAbstractPlottable *plottable, QMouseEvent *event)
This signal is emitted when a plottable is clicked.
\a event is the mouse event that caused the click and \a plottable is the plottable that received
the click.
\see plottableDoubleClick
*/
/*! \fn void QCustomPlot::plottableDoubleClick(QCPAbstractPlottable *plottable, QMouseEvent *event)
This signal is emitted when a plottable is double clicked.
\a event is the mouse event that caused the click and \a plottable is the plottable that received
the click.
\see plottableClick
*/
/*! \fn void QCustomPlot::itemClick(QCPAbstractItem *item, QMouseEvent *event)
This signal is emitted when an item is clicked.
\a event is the mouse event that caused the click and \a item is the item that received the
click.
\see itemDoubleClick
*/
/*! \fn void QCustomPlot::itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event)
This signal is emitted when an item is double clicked.
\a event is the mouse event that caused the click and \a item is the item that received the
click.
\see itemClick
*/
/*! \fn void QCustomPlot::axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event)
This signal is emitted when an axis is clicked.
\a event is the mouse event that caused the click, \a axis is the axis that received the click and
\a part indicates the part of the axis that was clicked.
\see axisDoubleClick
*/
/*! \fn void QCustomPlot::axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event)
This signal is emitted when an axis is double clicked.
\a event is the mouse event that caused the click, \a axis is the axis that received the click and
\a part indicates the part of the axis that was clicked.
\see axisClick
*/
/*! \fn void QCustomPlot::legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
This signal is emitted when a legend (item) is clicked.
\a event is the mouse event that caused the click, \a legend is the legend that received the
click and \a item is the legend item that received the click. If only the legend and no item is
clicked, \a item is 0. This happens for a click inside the legend padding or the space between
two items.
\see legendDoubleClick
*/
/*! \fn void QCustomPlot::legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
This signal is emitted when a legend (item) is double clicked.
\a event is the mouse event that caused the click, \a legend is the legend that received the
click and \a item is the legend item that received the click. If only the legend and no item is
clicked, \a item is 0. This happens for a click inside the legend padding or the space between
two items.
\see legendClick
*/
/*! \fn void QCustomPlot:: titleClick(QMouseEvent *event, QCPPlotTitle *title)
This signal is emitted when a plot title is clicked.
\a event is the mouse event that caused the click and \a title is the plot title that received
the click.
\see titleDoubleClick
*/
/*! \fn void QCustomPlot::titleDoubleClick(QMouseEvent *event, QCPPlotTitle *title)
This signal is emitted when a plot title is double clicked.
\a event is the mouse event that caused the click and \a title is the plot title that received
the click.
\see titleClick
*/
/*! \fn void QCustomPlot::selectionChangedByUser()
This signal is emitted after the user has changed the selection in the QCustomPlot, e.g. by
clicking. It is not emitted when the selection state of an object has changed programmatically by
a direct call to setSelected() on an object or by calling \ref deselectAll.
In addition to this signal, selectable objects also provide individual signals, for example
QCPAxis::selectionChanged or QCPAbstractPlottable::selectionChanged. Note that those signals are
emitted even if the selection state is changed programmatically.
See the documentation of \ref setInteractions for details about the selection mechanism.
\see selectedPlottables, selectedGraphs, selectedItems, selectedAxes, selectedLegends
*/
/*! \fn void QCustomPlot::beforeReplot()
This signal is emitted immediately before a replot takes place (caused by a call to the slot \ref
replot).
It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
replot synchronously, it won't cause an infinite recursion.
\see replot, afterReplot
*/
/*! \fn void QCustomPlot::afterReplot()
This signal is emitted immediately after a replot has taken place (caused by a call to the slot \ref
replot).
It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
replot synchronously, it won't cause an infinite recursion.
\see replot, beforeReplot
*/
/* end of documentation of signals */
/* start of documentation of public members */
/*! \var QCPAxis *QCustomPlot::xAxis
A pointer to the primary x Axis (bottom) of the main axis rect of the plot.
QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
default legend is removed due to manipulation of the layout system (e.g. by removing the main
axis rect), the corresponding pointers become 0.
*/
/*! \var QCPAxis *QCustomPlot::yAxis
A pointer to the primary y Axis (left) of the main axis rect of the plot.
QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
default legend is removed due to manipulation of the layout system (e.g. by removing the main
axis rect), the corresponding pointers become 0.
*/
/*! \var QCPAxis *QCustomPlot::xAxis2
A pointer to the secondary x Axis (top) of the main axis rect of the plot. Secondary axes are
invisible by default. Use QCPAxis::setVisible to change this (or use \ref
QCPAxisRect::setupFullAxesBox).
QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
default legend is removed due to manipulation of the layout system (e.g. by removing the main
axis rect), the corresponding pointers become 0.
*/
/*! \var QCPAxis *QCustomPlot::yAxis2
A pointer to the secondary y Axis (right) of the main axis rect of the plot. Secondary axes are
invisible by default. Use QCPAxis::setVisible to change this (or use \ref
QCPAxisRect::setupFullAxesBox).
QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
default legend is removed due to manipulation of the layout system (e.g. by removing the main
axis rect), the corresponding pointers become 0.
*/
/*! \var QCPLegend *QCustomPlot::legend
A pointer to the default legend of the main axis rect. The legend is invisible by default. Use
QCPLegend::setVisible to change this.
QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
layout system\endlink to add multiple legends to the plot, use the layout system interface to
access the new legend. For example, legends can be placed inside an axis rect's \ref
QCPAxisRect::insetLayout "inset layout", and must then also be accessed via the inset layout. If
the default legend is removed due to manipulation of the layout system (e.g. by removing the main
axis rect), the corresponding pointer becomes 0.
*/
/* end of documentation of public members */
/*!
Constructs a QCustomPlot and sets reasonable default values.
*/
QCustomPlot::QCustomPlot(QWidget *parent) :
QWidget(parent),
xAxis(0),
yAxis(0),
xAxis2(0),
yAxis2(0),
legend(0),
mPlotLayout(0),
mAutoAddPlottableToLegend(true),
mAntialiasedElements(QCP::aeNone),
mNotAntialiasedElements(QCP::aeNone),
mInteractions(0),
mSelectionTolerance(8),
mNoAntialiasingOnDrag(false),
mBackgroundBrush(Qt::white, Qt::SolidPattern),
mBackgroundScaled(true),
mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
mCurrentLayer(0),
mPlottingHints(QCP::phCacheLabels|QCP::phForceRepaint),
mMultiSelectModifier(Qt::ControlModifier),
mPaintBuffer(size()),
mMouseEventElement(0),
mReplotting(false)
{
setAttribute(Qt::WA_NoMousePropagation);
setAttribute(Qt::WA_OpaquePaintEvent);
setMouseTracking(true);
QLocale currentLocale = locale();
currentLocale.setNumberOptions(QLocale::OmitGroupSeparator);
setLocale(currentLocale);
// create initial layers:
mLayers.append(new QCPLayer(this, "background"));
mLayers.append(new QCPLayer(this, "grid"));
mLayers.append(new QCPLayer(this, "main"));
mLayers.append(new QCPLayer(this, "axes"));
mLayers.append(new QCPLayer(this, "legend"));
updateLayerIndices();
setCurrentLayer("main");
// create initial layout, axis rect and legend:
mPlotLayout = new QCPLayoutGrid;
mPlotLayout->initializeParentPlot(this);
mPlotLayout->setParent(this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will call QWidget::updateGeometry
QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true);
mPlotLayout->addElement(0, 0, defaultAxisRect);
xAxis = defaultAxisRect->axis(QCPAxis::atBottom);
yAxis = defaultAxisRect->axis(QCPAxis::atLeft);
xAxis2 = defaultAxisRect->axis(QCPAxis::atTop);
yAxis2 = defaultAxisRect->axis(QCPAxis::atRight);
legend = new QCPLegend;
legend->setVisible(false);
defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight|Qt::AlignTop);
defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12));
defaultAxisRect->setLayer("background");
xAxis->setLayer("axes");
yAxis->setLayer("axes");
xAxis2->setLayer("axes");
yAxis2->setLayer("axes");
xAxis->grid()->setLayer("grid");
yAxis->grid()->setLayer("grid");
xAxis2->grid()->setLayer("grid");
yAxis2->grid()->setLayer("grid");
legend->setLayer("legend");
setViewport(rect()); // needs to be called after mPlotLayout has been created
replot();
}
QCustomPlot::~QCustomPlot()
{
clearPlottables();
clearItems();
if (mPlotLayout)
{
delete mPlotLayout;
mPlotLayout = 0;
}
mCurrentLayer = 0;
qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed
mLayers.clear();
}
/*!
Sets which elements are forcibly drawn antialiased as an \a or combination of QCP::AntialiasedElement.
This overrides the antialiasing settings for whole element groups, normally controlled with the
\a setAntialiasing function on the individual elements. If an element is neither specified in
\ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
each individual element instance is used.
For example, if \a antialiasedElements contains \ref QCP::aePlottables, all plottables will be
drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
to.
if an element in \a antialiasedElements is already set in \ref setNotAntialiasedElements, it is
removed from there.
\see setNotAntialiasedElements
*/
void QCustomPlot::setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements)
{
mAntialiasedElements = antialiasedElements;
// make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
mNotAntialiasedElements |= ~mAntialiasedElements;
}
/*!
Sets whether the specified \a antialiasedElement is forcibly drawn antialiased.
See \ref setAntialiasedElements for details.
\see setNotAntialiasedElement
*/
void QCustomPlot::setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled)
{
if (!enabled && mAntialiasedElements.testFlag(antialiasedElement))
mAntialiasedElements &= ~antialiasedElement;
else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement))
mAntialiasedElements |= antialiasedElement;
// make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
mNotAntialiasedElements |= ~mAntialiasedElements;
}
/*!
Sets which elements are forcibly drawn not antialiased as an \a or combination of
QCP::AntialiasedElement.
This overrides the antialiasing settings for whole element groups, normally controlled with the
\a setAntialiasing function on the individual elements. If an element is neither specified in
\ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
each individual element instance is used.
For example, if \a notAntialiasedElements contains \ref QCP::aePlottables, no plottables will be
drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
to.
if an element in \a notAntialiasedElements is already set in \ref setAntialiasedElements, it is
removed from there.
\see setAntialiasedElements
*/
void QCustomPlot::setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements)
{
mNotAntialiasedElements = notAntialiasedElements;
// make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
mAntialiasedElements |= ~mNotAntialiasedElements;
}
/*!
Sets whether the specified \a notAntialiasedElement is forcibly drawn not antialiased.
See \ref setNotAntialiasedElements for details.
\see setAntialiasedElement
*/
void QCustomPlot::setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled)
{
if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement))
mNotAntialiasedElements &= ~notAntialiasedElement;
else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement))
mNotAntialiasedElements |= notAntialiasedElement;
// make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
mAntialiasedElements |= ~mNotAntialiasedElements;
}
/*!
If set to true, adding a plottable (e.g. a graph) to the QCustomPlot automatically also adds the
plottable to the legend (QCustomPlot::legend).
\see addPlottable, addGraph, QCPLegend::addItem
*/
void QCustomPlot::setAutoAddPlottableToLegend(bool on)
{
mAutoAddPlottableToLegend = on;
}
/*!
Sets the possible interactions of this QCustomPlot as an or-combination of \ref QCP::Interaction
enums. There are the following types of interactions:
<b>Axis range manipulation</b> is controlled via \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. When the
respective interaction is enabled, the user may drag axes ranges and zoom with the mouse wheel.
For details how to control which axes the user may drag/zoom and in what orientations, see \ref
QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeDragAxes,
\ref QCPAxisRect::setRangeZoomAxes.
<b>Plottable selection</b> is controlled by \ref QCP::iSelectPlottables. If \ref QCP::iSelectPlottables is
set, the user may select plottables (graphs, curves, bars,...) by clicking on them or in their
vicinity (\ref setSelectionTolerance). Whether the user can actually select a plottable can
further be restricted with the \ref QCPAbstractPlottable::setSelectable function on the specific
plottable. To find out whether a specific plottable is selected, call
QCPAbstractPlottable::selected(). To retrieve a list of all currently selected plottables, call
\ref selectedPlottables. If you're only interested in QCPGraphs, you may use the convenience
function \ref selectedGraphs.
<b>Item selection</b> is controlled by \ref QCP::iSelectItems. If \ref QCP::iSelectItems is set, the user
may select items (QCPItemLine, QCPItemText,...) by clicking on them or in their vicinity. To find
out whether a specific item is selected, call QCPAbstractItem::selected(). To retrieve a list of
all currently selected items, call \ref selectedItems.
<b>Axis selection</b> is controlled with \ref QCP::iSelectAxes. If \ref QCP::iSelectAxes is set, the user
may select parts of the axes by clicking on them. What parts exactly (e.g. Axis base line, tick
labels, axis label) are selectable can be controlled via \ref QCPAxis::setSelectableParts for
each axis. To retrieve a list of all axes that currently contain selected parts, call \ref
selectedAxes. Which parts of an axis are selected, can be retrieved with QCPAxis::selectedParts().
<b>Legend selection</b> is controlled with \ref QCP::iSelectLegend. If this is set, the user may
select the legend itself or individual items by clicking on them. What parts exactly are
selectable can be controlled via \ref QCPLegend::setSelectableParts. To find out whether the
legend or any of its child items are selected, check the value of QCPLegend::selectedParts. To
find out which child items are selected, call \ref QCPLegend::selectedItems.
<b>All other selectable elements</b> The selection of all other selectable objects (e.g.
QCPPlotTitle, or your own layerable subclasses) is controlled with \ref QCP::iSelectOther. If set, the
user may select those objects by clicking on them. To find out which are currently selected, you
need to check their selected state explicitly.
If the selection state has changed by user interaction, the \ref selectionChangedByUser signal is
emitted. Each selectable object additionally emits an individual selectionChanged signal whenever
their selection state has changed, i.e. not only by user interaction.
To allow multiple objects to be selected by holding the selection modifier (\ref
setMultiSelectModifier), set the flag \ref QCP::iMultiSelect.
\note In addition to the selection mechanism presented here, QCustomPlot always emits
corresponding signals, when an object is clicked or double clicked. see \ref plottableClick and
\ref plottableDoubleClick for example.
\see setInteraction, setSelectionTolerance
*/
void QCustomPlot::setInteractions(const QCP::Interactions &interactions)
{
mInteractions = interactions;
}
/*!
Sets the single \a interaction of this QCustomPlot to \a enabled.
For details about the interaction system, see \ref setInteractions.
\see setInteractions
*/
void QCustomPlot::setInteraction(const QCP::Interaction &interaction, bool enabled)
{
if (!enabled && mInteractions.testFlag(interaction))
mInteractions &= ~interaction;
else if (enabled && !mInteractions.testFlag(interaction))
mInteractions |= interaction;
}
/*!
Sets the tolerance that is used to decide whether a click selects an object (e.g. a plottable) or
not.
If the user clicks in the vicinity of the line of e.g. a QCPGraph, it's only regarded as a
potential selection when the minimum distance between the click position and the graph line is
smaller than \a pixels. Objects that are defined by an area (e.g. QCPBars) only react to clicks
directly inside the area and ignore this selection tolerance. In other words, it only has meaning
for parts of objects that are too thin to exactly hit with a click and thus need such a
tolerance.
\see setInteractions, QCPLayerable::selectTest
*/
void QCustomPlot::setSelectionTolerance(int pixels)
{
mSelectionTolerance = pixels;
}
/*!
Sets whether antialiasing is disabled for this QCustomPlot while the user is dragging axes
ranges. If many objects, especially plottables, are drawn antialiased, this greatly improves
performance during dragging. Thus it creates a more responsive user experience. As soon as the
user stops dragging, the last replot is done with normal antialiasing, to restore high image
quality.
\see setAntialiasedElements, setNotAntialiasedElements
*/
void QCustomPlot::setNoAntialiasingOnDrag(bool enabled)
{
mNoAntialiasingOnDrag = enabled;
}
/*!
Sets the plotting hints for this QCustomPlot instance as an \a or combination of QCP::PlottingHint.
\see setPlottingHint
*/
void QCustomPlot::setPlottingHints(const QCP::PlottingHints &hints)
{
mPlottingHints = hints;
}
/*!
Sets the specified plotting \a hint to \a enabled.
\see setPlottingHints
*/
void QCustomPlot::setPlottingHint(QCP::PlottingHint hint, bool enabled)
{
QCP::PlottingHints newHints = mPlottingHints;
if (!enabled)
newHints &= ~hint;
else
newHints |= hint;
if (newHints != mPlottingHints)
setPlottingHints(newHints);
}
/*!
Sets the keyboard modifier that will be recognized as multi-select-modifier.
If \ref QCP::iMultiSelect is specified in \ref setInteractions, the user may select multiple objects
by clicking on them one after the other while holding down \a modifier.
By default the multi-select-modifier is set to Qt::ControlModifier.
\see setInteractions
*/
void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier)
{
mMultiSelectModifier = modifier;
}
/*!
Sets the viewport of this QCustomPlot. The Viewport is the area that the top level layout
(QCustomPlot::plotLayout()) uses as its rect. Normally, the viewport is the entire widget rect.
This function is used to allow arbitrary size exports with \ref toPixmap, \ref savePng, \ref
savePdf, etc. by temporarily changing the viewport size.
*/
void QCustomPlot::setViewport(const QRect &rect)
{
mViewport = rect;
if (mPlotLayout)
mPlotLayout->setOuterRect(mViewport);
}
/*!
Sets \a pm as the viewport background pixmap (see \ref setViewport). The pixmap is always drawn
below all other objects in the plot.
For cases where the provided pixmap doesn't have the same size as the viewport, scaling can be
enabled with \ref setBackgroundScaled and the scaling mode (whether and how the aspect ratio is
preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
consider using the overloaded version of this function.
If a background brush was set with \ref setBackground(const QBrush &brush), the viewport will
first be filled with that brush, before drawing the background pixmap. This can be useful for
background pixmaps with translucent areas.
\see setBackgroundScaled, setBackgroundScaledMode
*/
void QCustomPlot::setBackground(const QPixmap &pm)
{
mBackgroundPixmap = pm;
mScaledBackgroundPixmap = QPixmap();
}
/*!
Sets the background brush of the viewport (see \ref setViewport).
Before drawing everything else, the background is filled with \a brush. If a background pixmap
was set with \ref setBackground(const QPixmap &pm), this brush will be used to fill the viewport
before the background pixmap is drawn. This can be useful for background pixmaps with translucent
areas.
Set \a brush to Qt::NoBrush or Qt::Transparent to leave background transparent. This can be
useful for exporting to image formats which support transparency, e.g. \ref savePng.
\see setBackgroundScaled, setBackgroundScaledMode
*/
void QCustomPlot::setBackground(const QBrush &brush)
{
mBackgroundBrush = brush;
}
/*! \overload
Allows setting the background pixmap of the viewport, whether it shall be scaled and how it
shall be scaled in one call.
\see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
*/
void QCustomPlot::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
{
mBackgroundPixmap = pm;
mScaledBackgroundPixmap = QPixmap();
mBackgroundScaled = scaled;
mBackgroundScaledMode = mode;
}
/*!
Sets whether the viewport background pixmap shall be scaled to fit the viewport. If \a scaled is
set to true, control whether and how the aspect ratio of the original pixmap is preserved with
\ref setBackgroundScaledMode.
Note that the scaled version of the original pixmap is buffered, so there is no performance
penalty on replots. (Except when the viewport dimensions are changed continuously.)
\see setBackground, setBackgroundScaledMode
*/
void QCustomPlot::setBackgroundScaled(bool scaled)
{
mBackgroundScaled = scaled;
}
/*!
If scaling of the viewport background pixmap is enabled (\ref setBackgroundScaled), use this
function to define whether and how the aspect ratio of the original pixmap is preserved.
\see setBackground, setBackgroundScaled
*/
void QCustomPlot::setBackgroundScaledMode(Qt::AspectRatioMode mode)
{
mBackgroundScaledMode = mode;
}
/*!
Returns the plottable with \a index. If the index is invalid, returns 0.
There is an overloaded version of this function with no parameter which returns the last added
plottable, see QCustomPlot::plottable()
\see plottableCount, addPlottable
*/
QCPAbstractPlottable *QCustomPlot::plottable(int index)
{
if (index >= 0 && index < mPlottables.size())
{
return mPlottables.at(index);
} else
{
qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
return 0;
}
}
/*! \overload
Returns the last plottable that was added with \ref addPlottable. If there are no plottables in
the plot, returns 0.
\see plottableCount, addPlottable
*/
QCPAbstractPlottable *QCustomPlot::plottable()
{
if (!mPlottables.isEmpty())
{
return mPlottables.last();
} else
return 0;
}
/*!
Adds the specified plottable to the plot and, if \ref setAutoAddPlottableToLegend is enabled, to
the legend (QCustomPlot::legend). QCustomPlot takes ownership of the plottable.
Returns true on success, i.e. when \a plottable isn't already in the plot and the parent plot of
\a plottable is this QCustomPlot (the latter is controlled by what axes were passed in the
plottable's constructor).
\see plottable, plottableCount, removePlottable, clearPlottables
*/
bool QCustomPlot::addPlottable(QCPAbstractPlottable *plottable)
{
if (mPlottables.contains(plottable))
{
qDebug() << Q_FUNC_INFO << "plottable already added to this QCustomPlot:" << reinterpret_cast<quintptr>(plottable);
return false;
}
if (plottable->parentPlot() != this)
{
qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(plottable);
return false;
}
mPlottables.append(plottable);
// possibly add plottable to legend:
if (mAutoAddPlottableToLegend)
plottable->addToLegend();
// special handling for QCPGraphs to maintain the simple graph interface:
if (QCPGraph *graph = qobject_cast<QCPGraph*>(plottable))
mGraphs.append(graph);
if (!plottable->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor)
plottable->setLayer(currentLayer());
return true;
}
/*!
Removes the specified plottable from the plot and, if necessary, from the legend (QCustomPlot::legend).
Returns true on success.
\see addPlottable, clearPlottables
*/
bool QCustomPlot::removePlottable(QCPAbstractPlottable *plottable)
{
if (!mPlottables.contains(plottable))
{
qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast<quintptr>(plottable);
return false;
}
// remove plottable from legend:
plottable->removeFromLegend();
// special handling for QCPGraphs to maintain the simple graph interface:
if (QCPGraph *graph = qobject_cast<QCPGraph*>(plottable))
mGraphs.removeOne(graph);
// remove plottable:
delete plottable;
mPlottables.removeOne(plottable);
return true;
}
/*! \overload
Removes the plottable by its \a index.
*/
bool QCustomPlot::removePlottable(int index)
{
if (index >= 0 && index < mPlottables.size())
return removePlottable(mPlottables[index]);
else
{
qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
return false;
}
}
/*!
Removes all plottables from the plot (and the QCustomPlot::legend, if necessary).
Returns the number of plottables removed.
\see removePlottable
*/
int QCustomPlot::clearPlottables()
{
int c = mPlottables.size();
for (int i=c-1; i >= 0; --i)
removePlottable(mPlottables[i]);
return c;
}
/*!
Returns the number of currently existing plottables in the plot
\see plottable, addPlottable
*/
int QCustomPlot::plottableCount() const
{
return mPlottables.size();
}
/*!
Returns a list of the selected plottables. If no plottables are currently selected, the list is empty.
There is a convenience function if you're only interested in selected graphs, see \ref selectedGraphs.
\see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelected
*/
QList<QCPAbstractPlottable*> QCustomPlot::selectedPlottables() const
{
QList<QCPAbstractPlottable*> result;
for (int i=0; i<mPlottables.size(); ++i)
{
if (mPlottables.at(i)->selected())
result.append(mPlottables.at(i));
}
return result;
}
/*!
Returns the plottable at the pixel position \a pos. Plottables that only consist of single lines
(like graphs) have a tolerance band around them, see \ref setSelectionTolerance. If multiple
plottables come into consideration, the one closest to \a pos is returned.
If \a onlySelectable is true, only plottables that are selectable
(QCPAbstractPlottable::setSelectable) are considered.
If there is no plottable at \a pos, the return value is 0.
\see itemAt, layoutElementAt
*/
QCPAbstractPlottable *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable) const
{
QCPAbstractPlottable *resultPlottable = 0;
double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value
for (int i=0; i<mPlottables.size(); ++i)
{
QCPAbstractPlottable *currentPlottable = mPlottables.at(i);
if (onlySelectable && !currentPlottable->selectable()) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPabstractPlottable::selectable
continue;
if ((currentPlottable->keyAxis()->axisRect()->rect() & currentPlottable->valueAxis()->axisRect()->rect()).contains(pos.toPoint())) // only consider clicks inside the rect that is spanned by the plottable's key/value axes
{
double currentDistance = currentPlottable->selectTest(pos, false);
if (currentDistance >= 0 && currentDistance < resultDistance)
{
resultPlottable = currentPlottable;
resultDistance = currentDistance;
}
}
}
return resultPlottable;
}
/*!
Returns whether this QCustomPlot instance contains the \a plottable.
\see addPlottable
*/
bool QCustomPlot::hasPlottable(QCPAbstractPlottable *plottable) const
{
return mPlottables.contains(plottable);
}
/*!
Returns the graph with \a index. If the index is invalid, returns 0.
There is an overloaded version of this function with no parameter which returns the last created
graph, see QCustomPlot::graph()
\see graphCount, addGraph
*/
QCPGraph *QCustomPlot::graph(int index) const
{
if (index >= 0 && index < mGraphs.size())
{
return mGraphs.at(index);
} else
{
qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
return 0;
}
}
/*! \overload
Returns the last graph, that was created with \ref addGraph. If there are no graphs in the plot,
returns 0.
\see graphCount, addGraph
*/
QCPGraph *QCustomPlot::graph() const
{
if (!mGraphs.isEmpty())
{
return mGraphs.last();
} else
return 0;
}
/*!
Creates a new graph inside the plot. If \a keyAxis and \a valueAxis are left unspecified (0), the
bottom (xAxis) is used as key and the left (yAxis) is used as value axis. If specified, \a
keyAxis and \a valueAxis must reside in this QCustomPlot.
\a keyAxis will be used as key axis (typically "x") and \a valueAxis as value axis (typically
"y") for the graph.
Returns a pointer to the newly created graph, or 0 if adding the graph failed.
\see graph, graphCount, removeGraph, clearGraphs
*/
QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis)
{
if (!keyAxis) keyAxis = xAxis;
if (!valueAxis) valueAxis = yAxis;
if (!keyAxis || !valueAxis)
{
qDebug() << Q_FUNC_INFO << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid (has been deleted)";
return 0;
}
if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this)
{
qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent";
return 0;
}
QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis);
if (addPlottable(newGraph))
{
newGraph->setName("Graph "+QString::number(mGraphs.size()));
return newGraph;
} else
{
delete newGraph;
return 0;
}
}
/*!
Removes the specified \a graph from the plot and, if necessary, from the QCustomPlot::legend. If
any other graphs in the plot have a channel fill set towards the removed graph, the channel fill
property of those graphs is reset to zero (no channel fill).
Returns true on success.
\see clearGraphs
*/
bool QCustomPlot::removeGraph(QCPGraph *graph)
{
return removePlottable(graph);
}
/*! \overload
Removes the graph by its \a index.
*/
bool QCustomPlot::removeGraph(int index)
{
if (index >= 0 && index < mGraphs.size())
return removeGraph(mGraphs[index]);
else
return false;
}
/*!
Removes all graphs from the plot (and the QCustomPlot::legend, if necessary).
Returns the number of graphs removed.
\see removeGraph
*/
int QCustomPlot::clearGraphs()
{
int c = mGraphs.size();
for (int i=c-1; i >= 0; --i)
removeGraph(mGraphs[i]);
return c;
}
/*!
Returns the number of currently existing graphs in the plot
\see graph, addGraph
*/
int QCustomPlot::graphCount() const
{
return mGraphs.size();
}
/*!
Returns a list of the selected graphs. If no graphs are currently selected, the list is empty.
If you are not only interested in selected graphs but other plottables like QCPCurve, QCPBars,
etc., use \ref selectedPlottables.
\see setInteractions, selectedPlottables, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelected
*/
QList<QCPGraph*> QCustomPlot::selectedGraphs() const
{
QList<QCPGraph*> result;
for (int i=0; i<mGraphs.size(); ++i)
{
if (mGraphs.at(i)->selected())
result.append(mGraphs.at(i));
}
return result;
}
/*!
Returns the item with \a index. If the index is invalid, returns 0.
There is an overloaded version of this function with no parameter which returns the last added
item, see QCustomPlot::item()
\see itemCount, addItem
*/
QCPAbstractItem *QCustomPlot::item(int index) const
{
if (index >= 0 && index < mItems.size())
{
return mItems.at(index);
} else
{
qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
return 0;
}
}
/*! \overload
Returns the last item, that was added with \ref addItem. If there are no items in the plot,
returns 0.
\see itemCount, addItem
*/
QCPAbstractItem *QCustomPlot::item() const
{
if (!mItems.isEmpty())
{
return mItems.last();
} else
return 0;
}
/*!
Adds the specified item to the plot. QCustomPlot takes ownership of the item.
Returns true on success, i.e. when \a item wasn't already in the plot and the parent plot of \a
item is this QCustomPlot.
\see item, itemCount, removeItem, clearItems
*/
bool QCustomPlot::addItem(QCPAbstractItem *item)
{
if (!mItems.contains(item) && item->parentPlot() == this)
{
mItems.append(item);
return true;
} else
{
qDebug() << Q_FUNC_INFO << "item either already in list or not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(item);
return false;
}
}
/*!
Removes the specified item from the plot.
Returns true on success.
\see addItem, clearItems
*/
bool QCustomPlot::removeItem(QCPAbstractItem *item)
{
if (mItems.contains(item))
{
delete item;
mItems.removeOne(item);
return true;
} else
{
qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast<quintptr>(item);
return false;
}
}
/*! \overload
Removes the item by its \a index.
*/
bool QCustomPlot::removeItem(int index)
{
if (index >= 0 && index < mItems.size())
return removeItem(mItems[index]);
else
{
qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
return false;
}
}
/*!
Removes all items from the plot.
Returns the number of items removed.
\see removeItem
*/
int QCustomPlot::clearItems()
{
int c = mItems.size();
for (int i=c-1; i >= 0; --i)
removeItem(mItems[i]);
return c;
}
/*!
Returns the number of currently existing items in the plot
\see item, addItem
*/
int QCustomPlot::itemCount() const
{
return mItems.size();
}
/*!
Returns a list of the selected items. If no items are currently selected, the list is empty.
\see setInteractions, QCPAbstractItem::setSelectable, QCPAbstractItem::setSelected
*/
QList<QCPAbstractItem*> QCustomPlot::selectedItems() const
{
QList<QCPAbstractItem*> result;
for (int i=0; i<mItems.size(); ++i)
{
if (mItems.at(i)->selected())
result.append(mItems.at(i));
}
return result;
}
/*!
Returns the item at the pixel position \a pos. Items that only consist of single lines (e.g. \ref
QCPItemLine or \ref QCPItemCurve) have a tolerance band around them, see \ref
setSelectionTolerance. If multiple items come into consideration, the one closest to \a pos is
returned.
If \a onlySelectable is true, only items that are selectable (QCPAbstractItem::setSelectable) are
considered.
If there is no item at \a pos, the return value is 0.
\see plottableAt, layoutElementAt
*/
QCPAbstractItem *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const
{
QCPAbstractItem *resultItem = 0;
double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value
for (int i=0; i<mItems.size(); ++i)
{
QCPAbstractItem *currentItem = mItems[i];
if (onlySelectable && !currentItem->selectable()) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractItem::selectable
continue;
if (!currentItem->clipToAxisRect() || currentItem->clipRect().contains(pos.toPoint())) // only consider clicks inside axis cliprect of the item if actually clipped to it
{
double currentDistance = currentItem->selectTest(pos, false);
if (currentDistance >= 0 && currentDistance < resultDistance)
{
resultItem = currentItem;
resultDistance = currentDistance;
}
}
}
return resultItem;
}
/*!
Returns whether this QCustomPlot contains the \a item.
\see addItem
*/
bool QCustomPlot::hasItem(QCPAbstractItem *item) const
{
return mItems.contains(item);
}
/*!
Returns the layer with the specified \a name. If there is no layer with the specified name, 0 is
returned.
Layer names are case-sensitive.
\see addLayer, moveLayer, removeLayer
*/
QCPLayer *QCustomPlot::layer(const QString &name) const
{
for (int i=0; i<mLayers.size(); ++i)
{
if (mLayers.at(i)->name() == name)
return mLayers.at(i);
}
return 0;
}
/*! \overload
Returns the layer by \a index. If the index is invalid, 0 is returned.
\see addLayer, moveLayer, removeLayer
*/
QCPLayer *QCustomPlot::layer(int index) const
{
if (index >= 0 && index < mLayers.size())
{
return mLayers.at(index);
} else
{
qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
return 0;
}
}
/*!
Returns the layer that is set as current layer (see \ref setCurrentLayer).
*/
QCPLayer *QCustomPlot::currentLayer() const
{
return mCurrentLayer;
}
/*!
Sets the layer with the specified \a name to be the current layer. All layerables (\ref
QCPLayerable), e.g. plottables and items, are created on the current layer.
Returns true on success, i.e. if there is a layer with the specified \a name in the QCustomPlot.
Layer names are case-sensitive.
\see addLayer, moveLayer, removeLayer, QCPLayerable::setLayer
*/
bool QCustomPlot::setCurrentLayer(const QString &name)
{
if (QCPLayer *newCurrentLayer = layer(name))
{
return setCurrentLayer(newCurrentLayer);
} else
{
qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name;
return false;
}
}
/*! \overload
Sets the provided \a layer to be the current layer.
Returns true on success, i.e. when \a layer is a valid layer in the QCustomPlot.
\see addLayer, moveLayer, removeLayer
*/
bool QCustomPlot::setCurrentLayer(QCPLayer *layer)
{
if (!mLayers.contains(layer))
{
qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
return false;
}
mCurrentLayer = layer;
return true;
}
/*!
Returns the number of currently existing layers in the plot
\see layer, addLayer
*/
int QCustomPlot::layerCount() const
{
return mLayers.size();
}
/*!
Adds a new layer to this QCustomPlot instance. The new layer will have the name \a name, which
must be unique. Depending on \a insertMode, it is positioned either below or above \a otherLayer.
Returns true on success, i.e. if there is no other layer named \a name and \a otherLayer is a
valid layer inside this QCustomPlot.
If \a otherLayer is 0, the highest layer in the QCustomPlot will be used.
For an explanation of what layers are in QCustomPlot, see the documentation of \ref QCPLayer.
\see layer, moveLayer, removeLayer
*/
bool QCustomPlot::addLayer(const QString &name, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode)
{
if (!otherLayer)
otherLayer = mLayers.last();
if (!mLayers.contains(otherLayer))
{
qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer);
return false;
}
if (layer(name))
{
qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name;
return false;
}
QCPLayer *newLayer = new QCPLayer(this, name);
mLayers.insert(otherLayer->index() + (insertMode==limAbove ? 1:0), newLayer);
updateLayerIndices();
return true;
}
/*!
Removes the specified \a layer and returns true on success.
All layerables (e.g. plottables and items) on the removed layer will be moved to the layer below
\a layer. If \a layer is the bottom layer, the layerables are moved to the layer above. In both
cases, the total rendering order of all layerables in the QCustomPlot is preserved.
If \a layer is the current layer (\ref setCurrentLayer), the layer below (or above, if bottom
layer) becomes the new current layer.
It is not possible to remove the last layer of the plot.
\see layer, addLayer, moveLayer
*/
bool QCustomPlot::removeLayer(QCPLayer *layer)
{
if (!mLayers.contains(layer))
{
qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
return false;
}
if (mLayers.size() < 2)
{
qDebug() << Q_FUNC_INFO << "can't remove last layer";
return false;
}
// append all children of this layer to layer below (if this is lowest layer, prepend to layer above)
int removedIndex = layer->index();
bool isFirstLayer = removedIndex==0;
QCPLayer *targetLayer = isFirstLayer ? mLayers.at(removedIndex+1) : mLayers.at(removedIndex-1);
QList<QCPLayerable*> children = layer->children();
if (isFirstLayer) // prepend in reverse order (so order relative to each other stays the same)
{
for (int i=children.size()-1; i>=0; --i)
children.at(i)->moveToLayer(targetLayer, true);
} else // append normally
{
for (int i=0; i<children.size(); ++i)
children.at(i)->moveToLayer(targetLayer, false);
}
// if removed layer is current layer, change current layer to layer below/above:
if (layer == mCurrentLayer)
setCurrentLayer(targetLayer);
// remove layer:
delete layer;
mLayers.removeOne(layer);
updateLayerIndices();
return true;
}
/*!
Moves the specified \a layer either above or below \a otherLayer. Whether it's placed above or
below is controlled with \a insertMode.
Returns true on success, i.e. when both \a layer and \a otherLayer are valid layers in the
QCustomPlot.
\see layer, addLayer, moveLayer
*/
bool QCustomPlot::moveLayer(QCPLayer *layer, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode)
{
if (!mLayers.contains(layer))
{
qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
return false;
}
if (!mLayers.contains(otherLayer))
{
qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer);
return false;
}
mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 1:0));
updateLayerIndices();
return true;
}
/*!
Returns the number of axis rects in the plot.
All axis rects can be accessed via QCustomPlot::axisRect().
Initially, only one axis rect exists in the plot.
\see axisRect, axisRects
*/
int QCustomPlot::axisRectCount() const
{
return axisRects().size();
}
/*!
Returns the axis rect with \a index.
Initially, only one axis rect (with index 0) exists in the plot. If multiple axis rects were
added, all of them may be accessed with this function in a linear fashion (even when they are
nested in a layout hierarchy or inside other axis rects via QCPAxisRect::insetLayout).
\see axisRectCount, axisRects
*/
QCPAxisRect *QCustomPlot::axisRect(int index) const
{
const QList<QCPAxisRect*> rectList = axisRects();
if (index >= 0 && index < rectList.size())
{
return rectList.at(index);
} else
{
qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index;
return 0;
}
}
/*!
Returns all axis rects in the plot.
\see axisRectCount, axisRect
*/
QList<QCPAxisRect*> QCustomPlot::axisRects() const
{
QList<QCPAxisRect*> result;
QStack<QCPLayoutElement*> elementStack;
if (mPlotLayout)
elementStack.push(mPlotLayout);
while (!elementStack.isEmpty())
{
QList<QCPLayoutElement*> subElements = elementStack.pop()->elements(false);
for (int i=0; i<subElements.size(); ++i)
{
if (QCPLayoutElement *element = subElements.at(i))
{
elementStack.push(element);
if (QCPAxisRect *ar = qobject_cast<QCPAxisRect*>(element))
result.append(ar);
}
}
}
return result;
}
/*!
Returns the layout element at pixel position \a pos. If there is no element at that position,
returns 0.
Only visible elements are used. If \ref QCPLayoutElement::setVisible on the element itself or on
any of its parent elements is set to false, it will not be considered.
\see itemAt, plottableAt
*/
QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const
{
QCPLayoutElement *current = mPlotLayout;
bool searchSubElements = true;
while (searchSubElements && current)
{
searchSubElements = false;
const QList<QCPLayoutElement*> elements = current->elements(false);
for (int i=0; i<elements.size(); ++i)
{
if (elements.at(i) && elements.at(i)->realVisibility() && elements.at(i)->selectTest(pos, false) >= 0)
{
current = elements.at(i);
searchSubElements = true;
break;
}
}
}
return current;
}
/*!
Returns the axes that currently have selected parts, i.e. whose selection state is not \ref
QCPAxis::spNone.
\see selectedPlottables, selectedLegends, setInteractions, QCPAxis::setSelectedParts,
QCPAxis::setSelectableParts
*/
QList<QCPAxis*> QCustomPlot::selectedAxes() const
{
QList<QCPAxis*> result, allAxes;
QList<QCPAxisRect*> rects = axisRects();
for (int i=0; i<rects.size(); ++i)
allAxes << rects.at(i)->axes();
for (int i=0; i<allAxes.size(); ++i)
{
if (allAxes.at(i)->selectedParts() != QCPAxis::spNone)
result.append(allAxes.at(i));
}
return result;
}
/*!
Returns the legends that currently have selected parts, i.e. whose selection state is not \ref
QCPLegend::spNone.
\see selectedPlottables, selectedAxes, setInteractions, QCPLegend::setSelectedParts,
QCPLegend::setSelectableParts, QCPLegend::selectedItems
*/
QList<QCPLegend*> QCustomPlot::selectedLegends() const
{
QList<QCPLegend*> result;
QStack<QCPLayoutElement*> elementStack;
if (mPlotLayout)
elementStack.push(mPlotLayout);
while (!elementStack.isEmpty())
{
QList<QCPLayoutElement*> subElements = elementStack.pop()->elements(false);
for (int i=0; i<subElements.size(); ++i)
{
if (QCPLayoutElement *element = subElements.at(i))
{
elementStack.push(element);
if (QCPLegend *leg = qobject_cast<QCPLegend*>(element))
{
if (leg->selectedParts() != QCPLegend::spNone)
result.append(leg);
}
}
}
}
return result;
}
/*!
Deselects all layerables (plottables, items, axes, legends,...) of the QCustomPlot.
Since calling this function is not a user interaction, this does not emit the \ref
selectionChangedByUser signal. The individual selectionChanged signals are emitted though, if the
objects were previously selected.
\see setInteractions, selectedPlottables, selectedItems, selectedAxes, selectedLegends
*/
void QCustomPlot::deselectAll()
{
for (int i=0; i<mLayers.size(); ++i)
{
QList<QCPLayerable*> layerables = mLayers.at(i)->children();
for (int k=0; k<layerables.size(); ++k)
layerables.at(k)->deselectEvent(0);
}
}
/*!
Causes a complete replot into the internal buffer. Finally, update() is called, to redraw the
buffer on the QCustomPlot widget surface. This is the method that must be called to make changes,
for example on the axis ranges or data points of graphs, visible.
Under a few circumstances, QCustomPlot causes a replot by itself. Those are resize events of the
QCustomPlot widget and user interactions (object selection and range dragging/zooming).
Before the replot happens, the signal \ref beforeReplot is emitted. After the replot, \ref
afterReplot is emitted. It is safe to mutually connect the replot slot with any of those two
signals on two QCustomPlots to make them replot synchronously, it won't cause an infinite
recursion.
*/
void QCustomPlot::replot()
{
if (mReplotting) // incase signals loop back to replot slot
return;
mReplotting = true;
emit beforeReplot();
mPaintBuffer.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent);
QCPPainter painter;
painter.begin(&mPaintBuffer);
if (painter.isActive())
{
painter.setRenderHint(QPainter::HighQualityAntialiasing); // to make Antialiasing look good if using the OpenGL graphicssystem
if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush)
painter.fillRect(mViewport, mBackgroundBrush);
draw(&painter);
painter.end();
if (mPlottingHints.testFlag(QCP::phForceRepaint))
repaint();
else
update();
} else // might happen if QCustomPlot has width or height zero
qDebug() << Q_FUNC_INFO << "Couldn't activate painter on buffer";
emit afterReplot();
mReplotting = false;
}
/*!
Rescales the axes such that all plottables (like graphs) in the plot are fully visible.
if \a onlyVisiblePlottables is set to true, only the plottables that have their visibility set to true
(QCPLayerable::setVisible), will be used to rescale the axes.
\see QCPAbstractPlottable::rescaleAxes, QCPAxis::rescale
*/
void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables)
{
// get a list of all axes in the plot:
QList<QCPAxis*> axes;
QList<QCPAxisRect*> rects = axisRects();
for (int i=0; i<rects.size(); ++i)
axes << rects.at(i)->axes();
// call rescale on all axes:
for (int i=0; i<axes.size(); ++i)
axes.at(i)->rescale(onlyVisiblePlottables);
}
/*!
Saves a PDF with the vectorized plot to the file \a fileName. The axis ratio as well as the scale
of texts and lines will be derived from the specified \a width and \a height. This means, the
output will look like the normal on-screen output of a QCustomPlot widget with the corresponding
pixel width and height. If either \a width or \a height is zero, the exported image will have the
same dimensions as the QCustomPlot widget currently has.
\a noCosmeticPen disables the use of cosmetic pens when drawing to the PDF file. Cosmetic pens
are pens with numerical width 0, which are always drawn as a one pixel wide line, no matter what
zoom factor is set in the PDF-Viewer. For more information about cosmetic pens, see the QPainter
and QPen documentation.
The objects of the plot will appear in the current selection state. If you don't want any
selected objects to be painted in their selected look, deselect everything with \ref deselectAll
before calling this function.
Returns true on success.
\warning
\li If you plan on editing the exported PDF file with a vector graphics editor like
Inkscape, it is advised to set \a noCosmeticPen to true to avoid losing those cosmetic lines
(which might be quite many, because cosmetic pens are the default for e.g. axes and tick marks).
\li If calling this function inside the constructor of the parent of the QCustomPlot widget
(i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
function uses the current width and height of the QCustomPlot widget. However, in Qt, these
aren't defined yet inside the constructor, so you would get an image that has strange
widths/heights.
\note On Android systems, this method does nothing and issues an according qDebug warning
message. This is also the case if for other reasons the define flag QT_NO_PRINTER is set.
\see savePng, saveBmp, saveJpg, saveRastered
*/
bool QCustomPlot::savePdf(const QString &fileName, bool noCosmeticPen, int width, int height)
{
bool success = false;
#ifdef QT_NO_PRINTER
Q_UNUSED(fileName)
Q_UNUSED(noCosmeticPen)
Q_UNUSED(width)
Q_UNUSED(height)
qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created.";
#else
int newWidth, newHeight;
if (width == 0 || height == 0)
{
newWidth = this->width();
newHeight = this->height();
} else
{
newWidth = width;
newHeight = height;
}
QPrinter printer(QPrinter::ScreenResolution);
printer.setOutputFileName(fileName);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setFullPage(true);
printer.setColorMode(QPrinter::Color);
QRect oldViewport = viewport();
setViewport(QRect(0, 0, newWidth, newHeight));
printer.setPaperSize(viewport().size(), QPrinter::DevicePixel);
QCPPainter printpainter;
if (printpainter.begin(&printer))
{
printpainter.setMode(QCPPainter::pmVectorized);
printpainter.setMode(QCPPainter::pmNoCaching);
printpainter.setMode(QCPPainter::pmNonCosmetic, noCosmeticPen);
printpainter.setWindow(mViewport);
if (mBackgroundBrush.style() != Qt::NoBrush &&
mBackgroundBrush.color() != Qt::white &&
mBackgroundBrush.color() != Qt::transparent &&
mBackgroundBrush.color().alpha() > 0) // draw pdf background color if not white/transparent
printpainter.fillRect(viewport(), mBackgroundBrush);
draw(&printpainter);
printpainter.end();
success = true;
}
setViewport(oldViewport);
#endif // QT_NO_PRINTER
return success;
}
/*!
Saves a PNG image file to \a fileName on disc. The output plot will have the dimensions \a width
and \a height in pixels. If either \a width or \a height is zero, the exported image will have
the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not
scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter.
For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
200*200 pixel resolution.
If you use a high scaling factor, it is recommended to enable antialiasing for all elements via
temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
QCustomPlot to place objects with sub-pixel accuracy.
\warning If calling this function inside the constructor of the parent of the QCustomPlot widget
(i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
function uses the current width and height of the QCustomPlot widget. However, in Qt, these
aren't defined yet inside the constructor, so you would get an image that has strange
widths/heights.
The objects of the plot will appear in the current selection state. If you don't want any selected
objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
this function.
If you want the PNG to have a transparent background, call \ref setBackground(const QBrush
&brush) with no brush (Qt::NoBrush) or a transparent color (Qt::transparent), before saving.
PNG compression can be controlled with the \a quality parameter which must be between 0 and 100 or
-1 to use the default setting.
Returns true on success. If this function fails, most likely the PNG format isn't supported by
the system, see Qt docs about QImageWriter::supportedImageFormats().
\see savePdf, saveBmp, saveJpg, saveRastered
*/
bool QCustomPlot::savePng(const QString &fileName, int width, int height, double scale, int quality)
{
return saveRastered(fileName, width, height, scale, "PNG", quality);
}
/*!
Saves a JPG image file to \a fileName on disc. The output plot will have the dimensions \a width
and \a height in pixels. If either \a width or \a height is zero, the exported image will have
the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not
scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter.
For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
200*200 pixel resolution.
If you use a high scaling factor, it is recommended to enable antialiasing for all elements via
temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
QCustomPlot to place objects with sub-pixel accuracy.
\warning If calling this function inside the constructor of the parent of the QCustomPlot widget
(i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
function uses the current width and height of the QCustomPlot widget. However, in Qt, these
aren't defined yet inside the constructor, so you would get an image that has strange
widths/heights.
The objects of the plot will appear in the current selection state. If you don't want any selected
objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
this function.
JPG compression can be controlled with the \a quality parameter which must be between 0 and 100 or
-1 to use the default setting.
Returns true on success. If this function fails, most likely the JPG format isn't supported by
the system, see Qt docs about QImageWriter::supportedImageFormats().
\see savePdf, savePng, saveBmp, saveRastered
*/
bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double scale, int quality)
{
return saveRastered(fileName, width, height, scale, "JPG", quality);
}
/*!
Saves a BMP image file to \a fileName on disc. The output plot will have the dimensions \a width
and \a height in pixels. If either \a width or \a height is zero, the exported image will have
the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not
scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter.
For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
200*200 pixel resolution.
If you use a high scaling factor, it is recommended to enable antialiasing for all elements via
temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
QCustomPlot to place objects with sub-pixel accuracy.
\warning If calling this function inside the constructor of the parent of the QCustomPlot widget
(i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
function uses the current width and height of the QCustomPlot widget. However, in Qt, these
aren't defined yet inside the constructor, so you would get an image that has strange
widths/heights.
The objects of the plot will appear in the current selection state. If you don't want any selected
objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
this function.
Returns true on success. If this function fails, most likely the BMP format isn't supported by
the system, see Qt docs about QImageWriter::supportedImageFormats().
\see savePdf, savePng, saveJpg, saveRastered
*/
bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double scale)
{
return saveRastered(fileName, width, height, scale, "BMP");
}
/*! \internal
Returns a minimum size hint that corresponds to the minimum size of the top level layout
(\ref plotLayout). To prevent QCustomPlot from being collapsed to size/width zero, set a minimum
size (setMinimumSize) either on the whole QCustomPlot or on any layout elements inside the plot.
This is especially important, when placed in a QLayout where other components try to take in as
much space as possible (e.g. QMdiArea).
*/
QSize QCustomPlot::minimumSizeHint() const
{
return mPlotLayout->minimumSizeHint();
}
/*! \internal
Returns a size hint that is the same as \ref minimumSizeHint.
*/
QSize QCustomPlot::sizeHint() const
{
return mPlotLayout->minimumSizeHint();
}
/*! \internal
Event handler for when the QCustomPlot widget needs repainting. This does not cause a \ref replot, but
draws the internal buffer on the widget surface.
*/
void QCustomPlot::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QPainter painter(this);
painter.drawPixmap(0, 0, mPaintBuffer);
}
/*! \internal
Event handler for a resize of the QCustomPlot widget. Causes the internal buffer to be resized to
the new size. The viewport (which becomes the outer rect of mPlotLayout) is resized
appropriately. Finally a \ref replot is performed.
*/
void QCustomPlot::resizeEvent(QResizeEvent *event)
{
// resize and repaint the buffer:
mPaintBuffer = QPixmap(event->size());
setViewport(rect());
replot();
}
/*! \internal
Event handler for when a double click occurs. Emits the \ref mouseDoubleClick signal, then emits
the specialized signals when certain objecs are clicked (e.g. \ref plottableDoubleClick, \ref
axisDoubleClick, etc.). Finally determines the affected layout element and forwards the event to
it.
\see mousePressEvent, mouseReleaseEvent
*/
void QCustomPlot::mouseDoubleClickEvent(QMouseEvent *event)
{
emit mouseDoubleClick(event);
QVariant details;
QCPLayerable *clickedLayerable = layerableAt(event->pos(), false, &details);
// emit specialized object double click signals:
if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(clickedLayerable))
emit plottableDoubleClick(ap, event);
else if (QCPAxis *ax = qobject_cast<QCPAxis*>(clickedLayerable))
emit axisDoubleClick(ax, details.value<QCPAxis::SelectablePart>(), event);
else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(clickedLayerable))
emit itemDoubleClick(ai, event);
else if (QCPLegend *lg = qobject_cast<QCPLegend*>(clickedLayerable))
emit legendDoubleClick(lg, 0, event);
else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(clickedLayerable))
emit legendDoubleClick(li->parentLegend(), li, event);
else if (QCPPlotTitle *pt = qobject_cast<QCPPlotTitle*>(clickedLayerable))
emit titleDoubleClick(event, pt);
// call double click event of affected layout element:
if (QCPLayoutElement *el = layoutElementAt(event->pos()))
el->mouseDoubleClickEvent(event);
// call release event of affected layout element (as in mouseReleaseEvent, since the mouseDoubleClick replaces the second release event in double click case):
if (mMouseEventElement)
{
mMouseEventElement->mouseReleaseEvent(event);
mMouseEventElement = 0;
}
//QWidget::mouseDoubleClickEvent(event); don't call base class implementation because it would just cause a mousePress/ReleaseEvent, which we don't want.
}
/*! \internal
Event handler for when a mouse button is pressed. Emits the mousePress signal. Then determines
the affected layout element and forwards the event to it.
\see mouseMoveEvent, mouseReleaseEvent
*/
void QCustomPlot::mousePressEvent(QMouseEvent *event)
{
emit mousePress(event);
mMousePressPos = event->pos(); // need this to determine in releaseEvent whether it was a click (no position change between press and release)
// call event of affected layout element:
mMouseEventElement = layoutElementAt(event->pos());
if (mMouseEventElement)
mMouseEventElement->mousePressEvent(event);
QWidget::mousePressEvent(event);
}
/*! \internal
Event handler for when the cursor is moved. Emits the \ref mouseMove signal.
If a layout element has mouse capture focus (a mousePressEvent happened on top of the layout
element before), the mouseMoveEvent is forwarded to that element.
\see mousePressEvent, mouseReleaseEvent
*/
void QCustomPlot::mouseMoveEvent(QMouseEvent *event)
{
emit mouseMove(event);
// call event of affected layout element:
if (mMouseEventElement)
mMouseEventElement->mouseMoveEvent(event);
QWidget::mouseMoveEvent(event);
}
/*! \internal
Event handler for when a mouse button is released. Emits the \ref mouseRelease signal.
If the mouse was moved less than a certain threshold in any direction since the \ref
mousePressEvent, it is considered a click which causes the selection mechanism (if activated via
\ref setInteractions) to possibly change selection states accordingly. Further, specialized mouse
click signals are emitted (e.g. \ref plottableClick, \ref axisClick, etc.)
If a layout element has mouse capture focus (a \ref mousePressEvent happened on top of the layout
element before), the \ref mouseReleaseEvent is forwarded to that element.
\see mousePressEvent, mouseMoveEvent
*/
void QCustomPlot::mouseReleaseEvent(QMouseEvent *event)
{
emit mouseRelease(event);
bool doReplot = false;
if ((mMousePressPos-event->pos()).manhattanLength() < 5) // determine whether it was a click operation
{
if (event->button() == Qt::LeftButton)
{
// handle selection mechanism:
QVariant details;
QCPLayerable *clickedLayerable = layerableAt(event->pos(), true, &details);
bool selectionStateChanged = false;
bool additive = mInteractions.testFlag(QCP::iMultiSelect) && event->modifiers().testFlag(mMultiSelectModifier);
if (clickedLayerable && mInteractions.testFlag(clickedLayerable->selectionCategory()))
{
// a layerable was actually clicked, call its selectEvent:
bool selChanged = false;
clickedLayerable->selectEvent(event, additive, details, &selChanged);
selectionStateChanged |= selChanged;
}
// deselect all other layerables if not additive selection:
if (!additive)
{
for (int i=0; i<mLayers.size(); ++i)
{
QList<QCPLayerable*> layerables = mLayers.at(i)->children();
for (int k=0; k<layerables.size(); ++k)
{
if (layerables.at(k) != clickedLayerable && mInteractions.testFlag(layerables.at(k)->selectionCategory()))
{
bool selChanged = false;
layerables.at(k)->deselectEvent(&selChanged);
selectionStateChanged |= selChanged;
}
}
}
}
doReplot = true;
if (selectionStateChanged)
emit selectionChangedByUser();
}
// emit specialized object click signals:
QVariant details;
QCPLayerable *clickedLayerable = layerableAt(event->pos(), false, &details); // for these signals, selectability is ignored, that's why we call this again with onlySelectable set to false
if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(clickedLayerable))
emit plottableClick(ap, event);
else if (QCPAxis *ax = qobject_cast<QCPAxis*>(clickedLayerable))
emit axisClick(ax, details.value<QCPAxis::SelectablePart>(), event);
else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(clickedLayerable))
emit itemClick(ai, event);
else if (QCPLegend *lg = qobject_cast<QCPLegend*>(clickedLayerable))
emit legendClick(lg, 0, event);
else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(clickedLayerable))
emit legendClick(li->parentLegend(), li, event);
else if (QCPPlotTitle *pt = qobject_cast<QCPPlotTitle*>(clickedLayerable))
emit titleClick(event, pt);
}
// call event of affected layout element:
if (mMouseEventElement)
{
mMouseEventElement->mouseReleaseEvent(event);
mMouseEventElement = 0;
}
if (doReplot || noAntialiasingOnDrag())
replot();
QWidget::mouseReleaseEvent(event);
}
/*! \internal
Event handler for mouse wheel events. First, the \ref mouseWheel signal is emitted. Then
determines the affected layout element and forwards the event to it.
*/
void QCustomPlot::wheelEvent(QWheelEvent *event)
{
emit mouseWheel(event);
// call event of affected layout element:
if (QCPLayoutElement *el = layoutElementAt(event->pos()))
el->wheelEvent(event);
QWidget::wheelEvent(event);
}
/*! \internal
This is the main draw function. It draws the entire plot, including background pixmap, with the
specified \a painter. Note that it does not fill the background with the background brush (as the
user may specify with \ref setBackground(const QBrush &brush)), this is up to the respective
functions calling this method (e.g. \ref replot, \ref toPixmap and \ref toPainter).
*/
void QCustomPlot::draw(QCPPainter *painter)
{
// update all axis tick vectors:
QList<QCPAxisRect*> rects = axisRects();
for (int i=0; i<rects.size(); ++i)
{
QList<QCPAxis*> axes = rects.at(i)->axes();
for (int k=0; k<axes.size(); ++k)
axes.at(k)->setupTickVectors();
}
// recalculate layout:
mPlotLayout->update();
// draw viewport background pixmap:
drawBackground(painter);
// draw all layered objects (grid, axes, plottables, items, legend,...):
for (int layerIndex=0; layerIndex < mLayers.size(); ++layerIndex)
{
QList<QCPLayerable*> layerChildren = mLayers.at(layerIndex)->children();
for (int k=0; k < layerChildren.size(); ++k)
{
QCPLayerable *child = layerChildren.at(k);
if (child->realVisibility())
{
painter->save();
painter->setClipRect(child->clipRect().translated(0, -1));
child->applyDefaultAntialiasingHint(painter);
child->draw(painter);
painter->restore();
}
}
}
}
/*! \internal
Draws the viewport background pixmap of the plot.
If a pixmap was provided via \ref setBackground, this function buffers the scaled version
depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
the viewport with the provided \a painter. The scaled version is buffered in
mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
the axis rect has changed in a way that requires a rescale of the background pixmap (this is
dependant on the \ref setBackgroundScaledMode), or when a differend axis backgroud pixmap was
set.
Note that this function does not draw a fill with the background brush (\ref setBackground(const
QBrush &brush)) beneath the pixmap.
\see setBackground, setBackgroundScaled, setBackgroundScaledMode
*/
void QCustomPlot::drawBackground(QCPPainter *painter)
{
// Note: background color is handled in individual replot/save functions
// draw background pixmap (on top of fill, if brush specified):
if (!mBackgroundPixmap.isNull())
{
if (mBackgroundScaled)
{
// check whether mScaledBackground needs to be updated:
QSize scaledSize(mBackgroundPixmap.size());
scaledSize.scale(mViewport.size(), mBackgroundScaledMode);
if (mScaledBackgroundPixmap.size() != scaledSize)
mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()) & mScaledBackgroundPixmap.rect());
} else
{
painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()));
}
}
}
/*! \internal
This method is used by \ref QCPAxisRect::removeAxis to report removed axes to the QCustomPlot
so it may clear its QCustomPlot::xAxis, yAxis, xAxis2 and yAxis2 members accordingly.
*/
void QCustomPlot::axisRemoved(QCPAxis *axis)
{
if (xAxis == axis)
xAxis = 0;
if (xAxis2 == axis)
xAxis2 = 0;
if (yAxis == axis)
yAxis = 0;
if (yAxis2 == axis)
yAxis2 = 0;
// Note: No need to take care of range drag axes and range zoom axes, because they are stored in smart pointers
}
/*! \internal
This method is used by the QCPLegend destructor to report legend removal to the QCustomPlot so
it may clear its QCustomPlot::legend member accordingly.
*/
void QCustomPlot::legendRemoved(QCPLegend *legend)
{
if (this->legend == legend)
this->legend = 0;
}
/*! \internal
Assigns all layers their index (QCPLayer::mIndex) in the mLayers list. This method is thus called
after every operation that changes the layer indices, like layer removal, layer creation, layer
moving.
*/
void QCustomPlot::updateLayerIndices() const
{
for (int i=0; i<mLayers.size(); ++i)
mLayers.at(i)->mIndex = i;
}
/*! \internal
Returns the layerable at pixel position \a pos. If \a onlySelectable is set to true, only those
layerables that are selectable will be considered. (Layerable subclasses communicate their
selectability via the QCPLayerable::selectTest method, by returning -1.)
\a selectionDetails is an output parameter that contains selection specifics of the affected
layerable. This is useful if the respective layerable shall be given a subsequent
QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains
information about which part of the layerable was hit, in multi-part layerables (e.g.
QCPAxis::SelectablePart).
*/
QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails) const
{
for (int layerIndex=mLayers.size()-1; layerIndex>=0; --layerIndex)
{
const QList<QCPLayerable*> layerables = mLayers.at(layerIndex)->children();
double minimumDistance = selectionTolerance()*1.1;
QCPLayerable *minimumDistanceLayerable = 0;
for (int i=layerables.size()-1; i>=0; --i)
{
if (!layerables.at(i)->realVisibility())
continue;
QVariant details;
double dist = layerables.at(i)->selectTest(pos, onlySelectable, &details);
if (dist >= 0 && dist < minimumDistance)
{
minimumDistance = dist;
minimumDistanceLayerable = layerables.at(i);
if (selectionDetails) *selectionDetails = details;
}
}
if (minimumDistance < selectionTolerance())
return minimumDistanceLayerable;
}
return 0;
}
/*!
Saves the plot to a rastered image file \a fileName in the image format \a format. The plot is
sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and scale 2.0 lead
to a full resolution file with width 200.) If the \a format supports compression, \a quality may
be between 0 and 100 to control it.
Returns true on success. If this function fails, most likely the given \a format isn't supported
by the system, see Qt docs about QImageWriter::supportedImageFormats().
\see saveBmp, saveJpg, savePng, savePdf
*/
bool QCustomPlot::saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality)
{
QPixmap buffer = toPixmap(width, height, scale);
if (!buffer.isNull())
return buffer.save(fileName, format, quality);
else
return false;
}
/*!
Renders the plot to a pixmap and returns it.
The plot is sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and
scale 2.0 lead to a full resolution pixmap with width 200.)
\see toPainter, saveRastered, saveBmp, savePng, saveJpg, savePdf
*/
QPixmap QCustomPlot::toPixmap(int width, int height, double scale)
{
// this method is somewhat similar to toPainter. Change something here, and a change in toPainter might be necessary, too.
int newWidth, newHeight;
if (width == 0 || height == 0)
{
newWidth = this->width();
newHeight = this->height();
} else
{
newWidth = width;
newHeight = height;
}
int scaledWidth = qRound(scale*newWidth);
int scaledHeight = qRound(scale*newHeight);
QPixmap result(scaledWidth, scaledHeight);
result.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); // if using non-solid pattern, make transparent now and draw brush pattern later
QCPPainter painter;
painter.begin(&result);
if (painter.isActive())
{
QRect oldViewport = viewport();
setViewport(QRect(0, 0, newWidth, newHeight));
painter.setMode(QCPPainter::pmNoCaching);
if (!qFuzzyCompare(scale, 1.0))
{
if (scale > 1.0) // for scale < 1 we always want cosmetic pens where possible, because else lines might disappear for very small scales
painter.setMode(QCPPainter::pmNonCosmetic);
painter.scale(scale, scale);
}
if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush)
painter.fillRect(mViewport, mBackgroundBrush);
draw(&painter);
setViewport(oldViewport);
painter.end();
} else // might happen if pixmap has width or height zero
{
qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap";
return QPixmap();
}
return result;
}
/*!
Renders the plot using the passed \a painter.
The plot is sized to \a width and \a height in pixels. If the \a painter's scale is not 1.0, the resulting plot will
appear scaled accordingly.
\note If you are restricted to using a QPainter (instead of QCPPainter), create a temporary QPicture and open a QCPPainter
on it. Then call \ref toPainter with this QCPPainter. After ending the paint operation on the picture, draw it with
the QPainter. This will reproduce the painter actions the QCPPainter took, with a QPainter.
\see toPixmap
*/
void QCustomPlot::toPainter(QCPPainter *painter, int width, int height)
{
// this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap might be necessary, too.
int newWidth, newHeight;
if (width == 0 || height == 0)
{
newWidth = this->width();
newHeight = this->height();
} else
{
newWidth = width;
newHeight = height;
}
if (painter->isActive())
{
QRect oldViewport = viewport();
setViewport(QRect(0, 0, newWidth, newHeight));
painter->setMode(QCPPainter::pmNoCaching);
// warning: the following is different in toPixmap, because a solid background color is applied there via QPixmap::fill
// here, we need to do this via QPainter::fillRect.
if (mBackgroundBrush.style() != Qt::NoBrush)
painter->fillRect(mViewport, mBackgroundBrush);
draw(painter);
setViewport(oldViewport);
} else
qDebug() << Q_FUNC_INFO << "Passed painter is not active";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPData
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPData
\brief Holds the data of one single data point for QCPGraph.
The container for storing multiple data points is \ref QCPDataMap.
The stored data is:
\li \a key: coordinate on the key axis of this data point
\li \a value: coordinate on the value axis of this data point
\li \a keyErrorMinus: negative error in the key dimension (for error bars)
\li \a keyErrorPlus: positive error in the key dimension (for error bars)
\li \a valueErrorMinus: negative error in the value dimension (for error bars)
\li \a valueErrorPlus: positive error in the value dimension (for error bars)
\see QCPDataMap
*/
/*!
Constructs a data point with key, value and all errors set to zero.
*/
QCPData::QCPData() :
key(0),
value(0),
keyErrorPlus(0),
keyErrorMinus(0),
valueErrorPlus(0),
valueErrorMinus(0)
{
}
/*!
Constructs a data point with the specified \a key and \a value. All errors are set to zero.
*/
QCPData::QCPData(double key, double value) :
key(key),
value(value),
keyErrorPlus(0),
keyErrorMinus(0),
valueErrorPlus(0),
valueErrorMinus(0)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPGraph
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPGraph
\brief A plottable representing a graph in a plot.
\image html QCPGraph.png
Usually QCustomPlot creates graphs internally via QCustomPlot::addGraph and the resulting
instance is accessed via QCustomPlot::graph.
To plot data, assign it with the \ref setData or \ref addData functions.
Graphs are used to display single-valued data. Single-valued means that there should only be one
data point per unique key coordinate. In other words, the graph can't have \a loops. If you do
want to plot non-single-valued curves, rather use the QCPCurve plottable.
\section appearance Changing the appearance
The appearance of the graph is mainly determined by the line style, scatter style, brush and pen
of the graph (\ref setLineStyle, \ref setScatterStyle, \ref setBrush, \ref setPen).
\subsection filling Filling under or between graphs
QCPGraph knows two types of fills: Normal graph fills towards the zero-value-line parallel to
the key axis of the graph, and fills between two graphs, called channel fills. To enable a fill,
just set a brush with \ref setBrush which is neither Qt::NoBrush nor fully transparent.
By default, a normal fill towards the zero-value-line will be drawn. To set up a channel fill
between this graph and another one, call \ref setChannelFillGraph with the other graph as
parameter.
\see QCustomPlot::addGraph, QCustomPlot::graph, QCPLegend::addGraph
*/
/*!
Constructs a graph which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
the same orientation. If either of these restrictions is violated, a corresponding message is
printed to the debug output (qDebug), the construction is not aborted, though.
The constructed QCPGraph can be added to the plot with QCustomPlot::addPlottable, QCustomPlot
then takes ownership of the graph.
To directly create a graph inside a plot, you can also use the simpler QCustomPlot::addGraph function.
*/
QCPGraph::QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) :
QCPAbstractPlottable(keyAxis, valueAxis)
{
mData = new QCPDataMap;
setPen(QPen(Qt::blue, 0));
setErrorPen(QPen(Qt::black));
setBrush(Qt::NoBrush);
setSelectedPen(QPen(QColor(80, 80, 255), 2.5));
setSelectedBrush(Qt::NoBrush);
setLineStyle(lsLine);
setErrorType(etNone);
setErrorBarSize(6);
setErrorBarSkipSymbol(true);
setChannelFillGraph(0);
}
QCPGraph::~QCPGraph()
{
delete mData;
}
/*!
Replaces the current data with the provided \a data.
If \a copy is set to true, data points in \a data will only be copied. if false, the graph
takes ownership of the passed data and replaces the internal data pointer with it. This is
significantly faster than copying for large datasets.
*/
void QCPGraph::setData(QCPDataMap *data, bool copy)
{
if (copy)
{
*mData = *data;
} else
{
delete mData;
mData = data;
}
}
/*! \overload
Replaces the current data with the provided points in \a key and \a value pairs. The provided
vectors should have equal length. Else, the number of added points will be the size of the
smallest vector.
*/
void QCPGraph::setData(const QVector<double> &key, const QVector<double> &value)
{
mData->clear();
int n = key.size();
n = qMin(n, value.size());
QCPData newData;
for (int i=0; i<n; ++i)
{
newData.key = key[i];
newData.value = value[i];
mData->insertMulti(newData.key, newData);
}
}
/*!
Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
symmetrical value error of the data points are set to the values in \a valueError.
For error bars to show appropriately, see \ref setErrorType.
The provided vectors should have equal length. Else, the number of added points will be the size of the
smallest vector.
For asymmetrical errors (plus different from minus), see the overloaded version of this function.
*/
void QCPGraph::setDataValueError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &valueError)
{
mData->clear();
int n = key.size();
n = qMin(n, value.size());
n = qMin(n, valueError.size());
QCPData newData;
for (int i=0; i<n; ++i)
{
newData.key = key[i];
newData.value = value[i];
newData.valueErrorMinus = valueError[i];
newData.valueErrorPlus = valueError[i];
mData->insertMulti(key[i], newData);
}
}
/*!
\overload
Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
negative value error of the data points are set to the values in \a valueErrorMinus, the positive
value error to \a valueErrorPlus.
For error bars to show appropriately, see \ref setErrorType.
The provided vectors should have equal length. Else, the number of added points will be the size of the
smallest vector.
*/
void QCPGraph::setDataValueError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &valueErrorMinus, const QVector<double> &valueErrorPlus)
{
mData->clear();
int n = key.size();
n = qMin(n, value.size());
n = qMin(n, valueErrorMinus.size());
n = qMin(n, valueErrorPlus.size());
QCPData newData;
for (int i=0; i<n; ++i)
{
newData.key = key[i];
newData.value = value[i];
newData.valueErrorMinus = valueErrorMinus[i];
newData.valueErrorPlus = valueErrorPlus[i];
mData->insertMulti(key[i], newData);
}
}
/*!
Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
symmetrical key error of the data points are set to the values in \a keyError.
For error bars to show appropriately, see \ref setErrorType.
The provided vectors should have equal length. Else, the number of added points will be the size of the
smallest vector.
For asymmetrical errors (plus different from minus), see the overloaded version of this function.
*/
void QCPGraph::setDataKeyError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyError)
{
mData->clear();
int n = key.size();
n = qMin(n, value.size());
n = qMin(n, keyError.size());
QCPData newData;
for (int i=0; i<n; ++i)
{
newData.key = key[i];
newData.value = value[i];
newData.keyErrorMinus = keyError[i];
newData.keyErrorPlus = keyError[i];
mData->insertMulti(key[i], newData);
}
}
/*!
\overload
Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
negative key error of the data points are set to the values in \a keyErrorMinus, the positive
key error to \a keyErrorPlus.
For error bars to show appropriately, see \ref setErrorType.
The provided vectors should have equal length. Else, the number of added points will be the size of the
smallest vector.
*/
void QCPGraph::setDataKeyError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyErrorMinus, const QVector<double> &keyErrorPlus)
{
mData->clear();
int n = key.size();
n = qMin(n, value.size());
n = qMin(n, keyErrorMinus.size());
n = qMin(n, keyErrorPlus.size());
QCPData newData;
for (int i=0; i<n; ++i)
{
newData.key = key[i];
newData.value = value[i];
newData.keyErrorMinus = keyErrorMinus[i];
newData.keyErrorPlus = keyErrorPlus[i];
mData->insertMulti(key[i], newData);
}
}
/*!
Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
symmetrical key and value errors of the data points are set to the values in \a keyError and \a valueError.
For error bars to show appropriately, see \ref setErrorType.
The provided vectors should have equal length. Else, the number of added points will be the size of the
smallest vector.
For asymmetrical errors (plus different from minus), see the overloaded version of this function.
*/
void QCPGraph::setDataBothError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyError, const QVector<double> &valueError)
{
mData->clear();
int n = key.size();
n = qMin(n, value.size());
n = qMin(n, valueError.size());
n = qMin(n, keyError.size());
QCPData newData;
for (int i=0; i<n; ++i)
{
newData.key = key[i];
newData.value = value[i];
newData.keyErrorMinus = keyError[i];
newData.keyErrorPlus = keyError[i];
newData.valueErrorMinus = valueError[i];
newData.valueErrorPlus = valueError[i];
mData->insertMulti(key[i], newData);
}
}
/*!
\overload
Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
negative key and value errors of the data points are set to the values in \a keyErrorMinus and \a valueErrorMinus. The positive
key and value errors are set to the values in \a keyErrorPlus \a valueErrorPlus.
For error bars to show appropriately, see \ref setErrorType.
The provided vectors should have equal length. Else, the number of added points will be the size of the
smallest vector.
*/
void QCPGraph::setDataBothError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyErrorMinus, const QVector<double> &keyErrorPlus, const QVector<double> &valueErrorMinus, const QVector<double> &valueErrorPlus)
{
mData->clear();
int n = key.size();
n = qMin(n, value.size());
n = qMin(n, valueErrorMinus.size());
n = qMin(n, valueErrorPlus.size());
n = qMin(n, keyErrorMinus.size());
n = qMin(n, keyErrorPlus.size());
QCPData newData;
for (int i=0; i<n; ++i)
{
newData.key = key[i];
newData.value = value[i];
newData.keyErrorMinus = keyErrorMinus[i];
newData.keyErrorPlus = keyErrorPlus[i];
newData.valueErrorMinus = valueErrorMinus[i];
newData.valueErrorPlus = valueErrorPlus[i];
mData->insertMulti(key[i], newData);
}
}
/*!
Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to
\ref lsNone and \ref setScatterStyle to the desired scatter style.
\see setScatterStyle
*/
void QCPGraph::setLineStyle(LineStyle ls)
{
mLineStyle = ls;
}
/*!
Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points
are drawn (e.g. for line-only-plots with appropriate line style).
\see QCPScatterStyle, setLineStyle
*/
void QCPGraph::setScatterStyle(const QCPScatterStyle &style)
{
mScatterStyle = style;
}
/*!
Sets which kind of error bars (Key Error, Value Error or both) should be drawn on each data
point. If you set \a errorType to something other than \ref etNone, make sure to actually pass
error data via the specific setData functions along with the data points (e.g. \ref
setDataValueError, \ref setDataKeyError, \ref setDataBothError).
\see ErrorType
*/
void QCPGraph::setErrorType(ErrorType errorType)
{
mErrorType = errorType;
}
/*!
Sets the pen with which the error bars will be drawn.
\see setErrorBarSize, setErrorType
*/
void QCPGraph::setErrorPen(const QPen &pen)
{
mErrorPen = pen;
}
/*!
Sets the width of the handles at both ends of an error bar in pixels.
*/
void QCPGraph::setErrorBarSize(double size)
{
mErrorBarSize = size;
}
/*!
If \a enabled is set to true, the error bar will not be drawn as a solid line under the scatter symbol but
leave some free space around the symbol.
This feature uses the current scatter size (\ref QCPScatterStyle::setSize) to determine the size
of the area to leave blank. So when drawing Pixmaps as scatter points (\ref
QCPScatterStyle::ssPixmap), the scatter size must be set manually to a value corresponding to the
size of the Pixmap, if the error bars should leave gaps to its boundaries.
\ref setErrorType, setErrorBarSize, setScatterStyle
*/
void QCPGraph::setErrorBarSkipSymbol(bool enabled)
{
mErrorBarSkipSymbol = enabled;
}
/*!
Sets the target graph for filling the area between this graph and \a targetGraph with the current
brush (\ref setBrush).
When \a targetGraph is set to 0, a normal graph fill to the zero-value-line will be shown. To
disable any filling, set the brush to Qt::NoBrush.
\see setBrush
*/
void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph)
{
// prevent setting channel target to this graph itself:
if (targetGraph == this)
{
qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself";
mChannelFillGraph = 0;
return;
}
// prevent setting channel target to a graph not in the plot:
if (targetGraph && targetGraph->mParentPlot != mParentPlot)
{
qDebug() << Q_FUNC_INFO << "targetGraph not in same plot";
mChannelFillGraph = 0;
return;
}
mChannelFillGraph = targetGraph;
}
/*!
Adds the provided data points in \a dataMap to the current data.
\see removeData
*/
void QCPGraph::addData(const QCPDataMap &dataMap)
{
mData->unite(dataMap);
}
/*! \overload
Adds the provided single data point in \a data to the current data.
\see removeData
*/
void QCPGraph::addData(const QCPData &data)
{
mData->insertMulti(data.key, data);
}
/*! \overload
Adds the provided single data point as \a key and \a value pair to the current data.
\see removeData
*/
void QCPGraph::addData(double key, double value)
{
QCPData newData;
newData.key = key;
newData.value = value;
mData->insertMulti(newData.key, newData);
}
/*! \overload
Adds the provided data points as \a key and \a value pairs to the current data.
\see removeData
*/
void QCPGraph::addData(const QVector<double> &keys, const QVector<double> &values)
{
int n = qMin(keys.size(), values.size());
QCPData newData;
for (int i=0; i<n; ++i)
{
newData.key = keys[i];
newData.value = values[i];
mData->insertMulti(newData.key, newData);
}
}
/*!
Removes all data points with keys smaller than \a key.
\see addData, clearData
*/
void QCPGraph::removeDataBefore(double key)
{
QCPDataMap::iterator it = mData->begin();
while (it != mData->end() && it.key() < key)
it = mData->erase(it);
}
/*!
Removes all data points with keys greater than \a key.
\see addData, clearData
*/
void QCPGraph::removeDataAfter(double key)
{
if (mData->isEmpty()) return;
QCPDataMap::iterator it = mData->upperBound(key);
while (it != mData->end())
it = mData->erase(it);
}
/*!
Removes all data points with keys between \a fromKey and \a toKey.
if \a fromKey is greater or equal to \a toKey, the function does nothing. To remove
a single data point with known key, use \ref removeData(double key).
\see addData, clearData
*/
void QCPGraph::removeData(double fromKey, double toKey)
{
if (fromKey >= toKey || mData->isEmpty()) return;
QCPDataMap::iterator it = mData->upperBound(fromKey);
QCPDataMap::iterator itEnd = mData->upperBound(toKey);
while (it != itEnd)
it = mData->erase(it);
}
/*! \overload
Removes a single data point at \a key. If the position is not known with absolute precision,
consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval around
the suspected position, depeding on the precision with which the key is known.
\see addData, clearData
*/
void QCPGraph::removeData(double key)
{
mData->remove(key);
}
/*!
Removes all data points.
\see removeData, removeDataAfter, removeDataBefore
*/
void QCPGraph::clearData()
{
mData->clear();
}
/* inherits documentation from base class */
double QCPGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if ((onlySelectable && !mSelectable) || mData->isEmpty())
return -1;
return pointDistance(pos);
}
/*! \overload
Allows to define whether error bars are taken into consideration when determining the new axis
range.
\see rescaleKeyAxis, rescaleValueAxis, QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
*/
void QCPGraph::rescaleAxes(bool onlyEnlarge, bool includeErrorBars) const
{
rescaleKeyAxis(onlyEnlarge, includeErrorBars);
rescaleValueAxis(onlyEnlarge, includeErrorBars);
}
/*! \overload
Allows to define whether error bars (of kind \ref QCPGraph::etKey) are taken into consideration
when determining the new axis range.
\see rescaleAxes, QCPAbstractPlottable::rescaleKeyAxis
*/
void QCPGraph::rescaleKeyAxis(bool onlyEnlarge, bool includeErrorBars) const
{
// this code is a copy of QCPAbstractPlottable::rescaleKeyAxis with the only change
// that getKeyRange is passed the includeErrorBars value.
if (mData->isEmpty()) return;
QCPAxis *keyAxis = mKeyAxis.data();
if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
SignDomain signDomain = sdBoth;
if (keyAxis->scaleType() == QCPAxis::stLogarithmic)
signDomain = (keyAxis->range().upper < 0 ? sdNegative : sdPositive);
bool validRange;
QCPRange newRange = getKeyRange(validRange, signDomain, includeErrorBars);
if (validRange)
{
if (onlyEnlarge)
{
if (keyAxis->range().lower < newRange.lower)
newRange.lower = keyAxis->range().lower;
if (keyAxis->range().upper > newRange.upper)
newRange.upper = keyAxis->range().upper;
}
keyAxis->setRange(newRange);
}
}
/*! \overload
Allows to define whether error bars (of kind \ref QCPGraph::etValue) are taken into consideration
when determining the new axis range.
\see rescaleAxes, QCPAbstractPlottable::rescaleValueAxis
*/
void QCPGraph::rescaleValueAxis(bool onlyEnlarge, bool includeErrorBars) const
{
// this code is a copy of QCPAbstractPlottable::rescaleValueAxis with the only change
// is that getValueRange is passed the includeErrorBars value.
if (mData->isEmpty()) return;
QCPAxis *valueAxis = mValueAxis.data();
if (!valueAxis) { qDebug() << Q_FUNC_INFO << "invalid value axis"; return; }
SignDomain signDomain = sdBoth;
if (valueAxis->scaleType() == QCPAxis::stLogarithmic)
signDomain = (valueAxis->range().upper < 0 ? sdNegative : sdPositive);
bool validRange;
QCPRange newRange = getValueRange(validRange, signDomain, includeErrorBars);
if (validRange)
{
if (onlyEnlarge)
{
if (valueAxis->range().lower < newRange.lower)
newRange.lower = valueAxis->range().lower;
if (valueAxis->range().upper > newRange.upper)
newRange.upper = valueAxis->range().upper;
}
valueAxis->setRange(newRange);
}
}
/* inherits documentation from base class */
void QCPGraph::draw(QCPPainter *painter)
{
if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (mKeyAxis.data()->range().size() <= 0 || mData->isEmpty()) return;
if (mLineStyle == lsNone && mScatterStyle.isNone()) return;
// allocate line and (if necessary) point vectors:
QVector<QPointF> *lineData = new QVector<QPointF>;
QVector<QCPData> *pointData = 0;
if (!mScatterStyle.isNone())
pointData = new QVector<QCPData>;
// fill vectors with data appropriate to plot style:
getPlotData(lineData, pointData);
// check data validity if flag set:
#ifdef QCUSTOMPLOT_CHECK_DATA
QCPDataMap::const_iterator it;
for (it = mData->constBegin(); it != mData->constEnd(); ++it)
{
if (QCP::isInvalidData(it.value().key, it.value().value) ||
QCP::isInvalidData(it.value().keyErrorPlus, it.value().keyErrorMinus) ||
QCP::isInvalidData(it.value().valueErrorPlus, it.value().valueErrorPlus))
qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid." << "Plottable name:" << name();
}
#endif
// draw fill of graph:
drawFill(painter, lineData);
// draw line:
if (mLineStyle == lsImpulse)
drawImpulsePlot(painter, lineData);
else if (mLineStyle != lsNone)
drawLinePlot(painter, lineData); // also step plots can be drawn as a line plot
// draw scatters:
if (pointData)
drawScatterPlot(painter, pointData);
// free allocated line and point vectors:
delete lineData;
if (pointData)
delete pointData;
}
/* inherits documentation from base class */
void QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
{
// draw fill:
if (mBrush.style() != Qt::NoBrush)
{
applyFillAntialiasingHint(painter);
painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
}
// draw line vertically centered:
if (mLineStyle != lsNone)
{
applyDefaultAntialiasingHint(painter);
painter->setPen(mPen);
painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens
}
// draw scatter symbol:
if (!mScatterStyle.isNone())
{
applyScattersAntialiasingHint(painter);
// scale scatter pixmap if it's too large to fit in legend icon rect:
if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
{
QCPScatterStyle scaledStyle(mScatterStyle);
scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
scaledStyle.applyTo(painter, mPen);
scaledStyle.drawShape(painter, QRectF(rect).center());
} else
{
mScatterStyle.applyTo(painter, mPen);
mScatterStyle.drawShape(painter, QRectF(rect).center());
}
}
}
/*! \internal
This function branches out to the line style specific "get(...)PlotData" functions, according to
the line style of the graph.
\a lineData will be filled with raw points that will be drawn with the according draw functions,
e.g. \ref drawLinePlot and \ref drawImpulsePlot. These aren't necessarily the original data
points, since for step plots for example, additional points are needed for drawing lines that
make up steps. If the line style of the graph is \ref lsNone, the \a lineData vector will be left
untouched.
\a pointData will be filled with the original data points so \ref drawScatterPlot can draw the
scatter symbols accordingly. If no scatters need to be drawn, i.e. the scatter style's shape is
\ref QCPScatterStyle::ssNone, pass 0 as \a pointData, and this step will be skipped.
\see getScatterPlotData, getLinePlotData, getStepLeftPlotData, getStepRightPlotData,
getStepCenterPlotData, getImpulsePlotData
*/
void QCPGraph::getPlotData(QVector<QPointF> *lineData, QVector<QCPData> *pointData) const
{
switch(mLineStyle)
{
case lsNone: getScatterPlotData(pointData); break;
case lsLine: getLinePlotData(lineData, pointData); break;
case lsStepLeft: getStepLeftPlotData(lineData, pointData); break;
case lsStepRight: getStepRightPlotData(lineData, pointData); break;
case lsStepCenter: getStepCenterPlotData(lineData, pointData); break;
case lsImpulse: getImpulsePlotData(lineData, pointData); break;
}
}
/*! \internal
If line style is \ref lsNone and the scatter style's shape is not \ref QCPScatterStyle::ssNone,
this function serves at providing the visible data points in \a pointData, so the \ref
drawScatterPlot function can draw the scatter points accordingly.
If line style is not \ref lsNone, this function is not called and the data for the scatter points
are (if needed) calculated inside the corresponding other "get(...)PlotData" functions.
\see drawScatterPlot
*/
void QCPGraph::getScatterPlotData(QVector<QCPData> *pointData) const
{
if (!pointData) return;
QCPAxis *keyAxis = mKeyAxis.data();
if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
// get visible data range:
QCPDataMap::const_iterator lower, upper;
int dataCount = 0;
getVisibleDataBounds(lower, upper, dataCount);
if (dataCount > 0)
{
// prepare vectors:
pointData->resize(dataCount);
// position data points:
QCPDataMap::const_iterator it = lower;
QCPDataMap::const_iterator upperEnd = upper+1;
int i = 0;
while (it != upperEnd)
{
(*pointData)[i] = it.value();
++i;
++it;
}
}
}
/*! \internal
Places the raw data points needed for a normal linearly connected graph in \a lineData.
As for all plot data retrieval functions, \a pointData just contains all unaltered data (scatter)
points that are visible for drawing scatter points, if necessary. If drawing scatter points is
disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
pointData, and the function will skip filling the vector.
\see drawLinePlot
*/
void QCPGraph::getLinePlotData(QVector<QPointF> *lineData, QVector<QCPData> *pointData) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (!lineData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; }
// get visible data range:
QCPDataMap::const_iterator lower, upper;
int dataCount = 0;
getVisibleDataBounds(lower, upper, dataCount);
if (dataCount > 0)
{
lineData->reserve(dataCount+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
lineData->resize(dataCount);
if (pointData)
pointData->resize(dataCount);
// position data points:
QCPDataMap::const_iterator it = lower;
QCPDataMap::const_iterator upperEnd = upper+1;
int i = 0;
if (keyAxis->orientation() == Qt::Vertical)
{
while (it != upperEnd)
{
if (pointData)
(*pointData)[i] = it.value();
(*lineData)[i].setX(valueAxis->coordToPixel(it.value().value));
(*lineData)[i].setY(keyAxis->coordToPixel(it.key()));
++i;
++it;
}
} else // key axis is horizontal
{
while (it != upperEnd)
{
if (pointData)
(*pointData)[i] = it.value();
(*lineData)[i].setX(keyAxis->coordToPixel(it.key()));
(*lineData)[i].setY(valueAxis->coordToPixel(it.value().value));
++i;
++it;
}
}
}
}
/*!
\internal
Places the raw data points needed for a step plot with left oriented steps in \a lineData.
As for all plot data retrieval functions, \a pointData just contains all unaltered data (scatter)
points that are visible for drawing scatter points, if necessary. If drawing scatter points is
disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
pointData, and the function will skip filling the vector.
\see drawLinePlot
*/
void QCPGraph::getStepLeftPlotData(QVector<QPointF> *lineData, QVector<QCPData> *pointData) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (!lineData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; }
// get visible data range:
QCPDataMap::const_iterator lower, upper;
int dataCount = 0;
getVisibleDataBounds(lower, upper, dataCount);
if (dataCount > 0)
{
lineData->reserve(dataCount*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
lineData->resize(dataCount*2); // multiplied by 2 because step plot needs two polyline points per one actual data point
if (pointData)
pointData->resize(dataCount);
// position data points:
QCPDataMap::const_iterator it = lower;
QCPDataMap::const_iterator upperEnd = upper+1;
int i = 0;
int ipoint = 0;
if (keyAxis->orientation() == Qt::Vertical)
{
double lastValue = valueAxis->coordToPixel(it.value().value);
double key;
while (it != upperEnd)
{
if (pointData)
{
(*pointData)[ipoint] = it.value();
++ipoint;
}
key = keyAxis->coordToPixel(it.key());
(*lineData)[i].setX(lastValue);
(*lineData)[i].setY(key);
++i;
lastValue = valueAxis->coordToPixel(it.value().value);
(*lineData)[i].setX(lastValue);
(*lineData)[i].setY(key);
++i;
++it;
}
} else // key axis is horizontal
{
double lastValue = valueAxis->coordToPixel(it.value().value);
double key;
while (it != upperEnd)
{
if (pointData)
{
(*pointData)[ipoint] = it.value();
++ipoint;
}
key = keyAxis->coordToPixel(it.key());
(*lineData)[i].setX(key);
(*lineData)[i].setY(lastValue);
++i;
lastValue = valueAxis->coordToPixel(it.value().value);
(*lineData)[i].setX(key);
(*lineData)[i].setY(lastValue);
++i;
++it;
}
}
}
}
/*!
\internal
Places the raw data points needed for a step plot with right oriented steps in \a lineData.
As for all plot data retrieval functions, \a pointData just contains all unaltered data (scatter)
points that are visible for drawing scatter points, if necessary. If drawing scatter points is
disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
pointData, and the function will skip filling the vector.
\see drawLinePlot
*/
void QCPGraph::getStepRightPlotData(QVector<QPointF> *lineData, QVector<QCPData> *pointData) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (!lineData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; }
// get visible data range:
QCPDataMap::const_iterator lower, upper;
int dataCount = 0;
getVisibleDataBounds(lower, upper, dataCount);
if (dataCount > 0)
{
lineData->reserve(dataCount*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
lineData->resize(dataCount*2); // multiplied by 2 because step plot needs two polyline points per one actual data point
if (pointData)
pointData->resize(dataCount);
// position points:
QCPDataMap::const_iterator it = lower;
QCPDataMap::const_iterator upperEnd = upper+1;
int i = 0;
int ipoint = 0;
if (keyAxis->orientation() == Qt::Vertical)
{
double lastKey = keyAxis->coordToPixel(it.key());
double value;
while (it != upperEnd)
{
if (pointData)
{
(*pointData)[ipoint] = it.value();
++ipoint;
}
value = valueAxis->coordToPixel(it.value().value);
(*lineData)[i].setX(value);
(*lineData)[i].setY(lastKey);
++i;
lastKey = keyAxis->coordToPixel(it.key());
(*lineData)[i].setX(value);
(*lineData)[i].setY(lastKey);
++i;
++it;
}
} else // key axis is horizontal
{
double lastKey = keyAxis->coordToPixel(it.key());
double value;
while (it != upperEnd)
{
if (pointData)
{
(*pointData)[ipoint] = it.value();
++ipoint;
}
value = valueAxis->coordToPixel(it.value().value);
(*lineData)[i].setX(lastKey);
(*lineData)[i].setY(value);
++i;
lastKey = keyAxis->coordToPixel(it.key());
(*lineData)[i].setX(lastKey);
(*lineData)[i].setY(value);
++i;
++it;
}
}
}
}
/*!
\internal
Places the raw data points needed for a step plot with centered steps in \a lineData.
As for all plot data retrieval functions, \a pointData just contains all unaltered data (scatter)
points that are visible for drawing scatter points, if necessary. If drawing scatter points is
disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
pointData, and the function will skip filling the vector.
\see drawLinePlot
*/
void QCPGraph::getStepCenterPlotData(QVector<QPointF> *lineData, QVector<QCPData> *pointData) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (!lineData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; }
// get visible data range:
QCPDataMap::const_iterator lower, upper;
int dataCount = 0;
getVisibleDataBounds(lower, upper, dataCount);
if (dataCount > 0)
{
// added 2 to reserve memory for lower/upper fill base points that might be needed for base fill
// multiplied by 2 because step plot needs two polyline points per one actual data point
lineData->reserve(dataCount*2+2);
lineData->resize(dataCount*2);
if (pointData)
pointData->resize(dataCount);
// position points:
QCPDataMap::const_iterator it = lower;
QCPDataMap::const_iterator upperEnd = upper+1;
int i = 0;
int ipoint = 0;
if (keyAxis->orientation() == Qt::Vertical)
{
double lastKey = keyAxis->coordToPixel(it.key());
double lastValue = valueAxis->coordToPixel(it.value().value);
double key;
if (pointData)
{
(*pointData)[ipoint] = it.value();
++ipoint;
}
(*lineData)[i].setX(lastValue);
(*lineData)[i].setY(lastKey);
++it;
++i;
while (it != upperEnd)
{
if (pointData)
{
(*pointData)[ipoint] = it.value();
++ipoint;
}
key = (keyAxis->coordToPixel(it.key())-lastKey)*0.5 + lastKey;
(*lineData)[i].setX(lastValue);
(*lineData)[i].setY(key);
++i;
lastValue = valueAxis->coordToPixel(it.value().value);
lastKey = keyAxis->coordToPixel(it.key());
(*lineData)[i].setX(lastValue);
(*lineData)[i].setY(key);
++it;
++i;
}
(*lineData)[i].setX(lastValue);
(*lineData)[i].setY(lastKey);
} else // key axis is horizontal
{
double lastKey = keyAxis->coordToPixel(it.key());
double lastValue = valueAxis->coordToPixel(it.value().value);
double key;
if (pointData)
{
(*pointData)[ipoint] = it.value();
++ipoint;
}
(*lineData)[i].setX(lastKey);
(*lineData)[i].setY(lastValue);
++it;
++i;
while (it != upperEnd)
{
if (pointData)
{
(*pointData)[ipoint] = it.value();
++ipoint;
}
key = (keyAxis->coordToPixel(it.key())-lastKey)*0.5 + lastKey;
(*lineData)[i].setX(key);
(*lineData)[i].setY(lastValue);
++i;
lastValue = valueAxis->coordToPixel(it.value().value);
lastKey = keyAxis->coordToPixel(it.key());
(*lineData)[i].setX(key);
(*lineData)[i].setY(lastValue);
++it;
++i;
}
(*lineData)[i].setX(lastKey);
(*lineData)[i].setY(lastValue);
}
}
}
/*!
\internal
Places the raw data points needed for an impulse plot in \a lineData.
As for all plot data retrieval functions, \a pointData just contains all unaltered data (scatter)
points that are visible for drawing scatter points, if necessary. If drawing scatter points is
disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
pointData, and the function will skip filling the vector.
\see drawImpulsePlot
*/
void QCPGraph::getImpulsePlotData(QVector<QPointF> *lineData, QVector<QCPData> *pointData) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (!lineData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; }
// get visible data range:
QCPDataMap::const_iterator lower, upper;
int dataCount = 0;
getVisibleDataBounds(lower, upper, dataCount);
if (dataCount > 0)
{
lineData->resize(dataCount*2); // no need to reserve 2 extra points, because there is no fill for impulse plot
if (pointData)
pointData->resize(dataCount);
// position data points:
QCPDataMap::const_iterator it = lower;
QCPDataMap::const_iterator upperEnd = upper+1;
int i = 0;
int ipoint = 0;
if (keyAxis->orientation() == Qt::Vertical)
{
double zeroPointX = valueAxis->coordToPixel(0);
double key;
while (it != upperEnd)
{
if (pointData)
{
(*pointData)[ipoint] = it.value();
++ipoint;
}
key = keyAxis->coordToPixel(it.key());
(*lineData)[i].setX(zeroPointX);
(*lineData)[i].setY(key);
++i;
(*lineData)[i].setX(valueAxis->coordToPixel(it.value().value));
(*lineData)[i].setY(key);
++i;
++it;
}
} else // key axis is horizontal
{
double zeroPointY = valueAxis->coordToPixel(0);
double key;
while (it != upperEnd)
{
if (pointData)
{
(*pointData)[ipoint] = it.value();
++ipoint;
}
key = keyAxis->coordToPixel(it.key());
(*lineData)[i].setX(key);
(*lineData)[i].setY(zeroPointY);
++i;
(*lineData)[i].setX(key);
(*lineData)[i].setY(valueAxis->coordToPixel(it.value().value));
++i;
++it;
}
}
}
}
/*! \internal
Draws the fill of the graph with the specified brush.
If the fill is a normal fill towards the zero-value-line, only the \a lineData is required (and
two extra points at the zero-value-line, which are added by \ref addFillBasePoints and removed by
\ref removeFillBasePoints after the fill drawing is done).
If the fill is a channel fill between this QCPGraph and another QCPGraph (mChannelFillGraph), the
more complex polygon is calculated with the \ref getChannelFillPolygon function.
\see drawLinePlot
*/
void QCPGraph::drawFill(QCPPainter *painter, QVector<QPointF> *lineData) const
{
if (mLineStyle == lsImpulse) return; // fill doesn't make sense for impulse plot
if (mainBrush().style() == Qt::NoBrush || mainBrush().color().alpha() == 0) return;
applyFillAntialiasingHint(painter);
if (!mChannelFillGraph)
{
// draw base fill under graph, fill goes all the way to the zero-value-line:
addFillBasePoints(lineData);
painter->setPen(Qt::NoPen);
painter->setBrush(mainBrush());
painter->drawPolygon(QPolygonF(*lineData));
removeFillBasePoints(lineData);
} else
{
// draw channel fill between this graph and mChannelFillGraph:
painter->setPen(Qt::NoPen);
painter->setBrush(mainBrush());
painter->drawPolygon(getChannelFillPolygon(lineData));
}
}
/*! \internal
Draws scatter symbols at every data point passed in \a pointData. scatter symbols are independent
of the line style and are always drawn if the scatter style's shape is not \ref
QCPScatterStyle::ssNone. Hence, the \a pointData vector is outputted by all "get(...)PlotData"
functions, together with the (line style dependent) line data.
\see drawLinePlot, drawImpulsePlot
*/
void QCPGraph::drawScatterPlot(QCPPainter *painter, QVector<QCPData> *pointData) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
// draw error bars:
if (mErrorType != etNone)
{
applyErrorBarsAntialiasingHint(painter);
painter->setPen(mErrorPen);
if (keyAxis->orientation() == Qt::Vertical)
{
for (int i=0; i<pointData->size(); ++i)
drawError(painter, valueAxis->coordToPixel(pointData->at(i).value), keyAxis->coordToPixel(pointData->at(i).key), pointData->at(i));
} else
{
for (int i=0; i<pointData->size(); ++i)
drawError(painter, keyAxis->coordToPixel(pointData->at(i).key), valueAxis->coordToPixel(pointData->at(i).value), pointData->at(i));
}
}
// draw scatter point symbols:
applyScattersAntialiasingHint(painter);
mScatterStyle.applyTo(painter, mPen);
if (keyAxis->orientation() == Qt::Vertical)
{
for (int i=0; i<pointData->size(); ++i)
mScatterStyle.drawShape(painter, valueAxis->coordToPixel(pointData->at(i).value), keyAxis->coordToPixel(pointData->at(i).key));
} else
{
for (int i=0; i<pointData->size(); ++i)
mScatterStyle.drawShape(painter, keyAxis->coordToPixel(pointData->at(i).key), valueAxis->coordToPixel(pointData->at(i).value));
}
}
/*! \internal
Draws line graphs from the provided data. It connects all points in \a lineData, which was
created by one of the "get(...)PlotData" functions for line styles that require simple line
connections between the point vector they create. These are for example \ref getLinePlotData,
\ref getStepLeftPlotData, \ref getStepRightPlotData and \ref getStepCenterPlotData.
\see drawScatterPlot, drawImpulsePlot
*/
void QCPGraph::drawLinePlot(QCPPainter *painter, QVector<QPointF> *lineData) const
{
// draw line of graph:
if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)
{
applyDefaultAntialiasingHint(painter);
painter->setPen(mainPen());
painter->setBrush(Qt::NoBrush);
/* Draws polyline in batches, currently not used:
int p = 0;
while (p < lineData->size())
{
int batch = qMin(25, lineData->size()-p);
if (p != 0)
{
++batch;
--p; // to draw the connection lines between two batches
}
painter->drawPolyline(lineData->constData()+p, batch);
p += batch;
}
*/
// if drawing solid line and not in PDF, use much faster line drawing instead of polyline:
if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) &&
painter->pen().style() == Qt::SolidLine &&
!painter->modes().testFlag(QCPPainter::pmVectorized)&&
!painter->modes().testFlag(QCPPainter::pmNoCaching))
{
for (int i=1; i<lineData->size(); ++i)
painter->drawLine(lineData->at(i-1), lineData->at(i));
} else
{
painter->drawPolyline(QPolygonF(*lineData));
}
}
}
/*! \internal
Draws impulses from the provided data, i.e. it connects all line pairs in \a lineData, which was
created by \ref getImpulsePlotData.
\see drawScatterPlot, drawLinePlot
*/
void QCPGraph::drawImpulsePlot(QCPPainter *painter, QVector<QPointF> *lineData) const
{
// draw impulses:
if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)
{
applyDefaultAntialiasingHint(painter);
QPen pen = mainPen();
pen.setCapStyle(Qt::FlatCap); // so impulse line doesn't reach beyond zero-line
painter->setPen(pen);
painter->setBrush(Qt::NoBrush);
painter->drawLines(*lineData);
}
}
/*! \internal
called by the scatter drawing function (\ref drawScatterPlot) to draw the error bars on one data
point. \a x and \a y pixel positions of the data point are passed since they are already known in
pixel coordinates in the drawing function, so we save some extra coordToPixel transforms here. \a
data is therefore only used for the errors, not key and value.
*/
void QCPGraph::drawError(QCPPainter *painter, double x, double y, const QCPData &data) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
double a, b; // positions of error bar bounds in pixels
double barWidthHalf = mErrorBarSize*0.5;
double skipSymbolMargin = mScatterStyle.size(); // pixels left blank per side, when mErrorBarSkipSymbol is true
if (keyAxis->orientation() == Qt::Vertical)
{
// draw key error vertically and value error horizontally
if (mErrorType == etKey || mErrorType == etBoth)
{
a = keyAxis->coordToPixel(data.key-data.keyErrorMinus);
b = keyAxis->coordToPixel(data.key+data.keyErrorPlus);
if (keyAxis->rangeReversed())
qSwap(a,b);
// draw spine:
if (mErrorBarSkipSymbol)
{
if (a-y > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin
painter->drawLine(QLineF(x, a, x, y+skipSymbolMargin));
if (y-b > skipSymbolMargin)
painter->drawLine(QLineF(x, y-skipSymbolMargin, x, b));
} else
painter->drawLine(QLineF(x, a, x, b));
// draw handles:
painter->drawLine(QLineF(x-barWidthHalf, a, x+barWidthHalf, a));
painter->drawLine(QLineF(x-barWidthHalf, b, x+barWidthHalf, b));
}
if (mErrorType == etValue || mErrorType == etBoth)
{
a = valueAxis->coordToPixel(data.value-data.valueErrorMinus);
b = valueAxis->coordToPixel(data.value+data.valueErrorPlus);
if (valueAxis->rangeReversed())
qSwap(a,b);
// draw spine:
if (mErrorBarSkipSymbol)
{
if (x-a > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin
painter->drawLine(QLineF(a, y, x-skipSymbolMargin, y));
if (b-x > skipSymbolMargin)
painter->drawLine(QLineF(x+skipSymbolMargin, y, b, y));
} else
painter->drawLine(QLineF(a, y, b, y));
// draw handles:
painter->drawLine(QLineF(a, y-barWidthHalf, a, y+barWidthHalf));
painter->drawLine(QLineF(b, y-barWidthHalf, b, y+barWidthHalf));
}
} else // mKeyAxis->orientation() is Qt::Horizontal
{
// draw value error vertically and key error horizontally
if (mErrorType == etKey || mErrorType == etBoth)
{
a = keyAxis->coordToPixel(data.key-data.keyErrorMinus);
b = keyAxis->coordToPixel(data.key+data.keyErrorPlus);
if (keyAxis->rangeReversed())
qSwap(a,b);
// draw spine:
if (mErrorBarSkipSymbol)
{
if (x-a > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin
painter->drawLine(QLineF(a, y, x-skipSymbolMargin, y));
if (b-x > skipSymbolMargin)
painter->drawLine(QLineF(x+skipSymbolMargin, y, b, y));
} else
painter->drawLine(QLineF(a, y, b, y));
// draw handles:
painter->drawLine(QLineF(a, y-barWidthHalf, a, y+barWidthHalf));
painter->drawLine(QLineF(b, y-barWidthHalf, b, y+barWidthHalf));
}
if (mErrorType == etValue || mErrorType == etBoth)
{
a = valueAxis->coordToPixel(data.value-data.valueErrorMinus);
b = valueAxis->coordToPixel(data.value+data.valueErrorPlus);
if (valueAxis->rangeReversed())
qSwap(a,b);
// draw spine:
if (mErrorBarSkipSymbol)
{
if (a-y > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin
painter->drawLine(QLineF(x, a, x, y+skipSymbolMargin));
if (y-b > skipSymbolMargin)
painter->drawLine(QLineF(x, y-skipSymbolMargin, x, b));
} else
painter->drawLine(QLineF(x, a, x, b));
// draw handles:
painter->drawLine(QLineF(x-barWidthHalf, a, x+barWidthHalf, a));
painter->drawLine(QLineF(x-barWidthHalf, b, x+barWidthHalf, b));
}
}
}
/*! \internal
called by the specific plot data generating functions "get(...)PlotData" to determine which data
range is visible, so only that needs to be processed.
\a lower returns an iterator to the lowest data point that needs to be taken into account when
plotting. Note that in order to get a clean plot all the way to the edge of the axes, \a lower
may still be outside the visible range.
\a upper returns an iterator to the highest data point. Same as before, \a upper may also lie
outside of the visible range.
\a count number of data points that need plotting, i.e. points between \a lower and \a upper,
including them. This is useful for allocating the array of <tt>QPointF</tt>s in the specific
drawing functions.
if the graph contains no data, \a count is zero and both \a lower and \a upper point to constEnd.
*/
void QCPGraph::getVisibleDataBounds(QCPDataMap::const_iterator &lower, QCPDataMap::const_iterator &upper, int &count) const
{
if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
if (mData->isEmpty())
{
lower = mData->constEnd();
upper = mData->constEnd();
count = 0;
return;
}
// get visible data range as QMap iterators
QCPDataMap::const_iterator lbound = mData->lowerBound(mKeyAxis.data()->range().lower);
QCPDataMap::const_iterator ubound = mData->upperBound(mKeyAxis.data()->range().upper);
bool lowoutlier = lbound != mData->constBegin(); // indicates whether there exist points below axis range
bool highoutlier = ubound != mData->constEnd(); // indicates whether there exist points above axis range
lower = (lowoutlier ? lbound-1 : lbound); // data point range that will be actually drawn
upper = (highoutlier ? ubound : ubound-1); // data point range that will be actually drawn
// count number of points in range lower to upper (including them), so we can allocate array for them in draw functions:
QCPDataMap::const_iterator it = lower;
count = 1;
while (it != upper)
{
++it;
++count;
}
}
/*! \internal
The line data vector generated by e.g. getLinePlotData contains only the line that connects the
data points. If the graph needs to be filled, two additional points need to be added at the
value-zero-line in the lower and upper key positions of the graph. This function calculates these
points and adds them to the end of \a lineData. Since the fill is typically drawn before the line
stroke, these added points need to be removed again after the fill is done, with the
removeFillBasePoints function.
The expanding of \a lineData by two points will not cause unnecessary memory reallocations,
because the data vector generation functions (getLinePlotData etc.) reserve two extra points when
they allocate memory for \a lineData.
\see removeFillBasePoints, lowerFillBasePoint, upperFillBasePoint
*/
void QCPGraph::addFillBasePoints(QVector<QPointF> *lineData) const
{
if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
// append points that close the polygon fill at the key axis:
if (mKeyAxis.data()->orientation() == Qt::Vertical)
{
*lineData << upperFillBasePoint(lineData->last().y());
*lineData << lowerFillBasePoint(lineData->first().y());
} else
{
*lineData << upperFillBasePoint(lineData->last().x());
*lineData << lowerFillBasePoint(lineData->first().x());
}
}
/*! \internal
removes the two points from \a lineData that were added by \ref addFillBasePoints.
\see addFillBasePoints, lowerFillBasePoint, upperFillBasePoint
*/
void QCPGraph::removeFillBasePoints(QVector<QPointF> *lineData) const
{
lineData->remove(lineData->size()-2, 2);
}
/*! \internal
called by \ref addFillBasePoints to conveniently assign the point which closes the fill polygon
on the lower side of the zero-value-line parallel to the key axis. The logarithmic axis scale
case is a bit special, since the zero-value-line in pixel coordinates is in positive or negative
infinity. So this case is handled separately by just closing the fill polygon on the axis which
lies in the direction towards the zero value.
\a lowerKey will be the the key (in pixels) of the returned point. Depending on whether the key
axis is horizontal or vertical, \a lowerKey will end up as the x or y value of the returned
point, respectively.
\see upperFillBasePoint, addFillBasePoints
*/
QPointF QCPGraph::lowerFillBasePoint(double lowerKey) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
QPointF point;
if (valueAxis->scaleType() == QCPAxis::stLinear)
{
if (keyAxis->axisType() == QCPAxis::atLeft)
{
point.setX(valueAxis->coordToPixel(0));
point.setY(lowerKey);
} else if (keyAxis->axisType() == QCPAxis::atRight)
{
point.setX(valueAxis->coordToPixel(0));
point.setY(lowerKey);
} else if (keyAxis->axisType() == QCPAxis::atTop)
{
point.setX(lowerKey);
point.setY(valueAxis->coordToPixel(0));
} else if (keyAxis->axisType() == QCPAxis::atBottom)
{
point.setX(lowerKey);
point.setY(valueAxis->coordToPixel(0));
}
} else // valueAxis->mScaleType == QCPAxis::stLogarithmic
{
// In logarithmic scaling we can't just draw to value zero so we just fill all the way
// to the axis which is in the direction towards zero
if (keyAxis->orientation() == Qt::Vertical)
{
if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
(valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
point.setX(keyAxis->axisRect()->right());
else
point.setX(keyAxis->axisRect()->left());
point.setY(lowerKey);
} else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom)
{
point.setX(lowerKey);
if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
(valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
point.setY(keyAxis->axisRect()->top());
else
point.setY(keyAxis->axisRect()->bottom());
}
}
return point;
}
/*! \internal
called by \ref addFillBasePoints to conveniently assign the point which closes the fill
polygon on the upper side of the zero-value-line parallel to the key axis. The logarithmic axis
scale case is a bit special, since the zero-value-line in pixel coordinates is in positive or
negative infinity. So this case is handled separately by just closing the fill polygon on the
axis which lies in the direction towards the zero value.
\a upperKey will be the the key (in pixels) of the returned point. Depending on whether the key
axis is horizontal or vertical, \a upperKey will end up as the x or y value of the returned
point, respectively.
\see lowerFillBasePoint, addFillBasePoints
*/
QPointF QCPGraph::upperFillBasePoint(double upperKey) const
{
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
QPointF point;
if (valueAxis->scaleType() == QCPAxis::stLinear)
{
if (keyAxis->axisType() == QCPAxis::atLeft)
{
point.setX(valueAxis->coordToPixel(0));
point.setY(upperKey);
} else if (keyAxis->axisType() == QCPAxis::atRight)
{
point.setX(valueAxis->coordToPixel(0));
point.setY(upperKey);
} else if (keyAxis->axisType() == QCPAxis::atTop)
{
point.setX(upperKey);
point.setY(valueAxis->coordToPixel(0));
} else if (keyAxis->axisType() == QCPAxis::atBottom)
{
point.setX(upperKey);
point.setY(valueAxis->coordToPixel(0));
}
} else // valueAxis->mScaleType == QCPAxis::stLogarithmic
{
// In logarithmic scaling we can't just draw to value 0 so we just fill all the way
// to the axis which is in the direction towards 0
if (keyAxis->orientation() == Qt::Vertical)
{
if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
(valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
point.setX(keyAxis->axisRect()->right());
else
point.setX(keyAxis->axisRect()->left());
point.setY(upperKey);
} else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom)
{
point.setX(upperKey);
if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
(valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
point.setY(keyAxis->axisRect()->top());
else
point.setY(keyAxis->axisRect()->bottom());
}
}
return point;
}
/*! \internal
Generates the polygon needed for drawing channel fills between this graph (data passed via \a
lineData) and the graph specified by mChannelFillGraph (data generated by calling its \ref
getPlotData function). May return an empty polygon if the key ranges have no overlap or fill
target graph and this graph don't have same orientation (i.e. both key axes horizontal or both
key axes vertical). For increased performance (due to implicit sharing), keep the returned
QPolygonF const.
*/
const QPolygonF QCPGraph::getChannelFillPolygon(const QVector<QPointF> *lineData) const
{
if (!mChannelFillGraph)
return QPolygonF();
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); }
if (!mChannelFillGraph.data()->mKeyAxis) { qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; return QPolygonF(); }
if (mChannelFillGraph.data()->mKeyAxis.data()->orientation() != keyAxis->orientation())
return QPolygonF(); // don't have same axis orientation, can't fill that (Note: if keyAxis fits, valueAxis will fit too, because it's always orthogonal to keyAxis)
if (lineData->isEmpty()) return QPolygonF();
QVector<QPointF> otherData;
mChannelFillGraph.data()->getPlotData(&otherData, 0);
if (otherData.isEmpty()) return QPolygonF();
QVector<QPointF> thisData;
thisData.reserve(lineData->size()+otherData.size()); // because we will join both vectors at end of this function
for (int i=0; i<lineData->size(); ++i) // don't use the vector<<(vector), it squeezes internally, which ruins the performance tuning with reserve()
thisData << lineData->at(i);
// pointers to be able to swap them, depending which data range needs cropping:
QVector<QPointF> *staticData = &thisData;
QVector<QPointF> *croppedData = &otherData;
// crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType):
if (keyAxis->orientation() == Qt::Horizontal)
{
// x is key
// if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys:
if (staticData->first().x() > staticData->last().x())
{
int size = staticData->size();
for (int i=0; i<size/2; ++i)
qSwap((*staticData)[i], (*staticData)[size-1-i]);
}
if (croppedData->first().x() > croppedData->last().x())
{
int size = croppedData->size();
for (int i=0; i<size/2; ++i)
qSwap((*croppedData)[i], (*croppedData)[size-1-i]);
}
// crop lower bound:
if (staticData->first().x() < croppedData->first().x()) // other one must be cropped
qSwap(staticData, croppedData);
int lowBound = findIndexBelowX(croppedData, staticData->first().x());
if (lowBound == -1) return QPolygonF(); // key ranges have no overlap
croppedData->remove(0, lowBound);
// set lowest point of cropped data to fit exactly key position of first static data
// point via linear interpolation:
if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
double slope;
if (croppedData->at(1).x()-croppedData->at(0).x() != 0)
slope = (croppedData->at(1).y()-croppedData->at(0).y())/(croppedData->at(1).x()-croppedData->at(0).x());
else
slope = 0;
(*croppedData)[0].setY(croppedData->at(0).y()+slope*(staticData->first().x()-croppedData->at(0).x()));
(*croppedData)[0].setX(staticData->first().x());
// crop upper bound:
if (staticData->last().x() > croppedData->last().x()) // other one must be cropped
qSwap(staticData, croppedData);
int highBound = findIndexAboveX(croppedData, staticData->last().x());
if (highBound == -1) return QPolygonF(); // key ranges have no overlap
croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
// set highest point of cropped data to fit exactly key position of last static data
// point via linear interpolation:
if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
int li = croppedData->size()-1; // last index
if (croppedData->at(li).x()-croppedData->at(li-1).x() != 0)
slope = (croppedData->at(li).y()-croppedData->at(li-1).y())/(croppedData->at(li).x()-croppedData->at(li-1).x());
else
slope = 0;
(*croppedData)[li].setY(croppedData->at(li-1).y()+slope*(staticData->last().x()-croppedData->at(li-1).x()));
(*croppedData)[li].setX(staticData->last().x());
} else // mKeyAxis->orientation() == Qt::Vertical
{
// y is key
// similar to "x is key" but switched x,y. Further, lower/upper meaning is inverted compared to x,
// because in pixel coordinates, y increases from top to bottom, not bottom to top like data coordinate.
// if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys:
if (staticData->first().y() < staticData->last().y())
{
int size = staticData->size();
for (int i=0; i<size/2; ++i)
qSwap((*staticData)[i], (*staticData)[size-1-i]);
}
if (croppedData->first().y() < croppedData->last().y())
{
int size = croppedData->size();
for (int i=0; i<size/2; ++i)
qSwap((*croppedData)[i], (*croppedData)[size-1-i]);
}
// crop lower bound:
if (staticData->first().y() > croppedData->first().y()) // other one must be cropped
qSwap(staticData, croppedData);
int lowBound = findIndexAboveY(croppedData, staticData->first().y());
if (lowBound == -1) return QPolygonF(); // key ranges have no overlap
croppedData->remove(0, lowBound);
// set lowest point of cropped data to fit exactly key position of first static data
// point via linear interpolation:
if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
double slope;
if (croppedData->at(1).y()-croppedData->at(0).y() != 0) // avoid division by zero in step plots
slope = (croppedData->at(1).x()-croppedData->at(0).x())/(croppedData->at(1).y()-croppedData->at(0).y());
else
slope = 0;
(*croppedData)[0].setX(croppedData->at(0).x()+slope*(staticData->first().y()-croppedData->at(0).y()));
(*croppedData)[0].setY(staticData->first().y());
// crop upper bound:
if (staticData->last().y() < croppedData->last().y()) // other one must be cropped
qSwap(staticData, croppedData);
int highBound = findIndexBelowY(croppedData, staticData->last().y());
if (highBound == -1) return QPolygonF(); // key ranges have no overlap
croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
// set highest point of cropped data to fit exactly key position of last static data
// point via linear interpolation:
if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
int li = croppedData->size()-1; // last index
if (croppedData->at(li).y()-croppedData->at(li-1).y() != 0) // avoid division by zero in step plots
slope = (croppedData->at(li).x()-croppedData->at(li-1).x())/(croppedData->at(li).y()-croppedData->at(li-1).y());
else
slope = 0;
(*croppedData)[li].setX(croppedData->at(li-1).x()+slope*(staticData->last().y()-croppedData->at(li-1).y()));
(*croppedData)[li].setY(staticData->last().y());
}
// return joined:
for (int i=otherData.size()-1; i>=0; --i) // insert reversed, otherwise the polygon will be twisted
thisData << otherData.at(i);
return QPolygonF(thisData);
}
/*! \internal
Finds the smallest index of \a data, whose points x value is just above \a x. Assumes x values in
\a data points are ordered ascending, as is the case when plotting with horizontal key axis.
Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
*/
int QCPGraph::findIndexAboveX(const QVector<QPointF> *data, double x) const
{
for (int i=data->size()-1; i>=0; --i)
{
if (data->at(i).x() < x)
{
if (i<data->size()-1)
return i+1;
else
return data->size()-1;
}
}
return -1;
}
/*! \internal
Finds the highest index of \a data, whose points x value is just below \a x. Assumes x values in
\a data points are ordered ascending, as is the case when plotting with horizontal key axis.
Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
*/
int QCPGraph::findIndexBelowX(const QVector<QPointF> *data, double x) const
{
for (int i=0; i<data->size(); ++i)
{
if (data->at(i).x() > x)
{
if (i>0)
return i-1;
else
return 0;
}
}
return -1;
}
/*! \internal
Finds the smallest index of \a data, whose points y value is just above \a y. Assumes y values in
\a data points are ordered descending, as is the case when plotting with vertical key axis.
Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
*/
int QCPGraph::findIndexAboveY(const QVector<QPointF> *data, double y) const
{
for (int i=0; i<data->size(); ++i)
{
if (data->at(i).y() < y)
{
if (i>0)
return i-1;
else
return 0;
}
}
return -1;
}
/*! \internal
Calculates the (minimum) distance (in pixels) the graph's representation has from the given \a
pixelPoint in pixels. This is used to determine whether the graph was clicked or not, e.g. in
\ref selectTest.
If either the graph has no data or if the line style is \ref lsNone and the scatter style's shape
is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the graph), returns
500.
*/
double QCPGraph::pointDistance(const QPointF &pixelPoint) const
{
if (mData->isEmpty())
{
qDebug() << Q_FUNC_INFO << "requested point distance on graph" << mName << "without data";
return 500;
}
if (mData->size() == 1)
{
QPointF dataPoint = coordsToPixels(mData->constBegin().key(), mData->constBegin().value().value);
return QVector2D(dataPoint-pixelPoint).length();
}
if (mLineStyle == lsNone && mScatterStyle.isNone())
return 500;
// calculate minimum distances to graph representation:
if (mLineStyle == lsNone)
{
// no line displayed, only calculate distance to scatter points:
QVector<QCPData> *pointData = new QVector<QCPData>;
getScatterPlotData(pointData);
double minDistSqr = std::numeric_limits<double>::max();
QPointF ptA;
QPointF ptB = coordsToPixels(pointData->at(0).key, pointData->at(0).value); // getScatterPlotData returns in plot coordinates, so transform to pixels
for (int i=1; i<pointData->size(); ++i)
{
ptA = ptB;
ptB = coordsToPixels(pointData->at(i).key, pointData->at(i).value);
double currentDistSqr = distSqrToLine(ptA, ptB, pixelPoint);
if (currentDistSqr < minDistSqr)
minDistSqr = currentDistSqr;
}
delete pointData;
return sqrt(minDistSqr);
} else
{
// line displayed calculate distance to line segments:
QVector<QPointF> *lineData = new QVector<QPointF>;
getPlotData(lineData, 0); // unlike with getScatterPlotData we get pixel coordinates here
double minDistSqr = std::numeric_limits<double>::max();
if (mLineStyle == lsImpulse)
{
// impulse plot differs from other line styles in that the lineData points are only pairwise connected:
for (int i=0; i<lineData->size()-1; i+=2) // iterate pairs
{
double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint);
if (currentDistSqr < minDistSqr)
minDistSqr = currentDistSqr;
}
} else
{
// all other line plots (line and step) connect points directly:
for (int i=0; i<lineData->size()-1; ++i)
{
double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint);
if (currentDistSqr < minDistSqr)
minDistSqr = currentDistSqr;
}
}
delete lineData;
return sqrt(minDistSqr);
}
}
/*! \internal
Finds the highest index of \a data, whose points y value is just below \a y. Assumes y values in
\a data points are ordered descending, as is the case when plotting with vertical key axis (since
keys are ordered ascending).
Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
*/
int QCPGraph::findIndexBelowY(const QVector<QPointF> *data, double y) const
{
for (int i=data->size()-1; i>=0; --i)
{
if (data->at(i).y() > y)
{
if (i<data->size()-1)
return i+1;
else
return data->size()-1;
}
}
return -1;
}
/* inherits documentation from base class */
QCPRange QCPGraph::getKeyRange(bool &validRange, SignDomain inSignDomain) const
{
// just call the specialized version which takes an additional argument whether error bars
// should also be taken into consideration for range calculation. We set this to true here.
return getKeyRange(validRange, inSignDomain, true);
}
/* inherits documentation from base class */
QCPRange QCPGraph::getValueRange(bool &validRange, SignDomain inSignDomain) const
{
// just call the specialized version which takes an additional argument whether error bars
// should also be taken into consideration for range calculation. We set this to true here.
return getValueRange(validRange, inSignDomain, true);
}
/*! \overload
Allows to specify whether the error bars should be included in the range calculation.
\see getKeyRange(bool &validRange, SignDomain inSignDomain)
*/
QCPRange QCPGraph::getKeyRange(bool &validRange, SignDomain inSignDomain, bool includeErrors) const
{
QCPRange range;
bool haveLower = false;
bool haveUpper = false;
double current, currentErrorMinus, currentErrorPlus;
if (inSignDomain == sdBoth) // range may be anywhere
{
QCPDataMap::const_iterator it = mData->constBegin();
while (it != mData->constEnd())
{
current = it.value().key;
currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0);
currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0);
if (current-currentErrorMinus < range.lower || !haveLower)
{
range.lower = current-currentErrorMinus;
haveLower = true;
}
if (current+currentErrorPlus > range.upper || !haveUpper)
{
range.upper = current+currentErrorPlus;
haveUpper = true;
}
++it;
}
} else if (inSignDomain == sdNegative) // range may only be in the negative sign domain
{
QCPDataMap::const_iterator it = mData->constBegin();
while (it != mData->constEnd())
{
current = it.value().key;
currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0);
currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0);
if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus < 0)
{
range.lower = current-currentErrorMinus;
haveLower = true;
}
if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus < 0)
{
range.upper = current+currentErrorPlus;
haveUpper = true;
}
if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to geht that point.
{
if ((current < range.lower || !haveLower) && current < 0)
{
range.lower = current;
haveLower = true;
}
if ((current > range.upper || !haveUpper) && current < 0)
{
range.upper = current;
haveUpper = true;
}
}
++it;
}
} else if (inSignDomain == sdPositive) // range may only be in the positive sign domain
{
QCPDataMap::const_iterator it = mData->constBegin();
while (it != mData->constEnd())
{
current = it.value().key;
currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0);
currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0);
if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus > 0)
{
range.lower = current-currentErrorMinus;
haveLower = true;
}
if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus > 0)
{
range.upper = current+currentErrorPlus;
haveUpper = true;
}
if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to get that point.
{
if ((current < range.lower || !haveLower) && current > 0)
{
range.lower = current;
haveLower = true;
}
if ((current > range.upper || !haveUpper) && current > 0)
{
range.upper = current;
haveUpper = true;
}
}
++it;
}
}
validRange = haveLower && haveUpper;
return range;
}
/*! \overload
Allows to specify whether the error bars should be included in the range calculation.
\see getValueRange(bool &validRange, SignDomain inSignDomain)
*/
QCPRange QCPGraph::getValueRange(bool &validRange, SignDomain inSignDomain, bool includeErrors) const
{
QCPRange range;
bool haveLower = false;
bool haveUpper = false;
double current, currentErrorMinus, currentErrorPlus;
if (inSignDomain == sdBoth) // range may be anywhere
{
QCPDataMap::const_iterator it = mData->constBegin();
while (it != mData->constEnd())
{
current = it.value().value;
currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0);
currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0);
if (current-currentErrorMinus < range.lower || !haveLower)
{
range.lower = current-currentErrorMinus;
haveLower = true;
}
if (current+currentErrorPlus > range.upper || !haveUpper)
{
range.upper = current+currentErrorPlus;
haveUpper = true;
}
++it;
}
} else if (inSignDomain == sdNegative) // range may only be in the negative sign domain
{
QCPDataMap::const_iterator it = mData->constBegin();
while (it != mData->constEnd())
{
current = it.value().value;
currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0);
currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0);
if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus < 0)
{
range.lower = current-currentErrorMinus;
haveLower = true;
}
if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus < 0)
{
range.upper = current+currentErrorPlus;
haveUpper = true;
}
if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to get that point.
{
if ((current < range.lower || !haveLower) && current < 0)
{
range.lower = current;
haveLower = true;
}
if ((current > range.upper || !haveUpper) && current < 0)
{
range.upper = current;
haveUpper = true;
}
}
++it;
}
} else if (inSignDomain == sdPositive) // range may only be in the positive sign domain
{
QCPDataMap::const_iterator it = mData->constBegin();
while (it != mData->constEnd())
{
current = it.value().value;
currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0);
currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0);
if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus > 0)
{
range.lower = current-currentErrorMinus;
haveLower = true;
}
if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus > 0)
{
range.upper = current+currentErrorPlus;
haveUpper = true;
}
if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to geht that point.
{
if ((current < range.lower || !haveLower) && current > 0)
{
range.lower = current;
haveLower = true;
}
if ((current > range.upper || !haveUpper) && current > 0)
{
range.upper = current;
haveUpper = true;
}
}
++it;
}
}
validRange = haveLower && haveUpper;
return range;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPCurveData
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPCurveData
\brief Holds the data of one single data point for QCPCurve.
The container for storing multiple data points is \ref QCPCurveDataMap.
The stored data is:
\li \a t: the free parameter of the curve at this curve point (cp. the mathematical vector <em>(x(t), y(t))</em>)
\li \a key: coordinate on the key axis of this curve point
\li \a value: coordinate on the value axis of this curve point
\see QCPCurveDataMap
*/
/*!
Constructs a curve data point with t, key and value set to zero.
*/
QCPCurveData::QCPCurveData() :
t(0),
key(0),
value(0)
{
}
/*!
Constructs a curve data point with the specified \a t, \a key and \a value.
*/
QCPCurveData::QCPCurveData(double t, double key, double value) :
t(t),
key(key),
value(value)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPCurve
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPCurve
\brief A plottable representing a parametric curve in a plot.
\image html QCPCurve.png
Unlike QCPGraph, plottables of this type may have multiple points with the same key coordinate,
so their visual representation can have \a loops. This is realized by introducing a third
coordinate \a t, which defines the order of the points described by the other two coordinates \a
x and \a y.
To plot data, assign it with the \ref setData or \ref addData functions.
\section appearance Changing the appearance
The appearance of the curve is determined by the pen and the brush (\ref setPen, \ref setBrush).
\section usage Usage
Like all data representing objects in QCustomPlot, the QCPCurve is a plottable (QCPAbstractPlottable). So
the plottable-interface of QCustomPlot applies (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.)
Usually, you first create an instance:
\code
QCPCurve *newCurve = new QCPCurve(customPlot->xAxis, customPlot->yAxis);\endcode
add it to the customPlot with QCustomPlot::addPlottable:
\code
customPlot->addPlottable(newCurve);\endcode
and then modify the properties of the newly created plottable, e.g.:
\code
newCurve->setName("Fermat's Spiral");
newCurve->setData(tData, xData, yData);\endcode
*/
/*!
Constructs a curve which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
the same orientation. If either of these restrictions is violated, a corresponding message is
printed to the debug output (qDebug), the construction is not aborted, though.
The constructed QCPCurve can be added to the plot with QCustomPlot::addPlottable, QCustomPlot
then takes ownership of the graph.
*/
QCPCurve::QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis) :
QCPAbstractPlottable(keyAxis, valueAxis)
{
mData = new QCPCurveDataMap;
mPen.setColor(Qt::blue);
mPen.setStyle(Qt::SolidLine);
mBrush.setColor(Qt::blue);
mBrush.setStyle(Qt::NoBrush);
mSelectedPen = mPen;
mSelectedPen.setWidthF(2.5);
mSelectedPen.setColor(QColor(80, 80, 255)); // lighter than Qt::blue of mPen
mSelectedBrush = mBrush;
setScatterStyle(QCPScatterStyle());
setLineStyle(lsLine);
}
QCPCurve::~QCPCurve()
{
delete mData;
}
/*!
Replaces the current data with the provided \a data.
If \a copy is set to true, data points in \a data will only be copied. if false, the plottable
takes ownership of the passed data and replaces the internal data pointer with it. This is
significantly faster than copying for large datasets.
*/
void QCPCurve::setData(QCPCurveDataMap *data, bool copy)
{
if (copy)
{
*mData = *data;
} else
{
delete mData;
mData = data;
}
}
/*! \overload
Replaces the current data with the provided points in \a t, \a key and \a value tuples. The
provided vectors should have equal length. Else, the number of added points will be the size of
the smallest vector.
*/
void QCPCurve::setData(const QVector<double> &t, const QVector<double> &key, const QVector<double> &value)
{
mData->clear();
int n = t.size();
n = qMin(n, key.size());
n = qMin(n, value.size());
QCPCurveData newData;
for (int i=0; i<n; ++i)
{
newData.t = t[i];
newData.key = key[i];
newData.value = value[i];
mData->insertMulti(newData.t, newData);
}
}
/*! \overload
Replaces the current data with the provided \a key and \a value pairs. The t parameter
of each data point will be set to the integer index of the respective key/value pair.
*/
void QCPCurve::setData(const QVector<double> &key, const QVector<double> &value)
{
mData->clear();
int n = key.size();
n = qMin(n, value.size());
QCPCurveData newData;
for (int i=0; i<n; ++i)
{
newData.t = i; // no t vector given, so we assign t the index of the key/value pair
newData.key = key[i];
newData.value = value[i];
mData->insertMulti(newData.t, newData);
}
}
/*!
Sets the visual appearance of single data points in the plot. If set to \ref
QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only plots with appropriate
line style).
\see QCPScatterStyle, setLineStyle
*/
void QCPCurve::setScatterStyle(const QCPScatterStyle &style)
{
mScatterStyle = style;
}
/*!
Sets how the single data points are connected in the plot or how they are represented visually
apart from the scatter symbol. For scatter-only plots, set \a style to \ref lsNone and \ref
setScatterStyle to the desired scatter style.
\see setScatterStyle
*/
void QCPCurve::setLineStyle(QCPCurve::LineStyle style)
{
mLineStyle = style;
}
/*!
Adds the provided data points in \a dataMap to the current data.
\see removeData
*/
void QCPCurve::addData(const QCPCurveDataMap &dataMap)
{
mData->unite(dataMap);
}
/*! \overload
Adds the provided single data point in \a data to the current data.
\see removeData
*/
void QCPCurve::addData(const QCPCurveData &data)
{
mData->insertMulti(data.t, data);
}
/*! \overload
Adds the provided single data point as \a t, \a key and \a value tuple to the current data
\see removeData
*/
void QCPCurve::addData(double t, double key, double value)
{
QCPCurveData newData;
newData.t = t;
newData.key = key;
newData.value = value;
mData->insertMulti(newData.t, newData);
}
/*! \overload
Adds the provided single data point as \a key and \a value pair to the current data The t
parameter of the data point is set to the t of the last data point plus 1. If there is no last
data point, t will be set to 0.
\see removeData
*/
void QCPCurve::addData(double key, double value)
{
QCPCurveData newData;
if (!mData->isEmpty())
newData.t = (mData->constEnd()-1).key()+1;
else
newData.t = 0;
newData.key = key;
newData.value = value;
mData->insertMulti(newData.t, newData);
}
/*! \overload
Adds the provided data points as \a t, \a key and \a value tuples to the current data.
\see removeData
*/
void QCPCurve::addData(const QVector<double> &ts, const QVector<double> &keys, const QVector<double> &values)
{
int n = ts.size();
n = qMin(n, keys.size());
n = qMin(n, values.size());
QCPCurveData newData;
for (int i=0; i<n; ++i)
{
newData.t = ts[i];
newData.key = keys[i];
newData.value = values[i];
mData->insertMulti(newData.t, newData);
}
}
/*!
Removes all data points with curve parameter t smaller than \a t.
\see addData, clearData
*/
void QCPCurve::removeDataBefore(double t)
{
QCPCurveDataMap::iterator it = mData->begin();
while (it != mData->end() && it.key() < t)
it = mData->erase(it);
}
/*!
Removes all data points with curve parameter t greater than \a t.
\see addData, clearData
*/
void QCPCurve::removeDataAfter(double t)
{
if (mData->isEmpty()) return;
QCPCurveDataMap::iterator it = mData->upperBound(t);
while (it != mData->end())
it = mData->erase(it);
}
/*!
Removes all data points with curve parameter t between \a fromt and \a tot. if \a fromt is
greater or equal to \a tot, the function does nothing. To remove a single data point with known
t, use \ref removeData(double t).
\see addData, clearData
*/
void QCPCurve::removeData(double fromt, double tot)
{
if (fromt >= tot || mData->isEmpty()) return;
QCPCurveDataMap::iterator it = mData->upperBound(fromt);
QCPCurveDataMap::iterator itEnd = mData->upperBound(tot);
while (it != itEnd)
it = mData->erase(it);
}
/*! \overload
Removes a single data point at curve parameter \a t. If the position is not known with absolute
precision, consider using \ref removeData(double fromt, double tot) with a small fuzziness
interval around the suspected position, depeding on the precision with which the curve parameter
is known.
\see addData, clearData
*/
void QCPCurve::removeData(double t)
{
mData->remove(t);
}
/*!
Removes all data points.
\see removeData, removeDataAfter, removeDataBefore
*/
void QCPCurve::clearData()
{
mData->clear();
}
/* inherits documentation from base class */
double QCPCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if ((onlySelectable && !mSelectable) || mData->isEmpty())
return -1;
return pointDistance(pos);
}
/* inherits documentation from base class */
void QCPCurve::draw(QCPPainter *painter)
{
if (mData->isEmpty()) return;
// allocate line vector:
QVector<QPointF> *lineData = new QVector<QPointF>;
// fill with curve data:
getCurveData(lineData);
// check data validity if flag set:
#ifdef QCUSTOMPLOT_CHECK_DATA
QCPCurveDataMap::const_iterator it;
for (it = mData->constBegin(); it != mData->constEnd(); ++it)
{
if (QCP::isInvalidData(it.value().t) ||
QCP::isInvalidData(it.value().key, it.value().value))
qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid." << "Plottable name:" << name();
}
#endif
// draw curve fill:
if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0)
{
applyFillAntialiasingHint(painter);
painter->setPen(Qt::NoPen);
painter->setBrush(mainBrush());
painter->drawPolygon(QPolygonF(*lineData));
}
// draw curve line:
if (mLineStyle != lsNone && mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)
{
applyDefaultAntialiasingHint(painter);
painter->setPen(mainPen());
painter->setBrush(Qt::NoBrush);
// if drawing solid line and not in PDF, use much faster line drawing instead of polyline:
if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) &&
painter->pen().style() == Qt::SolidLine &&
!painter->modes().testFlag(QCPPainter::pmVectorized) &&
!painter->modes().testFlag(QCPPainter::pmNoCaching))
{
for (int i=1; i<lineData->size(); ++i)
painter->drawLine(lineData->at(i-1), lineData->at(i));
} else
{
painter->drawPolyline(QPolygonF(*lineData));
}
}
// draw scatters:
if (!mScatterStyle.isNone())
drawScatterPlot(painter, lineData);
// free allocated line data:
delete lineData;
}
/* inherits documentation from base class */
void QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
{
// draw fill:
if (mBrush.style() != Qt::NoBrush)
{
applyFillAntialiasingHint(painter);
painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
}
// draw line vertically centered:
if (mLineStyle != lsNone)
{
applyDefaultAntialiasingHint(painter);
painter->setPen(mPen);
painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens
}
// draw scatter symbol:
if (!mScatterStyle.isNone())
{
applyScattersAntialiasingHint(painter);
// scale scatter pixmap if it's too large to fit in legend icon rect:
if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
{
QCPScatterStyle scaledStyle(mScatterStyle);
scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
scaledStyle.applyTo(painter, mPen);
scaledStyle.drawShape(painter, QRectF(rect).center());
} else
{
mScatterStyle.applyTo(painter, mPen);
mScatterStyle.drawShape(painter, QRectF(rect).center());
}
}
}
/*! \internal
Draws scatter symbols at every data point passed in \a pointData. scatter symbols are independent of
the line style and are always drawn if scatter shape is not \ref QCPScatterStyle::ssNone.
*/
void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> *pointData) const
{
// draw scatter point symbols:
applyScattersAntialiasingHint(painter);
mScatterStyle.applyTo(painter, mPen);
for (int i=0; i<pointData->size(); ++i)
mScatterStyle.drawShape(painter, pointData->at(i));
}
/*! \internal
called by QCPCurve::draw to generate a point vector (pixels) which represents the line of the
curve. Line segments that aren't visible in the current axis rect are handled in an optimized
way.
*/
void QCPCurve::getCurveData(QVector<QPointF> *lineData) const
{
/* Extended sides of axis rect R divide space into 9 regions:
1__|_4_|__7
2__|_R_|__8
3 | 6 | 9
General idea: If the two points of a line segment are in the same region (that is not R), the line segment corner is removed.
Curves outside R become straight lines closely outside of R which greatly reduces drawing time, yet keeps the look of lines and
fills inside R consistent.
The region R has index 5.
*/
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
QRect axisRect = mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect();
lineData->reserve(mData->size());
QCPCurveDataMap::const_iterator it;
int lastRegion = 5;
int currentRegion = 5;
double RLeft = keyAxis->range().lower;
double RRight = keyAxis->range().upper;
double RBottom = valueAxis->range().lower;
double RTop = valueAxis->range().upper;
double x, y; // current key/value
bool addedLastAlready = true;
bool firstPoint = true; // first point must always be drawn, to make sure fill works correctly
for (it = mData->constBegin(); it != mData->constEnd(); ++it)
{
x = it.value().key;
y = it.value().value;
// determine current region:
if (x < RLeft) // region 123
{
if (y > RTop)
currentRegion = 1;
else if (y < RBottom)
currentRegion = 3;
else
currentRegion = 2;
} else if (x > RRight) // region 789
{
if (y > RTop)
currentRegion = 7;
else if (y < RBottom)
currentRegion = 9;
else
currentRegion = 8;
} else // region 456
{
if (y > RTop)
currentRegion = 4;
else if (y < RBottom)
currentRegion = 6;
else
currentRegion = 5;
}
/*
Watch out, the next part is very tricky. It modifies the curve such that it seems like the
whole thing is still drawn, but actually the points outside the axisRect are simplified
("optimized") greatly. There are some subtle special cases when line segments are large and
thereby each subsequent point may be in a different region or even skip some.
*/
// determine whether to keep current point:
if (currentRegion == 5 || (firstPoint && mBrush.style() != Qt::NoBrush)) // current is in R, add current and last if it wasn't added already
{
if (!addedLastAlready) // in case curve just entered R, make sure the last point outside R is also drawn correctly
lineData->append(coordsToPixels((it-1).value().key, (it-1).value().value)); // add last point to vector
else if (lastRegion != 5) // added last already. If that's the case, we probably added it at optimized position. So go back and make sure it's at original position (else the angle changes under which this segment enters R)
{
if (!firstPoint) // because on firstPoint, currentRegion is 5 and addedLastAlready is true, although there is no last point
lineData->replace(lineData->size()-1, coordsToPixels((it-1).value().key, (it-1).value().value));
}
lineData->append(coordsToPixels(it.value().key, it.value().value)); // add current point to vector
addedLastAlready = true; // so in next iteration, we don't add this point twice
} else if (currentRegion != lastRegion) // changed region, add current and last if not added already
{
// using outsideCoordsToPixels instead of coorsToPixels for optimized point placement (places points just outside axisRect instead of potentially far away)
// if we're coming from R or we skip diagonally over the corner regions (so line might still be visible in R), we can't place points optimized
if (lastRegion == 5 || // coming from R
((lastRegion==2 && currentRegion==4) || (lastRegion==4 && currentRegion==2)) || // skip top left diagonal
((lastRegion==4 && currentRegion==8) || (lastRegion==8 && currentRegion==4)) || // skip top right diagonal
((lastRegion==8 && currentRegion==6) || (lastRegion==6 && currentRegion==8)) || // skip bottom right diagonal
((lastRegion==6 && currentRegion==2) || (lastRegion==2 && currentRegion==6)) // skip bottom left diagonal
)
{
// always add last point if not added already, original:
if (!addedLastAlready)
lineData->append(coordsToPixels((it-1).value().key, (it-1).value().value));
// add current point, original:
lineData->append(coordsToPixels(it.value().key, it.value().value));
} else // no special case that forbids optimized point placement, so do it:
{
// always add last point if not added already, optimized:
if (!addedLastAlready)
lineData->append(outsideCoordsToPixels((it-1).value().key, (it-1).value().value, currentRegion, axisRect));
// add current point, optimized:
lineData->append(outsideCoordsToPixels(it.value().key, it.value().value, currentRegion, axisRect));
}
addedLastAlready = true; // so that if next point enters 5, or crosses another region boundary, we don't add this point twice
} else // neither in R, nor crossed a region boundary, skip current point
{
addedLastAlready = false;
}
lastRegion = currentRegion;
firstPoint = false;
}
// If curve ends outside R, we want to add very last point so the fill looks like it should when the curve started inside R:
if (lastRegion != 5 && mBrush.style() != Qt::NoBrush && !mData->isEmpty())
lineData->append(coordsToPixels((mData->constEnd()-1).value().key, (mData->constEnd()-1).value().value));
}
/*! \internal
Calculates the (minimum) distance (in pixels) the curve's representation has from the given \a
pixelPoint in pixels. This is used to determine whether the curve was clicked or not, e.g. in
\ref selectTest.
*/
double QCPCurve::pointDistance(const QPointF &pixelPoint) const
{
if (mData->isEmpty())
{
qDebug() << Q_FUNC_INFO << "requested point distance on curve" << mName << "without data";
return 500;
}
if (mData->size() == 1)
{
QPointF dataPoint = coordsToPixels(mData->constBegin().key(), mData->constBegin().value().value);
return QVector2D(dataPoint-pixelPoint).length();
}
// calculate minimum distance to line segments:
QVector<QPointF> *lineData = new QVector<QPointF>;
getCurveData(lineData);
double minDistSqr = std::numeric_limits<double>::max();
for (int i=0; i<lineData->size()-1; ++i)
{
double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint);
if (currentDistSqr < minDistSqr)
minDistSqr = currentDistSqr;
}
delete lineData;
return sqrt(minDistSqr);
}
/*! \internal
This is a specialized \ref coordsToPixels function for points that are outside the visible
axisRect and just crossing a boundary (since \ref getCurveData reduces non-visible curve segments
to those line segments that cross region boundaries, see documentation there). It only uses the
coordinate parallel to the region boundary of the axisRect. The other coordinate is picked just
outside the axisRect (how far is determined by the scatter size and the line width). Together
with the optimization in \ref getCurveData this improves performance for large curves (or zoomed
in ones) significantly while keeping the illusion the whole curve and its filling is still being
drawn for the viewer.
*/
QPointF QCPCurve::outsideCoordsToPixels(double key, double value, int region, QRect axisRect) const
{
int margin = qCeil(qMax(mScatterStyle.size(), (double)mPen.widthF())) + 2;
QPointF result = coordsToPixels(key, value);
switch (region)
{
case 2: result.setX(axisRect.left()-margin); break; // left
case 8: result.setX(axisRect.right()+margin); break; // right
case 4: result.setY(axisRect.top()-margin); break; // top
case 6: result.setY(axisRect.bottom()+margin); break; // bottom
case 1: result.setX(axisRect.left()-margin);
result.setY(axisRect.top()-margin); break; // top left
case 7: result.setX(axisRect.right()+margin);
result.setY(axisRect.top()-margin); break; // top right
case 9: result.setX(axisRect.right()+margin);
result.setY(axisRect.bottom()+margin); break; // bottom right
case 3: result.setX(axisRect.left()-margin);
result.setY(axisRect.bottom()+margin); break; // bottom left
}
return result;
}
/* inherits documentation from base class */
QCPRange QCPCurve::getKeyRange(bool &validRange, SignDomain inSignDomain) const
{
QCPRange range;
bool haveLower = false;
bool haveUpper = false;
double current;
QCPCurveDataMap::const_iterator it = mData->constBegin();
while (it != mData->constEnd())
{
current = it.value().key;
if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0))
{
if (current < range.lower || !haveLower)
{
range.lower = current;
haveLower = true;
}
if (current > range.upper || !haveUpper)
{
range.upper = current;
haveUpper = true;
}
}
++it;
}
validRange = haveLower && haveUpper;
return range;
}
/* inherits documentation from base class */
QCPRange QCPCurve::getValueRange(bool &validRange, SignDomain inSignDomain) const
{
QCPRange range;
bool haveLower = false;
bool haveUpper = false;
double current;
QCPCurveDataMap::const_iterator it = mData->constBegin();
while (it != mData->constEnd())
{
current = it.value().value;
if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0))
{
if (current < range.lower || !haveLower)
{
range.lower = current;
haveLower = true;
}
if (current > range.upper || !haveUpper)
{
range.upper = current;
haveUpper = true;
}
}
++it;
}
validRange = haveLower && haveUpper;
return range;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPBarData
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPBarData
\brief Holds the data of one single data point (one bar) for QCPBars.
The container for storing multiple data points is \ref QCPBarDataMap.
The stored data is:
\li \a key: coordinate on the key axis of this bar
\li \a value: height coordinate on the value axis of this bar
\see QCPBarDataaMap
*/
/*!
Constructs a bar data point with key and value set to zero.
*/
QCPBarData::QCPBarData() :
key(0),
value(0)
{
}
/*!
Constructs a bar data point with the specified \a key and \a value.
*/
QCPBarData::QCPBarData(double key, double value) :
key(key),
value(value)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPBars
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPBars
\brief A plottable representing a bar chart in a plot.
\image html QCPBars.png
To plot data, assign it with the \ref setData or \ref addData functions.
\section appearance Changing the appearance
The appearance of the bars is determined by the pen and the brush (\ref setPen, \ref setBrush).
Bar charts are stackable. This means, Two QCPBars plottables can be placed on top of each other
(see \ref QCPBars::moveAbove). Then, when two bars are at the same key position, they will appear
stacked.
\section usage Usage
Like all data representing objects in QCustomPlot, the QCPBars is a plottable
(QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
(QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.)
Usually, you first create an instance:
\code
QCPBars *newBars = new QCPBars(customPlot->xAxis, customPlot->yAxis);\endcode
add it to the customPlot with QCustomPlot::addPlottable:
\code
customPlot->addPlottable(newBars);\endcode
and then modify the properties of the newly created plottable, e.g.:
\code
newBars->setName("Country population");
newBars->setData(xData, yData);\endcode
*/
/*! \fn QCPBars *QCPBars::barBelow() const
Returns the bars plottable that is directly below this bars plottable.
If there is no such plottable, returns 0.
\see barAbove, moveBelow, moveAbove
*/
/*! \fn QCPBars *QCPBars::barAbove() const
Returns the bars plottable that is directly above this bars plottable.
If there is no such plottable, returns 0.
\see barBelow, moveBelow, moveAbove
*/
/*!
Constructs a bar chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
the same orientation. If either of these restrictions is violated, a corresponding message is
printed to the debug output (qDebug), the construction is not aborted, though.
The constructed QCPBars can be added to the plot with QCustomPlot::addPlottable, QCustomPlot
then takes ownership of the bar chart.
*/
QCPBars::QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis) :
QCPAbstractPlottable(keyAxis, valueAxis)
{
mData = new QCPBarDataMap;
mPen.setColor(Qt::blue);
mPen.setStyle(Qt::SolidLine);
mBrush.setColor(QColor(40, 50, 255, 30));
mBrush.setStyle(Qt::SolidPattern);
mSelectedPen = mPen;
mSelectedPen.setWidthF(2.5);
mSelectedPen.setColor(QColor(80, 80, 255)); // lighter than Qt::blue of mPen
mSelectedBrush = mBrush;
mWidth = 0.75;
}
QCPBars::~QCPBars()
{
if (mBarBelow || mBarAbove)
connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking
delete mData;
}
/*!
Sets the width of the bars in plot (key) coordinates.
*/
void QCPBars::setWidth(double width)
{
mWidth = width;
}
/*!
Replaces the current data with the provided \a data.
If \a copy is set to true, data points in \a data will only be copied. if false, the plottable
takes ownership of the passed data and replaces the internal data pointer with it. This is
significantly faster than copying for large datasets.
*/
void QCPBars::setData(QCPBarDataMap *data, bool copy)
{
if (copy)
{
*mData = *data;
} else
{
delete mData;
mData = data;
}
}
/*! \overload
Replaces the current data with the provided points in \a key and \a value tuples. The
provided vectors should have equal length. Else, the number of added points will be the size of
the smallest vector.
*/
void QCPBars::setData(const QVector<double> &key, const QVector<double> &value)
{
mData->clear();
int n = key.size();
n = qMin(n, value.size());
QCPBarData newData;
for (int i=0; i<n; ++i)
{
newData.key = key[i];
newData.value = value[i];
mData->insertMulti(newData.key, newData);
}
}
/*!
Moves this bars plottable below \a bars. In other words, the bars of this plottable will appear
below the bars of \a bars. The move target \a bars must use the same key and value axis as this
plottable.
Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
has a bars object below itself, this bars object is inserted between the two. If this bars object
is already between two other bars, the two other bars will be stacked on top of each other after
the operation.
To remove this bars plottable from any stacking, set \a bars to 0.
\see moveBelow, barAbove, barBelow
*/
void QCPBars::moveBelow(QCPBars *bars)
{
if (bars == this) return;
if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data()))
{
qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
return;
}
// remove from stacking:
connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0
// if new bar given, insert this bar below it:
if (bars)
{
if (bars->mBarBelow)
connectBars(bars->mBarBelow.data(), this);
connectBars(this, bars);
}
}
/*!
Moves this bars plottable above \a bars. In other words, the bars of this plottable will appear
above the bars of \a bars. The move target \a bars must use the same key and value axis as this
plottable.
Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
has a bars object below itself, this bars object is inserted between the two. If this bars object
is already between two other bars, the two other bars will be stacked on top of each other after
the operation.
To remove this bars plottable from any stacking, set \a bars to 0.
\see moveBelow, barBelow, barAbove
*/
void QCPBars::moveAbove(QCPBars *bars)
{
if (bars == this) return;
if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data()))
{
qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
return;
}
// remove from stacking:
connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0
// if new bar given, insert this bar above it:
if (bars)
{
if (bars->mBarAbove)
connectBars(this, bars->mBarAbove.data());
connectBars(bars, this);
}
}
/*!
Adds the provided data points in \a dataMap to the current data.
\see removeData
*/
void QCPBars::addData(const QCPBarDataMap &dataMap)
{
mData->unite(dataMap);
}
/*! \overload
Adds the provided single data point in \a data to the current data.
\see removeData
*/
void QCPBars::addData(const QCPBarData &data)
{
mData->insertMulti(data.key, data);
}
/*! \overload
Adds the provided single data point as \a key and \a value tuple to the current data
\see removeData
*/
void QCPBars::addData(double key, double value)
{
QCPBarData newData;
newData.key = key;
newData.value = value;
mData->insertMulti(newData.key, newData);
}
/*! \overload
Adds the provided data points as \a key and \a value tuples to the current data.
\see removeData
*/
void QCPBars::addData(const QVector<double> &keys, const QVector<double> &values)
{
int n = keys.size();
n = qMin(n, values.size());
QCPBarData newData;
for (int i=0; i<n; ++i)
{
newData.key = keys[i];
newData.value = values[i];
mData->insertMulti(newData.key, newData);
}
}
/*!
Removes all data points with key smaller than \a key.
\see addData, clearData
*/
void QCPBars::removeDataBefore(double key)
{
QCPBarDataMap::iterator it = mData->begin();
while (it != mData->end() && it.key() < key)
it = mData->erase(it);
}
/*!
Removes all data points with key greater than \a key.
\see addData, clearData
*/
void QCPBars::removeDataAfter(double key)
{
if (mData->isEmpty()) return;
QCPBarDataMap::iterator it = mData->upperBound(key);
while (it != mData->end())
it = mData->erase(it);
}
/*!
Removes all data points with key between \a fromKey and \a toKey. if \a fromKey is
greater or equal to \a toKey, the function does nothing. To remove a single data point with known
key, use \ref removeData(double key).
\see addData, clearData
*/
void QCPBars::removeData(double fromKey, double toKey)
{
if (fromKey >= toKey || mData->isEmpty()) return;
QCPBarDataMap::iterator it = mData->upperBound(fromKey);
QCPBarDataMap::iterator itEnd = mData->upperBound(toKey);
while (it != itEnd)
it = mData->erase(it);
}
/*! \overload
Removes a single data point at \a key. If the position is not known with absolute precision,
consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval
around the suspected position, depeding on the precision with which the key is known.
\see addData, clearData
*/
void QCPBars::removeData(double key)
{
mData->remove(key);
}
/*!
Removes all data points.
\see removeData, removeDataAfter, removeDataBefore
*/
void QCPBars::clearData()
{
mData->clear();
}
/* inherits documentation from base class */
double QCPBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
QCPBarDataMap::ConstIterator it;
double posKey, posValue;
pixelsToCoords(pos, posKey, posValue);
for (it = mData->constBegin(); it != mData->constEnd(); ++it)
{
double baseValue = getBaseValue(it.key(), it.value().value >=0);
QCPRange keyRange(it.key()-mWidth*0.5, it.key()+mWidth*0.5);
QCPRange valueRange(baseValue, baseValue+it.value().value);
if (keyRange.contains(posKey) && valueRange.contains(posValue))
return mParentPlot->selectionTolerance()*0.99;
}
return -1;
}
/* inherits documentation from base class */
void QCPBars::draw(QCPPainter *painter)
{
if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
if (mData->isEmpty()) return;
QCPBarDataMap::const_iterator it;
for (it = mData->constBegin(); it != mData->constEnd(); ++it)
{
// skip bar if not visible in key axis range:
if (it.key()+mWidth*0.5 < mKeyAxis.data()->range().lower || it.key()-mWidth*0.5 > mKeyAxis.data()->range().upper)
continue;
// check data validity if flag set:
#ifdef QCUSTOMPLOT_CHECK_DATA
if (QCP::isInvalidData(it.value().key, it.value().value))
qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "of drawn range invalid." << "Plottable name:" << name();
#endif
QPolygonF barPolygon = getBarPolygon(it.key(), it.value().value);
// draw bar fill:
if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0)
{
applyFillAntialiasingHint(painter);
painter->setPen(Qt::NoPen);
painter->setBrush(mainBrush());
painter->drawPolygon(barPolygon);
}
// draw bar line:
if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)
{
applyDefaultAntialiasingHint(painter);
painter->setPen(mainPen());
painter->setBrush(Qt::NoBrush);
painter->drawPolyline(barPolygon);
}
}
}
/* inherits documentation from base class */
void QCPBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
{
// draw filled rect:
applyDefaultAntialiasingHint(painter);
painter->setBrush(mBrush);
painter->setPen(mPen);
QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67);
r.moveCenter(rect.center());
painter->drawRect(r);
}
/*! \internal
Returns the polygon of a single bar with \a key and \a value. The Polygon is open at the bottom
and shifted according to the bar stacking (see \ref moveAbove).
*/
QPolygonF QCPBars::getBarPolygon(double key, double value) const
{
QPolygonF result;
double baseValue = getBaseValue(key, value >= 0);
result << coordsToPixels(key-mWidth*0.5, baseValue);
result << coordsToPixels(key-mWidth*0.5, baseValue+value);
result << coordsToPixels(key+mWidth*0.5, baseValue+value);
result << coordsToPixels(key+mWidth*0.5, baseValue);
return result;
}
/*! \internal
This function is called to find at which value to start drawing the base of a bar at \a key, when
it is stacked on top of another QCPBars (e.g. with \ref moveAbove).
positive and negative bars are separated per stack (positive are stacked above 0-value upwards,
negative are stacked below 0-value downwards). This can be indicated with \a positive. So if the
bar for which we need the base value is negative, set \a positive to false.
*/
double QCPBars::getBaseValue(double key, bool positive) const
{
if (mBarBelow)
{
double max = 0;
// find bars of mBarBelow that are approximately at key and find largest one:
QCPBarDataMap::const_iterator it = mBarBelow.data()->mData->lowerBound(key-mWidth*0.1);
QCPBarDataMap::const_iterator itEnd = mBarBelow.data()->mData->upperBound(key+mWidth*0.1);
while (it != itEnd)
{
if ((positive && it.value().value > max) ||
(!positive && it.value().value < max))
max = it.value().value;
++it;
}
// recurse down the bar-stack to find the total height:
return max + mBarBelow.data()->getBaseValue(key, positive);
} else
return 0;
}
/*! \internal
Connects \a below and \a above to each other via their mBarAbove/mBarBelow properties.
The bar(s) currently below lower and upper will become disconnected to lower/upper.
If lower is zero, upper will be disconnected at the bottom.
If upper is zero, lower will be disconnected at the top.
*/
void QCPBars::connectBars(QCPBars *lower, QCPBars *upper)
{
if (!lower && !upper) return;
if (!lower) // disconnect upper at bottom
{
// disconnect old bar below upper:
if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
upper->mBarBelow.data()->mBarAbove = 0;
upper->mBarBelow = 0;
} else if (!upper) // disconnect lower at top
{
// disconnect old bar above lower:
if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
lower->mBarAbove.data()->mBarBelow = 0;
lower->mBarAbove = 0;
} else // connect lower and upper
{
// disconnect old bar above lower:
if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
lower->mBarAbove.data()->mBarBelow = 0;
// disconnect old bar below upper:
if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
upper->mBarBelow.data()->mBarAbove = 0;
lower->mBarAbove = upper;
upper->mBarBelow = lower;
}
}
/* inherits documentation from base class */
QCPRange QCPBars::getKeyRange(bool &validRange, SignDomain inSignDomain) const
{
QCPRange range;
bool haveLower = false;
bool haveUpper = false;
double current;
double barWidthHalf = mWidth*0.5;
QCPBarDataMap::const_iterator it = mData->constBegin();
while (it != mData->constEnd())
{
current = it.value().key;
if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current+barWidthHalf < 0) || (inSignDomain == sdPositive && current-barWidthHalf > 0))
{
if (current-barWidthHalf < range.lower || !haveLower)
{
range.lower = current-barWidthHalf;
haveLower = true;
}
if (current+barWidthHalf > range.upper || !haveUpper)
{
range.upper = current+barWidthHalf;
haveUpper = true;
}
}
++it;
}
validRange = haveLower && haveUpper;
return range;
}
/* inherits documentation from base class */
QCPRange QCPBars::getValueRange(bool &validRange, SignDomain inSignDomain) const
{
QCPRange range;
bool haveLower = true; // set to true, because 0 should always be visible in bar charts
bool haveUpper = true; // set to true, because 0 should always be visible in bar charts
double current;
QCPBarDataMap::const_iterator it = mData->constBegin();
while (it != mData->constEnd())
{
current = it.value().value + getBaseValue(it.value().key, it.value().value >= 0);
if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0))
{
if (current < range.lower || !haveLower)
{
range.lower = current;
haveLower = true;
}
if (current > range.upper || !haveUpper)
{
range.upper = current;
haveUpper = true;
}
}
++it;
}
validRange = range.lower < range.upper;
return range;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPStatisticalBox
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPStatisticalBox
\brief A plottable representing a single statistical box in a plot.
\image html QCPStatisticalBox.png
To plot data, assign it with the individual parameter functions or use \ref setData to set all
parameters at once. The individual funcions are:
\li \ref setMinimum
\li \ref setLowerQuartile
\li \ref setMedian
\li \ref setUpperQuartile
\li \ref setMaximum
Additionally you can define a list of outliers, drawn as circle datapoints:
\li \ref setOutliers
\section appearance Changing the appearance
The appearance of the box itself is controlled via \ref setPen and \ref setBrush. You may change
the width of the box with \ref setWidth in plot coordinates (not pixels).
Analog functions exist for the minimum/maximum-whiskers: \ref setWhiskerPen, \ref
setWhiskerBarPen, \ref setWhiskerWidth. The whisker width is the width of the bar at the top
(maximum) and bottom (minimum).
The median indicator line has its own pen, \ref setMedianPen.
If the whisker backbone pen is changed, make sure to set the capStyle to Qt::FlatCap. Else, the
backbone line might exceed the whisker bars by a few pixels due to the pen cap being not
perfectly flat.
The Outlier data points are drawn as normal scatter points. Their look can be controlled with
\ref setOutlierStyle
\section usage Usage
Like all data representing objects in QCustomPlot, the QCPStatisticalBox is a plottable
(QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
(QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.)
Usually, you first create an instance:
\code
QCPStatisticalBox *newBox = new QCPStatisticalBox(customPlot->xAxis, customPlot->yAxis);\endcode
add it to the customPlot with QCustomPlot::addPlottable:
\code
customPlot->addPlottable(newBox);\endcode
and then modify the properties of the newly created plottable, e.g.:
\code
newBox->setName("Measurement Series 1");
newBox->setData(1, 3, 4, 5, 7);
newBox->setOutliers(QVector<double>() << 0.5 << 0.64 << 7.2 << 7.42);\endcode
*/
/*!
Constructs a statistical box which uses \a keyAxis as its key axis ("x") and \a valueAxis as its
value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and
not have the same orientation. If either of these restrictions is violated, a corresponding
message is printed to the debug output (qDebug), the construction is not aborted, though.
The constructed statistical box can be added to the plot with QCustomPlot::addPlottable,
QCustomPlot then takes ownership of the statistical box.
*/
QCPStatisticalBox::QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis) :
QCPAbstractPlottable(keyAxis, valueAxis),
mKey(0),
mMinimum(0),
mLowerQuartile(0),
mMedian(0),
mUpperQuartile(0),
mMaximum(0)
{
setOutlierStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::blue, 6));
setWhiskerWidth(0.2);
setWidth(0.5);
setPen(QPen(Qt::black));
setSelectedPen(QPen(Qt::blue, 2.5));
setMedianPen(QPen(Qt::black, 3, Qt::SolidLine, Qt::FlatCap));
setWhiskerPen(QPen(Qt::black, 0, Qt::DashLine, Qt::FlatCap));
setWhiskerBarPen(QPen(Qt::black));
setBrush(Qt::NoBrush);
setSelectedBrush(Qt::NoBrush);
}
/*!
Sets the key coordinate of the statistical box.
*/
void QCPStatisticalBox::setKey(double key)
{
mKey = key;
}
/*!
Sets the parameter "minimum" of the statistical box plot. This is the position of the lower
whisker, typically the minimum measurement of the sample that's not considered an outlier.
\see setMaximum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth
*/
void QCPStatisticalBox::setMinimum(double value)
{
mMinimum = value;
}
/*!
Sets the parameter "lower Quartile" of the statistical box plot. This is the lower end of the
box. The lower and the upper quartiles are the two statistical quartiles around the median of the
sample, they contain 50% of the sample data.
\see setUpperQuartile, setPen, setBrush, setWidth
*/
void QCPStatisticalBox::setLowerQuartile(double value)
{
mLowerQuartile = value;
}
/*!
Sets the parameter "median" of the statistical box plot. This is the value of the median mark
inside the quartile box. The median separates the sample data in half (50% of the sample data is
below/above the median).
\see setMedianPen
*/
void QCPStatisticalBox::setMedian(double value)
{
mMedian = value;
}
/*!
Sets the parameter "upper Quartile" of the statistical box plot. This is the upper end of the
box. The lower and the upper quartiles are the two statistical quartiles around the median of the
sample, they contain 50% of the sample data.
\see setLowerQuartile, setPen, setBrush, setWidth
*/
void QCPStatisticalBox::setUpperQuartile(double value)
{
mUpperQuartile = value;
}
/*!
Sets the parameter "maximum" of the statistical box plot. This is the position of the upper
whisker, typically the maximum measurement of the sample that's not considered an outlier.
\see setMinimum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth
*/
void QCPStatisticalBox::setMaximum(double value)
{
mMaximum = value;
}
/*!
Sets a vector of outlier values that will be drawn as circles. Any data points in the sample that
are not within the whiskers (\ref setMinimum, \ref setMaximum) should be considered outliers and
displayed as such.
\see setOutlierStyle
*/
void QCPStatisticalBox::setOutliers(const QVector<double> &values)
{
mOutliers = values;
}
/*!
Sets all parameters of the statistical box plot at once.
\see setKey, setMinimum, setLowerQuartile, setMedian, setUpperQuartile, setMaximum
*/
void QCPStatisticalBox::setData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum)
{
setKey(key);
setMinimum(minimum);
setLowerQuartile(lowerQuartile);
setMedian(median);
setUpperQuartile(upperQuartile);
setMaximum(maximum);
}
/*!
Sets the width of the box in key coordinates.
\see setWhiskerWidth
*/
void QCPStatisticalBox::setWidth(double width)
{
mWidth = width;
}
/*!
Sets the width of the whiskers (\ref setMinimum, \ref setMaximum) in key coordinates.
\see setWidth
*/
void QCPStatisticalBox::setWhiskerWidth(double width)
{
mWhiskerWidth = width;
}
/*!
Sets the pen used for drawing the whisker backbone (That's the line parallel to the value axis).
Make sure to set the \a pen capStyle to Qt::FlatCap to prevent the whisker backbone from reaching
a few pixels past the whisker bars, when using a non-zero pen width.
\see setWhiskerBarPen
*/
void QCPStatisticalBox::setWhiskerPen(const QPen &pen)
{
mWhiskerPen = pen;
}
/*!
Sets the pen used for drawing the whisker bars (Those are the lines parallel to the key axis at
each end of the whisker backbone).
\see setWhiskerPen
*/
void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen)
{
mWhiskerBarPen = pen;
}
/*!
Sets the pen used for drawing the median indicator line inside the statistical box.
*/
void QCPStatisticalBox::setMedianPen(const QPen &pen)
{
mMedianPen = pen;
}
/*!
Sets the appearance of the outlier data points.
\see setOutliers
*/
void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle &style)
{
mOutlierStyle = style;
}
/* inherits documentation from base class */
void QCPStatisticalBox::clearData()
{
setOutliers(QVector<double>());
setKey(0);
setMinimum(0);
setLowerQuartile(0);
setMedian(0);
setUpperQuartile(0);
setMaximum(0);
}
/* inherits documentation from base class */
double QCPStatisticalBox::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
double posKey, posValue;
pixelsToCoords(pos, posKey, posValue);
// quartile box:
QCPRange keyRange(mKey-mWidth*0.5, mKey+mWidth*0.5);
QCPRange valueRange(mLowerQuartile, mUpperQuartile);
if (keyRange.contains(posKey) && valueRange.contains(posValue))
return mParentPlot->selectionTolerance()*0.99;
// min/max whiskers:
if (QCPRange(mMinimum, mMaximum).contains(posValue))
return qAbs(mKeyAxis.data()->coordToPixel(mKey)-mKeyAxis.data()->coordToPixel(posKey));
return -1;
}
/* inherits documentation from base class */
void QCPStatisticalBox::draw(QCPPainter *painter)
{
if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
// check data validity if flag set:
#ifdef QCUSTOMPLOT_CHECK_DATA
if (QCP::isInvalidData(mKey, mMedian) ||
QCP::isInvalidData(mLowerQuartile, mUpperQuartile) ||
QCP::isInvalidData(mMinimum, mMaximum))
qDebug() << Q_FUNC_INFO << "Data point at" << mKey << "of drawn range has invalid data." << "Plottable name:" << name();
for (int i=0; i<mOutliers.size(); ++i)
if (QCP::isInvalidData(mOutliers.at(i)))
qDebug() << Q_FUNC_INFO << "Data point outlier at" << mKey << "of drawn range invalid." << "Plottable name:" << name();
#endif
QRectF quartileBox;
drawQuartileBox(painter, &quartileBox);
painter->save();
painter->setClipRect(quartileBox, Qt::IntersectClip);
drawMedian(painter);
painter->restore();
drawWhiskers(painter);
drawOutliers(painter);
}
/* inherits documentation from base class */
void QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
{
// draw filled rect:
applyDefaultAntialiasingHint(painter);
painter->setPen(mPen);
painter->setBrush(mBrush);
QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67);
r.moveCenter(rect.center());
painter->drawRect(r);
}
/*! \internal
Draws the quartile box. \a box is an output parameter that returns the quartile box (in pixel
coordinates) which is used to set the clip rect of the painter before calling \ref drawMedian (so
the median doesn't draw outside the quartile box).
*/
void QCPStatisticalBox::drawQuartileBox(QCPPainter *painter, QRectF *quartileBox) const
{
QRectF box;
box.setTopLeft(coordsToPixels(mKey-mWidth*0.5, mUpperQuartile));
box.setBottomRight(coordsToPixels(mKey+mWidth*0.5, mLowerQuartile));
applyDefaultAntialiasingHint(painter);
painter->setPen(mainPen());
painter->setBrush(mainBrush());
painter->drawRect(box);
if (quartileBox)
*quartileBox = box;
}
/*! \internal
Draws the median line inside the quartile box.
*/
void QCPStatisticalBox::drawMedian(QCPPainter *painter) const
{
QLineF medianLine;
medianLine.setP1(coordsToPixels(mKey-mWidth*0.5, mMedian));
medianLine.setP2(coordsToPixels(mKey+mWidth*0.5, mMedian));
applyDefaultAntialiasingHint(painter);
painter->setPen(mMedianPen);
painter->drawLine(medianLine);
}
/*! \internal
Draws both whisker backbones and bars.
*/
void QCPStatisticalBox::drawWhiskers(QCPPainter *painter) const
{
QLineF backboneMin, backboneMax, barMin, barMax;
backboneMax.setPoints(coordsToPixels(mKey, mUpperQuartile), coordsToPixels(mKey, mMaximum));
backboneMin.setPoints(coordsToPixels(mKey, mLowerQuartile), coordsToPixels(mKey, mMinimum));
barMax.setPoints(coordsToPixels(mKey-mWhiskerWidth*0.5, mMaximum), coordsToPixels(mKey+mWhiskerWidth*0.5, mMaximum));
barMin.setPoints(coordsToPixels(mKey-mWhiskerWidth*0.5, mMinimum), coordsToPixels(mKey+mWhiskerWidth*0.5, mMinimum));
applyErrorBarsAntialiasingHint(painter);
painter->setPen(mWhiskerPen);
painter->drawLine(backboneMin);
painter->drawLine(backboneMax);
painter->setPen(mWhiskerBarPen);
painter->drawLine(barMin);
painter->drawLine(barMax);
}
/*! \internal
Draws the outlier scatter points.
*/
void QCPStatisticalBox::drawOutliers(QCPPainter *painter) const
{
applyScattersAntialiasingHint(painter);
mOutlierStyle.applyTo(painter, mPen);
for (int i=0; i<mOutliers.size(); ++i)
mOutlierStyle.drawShape(painter, coordsToPixels(mKey, mOutliers.at(i)));
}
/* inherits documentation from base class */
QCPRange QCPStatisticalBox::getKeyRange(bool &validRange, SignDomain inSignDomain) const
{
validRange = mWidth > 0;
if (inSignDomain == sdBoth)
{
return QCPRange(mKey-mWidth*0.5, mKey+mWidth*0.5);
} else if (inSignDomain == sdNegative)
{
if (mKey+mWidth*0.5 < 0)
return QCPRange(mKey-mWidth*0.5, mKey+mWidth*0.5);
else if (mKey < 0)
return QCPRange(mKey-mWidth*0.5, mKey);
else
{
validRange = false;
return QCPRange();
}
} else if (inSignDomain == sdPositive)
{
if (mKey-mWidth*0.5 > 0)
return QCPRange(mKey-mWidth*0.5, mKey+mWidth*0.5);
else if (mKey > 0)
return QCPRange(mKey, mKey+mWidth*0.5);
else
{
validRange = false;
return QCPRange();
}
}
validRange = false;
return QCPRange();
}
/* inherits documentation from base class */
QCPRange QCPStatisticalBox::getValueRange(bool &validRange, SignDomain inSignDomain) const
{
if (inSignDomain == sdBoth)
{
double lower = qMin(mMinimum, qMin(mMedian, mLowerQuartile));
double upper = qMax(mMaximum, qMax(mMedian, mUpperQuartile));
for (int i=0; i<mOutliers.size(); ++i)
{
if (mOutliers.at(i) < lower)
lower = mOutliers.at(i);
if (mOutliers.at(i) > upper)
upper = mOutliers.at(i);
}
validRange = upper > lower;
return QCPRange(lower, upper);
} else
{
QVector<double> values; // values that must be considered (i.e. all outliers and the five box-parameters)
values.reserve(mOutliers.size() + 5);
values << mMaximum << mUpperQuartile << mMedian << mLowerQuartile << mMinimum;
values << mOutliers;
// go through values and find the ones in legal range:
bool haveUpper = false;
bool haveLower = false;
double upper = 0;
double lower = 0;
for (int i=0; i<values.size(); ++i)
{
if ((inSignDomain == sdNegative && values.at(i) < 0) ||
(inSignDomain == sdPositive && values.at(i) > 0))
{
if (values.at(i) > upper || !haveUpper)
{
upper = values.at(i);
haveUpper = true;
}
if (values.at(i) < lower || !haveLower)
{
lower = values.at(i);
haveLower = true;
}
}
}
// return the bounds if we found some sensible values:
if (haveLower && haveUpper && lower < upper)
{
validRange = true;
return QCPRange(lower, upper);
} else
{
validRange = false;
return QCPRange();
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemStraightLine
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemStraightLine
\brief A straight line that spans infinitely in both directions
\image html QCPItemStraightLine.png "Straight line example. Blue dotted circles are anchors, solid blue discs are positions."
It has two positions, \a point1 and \a point2, which define the straight line.
*/
/*!
Creates a straight line item and sets default values.
The constructed item can be added to the plot with QCustomPlot::addItem.
*/
QCPItemStraightLine::QCPItemStraightLine(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
point1(createPosition("point1")),
point2(createPosition("point2"))
{
point1->setCoords(0, 0);
point2->setCoords(1, 1);
setPen(QPen(Qt::black));
setSelectedPen(QPen(Qt::blue,2));
}
QCPItemStraightLine::~QCPItemStraightLine()
{
}
/*!
Sets the pen that will be used to draw the line
\see setSelectedPen
*/
void QCPItemStraightLine::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used to draw the line when selected
\see setPen, setSelected
*/
void QCPItemStraightLine::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/* inherits documentation from base class */
double QCPItemStraightLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
return distToStraightLine(QVector2D(point1->pixelPoint()), QVector2D(point2->pixelPoint()-point1->pixelPoint()), QVector2D(pos));
}
/* inherits documentation from base class */
void QCPItemStraightLine::draw(QCPPainter *painter)
{
QVector2D start(point1->pixelPoint());
QVector2D end(point2->pixelPoint());
// get visible segment of straight line inside clipRect:
double clipPad = mainPen().widthF();
QLineF line = getRectClippedStraightLine(start, end-start, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
// paint visible segment, if existent:
if (!line.isNull())
{
painter->setPen(mainPen());
painter->drawLine(line);
}
}
/*! \internal
finds the shortest distance of \a point to the straight line defined by the base point \a
base and the direction vector \a vec.
This is a helper function for \ref selectTest.
*/
double QCPItemStraightLine::distToStraightLine(const QVector2D &base, const QVector2D &vec, const QVector2D &point) const
{
return qAbs((base.y()-point.y())*vec.x()-(base.x()-point.x())*vec.y())/vec.length();
}
/*! \internal
Returns the section of the straight line defined by \a base and direction vector \a
vec, that is visible in the specified \a rect.
This is a helper function for \ref draw.
*/
QLineF QCPItemStraightLine::getRectClippedStraightLine(const QVector2D &base, const QVector2D &vec, const QRect &rect) const
{
double bx, by;
double gamma;
QLineF result;
if (vec.x() == 0 && vec.y() == 0)
return result;
if (qFuzzyIsNull(vec.x())) // line is vertical
{
// check top of rect:
bx = rect.left();
by = rect.top();
gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
if (gamma >= 0 && gamma <= rect.width())
result.setLine(bx+gamma, rect.top(), bx+gamma, rect.bottom()); // no need to check bottom because we know line is vertical
} else if (qFuzzyIsNull(vec.y())) // line is horizontal
{
// check left of rect:
bx = rect.left();
by = rect.top();
gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
if (gamma >= 0 && gamma <= rect.height())
result.setLine(rect.left(), by+gamma, rect.right(), by+gamma); // no need to check right because we know line is horizontal
} else // line is skewed
{
QList<QVector2D> pointVectors;
// check top of rect:
bx = rect.left();
by = rect.top();
gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
if (gamma >= 0 && gamma <= rect.width())
pointVectors.append(QVector2D(bx+gamma, by));
// check bottom of rect:
bx = rect.left();
by = rect.bottom();
gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
if (gamma >= 0 && gamma <= rect.width())
pointVectors.append(QVector2D(bx+gamma, by));
// check left of rect:
bx = rect.left();
by = rect.top();
gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
if (gamma >= 0 && gamma <= rect.height())
pointVectors.append(QVector2D(bx, by+gamma));
// check right of rect:
bx = rect.right();
by = rect.top();
gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
if (gamma >= 0 && gamma <= rect.height())
pointVectors.append(QVector2D(bx, by+gamma));
// evaluate points:
if (pointVectors.size() == 2)
{
result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
} else if (pointVectors.size() > 2)
{
// line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance:
double distSqrMax = 0;
QVector2D pv1, pv2;
for (int i=0; i<pointVectors.size()-1; ++i)
{
for (int k=i+1; k<pointVectors.size(); ++k)
{
double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared();
if (distSqr > distSqrMax)
{
pv1 = pointVectors.at(i);
pv2 = pointVectors.at(k);
distSqrMax = distSqr;
}
}
}
result.setPoints(pv1.toPointF(), pv2.toPointF());
}
}
return result;
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the
item is not selected and mSelectedPen when it is.
*/
QPen QCPItemStraightLine::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemLine
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemLine
\brief A line from one point to another
\image html QCPItemLine.png "Line example. Blue dotted circles are anchors, solid blue discs are positions."
It has two positions, \a start and \a end, which define the end points of the line.
With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow.
*/
/*!
Creates a line item and sets default values.
The constructed item can be added to the plot with QCustomPlot::addItem.
*/
QCPItemLine::QCPItemLine(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
start(createPosition("start")),
end(createPosition("end"))
{
start->setCoords(0, 0);
end->setCoords(1, 1);
setPen(QPen(Qt::black));
setSelectedPen(QPen(Qt::blue,2));
}
QCPItemLine::~QCPItemLine()
{
}
/*!
Sets the pen that will be used to draw the line
\see setSelectedPen
*/
void QCPItemLine::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used to draw the line when selected
\see setPen, setSelected
*/
void QCPItemLine::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/*!
Sets the line ending style of the head. The head corresponds to the \a end position.
Note that due to the overloaded QCPLineEnding constructor, you may directly specify
a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
\see setTail
*/
void QCPItemLine::setHead(const QCPLineEnding &head)
{
mHead = head;
}
/*!
Sets the line ending style of the tail. The tail corresponds to the \a start position.
Note that due to the overloaded QCPLineEnding constructor, you may directly specify
a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
\see setHead
*/
void QCPItemLine::setTail(const QCPLineEnding &tail)
{
mTail = tail;
}
/* inherits documentation from base class */
double QCPItemLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
return qSqrt(distSqrToLine(start->pixelPoint(), end->pixelPoint(), pos));
}
/* inherits documentation from base class */
void QCPItemLine::draw(QCPPainter *painter)
{
QVector2D startVec(start->pixelPoint());
QVector2D endVec(end->pixelPoint());
if (startVec.toPoint() == endVec.toPoint())
return;
// get visible segment of straight line inside clipRect:
double clipPad = qMax(mHead.boundingDistance(), mTail.boundingDistance());
clipPad = qMax(clipPad, (double)mainPen().widthF());
QLineF line = getRectClippedLine(startVec, endVec, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
// paint visible segment, if existent:
if (!line.isNull())
{
painter->setPen(mainPen());
painter->drawLine(line);
painter->setBrush(Qt::SolidPattern);
if (mTail.style() != QCPLineEnding::esNone)
mTail.draw(painter, startVec, startVec-endVec);
if (mHead.style() != QCPLineEnding::esNone)
mHead.draw(painter, endVec, endVec-startVec);
}
}
/*! \internal
Returns the section of the line defined by \a start and \a end, that is visible in the specified
\a rect.
This is a helper function for \ref draw.
*/
QLineF QCPItemLine::getRectClippedLine(const QVector2D &start, const QVector2D &end, const QRect &rect) const
{
bool containsStart = rect.contains(start.x(), start.y());
bool containsEnd = rect.contains(end.x(), end.y());
if (containsStart && containsEnd)
return QLineF(start.toPointF(), end.toPointF());
QVector2D base = start;
QVector2D vec = end-start;
double bx, by;
double gamma, mu;
QLineF result;
QList<QVector2D> pointVectors;
if (!qFuzzyIsNull(vec.y())) // line is not horizontal
{
// check top of rect:
bx = rect.left();
by = rect.top();
mu = (by-base.y())/vec.y();
if (mu >= 0 && mu <= 1)
{
gamma = base.x()-bx + mu*vec.x();
if (gamma >= 0 && gamma <= rect.width())
pointVectors.append(QVector2D(bx+gamma, by));
}
// check bottom of rect:
bx = rect.left();
by = rect.bottom();
mu = (by-base.y())/vec.y();
if (mu >= 0 && mu <= 1)
{
gamma = base.x()-bx + mu*vec.x();
if (gamma >= 0 && gamma <= rect.width())
pointVectors.append(QVector2D(bx+gamma, by));
}
}
if (!qFuzzyIsNull(vec.x())) // line is not vertical
{
// check left of rect:
bx = rect.left();
by = rect.top();
mu = (bx-base.x())/vec.x();
if (mu >= 0 && mu <= 1)
{
gamma = base.y()-by + mu*vec.y();
if (gamma >= 0 && gamma <= rect.height())
pointVectors.append(QVector2D(bx, by+gamma));
}
// check right of rect:
bx = rect.right();
by = rect.top();
mu = (bx-base.x())/vec.x();
if (mu >= 0 && mu <= 1)
{
gamma = base.y()-by + mu*vec.y();
if (gamma >= 0 && gamma <= rect.height())
pointVectors.append(QVector2D(bx, by+gamma));
}
}
if (containsStart)
pointVectors.append(start);
if (containsEnd)
pointVectors.append(end);
// evaluate points:
if (pointVectors.size() == 2)
{
result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
} else if (pointVectors.size() > 2)
{
// line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance:
double distSqrMax = 0;
QVector2D pv1, pv2;
for (int i=0; i<pointVectors.size()-1; ++i)
{
for (int k=i+1; k<pointVectors.size(); ++k)
{
double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared();
if (distSqr > distSqrMax)
{
pv1 = pointVectors.at(i);
pv2 = pointVectors.at(k);
distSqrMax = distSqr;
}
}
}
result.setPoints(pv1.toPointF(), pv2.toPointF());
}
return result;
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the
item is not selected and mSelectedPen when it is.
*/
QPen QCPItemLine::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemCurve
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemCurve
\brief A curved line from one point to another
\image html QCPItemCurve.png "Curve example. Blue dotted circles are anchors, solid blue discs are positions."
It has four positions, \a start and \a end, which define the end points of the line, and two
control points which define the direction the line exits from the start and the direction from
which it approaches the end: \a startDir and \a endDir.
With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an
arrow.
Often it is desirable for the control points to stay at fixed relative positions to the start/end
point. This can be achieved by setting the parent anchor e.g. of \a startDir simply to \a start,
and then specify the desired pixel offset with QCPItemPosition::setCoords on \a startDir.
*/
/*!
Creates a curve item and sets default values.
The constructed item can be added to the plot with QCustomPlot::addItem.
*/
QCPItemCurve::QCPItemCurve(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
start(createPosition("start")),
startDir(createPosition("startDir")),
endDir(createPosition("endDir")),
end(createPosition("end"))
{
start->setCoords(0, 0);
startDir->setCoords(0.5, 0);
endDir->setCoords(0, 0.5);
end->setCoords(1, 1);
setPen(QPen(Qt::black));
setSelectedPen(QPen(Qt::blue,2));
}
QCPItemCurve::~QCPItemCurve()
{
}
/*!
Sets the pen that will be used to draw the line
\see setSelectedPen
*/
void QCPItemCurve::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used to draw the line when selected
\see setPen, setSelected
*/
void QCPItemCurve::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/*!
Sets the line ending style of the head. The head corresponds to the \a end position.
Note that due to the overloaded QCPLineEnding constructor, you may directly specify
a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
\see setTail
*/
void QCPItemCurve::setHead(const QCPLineEnding &head)
{
mHead = head;
}
/*!
Sets the line ending style of the tail. The tail corresponds to the \a start position.
Note that due to the overloaded QCPLineEnding constructor, you may directly specify
a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
\see setHead
*/
void QCPItemCurve::setTail(const QCPLineEnding &tail)
{
mTail = tail;
}
/* inherits documentation from base class */
double QCPItemCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
QPointF startVec(start->pixelPoint());
QPointF startDirVec(startDir->pixelPoint());
QPointF endDirVec(endDir->pixelPoint());
QPointF endVec(end->pixelPoint());
QPainterPath cubicPath(startVec);
cubicPath.cubicTo(startDirVec, endDirVec, endVec);
QPolygonF polygon = cubicPath.toSubpathPolygons().first();
double minDistSqr = std::numeric_limits<double>::max();
for (int i=1; i<polygon.size(); ++i)
{
double distSqr = distSqrToLine(polygon.at(i-1), polygon.at(i), pos);
if (distSqr < minDistSqr)
minDistSqr = distSqr;
}
return qSqrt(minDistSqr);
}
/* inherits documentation from base class */
void QCPItemCurve::draw(QCPPainter *painter)
{
QPointF startVec(start->pixelPoint());
QPointF startDirVec(startDir->pixelPoint());
QPointF endDirVec(endDir->pixelPoint());
QPointF endVec(end->pixelPoint());
if (QVector2D(endVec-startVec).length() > 1e10) // too large curves cause crash
return;
QPainterPath cubicPath(startVec);
cubicPath.cubicTo(startDirVec, endDirVec, endVec);
// paint visible segment, if existent:
QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF());
QRect cubicRect = cubicPath.controlPointRect().toRect();
if (cubicRect.isEmpty()) // may happen when start and end exactly on same x or y position
cubicRect.adjust(0, 0, 1, 1);
if (clip.intersects(cubicRect))
{
painter->setPen(mainPen());
painter->drawPath(cubicPath);
painter->setBrush(Qt::SolidPattern);
if (mTail.style() != QCPLineEnding::esNone)
mTail.draw(painter, QVector2D(startVec), M_PI-cubicPath.angleAtPercent(0)/180.0*M_PI);
if (mHead.style() != QCPLineEnding::esNone)
mHead.draw(painter, QVector2D(endVec), -cubicPath.angleAtPercent(1)/180.0*M_PI);
}
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the
item is not selected and mSelectedPen when it is.
*/
QPen QCPItemCurve::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemRect
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemRect
\brief A rectangle
\image html QCPItemRect.png "Rectangle example. Blue dotted circles are anchors, solid blue discs are positions."
It has two positions, \a topLeft and \a bottomRight, which define the rectangle.
*/
/*!
Creates a rectangle item and sets default values.
The constructed item can be added to the plot with QCustomPlot::addItem.
*/
QCPItemRect::QCPItemRect(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
topLeft(createPosition("topLeft")),
bottomRight(createPosition("bottomRight")),
top(createAnchor("top", aiTop)),
topRight(createAnchor("topRight", aiTopRight)),
right(createAnchor("right", aiRight)),
bottom(createAnchor("bottom", aiBottom)),
bottomLeft(createAnchor("bottomLeft", aiBottomLeft)),
left(createAnchor("left", aiLeft))
{
topLeft->setCoords(0, 1);
bottomRight->setCoords(1, 0);
setPen(QPen(Qt::black));
setSelectedPen(QPen(Qt::blue,2));
setBrush(Qt::NoBrush);
setSelectedBrush(Qt::NoBrush);
}
QCPItemRect::~QCPItemRect()
{
}
/*!
Sets the pen that will be used to draw the line of the rectangle
\see setSelectedPen, setBrush
*/
void QCPItemRect::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used to draw the line of the rectangle when selected
\see setPen, setSelected
*/
void QCPItemRect::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/*!
Sets the brush that will be used to fill the rectangle. To disable filling, set \a brush to
Qt::NoBrush.
\see setSelectedBrush, setPen
*/
void QCPItemRect::setBrush(const QBrush &brush)
{
mBrush = brush;
}
/*!
Sets the brush that will be used to fill the rectangle when selected. To disable filling, set \a
brush to Qt::NoBrush.
\see setBrush
*/
void QCPItemRect::setSelectedBrush(const QBrush &brush)
{
mSelectedBrush = brush;
}
/* inherits documentation from base class */
double QCPItemRect::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()).normalized();
bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
return rectSelectTest(rect, pos, filledRect);
}
/* inherits documentation from base class */
void QCPItemRect::draw(QCPPainter *painter)
{
QPointF p1 = topLeft->pixelPoint();
QPointF p2 = bottomRight->pixelPoint();
if (p1.toPoint() == p2.toPoint())
return;
QRectF rect = QRectF(p1, p2).normalized();
double clipPad = mainPen().widthF();
QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
if (boundingRect.intersects(clipRect())) // only draw if bounding rect of rect item is visible in cliprect
{
painter->setPen(mainPen());
painter->setBrush(mainBrush());
painter->drawRect(rect);
}
}
/* inherits documentation from base class */
QPointF QCPItemRect::anchorPixelPoint(int anchorId) const
{
QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint());
switch (anchorId)
{
case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
case aiTopRight: return rect.topRight();
case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
case aiBottomLeft: return rect.bottomLeft();
case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;
}
qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
return QPointF();
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
and mSelectedPen when it is.
*/
QPen QCPItemRect::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
/*! \internal
Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
is not selected and mSelectedBrush when it is.
*/
QBrush QCPItemRect::mainBrush() const
{
return mSelected ? mSelectedBrush : mBrush;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemText
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemText
\brief A text label
\image html QCPItemText.png "Text example. Blue dotted circles are anchors, solid blue discs are positions."
Its position is defined by the member \a position and the setting of \ref setPositionAlignment.
The latter controls which part of the text rect shall be aligned with \a position.
The text alignment itself (i.e. left, center, right) can be controlled with \ref
setTextAlignment.
The text may be rotated around the \a position point with \ref setRotation.
*/
/*!
Creates a text item and sets default values.
The constructed item can be added to the plot with QCustomPlot::addItem.
*/
QCPItemText::QCPItemText(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
position(createPosition("position")),
topLeft(createAnchor("topLeft", aiTopLeft)),
top(createAnchor("top", aiTop)),
topRight(createAnchor("topRight", aiTopRight)),
right(createAnchor("right", aiRight)),
bottomRight(createAnchor("bottomRight", aiBottomRight)),
bottom(createAnchor("bottom", aiBottom)),
bottomLeft(createAnchor("bottomLeft", aiBottomLeft)),
left(createAnchor("left", aiLeft))
{
position->setCoords(0, 0);
setRotation(0);
setTextAlignment(Qt::AlignTop|Qt::AlignHCenter);
setPositionAlignment(Qt::AlignCenter);
setText("text");
setPen(Qt::NoPen);
setSelectedPen(Qt::NoPen);
setBrush(Qt::NoBrush);
setSelectedBrush(Qt::NoBrush);
setColor(Qt::black);
setSelectedColor(Qt::blue);
}
QCPItemText::~QCPItemText()
{
}
/*!
Sets the color of the text.
*/
void QCPItemText::setColor(const QColor &color)
{
mColor = color;
}
/*!
Sets the color of the text that will be used when the item is selected.
*/
void QCPItemText::setSelectedColor(const QColor &color)
{
mSelectedColor = color;
}
/*!
Sets the pen that will be used do draw a rectangular border around the text. To disable the
border, set \a pen to Qt::NoPen.
\see setSelectedPen, setBrush, setPadding
*/
void QCPItemText::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used do draw a rectangular border around the text, when the item is
selected. To disable the border, set \a pen to Qt::NoPen.
\see setPen
*/
void QCPItemText::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/*!
Sets the brush that will be used do fill the background of the text. To disable the
background, set \a brush to Qt::NoBrush.
\see setSelectedBrush, setPen, setPadding
*/
void QCPItemText::setBrush(const QBrush &brush)
{
mBrush = brush;
}
/*!
Sets the brush that will be used do fill the background of the text, when the item is selected. To disable the
background, set \a brush to Qt::NoBrush.
\see setBrush
*/
void QCPItemText::setSelectedBrush(const QBrush &brush)
{
mSelectedBrush = brush;
}
/*!
Sets the font of the text.
\see setSelectedFont, setColor
*/
void QCPItemText::setFont(const QFont &font)
{
mFont = font;
}
/*!
Sets the font of the text that will be used when the item is selected.
\see setFont
*/
void QCPItemText::setSelectedFont(const QFont &font)
{
mSelectedFont = font;
}
/*!
Sets the text that will be displayed. Multi-line texts are supported by inserting a line break
character, e.g. '\n'.
\see setFont, setColor, setTextAlignment
*/
void QCPItemText::setText(const QString &text)
{
mText = text;
}
/*!
Sets which point of the text rect shall be aligned with \a position.
Examples:
\li If \a alignment is <tt>Qt::AlignHCenter | Qt::AlignTop</tt>, the text will be positioned such
that the top of the text rect will be horizontally centered on \a position.
\li If \a alignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt>, \a position will indicate the
bottom left corner of the text rect.
If you want to control the alignment of (multi-lined) text within the text rect, use \ref
setTextAlignment.
*/
void QCPItemText::setPositionAlignment(Qt::Alignment alignment)
{
mPositionAlignment = alignment;
}
/*!
Controls how (multi-lined) text is aligned inside the text rect (typically Qt::AlignLeft, Qt::AlignCenter or Qt::AlignRight).
*/
void QCPItemText::setTextAlignment(Qt::Alignment alignment)
{
mTextAlignment = alignment;
}
/*!
Sets the angle in degrees by which the text (and the text rectangle, if visible) will be rotated
around \a position.
*/
void QCPItemText::setRotation(double degrees)
{
mRotation = degrees;
}
/*!
Sets the distance between the border of the text rectangle and the text. The appearance (and
visibility) of the text rectangle can be controlled with \ref setPen and \ref setBrush.
*/
void QCPItemText::setPadding(const QMargins &padding)
{
mPadding = padding;
}
/* inherits documentation from base class */
double QCPItemText::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
// The rect may be rotated, so we transform the actual clicked pos to the rotated
// coordinate system, so we can use the normal rectSelectTest function for non-rotated rects:
QPointF positionPixels(position->pixelPoint());
QTransform inputTransform;
inputTransform.translate(positionPixels.x(), positionPixels.y());
inputTransform.rotate(-mRotation);
inputTransform.translate(-positionPixels.x(), -positionPixels.y());
QPointF rotatedPos = inputTransform.map(pos);
QFontMetrics fontMetrics(mFont);
QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment);
textBoxRect.moveTopLeft(textPos.toPoint());
return rectSelectTest(textBoxRect, rotatedPos, true);
}
/* inherits documentation from base class */
void QCPItemText::draw(QCPPainter *painter)
{
QPointF pos(position->pixelPoint());
QTransform transform = painter->transform();
transform.translate(pos.x(), pos.y());
if (!qFuzzyIsNull(mRotation))
transform.rotate(mRotation);
painter->setFont(mainFont());
QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation
textRect.moveTopLeft(textPos.toPoint()+QPoint(mPadding.left(), mPadding.top()));
textBoxRect.moveTopLeft(textPos.toPoint());
double clipPad = mainPen().widthF();
QRect boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect())))
{
painter->setTransform(transform);
if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) ||
(mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0))
{
painter->setPen(mainPen());
painter->setBrush(mainBrush());
painter->drawRect(textBoxRect);
}
painter->setBrush(Qt::NoBrush);
painter->setPen(QPen(mainColor()));
painter->drawText(textRect, Qt::TextDontClip|mTextAlignment, mText);
}
}
/* inherits documentation from base class */
QPointF QCPItemText::anchorPixelPoint(int anchorId) const
{
// get actual rect points (pretty much copied from draw function):
QPointF pos(position->pixelPoint());
QTransform transform;
transform.translate(pos.x(), pos.y());
if (!qFuzzyIsNull(mRotation))
transform.rotate(mRotation);
QFontMetrics fontMetrics(mainFont());
QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
QRectF textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation
textBoxRect.moveTopLeft(textPos.toPoint());
QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect));
switch (anchorId)
{
case aiTopLeft: return rectPoly.at(0);
case aiTop: return (rectPoly.at(0)+rectPoly.at(1))*0.5;
case aiTopRight: return rectPoly.at(1);
case aiRight: return (rectPoly.at(1)+rectPoly.at(2))*0.5;
case aiBottomRight: return rectPoly.at(2);
case aiBottom: return (rectPoly.at(2)+rectPoly.at(3))*0.5;
case aiBottomLeft: return rectPoly.at(3);
case aiLeft: return (rectPoly.at(3)+rectPoly.at(0))*0.5;
}
qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
return QPointF();
}
/*! \internal
Returns the point that must be given to the QPainter::drawText function (which expects the top
left point of the text rect), according to the position \a pos, the text bounding box \a rect and
the requested \a positionAlignment.
For example, if \a positionAlignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt> the returned point
will be shifted upward by the height of \a rect, starting from \a pos. So if the text is finally
drawn at that point, the lower left corner of the resulting text rect is at \a pos.
*/
QPointF QCPItemText::getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const
{
if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft|Qt::AlignTop))
return pos;
QPointF result = pos; // start at top left
if (positionAlignment.testFlag(Qt::AlignHCenter))
result.rx() -= rect.width()/2.0;
else if (positionAlignment.testFlag(Qt::AlignRight))
result.rx() -= rect.width();
if (positionAlignment.testFlag(Qt::AlignVCenter))
result.ry() -= rect.height()/2.0;
else if (positionAlignment.testFlag(Qt::AlignBottom))
result.ry() -= rect.height();
return result;
}
/*! \internal
Returns the font that should be used for drawing text. Returns mFont when the item is not selected
and mSelectedFont when it is.
*/
QFont QCPItemText::mainFont() const
{
return mSelected ? mSelectedFont : mFont;
}
/*! \internal
Returns the color that should be used for drawing text. Returns mColor when the item is not
selected and mSelectedColor when it is.
*/
QColor QCPItemText::mainColor() const
{
return mSelected ? mSelectedColor : mColor;
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
and mSelectedPen when it is.
*/
QPen QCPItemText::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
/*! \internal
Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
is not selected and mSelectedBrush when it is.
*/
QBrush QCPItemText::mainBrush() const
{
return mSelected ? mSelectedBrush : mBrush;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemEllipse
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemEllipse
\brief An ellipse
\image html QCPItemEllipse.png "Ellipse example. Blue dotted circles are anchors, solid blue discs are positions."
It has two positions, \a topLeft and \a bottomRight, which define the rect the ellipse will be drawn in.
*/
/*!
Creates an ellipse item and sets default values.
The constructed item can be added to the plot with QCustomPlot::addItem.
*/
QCPItemEllipse::QCPItemEllipse(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
topLeft(createPosition("topLeft")),
bottomRight(createPosition("bottomRight")),
topLeftRim(createAnchor("topLeftRim", aiTopLeftRim)),
top(createAnchor("top", aiTop)),
topRightRim(createAnchor("topRightRim", aiTopRightRim)),
right(createAnchor("right", aiRight)),
bottomRightRim(createAnchor("bottomRightRim", aiBottomRightRim)),
bottom(createAnchor("bottom", aiBottom)),
bottomLeftRim(createAnchor("bottomLeftRim", aiBottomLeftRim)),
left(createAnchor("left", aiLeft)),
center(createAnchor("center", aiCenter))
{
topLeft->setCoords(0, 1);
bottomRight->setCoords(1, 0);
setPen(QPen(Qt::black));
setSelectedPen(QPen(Qt::blue, 2));
setBrush(Qt::NoBrush);
setSelectedBrush(Qt::NoBrush);
}
QCPItemEllipse::~QCPItemEllipse()
{
}
/*!
Sets the pen that will be used to draw the line of the ellipse
\see setSelectedPen, setBrush
*/
void QCPItemEllipse::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used to draw the line of the ellipse when selected
\see setPen, setSelected
*/
void QCPItemEllipse::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/*!
Sets the brush that will be used to fill the ellipse. To disable filling, set \a brush to
Qt::NoBrush.
\see setSelectedBrush, setPen
*/
void QCPItemEllipse::setBrush(const QBrush &brush)
{
mBrush = brush;
}
/*!
Sets the brush that will be used to fill the ellipse when selected. To disable filling, set \a
brush to Qt::NoBrush.
\see setBrush
*/
void QCPItemEllipse::setSelectedBrush(const QBrush &brush)
{
mSelectedBrush = brush;
}
/* inherits documentation from base class */
double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
double result = -1;
QPointF p1 = topLeft->pixelPoint();
QPointF p2 = bottomRight->pixelPoint();
QPointF center((p1+p2)/2.0);
double a = qAbs(p1.x()-p2.x())/2.0;
double b = qAbs(p1.y()-p2.y())/2.0;
double x = pos.x()-center.x();
double y = pos.y()-center.y();
// distance to border:
double c = 1.0/qSqrt(x*x/(a*a)+y*y/(b*b));
result = qAbs(c-1)*qSqrt(x*x+y*y);
// filled ellipse, allow click inside to count as hit:
if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0)
{
if (x*x/(a*a) + y*y/(b*b) <= 1)
result = mParentPlot->selectionTolerance()*0.99;
}
return result;
}
/* inherits documentation from base class */
void QCPItemEllipse::draw(QCPPainter *painter)
{
QPointF p1 = topLeft->pixelPoint();
QPointF p2 = bottomRight->pixelPoint();
if (p1.toPoint() == p2.toPoint())
return;
QRectF ellipseRect = QRectF(p1, p2).normalized();
QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF());
if (ellipseRect.intersects(clip)) // only draw if bounding rect of ellipse is visible in cliprect
{
painter->setPen(mainPen());
painter->setBrush(mainBrush());
#ifdef __EXCEPTIONS
try // drawEllipse sometimes throws exceptions if ellipse is too big
{
#endif
painter->drawEllipse(ellipseRect);
#ifdef __EXCEPTIONS
} catch (...)
{
qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible";
setVisible(false);
}
#endif
}
}
/* inherits documentation from base class */
QPointF QCPItemEllipse::anchorPixelPoint(int anchorId) const
{
QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint());
switch (anchorId)
{
case aiTopLeftRim: return rect.center()+(rect.topLeft()-rect.center())*1/qSqrt(2);
case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
case aiTopRightRim: return rect.center()+(rect.topRight()-rect.center())*1/qSqrt(2);
case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
case aiBottomRightRim: return rect.center()+(rect.bottomRight()-rect.center())*1/qSqrt(2);
case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
case aiBottomLeftRim: return rect.center()+(rect.bottomLeft()-rect.center())*1/qSqrt(2);
case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;
case aiCenter: return (rect.topLeft()+rect.bottomRight())*0.5;
}
qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
return QPointF();
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
and mSelectedPen when it is.
*/
QPen QCPItemEllipse::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
/*! \internal
Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
is not selected and mSelectedBrush when it is.
*/
QBrush QCPItemEllipse::mainBrush() const
{
return mSelected ? mSelectedBrush : mBrush;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemPixmap
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemPixmap
\brief An arbitrary pixmap
\image html QCPItemPixmap.png "Pixmap example. Blue dotted circles are anchors, solid blue discs are positions."
It has two positions, \a topLeft and \a bottomRight, which define the rectangle the pixmap will
be drawn in. Depending on the scale setting (\ref setScaled), the pixmap will be either scaled to
fit the rectangle or be drawn aligned to the topLeft position.
If scaling is enabled and \a topLeft is further to the bottom/right than \a bottomRight (as shown
on the right side of the example image), the pixmap will be flipped in the respective
orientations.
*/
/*!
Creates a rectangle item and sets default values.
The constructed item can be added to the plot with QCustomPlot::addItem.
*/
QCPItemPixmap::QCPItemPixmap(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
topLeft(createPosition("topLeft")),
bottomRight(createPosition("bottomRight")),
top(createAnchor("top", aiTop)),
topRight(createAnchor("topRight", aiTopRight)),
right(createAnchor("right", aiRight)),
bottom(createAnchor("bottom", aiBottom)),
bottomLeft(createAnchor("bottomLeft", aiBottomLeft)),
left(createAnchor("left", aiLeft))
{
topLeft->setCoords(0, 1);
bottomRight->setCoords(1, 0);
setPen(Qt::NoPen);
setSelectedPen(QPen(Qt::blue));
setScaled(false, Qt::KeepAspectRatio);
}
QCPItemPixmap::~QCPItemPixmap()
{
}
/*!
Sets the pixmap that will be displayed.
*/
void QCPItemPixmap::setPixmap(const QPixmap &pixmap)
{
mPixmap = pixmap;
if (mPixmap.isNull())
qDebug() << Q_FUNC_INFO << "pixmap is null";
}
/*!
Sets whether the pixmap will be scaled to fit the rectangle defined by the \a topLeft and \a
bottomRight positions.
*/
void QCPItemPixmap::setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode)
{
mScaled = scaled;
mAspectRatioMode = aspectRatioMode;
updateScaledPixmap();
}
/*!
Sets the pen that will be used to draw a border around the pixmap.
\see setSelectedPen, setBrush
*/
void QCPItemPixmap::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used to draw a border around the pixmap when selected
\see setPen, setSelected
*/
void QCPItemPixmap::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/* inherits documentation from base class */
double QCPItemPixmap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
return rectSelectTest(getFinalRect(), pos, true);
}
/* inherits documentation from base class */
void QCPItemPixmap::draw(QCPPainter *painter)
{
bool flipHorz = false;
bool flipVert = false;
QRect rect = getFinalRect(&flipHorz, &flipVert);
double clipPad = mainPen().style() == Qt::NoPen ? 0 : mainPen().widthF();
QRect boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
if (boundingRect.intersects(clipRect()))
{
updateScaledPixmap(rect, flipHorz, flipVert);
painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap);
QPen pen = mainPen();
if (pen.style() != Qt::NoPen)
{
painter->setPen(pen);
painter->setBrush(Qt::NoBrush);
painter->drawRect(rect);
}
}
}
/* inherits documentation from base class */
QPointF QCPItemPixmap::anchorPixelPoint(int anchorId) const
{
bool flipHorz;
bool flipVert;
QRect rect = getFinalRect(&flipHorz, &flipVert);
// we actually want denormal rects (negative width/height) here, so restore
// the flipped state:
if (flipHorz)
rect.adjust(rect.width(), 0, -rect.width(), 0);
if (flipVert)
rect.adjust(0, rect.height(), 0, -rect.height());
switch (anchorId)
{
case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
case aiTopRight: return rect.topRight();
case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
case aiBottomLeft: return rect.bottomLeft();
case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;;
}
qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
return QPointF();
}
/*! \internal
Creates the buffered scaled image (\a mScaledPixmap) to fit the specified \a finalRect. The
parameters \a flipHorz and \a flipVert control whether the resulting image shall be flipped
horizontally or vertically. (This is used when \a topLeft is further to the bottom/right than \a
bottomRight.)
This function only creates the scaled pixmap when the buffered pixmap has a different size than
the expected result, so calling this function repeatedly, e.g. in the \ref draw function, does
not cause expensive rescaling every time.
If scaling is disabled, sets mScaledPixmap to a null QPixmap.
*/
void QCPItemPixmap::updateScaledPixmap(QRect finalRect, bool flipHorz, bool flipVert)
{
if (mPixmap.isNull())
return;
if (mScaled)
{
if (finalRect.isNull())
finalRect = getFinalRect(&flipHorz, &flipVert);
if (finalRect.size() != mScaledPixmap.size())
{
mScaledPixmap = mPixmap.scaled(finalRect.size(), mAspectRatioMode, Qt::SmoothTransformation);
if (flipHorz || flipVert)
mScaledPixmap = QPixmap::fromImage(mScaledPixmap.toImage().mirrored(flipHorz, flipVert));
}
} else if (!mScaledPixmap.isNull())
mScaledPixmap = QPixmap();
}
/*! \internal
Returns the final (tight) rect the pixmap is drawn in, depending on the current item positions
and scaling settings.
The output parameters \a flippedHorz and \a flippedVert return whether the pixmap should be drawn
flipped horizontally or vertically in the returned rect. (The returned rect itself is always
normalized, i.e. the top left corner of the rect is actually further to the top/left than the
bottom right corner). This is the case when the item position \a topLeft is further to the
bottom/right than \a bottomRight.
If scaling is disabled, returns a rect with size of the original pixmap and the top left corner
aligned with the item position \a topLeft. The position \a bottomRight is ignored.
*/
QRect QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const
{
QRect result;
bool flipHorz = false;
bool flipVert = false;
QPoint p1 = topLeft->pixelPoint().toPoint();
QPoint p2 = bottomRight->pixelPoint().toPoint();
if (p1 == p2)
return QRect(p1, QSize(0, 0));
if (mScaled)
{
QSize newSize = QSize(p2.x()-p1.x(), p2.y()-p1.y());
QPoint topLeft = p1;
if (newSize.width() < 0)
{
flipHorz = true;
newSize.rwidth() *= -1;
topLeft.setX(p2.x());
}
if (newSize.height() < 0)
{
flipVert = true;
newSize.rheight() *= -1;
topLeft.setY(p2.y());
}
QSize scaledSize = mPixmap.size();
scaledSize.scale(newSize, mAspectRatioMode);
result = QRect(topLeft, scaledSize);
} else
{
result = QRect(p1, mPixmap.size());
}
if (flippedHorz)
*flippedHorz = flipHorz;
if (flippedVert)
*flippedVert = flipVert;
return result;
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
and mSelectedPen when it is.
*/
QPen QCPItemPixmap::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemTracer
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemTracer
\brief Item that sticks to QCPGraph data points
\image html QCPItemTracer.png "Tracer example. Blue dotted circles are anchors, solid blue discs are positions."
The tracer can be connected with a QCPGraph via \ref setGraph. Then it will automatically adopt
the coordinate axes of the graph and update its \a position to be on the graph's data. This means
the key stays controllable via \ref setGraphKey, but the value will follow the graph data. If a
QCPGraph is connected, note that setting the coordinates of the tracer item directly via \a
position will have no effect because they will be overriden in the next redraw (this is when the
coordinate update happens).
If the specified key in \ref setGraphKey is outside the key bounds of the graph, the tracer will
stay at the corresponding end of the graph.
With \ref setInterpolating you may specify whether the tracer may only stay exactly on data
points or whether it interpolates data points linearly, if given a key that lies between two data
points of the graph.
The tracer has different visual styles, see \ref setStyle. It is also possible to make the tracer
have no own visual appearance (set the style to \ref tsNone), and just connect other item
positions to the tracer \a position (used as an anchor) via \ref
QCPItemPosition::setParentAnchor.
\note The tracer position is only automatically updated upon redraws. So when the data of the
graph changes and immediately afterwards (without a redraw) the a position coordinates of the
tracer are retrieved, they will not reflect the updated data of the graph. In this case \ref
updatePosition must be called manually, prior to reading the tracer coordinates.
*/
/*!
Creates a tracer item and sets default values.
The constructed item can be added to the plot with QCustomPlot::addItem.
*/
QCPItemTracer::QCPItemTracer(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
position(createPosition("position")),
mGraph(0)
{
position->setCoords(0, 0);
setBrush(Qt::NoBrush);
setSelectedBrush(Qt::NoBrush);
setPen(QPen(Qt::black));
setSelectedPen(QPen(Qt::blue, 2));
setStyle(tsCrosshair);
setSize(6);
setInterpolating(false);
setGraphKey(0);
}
QCPItemTracer::~QCPItemTracer()
{
}
/*!
Sets the pen that will be used to draw the line of the tracer
\see setSelectedPen, setBrush
*/
void QCPItemTracer::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used to draw the line of the tracer when selected
\see setPen, setSelected
*/
void QCPItemTracer::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/*!
Sets the brush that will be used to draw any fills of the tracer
\see setSelectedBrush, setPen
*/
void QCPItemTracer::setBrush(const QBrush &brush)
{
mBrush = brush;
}
/*!
Sets the brush that will be used to draw any fills of the tracer, when selected.
\see setBrush, setSelected
*/
void QCPItemTracer::setSelectedBrush(const QBrush &brush)
{
mSelectedBrush = brush;
}
/*!
Sets the size of the tracer in pixels, if the style supports setting a size (e.g. \ref tsSquare
does, \ref tsCrosshair does not).
*/
void QCPItemTracer::setSize(double size)
{
mSize = size;
}
/*!
Sets the style/visual appearance of the tracer.
If you only want to use the tracer \a position as an anchor for other items, set \a style to
\ref tsNone.
*/
void QCPItemTracer::setStyle(QCPItemTracer::TracerStyle style)
{
mStyle = style;
}
/*!
Sets the QCPGraph this tracer sticks to. The tracer \a position will be set to type
QCPItemPosition::ptPlotCoords and the axes will be set to the axes of \a graph.
To free the tracer from any graph, set \a graph to 0. The tracer \a position can then be placed
freely like any other item position. This is the state the tracer will assume when its graph gets
deleted while still attached to it.
\see setGraphKey
*/
void QCPItemTracer::setGraph(QCPGraph *graph)
{
if (graph)
{
if (graph->parentPlot() == mParentPlot)
{
position->setType(QCPItemPosition::ptPlotCoords);
position->setAxes(graph->keyAxis(), graph->valueAxis());
mGraph = graph;
updatePosition();
} else
qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item";
} else
{
mGraph = 0;
}
}
/*!
Sets the key of the graph's data point the tracer will be positioned at. This is the only free
coordinate of a tracer when attached to a graph.
Depending on \ref setInterpolating, the tracer will be either positioned on the data point
closest to \a key, or will stay exactly at \a key and interpolate the value linearly.
\see setGraph, setInterpolating
*/
void QCPItemTracer::setGraphKey(double key)
{
mGraphKey = key;
}
/*!
Sets whether the value of the graph's data points shall be interpolated, when positioning the
tracer.
If \a enabled is set to false and a key is given with \ref setGraphKey, the tracer is placed on
the data point of the graph which is closest to the key, but which is not necessarily exactly
there. If \a enabled is true, the tracer will be positioned exactly at the specified key, and
the appropriate value will be interpolated from the graph's data points linearly.
\see setGraph, setGraphKey
*/
void QCPItemTracer::setInterpolating(bool enabled)
{
mInterpolating = enabled;
}
/* inherits documentation from base class */
double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
QPointF center(position->pixelPoint());
double w = mSize/2.0;
QRect clip = clipRect();
switch (mStyle)
{
case tsNone: return -1;
case tsPlus:
{
if (clipRect().intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
return qSqrt(qMin(distSqrToLine(center+QPointF(-w, 0), center+QPointF(w, 0), pos),
distSqrToLine(center+QPointF(0, -w), center+QPointF(0, w), pos)));
break;
}
case tsCrosshair:
{
return qSqrt(qMin(distSqrToLine(QPointF(clip.left(), center.y()), QPointF(clip.right(), center.y()), pos),
distSqrToLine(QPointF(center.x(), clip.top()), QPointF(center.x(), clip.bottom()), pos)));
}
case tsCircle:
{
if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
{
// distance to border:
double centerDist = QVector2D(center-pos).length();
double circleLine = w;
double result = qAbs(centerDist-circleLine);
// filled ellipse, allow click inside to count as hit:
if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0)
{
if (centerDist <= circleLine)
result = mParentPlot->selectionTolerance()*0.99;
}
return result;
}
break;
}
case tsSquare:
{
if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
{
QRectF rect = QRectF(center-QPointF(w, w), center+QPointF(w, w));
bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
return rectSelectTest(rect, pos, filledRect);
}
break;
}
}
return -1;
}
/* inherits documentation from base class */
void QCPItemTracer::draw(QCPPainter *painter)
{
updatePosition();
if (mStyle == tsNone)
return;
painter->setPen(mainPen());
painter->setBrush(mainBrush());
QPointF center(position->pixelPoint());
double w = mSize/2.0;
QRect clip = clipRect();
switch (mStyle)
{
case tsNone: return;
case tsPlus:
{
if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
{
painter->drawLine(QLineF(center+QPointF(-w, 0), center+QPointF(w, 0)));
painter->drawLine(QLineF(center+QPointF(0, -w), center+QPointF(0, w)));
}
break;
}
case tsCrosshair:
{
if (center.y() > clip.top() && center.y() < clip.bottom())
painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y()));
if (center.x() > clip.left() && center.x() < clip.right())
painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom()));
break;
}
case tsCircle:
{
if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
painter->drawEllipse(center, w, w);
break;
}
case tsSquare:
{
if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
painter->drawRect(QRectF(center-QPointF(w, w), center+QPointF(w, w)));
break;
}
}
}
/*!
If the tracer is connected with a graph (\ref setGraph), this function updates the tracer's \a
position to reside on the graph data, depending on the configured key (\ref setGraphKey).
It is called automatically on every redraw and normally doesn't need to be called manually. One
exception is when you want to read the tracer coordinates via \a position and are not sure that
the graph's data (or the tracer key with \ref setGraphKey) hasn't changed since the last redraw.
In that situation, call this function before accessing \a position, to make sure you don't get
out-of-date coordinates.
If there is no graph set on this tracer, this function does nothing.
*/
void QCPItemTracer::updatePosition()
{
if (mGraph)
{
if (mParentPlot->hasPlottable(mGraph))
{
if (mGraph->data()->size() > 1)
{
QCPDataMap::const_iterator first = mGraph->data()->constBegin();
QCPDataMap::const_iterator last = mGraph->data()->constEnd()-1;
if (mGraphKey < first.key())
position->setCoords(first.key(), first.value().value);
else if (mGraphKey > last.key())
position->setCoords(last.key(), last.value().value);
else
{
QCPDataMap::const_iterator it = mGraph->data()->lowerBound(mGraphKey);
if (it != first) // mGraphKey is somewhere between iterators
{
QCPDataMap::const_iterator prevIt = it-1;
if (mInterpolating)
{
// interpolate between iterators around mGraphKey:
double slope = 0;
if (!qFuzzyCompare((double)it.key(), (double)prevIt.key()))
slope = (it.value().value-prevIt.value().value)/(it.key()-prevIt.key());
position->setCoords(mGraphKey, (mGraphKey-prevIt.key())*slope+prevIt.value().value);
} else
{
// find iterator with key closest to mGraphKey:
if (mGraphKey < (prevIt.key()+it.key())*0.5)
it = prevIt;
position->setCoords(it.key(), it.value().value);
}
} else // mGraphKey is exactly on first iterator
position->setCoords(it.key(), it.value().value);
}
} else if (mGraph->data()->size() == 1)
{
QCPDataMap::const_iterator it = mGraph->data()->constBegin();
position->setCoords(it.key(), it.value().value);
} else
qDebug() << Q_FUNC_INFO << "graph has no data";
} else
qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)";
}
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
and mSelectedPen when it is.
*/
QPen QCPItemTracer::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
/*! \internal
Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
is not selected and mSelectedBrush when it is.
*/
QBrush QCPItemTracer::mainBrush() const
{
return mSelected ? mSelectedBrush : mBrush;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemBracket
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPItemBracket
\brief A bracket for referencing/highlighting certain parts in the plot.
\image html QCPItemBracket.png "Bracket example. Blue dotted circles are anchors, solid blue discs are positions."
It has two positions, \a left and \a right, which define the span of the bracket. If \a left is
actually farther to the left than \a right, the bracket is opened to the bottom, as shown in the
example image.
The bracket supports multiple styles via \ref setStyle. The length, i.e. how far the bracket
stretches away from the embraced span, can be controlled with \ref setLength.
\image html QCPItemBracket-length.png
<center>Demonstrating the effect of different values for \ref setLength, for styles \ref
bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
It provides an anchor \a center, to allow connection of other items, e.g. an arrow (QCPItemLine
or QCPItemCurve) or a text label (QCPItemText), to the bracket.
*/
/*!
Creates a bracket item and sets default values.
The constructed item can be added to the plot with QCustomPlot::addItem.
*/
QCPItemBracket::QCPItemBracket(QCustomPlot *parentPlot) :
QCPAbstractItem(parentPlot),
left(createPosition("left")),
right(createPosition("right")),
center(createAnchor("center", aiCenter))
{
left->setCoords(0, 0);
right->setCoords(1, 1);
setPen(QPen(Qt::black));
setSelectedPen(QPen(Qt::blue, 2));
setLength(8);
setStyle(bsCalligraphic);
}
QCPItemBracket::~QCPItemBracket()
{
}
/*!
Sets the pen that will be used to draw the bracket.
Note that when the style is \ref bsCalligraphic, only the color will be taken from the pen, the
stroke and width are ignored. To change the apparent stroke width of a calligraphic bracket, use
\ref setLength, which has a similar effect.
\see setSelectedPen
*/
void QCPItemBracket::setPen(const QPen &pen)
{
mPen = pen;
}
/*!
Sets the pen that will be used to draw the bracket when selected
\see setPen, setSelected
*/
void QCPItemBracket::setSelectedPen(const QPen &pen)
{
mSelectedPen = pen;
}
/*!
Sets the \a length in pixels how far the bracket extends in the direction towards the embraced
span of the bracket (i.e. perpendicular to the <i>left</i>-<i>right</i>-direction)
\image html QCPItemBracket-length.png
<center>Demonstrating the effect of different values for \ref setLength, for styles \ref
bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
*/
void QCPItemBracket::setLength(double length)
{
mLength = length;
}
/*!
Sets the style of the bracket, i.e. the shape/visual appearance.
\see setPen
*/
void QCPItemBracket::setStyle(QCPItemBracket::BracketStyle style)
{
mStyle = style;
}
/* inherits documentation from base class */
double QCPItemBracket::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
QVector2D leftVec(left->pixelPoint());
QVector2D rightVec(right->pixelPoint());
if (leftVec.toPoint() == rightVec.toPoint())
return -1;
QVector2D widthVec = (rightVec-leftVec)*0.5;
QVector2D lengthVec(-widthVec.y(), widthVec.x());
lengthVec = lengthVec.normalized()*mLength;
QVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
return qSqrt(distSqrToLine((centerVec-widthVec).toPointF(), (centerVec+widthVec).toPointF(), pos));
}
/* inherits documentation from base class */
void QCPItemBracket::draw(QCPPainter *painter)
{
QVector2D leftVec(left->pixelPoint());
QVector2D rightVec(right->pixelPoint());
if (leftVec.toPoint() == rightVec.toPoint())
return;
QVector2D widthVec = (rightVec-leftVec)*0.5;
QVector2D lengthVec(-widthVec.y(), widthVec.x());
lengthVec = lengthVec.normalized()*mLength;
QVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
QPolygon boundingPoly;
boundingPoly << leftVec.toPoint() << rightVec.toPoint()
<< (rightVec-lengthVec).toPoint() << (leftVec-lengthVec).toPoint();
QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF());
if (clip.intersects(boundingPoly.boundingRect()))
{
painter->setPen(mainPen());
switch (mStyle)
{
case bsSquare:
{
painter->drawLine((centerVec+widthVec).toPointF(), (centerVec-widthVec).toPointF());
painter->drawLine((centerVec+widthVec).toPointF(), (centerVec+widthVec+lengthVec).toPointF());
painter->drawLine((centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
break;
}
case bsRound:
{
painter->setBrush(Qt::NoBrush);
QPainterPath path;
path.moveTo((centerVec+widthVec+lengthVec).toPointF());
path.cubicTo((centerVec+widthVec).toPointF(), (centerVec+widthVec).toPointF(), centerVec.toPointF());
path.cubicTo((centerVec-widthVec).toPointF(), (centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
painter->drawPath(path);
break;
}
case bsCurly:
{
painter->setBrush(Qt::NoBrush);
QPainterPath path;
path.moveTo((centerVec+widthVec+lengthVec).toPointF());
path.cubicTo((centerVec+widthVec*1-lengthVec*0.8).toPointF(), (centerVec+0.4*widthVec+1*lengthVec).toPointF(), centerVec.toPointF());
path.cubicTo((centerVec-0.4*widthVec+1*lengthVec).toPointF(), (centerVec-widthVec*1-lengthVec*0.8).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
painter->drawPath(path);
break;
}
case bsCalligraphic:
{
painter->setPen(Qt::NoPen);
painter->setBrush(QBrush(mainPen().color()));
QPainterPath path;
path.moveTo((centerVec+widthVec+lengthVec).toPointF());
path.cubicTo((centerVec+widthVec*1-lengthVec*0.8).toPointF(), (centerVec+0.4*widthVec+0.8*lengthVec).toPointF(), centerVec.toPointF());
path.cubicTo((centerVec-0.4*widthVec+0.8*lengthVec).toPointF(), (centerVec-widthVec*1-lengthVec*0.8).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
path.cubicTo((centerVec-widthVec*1-lengthVec*0.5).toPointF(), (centerVec-0.2*widthVec+1.2*lengthVec).toPointF(), (centerVec+lengthVec*0.2).toPointF());
path.cubicTo((centerVec+0.2*widthVec+1.2*lengthVec).toPointF(), (centerVec+widthVec*1-lengthVec*0.5).toPointF(), (centerVec+widthVec+lengthVec).toPointF());
painter->drawPath(path);
break;
}
}
}
}
/* inherits documentation from base class */
QPointF QCPItemBracket::anchorPixelPoint(int anchorId) const
{
QVector2D leftVec(left->pixelPoint());
QVector2D rightVec(right->pixelPoint());
if (leftVec.toPoint() == rightVec.toPoint())
return leftVec.toPointF();
QVector2D widthVec = (rightVec-leftVec)*0.5;
QVector2D lengthVec(-widthVec.y(), widthVec.x());
lengthVec = lengthVec.normalized()*mLength;
QVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
switch (anchorId)
{
case aiCenter:
return centerVec.toPointF();
}
qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
return QPointF();
}
/*! \internal
Returns the pen that should be used for drawing lines. Returns mPen when the
item is not selected and mSelectedPen when it is.
*/
QPen QCPItemBracket::mainPen() const
{
return mSelected ? mSelectedPen : mPen;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAxisRect
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAxisRect
\brief Holds multiple axes and arranges them in a rectangular shape.
This class represents an axis rect, a rectangular area that is bounded on all sides with an
arbitrary number of axes.
Initially QCustomPlot has one axis rect, accessible via QCustomPlot::axisRect(). However, the
layout system allows to have multiple axis rects, e.g. arranged in a grid layout
(QCustomPlot::plotLayout).
By default, QCPAxisRect comes with four axes, at bottom, top, left and right. They can be
accessed via \ref axis by providing the respective axis type (\ref QCPAxis::AxisType) and index.
If you need all axes in the axis rect, use \ref axes. The top and right axes are set to be
invisible initially (QCPAxis::setVisible). To add more axes to a side, use \ref addAxis or \ref
addAxes. To remove an axis, use \ref removeAxis.
The axis rect layerable itself only draws a background pixmap or color, if specified (\ref
setBackground). It is placed on the "background" layer initially (see \ref QCPLayer for an
explanation of the QCustomPlot layer system). The axes that are held by the axis rect can be
placed on other layers, independently of the axis rect.
Every axis rect has a child layout of type \ref QCPLayoutInset. It is accessible via \ref
insetLayout and can be used to have other layout elements (or even other layouts with multiple
elements) hovering inside the axis rect.
If an axis rect is clicked and dragged, it processes this by moving certain axis ranges. The
behaviour can be controlled with \ref setRangeDrag and \ref setRangeDragAxes. If the mouse wheel
is scrolled while the cursor is on the axis rect, certain axes are scaled. This is controllable
via \ref setRangeZoom, \ref setRangeZoomAxes and \ref setRangeZoomFactor. These interactions are
only enabled if \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag and \ref
QCP::iRangeZoom.
\image html AxisRectSpacingOverview.png
<center>Overview of the spacings and paddings that define the geometry of an axis. The dashed
line on the far left indicates the viewport/widget border.</center>
*/
/* start documentation of inline functions */
/*! \fn QCPLayoutInset *QCPAxisRect::insetLayout() const
Returns the inset layout of this axis rect. It can be used to place other layout elements (or
even layouts with multiple other elements) inside/on top of an axis rect.
\see QCPLayoutInset
*/
/*! \fn int QCPAxisRect::left() const
Returns the pixel position of the left border of this axis rect. Margins are not taken into
account here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn int QCPAxisRect::right() const
Returns the pixel position of the right border of this axis rect. Margins are not taken into
account here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn int QCPAxisRect::top() const
Returns the pixel position of the top border of this axis rect. Margins are not taken into
account here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn int QCPAxisRect::bottom() const
Returns the pixel position of the bottom border of this axis rect. Margins are not taken into
account here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn int QCPAxisRect::width() const
Returns the pixel width of this axis rect. Margins are not taken into account here, so the
returned value is with respect to the inner \ref rect.
*/
/*! \fn int QCPAxisRect::height() const
Returns the pixel height of this axis rect. Margins are not taken into account here, so the
returned value is with respect to the inner \ref rect.
*/
/*! \fn QSize QCPAxisRect::size() const
Returns the pixel size of this axis rect. Margins are not taken into account here, so the
returned value is with respect to the inner \ref rect.
*/
/*! \fn QPoint QCPAxisRect::topLeft() const
Returns the top left corner of this axis rect in pixels. Margins are not taken into account here,
so the returned value is with respect to the inner \ref rect.
*/
/*! \fn QPoint QCPAxisRect::topRight() const
Returns the top right corner of this axis rect in pixels. Margins are not taken into account
here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn QPoint QCPAxisRect::bottomLeft() const
Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account
here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn QPoint QCPAxisRect::bottomRight() const
Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account
here, so the returned value is with respect to the inner \ref rect.
*/
/*! \fn QPoint QCPAxisRect::center() const
Returns the center of this axis rect in pixels. Margins are not taken into account here, so the
returned value is with respect to the inner \ref rect.
*/
/* end documentation of inline functions */
/*!
Creates a QCPAxisRect instance and sets default values. An axis is added for each of the four
sides, the top and right axes are set invisible initially.
*/
QCPAxisRect::QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes) :
QCPLayoutElement(parentPlot),
mBackgroundBrush(Qt::NoBrush),
mBackgroundScaled(true),
mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
mInsetLayout(new QCPLayoutInset),
mRangeDrag(Qt::Horizontal|Qt::Vertical),
mRangeZoom(Qt::Horizontal|Qt::Vertical),
mRangeZoomFactorHorz(0.85),
mRangeZoomFactorVert(0.85),
mDragging(false)
{
mInsetLayout->initializeParentPlot(mParentPlot);
mInsetLayout->setParentLayerable(this);
mInsetLayout->setParent(this);
setMinimumSize(50, 50);
setMinimumMargins(QMargins(15, 15, 15, 15));
mAxes.insert(QCPAxis::atLeft, QList<QCPAxis*>());
mAxes.insert(QCPAxis::atRight, QList<QCPAxis*>());
mAxes.insert(QCPAxis::atTop, QList<QCPAxis*>());
mAxes.insert(QCPAxis::atBottom, QList<QCPAxis*>());
if (setupDefaultAxes)
{
QCPAxis *xAxis = addAxis(QCPAxis::atBottom);
QCPAxis *yAxis = addAxis(QCPAxis::atLeft);
QCPAxis *xAxis2 = addAxis(QCPAxis::atTop);
QCPAxis *yAxis2 = addAxis(QCPAxis::atRight);
setRangeDragAxes(xAxis, yAxis);
setRangeZoomAxes(xAxis, yAxis);
xAxis2->setVisible(false);
yAxis2->setVisible(false);
xAxis->grid()->setVisible(true);
yAxis->grid()->setVisible(true);
xAxis2->grid()->setVisible(false);
yAxis2->grid()->setVisible(false);
xAxis2->grid()->setZeroLinePen(Qt::NoPen);
yAxis2->grid()->setZeroLinePen(Qt::NoPen);
xAxis2->grid()->setVisible(false);
yAxis2->grid()->setVisible(false);
}
}
QCPAxisRect::~QCPAxisRect()
{
delete mInsetLayout;
mInsetLayout = 0;
QList<QCPAxis*> axesList = axes();
for (int i=0; i<axesList.size(); ++i)
removeAxis(axesList.at(i));
}
/*!
Returns the number of axes on the axis rect side specified with \a type.
\see axis
*/
int QCPAxisRect::axisCount(QCPAxis::AxisType type) const
{
return mAxes.value(type).size();
}
/*!
Returns the axis with the given \a index on the axis rect side specified with \a type.
\see axisCount, axes
*/
QCPAxis *QCPAxisRect::axis(QCPAxis::AxisType type, int index) const
{
QList<QCPAxis*> ax(mAxes.value(type));
if (index >= 0 && index < ax.size())
{
return ax.at(index);
} else
{
qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index;
return 0;
}
}
/*!
Returns all axes on the axis rect sides specified with \a types.
\a types may be a single \ref QCPAxis::AxisType or an <tt>or</tt>-combination, to get the axes of
multiple sides.
\see axis
*/
QList<QCPAxis*> QCPAxisRect::axes(QCPAxis::AxisTypes types) const
{
QList<QCPAxis*> result;
if (types.testFlag(QCPAxis::atLeft))
result << mAxes.value(QCPAxis::atLeft);
if (types.testFlag(QCPAxis::atRight))
result << mAxes.value(QCPAxis::atRight);
if (types.testFlag(QCPAxis::atTop))
result << mAxes.value(QCPAxis::atTop);
if (types.testFlag(QCPAxis::atBottom))
result << mAxes.value(QCPAxis::atBottom);
return result;
}
/*! \overload
Returns all axes of this axis rect.
*/
QList<QCPAxis*> QCPAxisRect::axes() const
{
QList<QCPAxis*> result;
QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes);
while (it.hasNext())
{
it.next();
result << it.value();
}
return result;
}
/*!
Adds a new axis to the axis rect side specified with \a type, and returns it.
If an axis rect side already contains one or more axes, the lower and upper endings of the new
axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are initialized to \ref
QCPLineEnding::esHalfBar.
\see addAxes, setupFullAxesBox
*/
QCPAxis *QCPAxisRect::addAxis(QCPAxis::AxisType type)
{
QCPAxis *newAxis = new QCPAxis(this, type);
if (mAxes[type].size() > 0) // multiple axes on one side, add half-bar axis ending to additional axes with offset
{
bool invert = (type == QCPAxis::atRight) || (type == QCPAxis::atBottom);
newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, !invert));
newAxis->setUpperEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, invert));
}
mAxes[type].append(newAxis);
return newAxis;
}
/*!
Adds a new axis with \ref addAxis to each axis rect side specified in \a types. This may be an
<tt>or</tt>-combination of QCPAxis::AxisType, so axes can be added to multiple sides at once.
Returns a list of the added axes.
\see addAxis, setupFullAxesBox
*/
QList<QCPAxis*> QCPAxisRect::addAxes(QCPAxis::AxisTypes types)
{
QList<QCPAxis*> result;
if (types.testFlag(QCPAxis::atLeft))
result << addAxis(QCPAxis::atLeft);
if (types.testFlag(QCPAxis::atRight))
result << addAxis(QCPAxis::atRight);
if (types.testFlag(QCPAxis::atTop))
result << addAxis(QCPAxis::atTop);
if (types.testFlag(QCPAxis::atBottom))
result << addAxis(QCPAxis::atBottom);
return result;
}
/*!
Removes the specified \a axis from the axis rect and deletes it.
Returns true on success, i.e. if \a axis was a valid axis in this axis rect.
\see addAxis
*/
bool QCPAxisRect::removeAxis(QCPAxis *axis)
{
// don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis containers:
QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes);
while (it.hasNext())
{
it.next();
if (it.value().contains(axis))
{
mAxes[it.key()].removeOne(axis);
if (qobject_cast<QCustomPlot*>(parentPlot())) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the axis rect is not in any layout and thus QObject-child of QCustomPlot)
parentPlot()->axisRemoved(axis);
delete axis;
return true;
}
}
qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast<quintptr>(axis);
return false;
}
/*!
Convenience function to create an axis on each side that doesn't have any axes yet and set their
visibility to true. Further, the top/right axes are assigned the following properties of the
bottom/left axes:
\li range (\ref QCPAxis::setRange)
\li range reversed (\ref QCPAxis::setRangeReversed)
\li scale type (\ref QCPAxis::setScaleType)
\li scale log base (\ref QCPAxis::setScaleLogBase)
\li ticks (\ref QCPAxis::setTicks)
\li auto (major) tick count (\ref QCPAxis::setAutoTickCount)
\li sub tick count (\ref QCPAxis::setSubTickCount)
\li auto sub ticks (\ref QCPAxis::setAutoSubTicks)
\li tick step (\ref QCPAxis::setTickStep)
\li auto tick step (\ref QCPAxis::setAutoTickStep)
\li number format (\ref QCPAxis::setNumberFormat)
\li number precision (\ref QCPAxis::setNumberPrecision)
\li tick label type (\ref QCPAxis::setTickLabelType)
\li date time format (\ref QCPAxis::setDateTimeFormat)
\li date time spec (\ref QCPAxis::setDateTimeSpec)
Tick labels (\ref QCPAxis::setTickLabels) of the right and top axes are set to false.
If \a connectRanges is true, the \ref QCPAxis::rangeChanged "rangeChanged" signals of the bottom
and left axes are connected to the \ref QCPAxis::setRange slots of the top and right axes.
*/
void QCPAxisRect::setupFullAxesBox(bool connectRanges)
{
QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2;
if (axisCount(QCPAxis::atBottom) == 0)
xAxis = addAxis(QCPAxis::atBottom);
else
xAxis = axis(QCPAxis::atBottom);
if (axisCount(QCPAxis::atLeft) == 0)
yAxis = addAxis(QCPAxis::atLeft);
else
yAxis = axis(QCPAxis::atLeft);
if (axisCount(QCPAxis::atTop) == 0)
xAxis2 = addAxis(QCPAxis::atTop);
else
xAxis2 = axis(QCPAxis::atTop);
if (axisCount(QCPAxis::atRight) == 0)
yAxis2 = addAxis(QCPAxis::atRight);
else
yAxis2 = axis(QCPAxis::atRight);
xAxis->setVisible(true);
yAxis->setVisible(true);
xAxis2->setVisible(true);
yAxis2->setVisible(true);
xAxis2->setTickLabels(false);
yAxis2->setTickLabels(false);
xAxis2->setRange(xAxis->range());
xAxis2->setRangeReversed(xAxis->rangeReversed());
xAxis2->setScaleType(xAxis->scaleType());
xAxis2->setScaleLogBase(xAxis->scaleLogBase());
xAxis2->setTicks(xAxis->ticks());
xAxis2->setAutoTickCount(xAxis->autoTickCount());
xAxis2->setSubTickCount(xAxis->subTickCount());
xAxis2->setAutoSubTicks(xAxis->autoSubTicks());
xAxis2->setTickStep(xAxis->tickStep());
xAxis2->setAutoTickStep(xAxis->autoTickStep());
xAxis2->setNumberFormat(xAxis->numberFormat());
xAxis2->setNumberPrecision(xAxis->numberPrecision());
xAxis2->setTickLabelType(xAxis->tickLabelType());
xAxis2->setDateTimeFormat(xAxis->dateTimeFormat());
xAxis2->setDateTimeSpec(xAxis->dateTimeSpec());
yAxis2->setRange(yAxis->range());
yAxis2->setRangeReversed(yAxis->rangeReversed());
yAxis2->setScaleType(yAxis->scaleType());
yAxis2->setScaleLogBase(yAxis->scaleLogBase());
yAxis2->setTicks(yAxis->ticks());
yAxis2->setAutoTickCount(yAxis->autoTickCount());
yAxis2->setSubTickCount(yAxis->subTickCount());
yAxis2->setAutoSubTicks(yAxis->autoSubTicks());
yAxis2->setTickStep(yAxis->tickStep());
yAxis2->setAutoTickStep(yAxis->autoTickStep());
yAxis2->setNumberFormat(yAxis->numberFormat());
yAxis2->setNumberPrecision(yAxis->numberPrecision());
yAxis2->setTickLabelType(yAxis->tickLabelType());
yAxis2->setDateTimeFormat(yAxis->dateTimeFormat());
yAxis2->setDateTimeSpec(yAxis->dateTimeSpec());
if (connectRanges)
{
connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange)));
connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange)));
}
}
/*!
Returns a list of all the plottables that are associated with this axis rect.
A plottable is considered associated with an axis rect if its key or value axis (or both) is in
this axis rect.
\see graphs, items
*/
QList<QCPAbstractPlottable*> QCPAxisRect::plottables() const
{
// Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate entries
QList<QCPAbstractPlottable*> result;
for (int i=0; i<mParentPlot->mPlottables.size(); ++i)
{
if (mParentPlot->mPlottables.at(i)->keyAxis()->axisRect() == this ||mParentPlot->mPlottables.at(i)->valueAxis()->axisRect() == this)
result.append(mParentPlot->mPlottables.at(i));
}
return result;
}
/*!
Returns a list of all the graphs that are associated with this axis rect.
A graph is considered associated with an axis rect if its key or value axis (or both) is in
this axis rect.
\see plottables, items
*/
QList<QCPGraph*> QCPAxisRect::graphs() const
{
// Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries
QList<QCPGraph*> result;
for (int i=0; i<mParentPlot->mGraphs.size(); ++i)
{
if (mParentPlot->mGraphs.at(i)->keyAxis()->axisRect() == this || mParentPlot->mGraphs.at(i)->valueAxis()->axisRect() == this)
result.append(mParentPlot->mGraphs.at(i));
}
return result;
}
/*!
Returns a list of all the items that are associated with this axis rect.
An item is considered associated with an axis rect if any of its positions has key or value axis
set to an axis that is in this axis rect, or if any of its positions has \ref
QCPItemPosition::setAxisRect set to the axis rect, or if the clip axis rect (\ref
QCPAbstractItem::setClipAxisRect) is set to this axis rect.
\see plottables, graphs
*/
QList<QCPAbstractItem *> QCPAxisRect::items() const
{
// Note: don't just append all QCPAxis::items() into a list, because we might get duplicate entries
// and miss those items that have this axis rect as clipAxisRect.
QList<QCPAbstractItem*> result;
for (int itemId=0; itemId<mParentPlot->mItems.size(); ++itemId)
{
if (mParentPlot->mItems.at(itemId)->clipAxisRect() == this)
{
result.append(mParentPlot->mItems.at(itemId));
continue;
}
QList<QCPItemPosition*> positions = mParentPlot->mItems.at(itemId)->positions();
for (int posId=0; posId<positions.size(); ++posId)
{
if (positions.at(posId)->axisRect() == this ||
positions.at(posId)->keyAxis()->axisRect() == this ||
positions.at(posId)->valueAxis()->axisRect() == this)
{
result.append(mParentPlot->mItems.at(itemId));
break;
}
}
}
return result;
}
/*!
This method is called automatically upon replot and doesn't need to be called by users of
QCPAxisRect.
Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update),
and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its
QCPInsetLayout::update function.
*/
void QCPAxisRect::update()
{
QCPLayoutElement::update();
// pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout):
mInsetLayout->setOuterRect(rect());
mInsetLayout->update();
}
/* inherits documentation from base class */
QList<QCPLayoutElement*> QCPAxisRect::elements(bool recursive) const
{
QList<QCPLayoutElement*> result;
if (mInsetLayout)
{
result << mInsetLayout;
if (recursive)
result << mInsetLayout->elements(recursive);
}
return result;
}
/* inherits documentation from base class */
void QCPAxisRect::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
painter->setAntialiasing(false);
}
/* inherits documentation from base class */
void QCPAxisRect::draw(QCPPainter *painter)
{
drawBackground(painter);
}
/*!
Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the
axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect
backgrounds are usually drawn below everything else.
For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be
enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio
is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
consider using the overloaded version of this function.
Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref
setBackground(const QBrush &brush).
\see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush)
*/
void QCPAxisRect::setBackground(const QPixmap &pm)
{
mBackgroundPixmap = pm;
mScaledBackgroundPixmap = QPixmap();
}
/*! \overload
Sets \a brush as the background brush. The axis rect background will be filled with this brush.
Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds
are usually drawn below everything else.
The brush will be drawn before (under) any background pixmap, which may be specified with \ref
setBackground(const QPixmap &pm).
To disable drawing of a background brush, set \a brush to Qt::NoBrush.
\see setBackground(const QPixmap &pm)
*/
void QCPAxisRect::setBackground(const QBrush &brush)
{
mBackgroundBrush = brush;
}
/*! \overload
Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it
shall be scaled in one call.
\see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
*/
void QCPAxisRect::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
{
mBackgroundPixmap = pm;
mScaledBackgroundPixmap = QPixmap();
mBackgroundScaled = scaled;
mBackgroundScaledMode = mode;
}
/*!
Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled
is set to true, you may control whether and how the aspect ratio of the original pixmap is
preserved with \ref setBackgroundScaledMode.
Note that the scaled version of the original pixmap is buffered, so there is no performance
penalty on replots. (Except when the axis rect dimensions are changed continuously.)
\see setBackground, setBackgroundScaledMode
*/
void QCPAxisRect::setBackgroundScaled(bool scaled)
{
mBackgroundScaled = scaled;
}
/*!
If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to
define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved.
\see setBackground, setBackgroundScaled
*/
void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode)
{
mBackgroundScaledMode = mode;
}
/*!
Returns the range drag axis of the \a orientation provided.
\see setRangeDragAxes
*/
QCPAxis *QCPAxisRect::rangeDragAxis(Qt::Orientation orientation)
{
return (orientation == Qt::Horizontal ? mRangeDragHorzAxis.data() : mRangeDragVertAxis.data());
}
/*!
Returns the range zoom axis of the \a orientation provided.
\see setRangeZoomAxes
*/
QCPAxis *QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation)
{
return (orientation == Qt::Horizontal ? mRangeZoomHorzAxis.data() : mRangeZoomVertAxis.data());
}
/*!
Returns the range zoom factor of the \a orientation provided.
\see setRangeZoomFactor
*/
double QCPAxisRect::rangeZoomFactor(Qt::Orientation orientation)
{
return (orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert);
}
/*!
Sets which axis orientation may be range dragged by the user with mouse interaction.
What orientation corresponds to which specific axis can be set with
\ref setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical). By
default, the horizontal axis is the bottom axis (xAxis) and the vertical axis
is the left axis (yAxis).
To disable range dragging entirely, pass 0 as \a orientations or remove \ref QCP::iRangeDrag from \ref
QCustomPlot::setInteractions. To enable range dragging for both directions, pass <tt>Qt::Horizontal |
Qt::Vertical</tt> as \a orientations.
In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions
contains \ref QCP::iRangeDrag to enable the range dragging interaction.
\see setRangeZoom, setRangeDragAxes, setNoAntialiasingOnDrag
*/
void QCPAxisRect::setRangeDrag(Qt::Orientations orientations)
{
mRangeDrag = orientations;
}
/*!
Sets which axis orientation may be zoomed by the user with the mouse wheel. What orientation
corresponds to which specific axis can be set with \ref setRangeZoomAxes(QCPAxis *horizontal,
QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical
axis is the left axis (yAxis).
To disable range zooming entirely, pass 0 as \a orientations or remove \ref QCP::iRangeZoom from \ref
QCustomPlot::setInteractions. To enable range zooming for both directions, pass <tt>Qt::Horizontal |
Qt::Vertical</tt> as \a orientations.
In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions
contains \ref QCP::iRangeZoom to enable the range zooming interaction.
\see setRangeZoomFactor, setRangeZoomAxes, setRangeDrag
*/
void QCPAxisRect::setRangeZoom(Qt::Orientations orientations)
{
mRangeZoom = orientations;
}
/*!
Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging
on the QCustomPlot widget.
\see setRangeZoomAxes
*/
void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical)
{
mRangeDragHorzAxis = horizontal;
mRangeDragVertAxis = vertical;
}
/*!
Sets the axes whose range will be zoomed when \ref setRangeZoom enables mouse wheel zooming on the
QCustomPlot widget. The two axes can be zoomed with different strengths, when different factors
are passed to \ref setRangeZoomFactor(double horizontalFactor, double verticalFactor).
\see setRangeDragAxes
*/
void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical)
{
mRangeZoomHorzAxis = horizontal;
mRangeZoomVertAxis = vertical;
}
/*!
Sets how strong one rotation step of the mouse wheel zooms, when range zoom was activated with
\ref setRangeZoom. The two parameters \a horizontalFactor and \a verticalFactor provide a way to
let the horizontal axis zoom at different rates than the vertical axis. Which axis is horizontal
and which is vertical, can be set with \ref setRangeZoomAxes.
When the zoom factor is greater than one, scrolling the mouse wheel backwards (towards the user)
will zoom in (make the currently visible range smaller). For zoom factors smaller than one, the
same scrolling direction will zoom out.
*/
void QCPAxisRect::setRangeZoomFactor(double horizontalFactor, double verticalFactor)
{
mRangeZoomFactorHorz = horizontalFactor;
mRangeZoomFactorVert = verticalFactor;
}
/*! \overload
Sets both the horizontal and vertical zoom \a factor.
*/
void QCPAxisRect::setRangeZoomFactor(double factor)
{
mRangeZoomFactorHorz = factor;
mRangeZoomFactorVert = factor;
}
/*! \internal
Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a
pixmap.
If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an
according filling inside the axis rect with the provided \a painter.
Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version
depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
the axis rect with the provided \a painter. The scaled version is buffered in
mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
the axis rect has changed in a way that requires a rescale of the background pixmap (this is
dependant on the \ref setBackgroundScaledMode), or when a differend axis backgroud pixmap was
set.
\see setBackground, setBackgroundScaled, setBackgroundScaledMode
*/
void QCPAxisRect::drawBackground(QCPPainter *painter)
{
// draw background fill:
if (mBackgroundBrush != Qt::NoBrush)
painter->fillRect(mRect, mBackgroundBrush);
// draw background pixmap (on top of fill, if brush specified):
if (!mBackgroundPixmap.isNull())
{
if (mBackgroundScaled)
{
// check whether mScaledBackground needs to be updated:
QSize scaledSize(mBackgroundPixmap.size());
scaledSize.scale(mRect.size(), mBackgroundScaledMode);
if (mScaledBackgroundPixmap.size() != scaledSize)
mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
painter->drawPixmap(mRect.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect());
} else
{
painter->drawPixmap(mRect.topLeft(), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()));
}
}
}
/*! \internal
This function makes sure multiple axes on the side specified with \a type don't collide, but are
distributed according to their respective space requirement (QCPAxis::calculateMargin).
It does this by setting an appropriate offset (\ref QCPAxis::setOffset) on all axes except the
one with index zero.
This function is called by \ref calculateAutoMargin.
*/
void QCPAxisRect::updateAxesOffset(QCPAxis::AxisType type)
{
const QList<QCPAxis*> axesList = mAxes.value(type);
for (int i=1; i<axesList.size(); ++i)
axesList.at(i)->setOffset(axesList.at(i-1)->offset() + axesList.at(i-1)->calculateMargin() + axesList.at(i)->tickLengthIn());
}
/* inherits documentation from base class */
int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side)
{
if (!mAutoMargins.testFlag(side))
qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin";
updateAxesOffset(QCPAxis::marginSideToAxisType(side));
// note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call
const QList<QCPAxis*> axesList = mAxes.value(QCPAxis::marginSideToAxisType(side));
if (axesList.size() > 0)
return axesList.last()->offset() + axesList.last()->calculateMargin();
else
return 0;
}
/*! \internal
Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is
pressed, the range dragging interaction is initialized (the actual range manipulation happens in
the \ref mouseMoveEvent).
The mDragging flag is set to true and some anchor points are set that are needed to determine the
distance the mouse was dragged in the mouse move/release events later.
\see mouseMoveEvent, mouseReleaseEvent
*/
void QCPAxisRect::mousePressEvent(QMouseEvent *event)
{
mDragStart = event->pos(); // need this even when not LeftButton is pressed, to determine in releaseEvent whether it was a full click (no position change between press and release)
if (event->buttons() & Qt::LeftButton)
{
mDragging = true;
// initialize antialiasing backup in case we start dragging:
if (mParentPlot->noAntialiasingOnDrag())
{
mAADragBackup = mParentPlot->antialiasedElements();
mNotAADragBackup = mParentPlot->notAntialiasedElements();
}
// Mouse range dragging interaction:
if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
{
if (mRangeDragHorzAxis)
mDragStartHorzRange = mRangeDragHorzAxis.data()->range();
if (mRangeDragVertAxis)
mDragStartVertRange = mRangeDragVertAxis.data()->range();
}
}
}
/*! \internal
Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a
preceding \ref mousePressEvent, the range is moved accordingly.
\see mousePressEvent, mouseReleaseEvent
*/
void QCPAxisRect::mouseMoveEvent(QMouseEvent *event)
{
// Mouse range dragging interaction:
if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag))
{
if (mRangeDrag.testFlag(Qt::Horizontal))
{
if (QCPAxis *rangeDragHorzAxis = mRangeDragHorzAxis.data())
{
if (rangeDragHorzAxis->mScaleType == QCPAxis::stLinear)
{
double diff = rangeDragHorzAxis->pixelToCoord(mDragStart.x()) - rangeDragHorzAxis->pixelToCoord(event->pos().x());
rangeDragHorzAxis->setRange(mDragStartHorzRange.lower+diff, mDragStartHorzRange.upper+diff);
} else if (rangeDragHorzAxis->mScaleType == QCPAxis::stLogarithmic)
{
double diff = rangeDragHorzAxis->pixelToCoord(mDragStart.x()) / rangeDragHorzAxis->pixelToCoord(event->pos().x());
rangeDragHorzAxis->setRange(mDragStartHorzRange.lower*diff, mDragStartHorzRange.upper*diff);
}
}
}
if (mRangeDrag.testFlag(Qt::Vertical))
{
if (QCPAxis *rangeDragVertAxis = mRangeDragVertAxis.data())
{
if (rangeDragVertAxis->mScaleType == QCPAxis::stLinear)
{
double diff = rangeDragVertAxis->pixelToCoord(mDragStart.y()) - rangeDragVertAxis->pixelToCoord(event->pos().y());
rangeDragVertAxis->setRange(mDragStartVertRange.lower+diff, mDragStartVertRange.upper+diff);
} else if (rangeDragVertAxis->mScaleType == QCPAxis::stLogarithmic)
{
double diff = rangeDragVertAxis->pixelToCoord(mDragStart.y()) / rangeDragVertAxis->pixelToCoord(event->pos().y());
rangeDragVertAxis->setRange(mDragStartVertRange.lower*diff, mDragStartVertRange.upper*diff);
}
}
}
if (mRangeDrag != 0) // if either vertical or horizontal drag was enabled, do a replot
{
if (mParentPlot->noAntialiasingOnDrag())
mParentPlot->setNotAntialiasedElements(QCP::aeAll);
mParentPlot->replot();
}
}
}
/* inherits documentation from base class */
void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event)
{
Q_UNUSED(event)
mDragging = false;
if (mParentPlot->noAntialiasingOnDrag())
{
mParentPlot->setAntialiasedElements(mAADragBackup);
mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
}
}
/*! \internal
Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the
ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of
the scaling operation is the current cursor position inside the axis rect. The scaling factor is
dependant on the mouse wheel delta (which direction the wheel was rotated) to provide a natural
zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor.
Note, that event->delta() is usually +/-120 for single rotation steps. However, if the mouse
wheel is turned rapidly, many steps may bunch up to one event, so the event->delta() may then be
multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as
exponent of the range zoom factor. This takes care of the wheel direction automatically, by
inverting the factor, when the wheel step is negative (f^-1 = 1/f).
*/
void QCPAxisRect::wheelEvent(QWheelEvent *event)
{
// Mouse range zooming interaction:
if (mParentPlot->interactions().testFlag(QCP::iRangeZoom))
{
if (mRangeZoom != 0)
{
double factor;
double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually
if (mRangeZoom.testFlag(Qt::Horizontal))
{
factor = pow(mRangeZoomFactorHorz, wheelSteps);
if (mRangeZoomHorzAxis.data())
mRangeZoomHorzAxis.data()->scaleRange(factor, mRangeZoomHorzAxis.data()->pixelToCoord(event->pos().x()));
}
if (mRangeZoom.testFlag(Qt::Vertical))
{
factor = pow(mRangeZoomFactorVert, wheelSteps);
if (mRangeZoomVertAxis.data())
mRangeZoomVertAxis.data()->scaleRange(factor, mRangeZoomVertAxis.data()->pixelToCoord(event->pos().y()));
}
mParentPlot->replot();
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAbstractLegendItem
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPAbstractLegendItem
\brief The abstract base class for all entries in a QCPLegend.
It defines a very basic interface for entries in a QCPLegend. For representing plottables in the
legend, the subclass \ref QCPPlottableLegendItem is more suitable.
Only derive directly from this class when you need absolute freedom (e.g. a custom legend entry
that's not even associated with a plottable).
You must implement the following pure virtual functions:
\li \ref draw (from QCPLayerable)
You inherit the following members you may use:
<table>
<tr>
<td>QCPLegend *\b mParentLegend</td>
<td>A pointer to the parent QCPLegend.</td>
</tr><tr>
<td>QFont \b mFont</td>
<td>The generic font of the item. You should use this font for all or at least the most prominent text of the item.</td>
</tr>
</table>
*/
/* start of documentation of signals */
/*! \fn void QCPAbstractLegendItem::selectionChanged(bool selected)
This signal is emitted when the selection state of this legend item has changed, either by user
interaction or by a direct call to \ref setSelected.
*/
/* end of documentation of signals */
/*!
Constructs a QCPAbstractLegendItem and associates it with the QCPLegend \a parent. This does not
cause the item to be added to \a parent, so \ref QCPLegend::addItem must be called separately.
*/
QCPAbstractLegendItem::QCPAbstractLegendItem(QCPLegend *parent) :
QCPLayoutElement(parent->parentPlot()),
mParentLegend(parent),
mFont(parent->font()),
mTextColor(parent->textColor()),
mSelectedFont(parent->selectedFont()),
mSelectedTextColor(parent->selectedTextColor()),
mSelectable(true),
mSelected(false)
{
setLayer("legend");
setMargins(QMargins(8, 2, 8, 2));
}
/*!
Sets the default font of this specific legend item to \a font.
\see setTextColor, QCPLegend::setFont
*/
void QCPAbstractLegendItem::setFont(const QFont &font)
{
mFont = font;
}
/*!
Sets the default text color of this specific legend item to \a color.
\see setFont, QCPLegend::setTextColor
*/
void QCPAbstractLegendItem::setTextColor(const QColor &color)
{
mTextColor = color;
}
/*!
When this legend item is selected, \a font is used to draw generic text, instead of the normal
font set with \ref setFont.
\see setFont, QCPLegend::setSelectedFont
*/
void QCPAbstractLegendItem::setSelectedFont(const QFont &font)
{
mSelectedFont = font;
}
/*!
When this legend item is selected, \a color is used to draw generic text, instead of the normal
color set with \ref setTextColor.
\see setTextColor, QCPLegend::setSelectedTextColor
*/
void QCPAbstractLegendItem::setSelectedTextColor(const QColor &color)
{
mSelectedTextColor = color;
}
/*!
Sets whether this specific legend item is selectable.
\see setSelectedParts, QCustomPlot::setInteractions
*/
void QCPAbstractLegendItem::setSelectable(bool selectable)
{
mSelectable = selectable;
}
/*!
Sets whether this specific legend item is selected.
It is possible to set the selection state of this item by calling this function directly, even if
setSelectable is set to false.
\see setSelectableParts, QCustomPlot::setInteractions
*/
void QCPAbstractLegendItem::setSelected(bool selected)
{
if (mSelected != selected)
{
mSelected = selected;
emit selectionChanged(mSelected);
}
}
/* inherits documentation from base class */
double QCPAbstractLegendItem::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (!mParentPlot) return -1;
if (onlySelectable && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems)))
return -1;
if (mRect.contains(pos.toPoint()))
return mParentPlot->selectionTolerance()*0.99;
else
return -1;
}
/* inherits documentation from base class */
void QCPAbstractLegendItem::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems);
}
/* inherits documentation from base class */
QRect QCPAbstractLegendItem::clipRect() const
{
return mOuterRect;
}
/* inherits documentation from base class */
void QCPAbstractLegendItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
Q_UNUSED(event)
Q_UNUSED(details)
if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems))
{
bool selBefore = mSelected;
setSelected(additive ? !mSelected : true);
if (selectionStateChanged)
*selectionStateChanged = mSelected != selBefore;
}
}
/* inherits documentation from base class */
void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged)
{
if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems))
{
bool selBefore = mSelected;
setSelected(false);
if (selectionStateChanged)
*selectionStateChanged = mSelected != selBefore;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPPlottableLegendItem
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPPlottableLegendItem
\brief A legend item representing a plottable with an icon and the plottable name.
This is the standard legend item for plottables. It displays an icon of the plottable next to the
plottable name. The icon is drawn by the respective plottable itself (\ref
QCPAbstractPlottable::drawLegendIcon), and tries to give an intuitive symbol for the plottable.
For example, the QCPGraph draws a centered horizontal line and/or a single scatter point in the
middle.
Legend items of this type are always associated with one plottable (retrievable via the
plottable() function and settable with the constructor). You may change the font of the plottable
name with \ref setFont. Icon padding and border pen is taken from the parent QCPLegend, see \ref
QCPLegend::setIconBorderPen and \ref QCPLegend::setIconTextPadding.
The function \ref QCPAbstractPlottable::addToLegend/\ref QCPAbstractPlottable::removeFromLegend
creates/removes legend items of this type in the default implementation. However, these functions
may be reimplemented such that a different kind of legend item (e.g a direct subclass of
QCPAbstractLegendItem) is used for that plottable.
Since QCPLegend is based on QCPLayoutGrid, a legend item itself is just a subclass of
QCPLayoutElement. While it could be added to a legend (or any other layout) via the normal layout
interface, QCPLegend has specialized functions for handling legend items conveniently, see the
documentation of \ref QCPLegend.
*/
/*!
Creates a new legend item associated with \a plottable.
Once it's created, it can be added to the legend via \ref QCPLegend::addItem.
A more convenient way of adding/removing a plottable to/from the legend is via the functions \ref
QCPAbstractPlottable::addToLegend and \ref QCPAbstractPlottable::removeFromLegend.
*/
QCPPlottableLegendItem::QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable) :
QCPAbstractLegendItem(parent),
mPlottable(plottable)
{
}
/*! \internal
Returns the pen that shall be used to draw the icon border, taking into account the selection
state of this item.
*/
QPen QCPPlottableLegendItem::getIconBorderPen() const
{
return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen();
}
/*! \internal
Returns the text color that shall be used to draw text, taking into account the selection state
of this item.
*/
QColor QCPPlottableLegendItem::getTextColor() const
{
return mSelected ? mSelectedTextColor : mTextColor;
}
/*! \internal
Returns the font that shall be used to draw text, taking into account the selection state of this
item.
*/
QFont QCPPlottableLegendItem::getFont() const
{
return mSelected ? mSelectedFont : mFont;
}
/*! \internal
Draws the item with \a painter. The size and position of the drawn legend item is defined by the
parent layout (typically a \ref QCPLegend) and the \ref minimumSizeHint and \ref maximumSizeHint
of this legend item.
*/
void QCPPlottableLegendItem::draw(QCPPainter *painter)
{
if (!mPlottable) return;
painter->setFont(getFont());
painter->setPen(QPen(getTextColor()));
QSizeF iconSize = mParentLegend->iconSize();
QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name());
QRectF iconRect(mRect.topLeft(), iconSize);
int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops
painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name());
// draw icon:
painter->save();
painter->setClipRect(iconRect, Qt::IntersectClip);
mPlottable->drawLegendIcon(painter, iconRect);
painter->restore();
// draw icon border:
if (getIconBorderPen().style() != Qt::NoPen)
{
painter->setPen(getIconBorderPen());
painter->setBrush(Qt::NoBrush);
painter->drawRect(iconRect);
}
}
/*! \internal
Calculates and returns the size of this item. This includes the icon, the text and the padding in
between.
*/
QSize QCPPlottableLegendItem::minimumSizeHint() const
{
if (!mPlottable) return QSize();
QSize result(0, 0);
QRect textRect;
QFontMetrics fontMetrics(getFont());
QSize iconSize = mParentLegend->iconSize();
textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name());
result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width() + mMargins.left() + mMargins.right());
result.setHeight(qMax(textRect.height(), iconSize.height()) + mMargins.top() + mMargins.bottom());
return result;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLegend
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPLegend
\brief Manages a legend inside a QCustomPlot.
A legend is a small box somewhere in the plot which lists plottables with their name and icon.
Normally, the legend is populated by calling \ref QCPAbstractPlottable::addToLegend. The
respective legend item can be removed with \ref QCPAbstractPlottable::removeFromLegend. However,
QCPLegend also offers an interface to add and manipulate legend items directly: \ref item, \ref
itemWithPlottable, \ref itemCount, \ref addItem, \ref removeItem, etc.
The QCPLegend derives from QCPLayoutGrid and as such can be placed in any position a
QCPLayoutElement may be positioned. The legend items are themselves QCPLayoutElements which are
placed in the grid layout of the legend. QCPLegend only adds an interface specialized for
handling child elements of type QCPAbstractLegendItem, as mentioned above. In principle, any
other layout elements may also be added to a legend via the normal \ref QCPLayoutGrid interface.
However, the QCPAbstractLegendItem-Interface will ignore those elements (e.g. \ref itemCount will
only return the number of items with QCPAbstractLegendItems type).
By default, every QCustomPlot has one legend (QCustomPlot::legend) which is placed in the inset
layout of the main axis rect (\ref QCPAxisRect::insetLayout). To move the legend to another
position inside the axis rect, use the methods of the \ref QCPLayoutInset. To move the legend
outside of the axis rect, place it anywhere else with the QCPLayout/QCPLayoutElement interface.
*/
/* start of documentation of signals */
/*! \fn void QCPLegend::selectionChanged(QCPLegend::SelectableParts selection);
This signal is emitted when the selection state of this legend has changed.
\see setSelectedParts, setSelectableParts
*/
/* end of documentation of signals */
/*!
Constructs a new QCPLegend instance with \a parentPlot as the containing plot and default values.
Note that by default, QCustomPlot already contains a legend ready to be used as
QCustomPlot::legend
*/
QCPLegend::QCPLegend()
{
setRowSpacing(0);
setColumnSpacing(10);
setMargins(QMargins(2, 3, 2, 2));
setAntialiased(false);
setIconSize(32, 18);
setIconTextPadding(7);
setSelectableParts(spLegendBox | spItems);
setSelectedParts(spNone);
setBorderPen(QPen(Qt::black));
setSelectedBorderPen(QPen(Qt::blue, 2));
setIconBorderPen(Qt::NoPen);
setSelectedIconBorderPen(QPen(Qt::blue, 2));
setBrush(Qt::white);
setSelectedBrush(Qt::white);
setTextColor(Qt::black);
setSelectedTextColor(Qt::blue);
}
QCPLegend::~QCPLegend()
{
clearItems();
if (mParentPlot)
mParentPlot->legendRemoved(this);
}
/* no doc for getter, see setSelectedParts */
QCPLegend::SelectableParts QCPLegend::selectedParts() const
{
// check whether any legend elements selected, if yes, add spItems to return value
bool hasSelectedItems = false;
for (int i=0; i<itemCount(); ++i)
{
if (item(i) && item(i)->selected())
{
hasSelectedItems = true;
break;
}
}
if (hasSelectedItems)
return mSelectedParts | spItems;
else
return mSelectedParts & ~spItems;
}
/*!
Sets the pen, the border of the entire legend is drawn with.
*/
void QCPLegend::setBorderPen(const QPen &pen)
{
mBorderPen = pen;
}
/*!
Sets the brush of the legend background.
*/
void QCPLegend::setBrush(const QBrush &brush)
{
mBrush = brush;
}
/*!
Sets the default font of legend text. Legend items that draw text (e.g. the name of a graph) will
use this font by default. However, a different font can be specified on a per-item-basis by
accessing the specific legend item.
This function will also set \a font on all already existing legend items.
\see QCPAbstractLegendItem::setFont
*/
void QCPLegend::setFont(const QFont &font)
{
mFont = font;
for (int i=0; i<itemCount(); ++i)
{
if (item(i))
item(i)->setFont(mFont);
}
}
/*!
Sets the default color of legend text. Legend items that draw text (e.g. the name of a graph)
will use this color by default. However, a different colors can be specified on a per-item-basis
by accessing the specific legend item.
This function will also set \a color on all already existing legend items.
\see QCPAbstractLegendItem::setTextColor
*/
void QCPLegend::setTextColor(const QColor &color)
{
mTextColor = color;
for (int i=0; i<itemCount(); ++i)
{
if (item(i))
item(i)->setTextColor(color);
}
}
/*!
Sets the size of legend icons. Legend items that draw an icon (e.g. a visual
representation of the graph) will use this size by default.
*/
void QCPLegend::setIconSize(const QSize &size)
{
mIconSize = size;
}
/*! \overload
*/
void QCPLegend::setIconSize(int width, int height)
{
mIconSize.setWidth(width);
mIconSize.setHeight(height);
}
/*!
Sets the horizontal space in pixels between the legend icon and the text next to it.
Legend items that draw an icon (e.g. a visual representation of the graph) and text (e.g. the
name of the graph) will use this space by default.
*/
void QCPLegend::setIconTextPadding(int padding)
{
mIconTextPadding = padding;
}
/*!
Sets the pen used to draw a border around each legend icon. Legend items that draw an
icon (e.g. a visual representation of the graph) will use this pen by default.
If no border is wanted, set this to \a Qt::NoPen.
*/
void QCPLegend::setIconBorderPen(const QPen &pen)
{
mIconBorderPen = pen;
}
/*!
Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
(When \ref QCustomPlot::setInteractions contains iSelectLegend.)
However, even when \a selectable is set to a value not allowing the selection of a specific part,
it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
directly.
\see SelectablePart, setSelectedParts
*/
void QCPLegend::setSelectableParts(const SelectableParts &selectable)
{
mSelectableParts = selectable;
}
/*!
Sets the selected state of the respective legend parts described by \ref SelectablePart. When a part
is selected, it uses a different pen/font and brush. If some legend items are selected and \a selected
doesn't contain \ref spItems, those items become deselected.
The entire selection mechanism is handled automatically when \ref QCustomPlot::setInteractions
contains iSelectLegend. You only need to call this function when you wish to change the selection
state manually.
This function can change the selection state of a part even when \ref setSelectableParts was set to a
value that actually excludes the part.
emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
Note that it doesn't make sense to set the selected state \ref spItems here when it wasn't set
before, because there's no way to specify which exact items to newly select. Do this by calling
\ref QCPAbstractLegendItem::setSelected directly on the legend item you wish to select.
\see SelectablePart, setSelectableParts, selectTest, setSelectedBorderPen, setSelectedIconBorderPen, setSelectedBrush,
setSelectedFont
*/
void QCPLegend::setSelectedParts(const SelectableParts &selected)
{
SelectableParts newSelected = selected;
mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed
if (mSelectedParts != newSelected)
{
if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) // attempt to set spItems flag (can't do that)
{
qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be unset with this function";
newSelected &= ~spItems;
}
if (mSelectedParts.testFlag(spItems) && !newSelected.testFlag(spItems)) // spItems flag was unset, so clear item selection
{
for (int i=0; i<itemCount(); ++i)
{
if (item(i))
item(i)->setSelected(false);
}
}
mSelectedParts = newSelected;
emit selectionChanged(mSelectedParts);
}
}
/*!
When the legend box is selected, this pen is used to draw the border instead of the normal pen
set via \ref setBorderPen.
\see setSelectedParts, setSelectableParts, setSelectedBrush
*/
void QCPLegend::setSelectedBorderPen(const QPen &pen)
{
mSelectedBorderPen = pen;
}
/*!
Sets the pen legend items will use to draw their icon borders, when they are selected.
\see setSelectedParts, setSelectableParts, setSelectedFont
*/
void QCPLegend::setSelectedIconBorderPen(const QPen &pen)
{
mSelectedIconBorderPen = pen;
}
/*!
When the legend box is selected, this brush is used to draw the legend background instead of the normal brush
set via \ref setBrush.
\see setSelectedParts, setSelectableParts, setSelectedBorderPen
*/
void QCPLegend::setSelectedBrush(const QBrush &brush)
{
mSelectedBrush = brush;
}
/*!
Sets the default font that is used by legend items when they are selected.
This function will also set \a font on all already existing legend items.
\see setFont, QCPAbstractLegendItem::setSelectedFont
*/
void QCPLegend::setSelectedFont(const QFont &font)
{
mSelectedFont = font;
for (int i=0; i<itemCount(); ++i)
{
if (item(i))
item(i)->setSelectedFont(font);
}
}
/*!
Sets the default text color that is used by legend items when they are selected.
This function will also set \a color on all already existing legend items.
\see setTextColor, QCPAbstractLegendItem::setSelectedTextColor
*/
void QCPLegend::setSelectedTextColor(const QColor &color)
{
mSelectedTextColor = color;
for (int i=0; i<itemCount(); ++i)
{
if (item(i))
item(i)->setSelectedTextColor(color);
}
}
/*!
Returns the item with index \a i.
\see itemCount
*/
QCPAbstractLegendItem *QCPLegend::item(int index) const
{
return qobject_cast<QCPAbstractLegendItem*>(elementAt(index));
}
/*!
Returns the QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*).
If such an item isn't in the legend, returns 0.
\see hasItemWithPlottable
*/
QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable *plottable) const
{
for (int i=0; i<itemCount(); ++i)
{
if (QCPPlottableLegendItem *pli = qobject_cast<QCPPlottableLegendItem*>(item(i)))
{
if (pli->plottable() == plottable)
return pli;
}
}
return 0;
}
/*!
Returns the number of items currently in the legend.
\see item
*/
int QCPLegend::itemCount() const
{
return elementCount();
}
/*!
Returns whether the legend contains \a itm.
*/
bool QCPLegend::hasItem(QCPAbstractLegendItem *item) const
{
for (int i=0; i<itemCount(); ++i)
{
if (item == this->item(i))
return true;
}
return false;
}
/*!
Returns whether the legend contains a QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*).
If such an item isn't in the legend, returns false.
\see itemWithPlottable
*/
bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) const
{
return itemWithPlottable(plottable);
}
/*!
Adds \a item to the legend, if it's not present already.
Returns true on sucess, i.e. if the item wasn't in the list already and has been successfuly added.
The legend takes ownership of the item.
*/
bool QCPLegend::addItem(QCPAbstractLegendItem *item)
{
if (!hasItem(item))
{
return addElement(rowCount(), 0, item);
} else
return false;
}
/*!
Removes the item with index \a index from the legend.
Returns true, if successful.
\see itemCount, clearItems
*/
bool QCPLegend::removeItem(int index)
{
if (QCPAbstractLegendItem *ali = item(index))
{
bool success = remove(ali);
simplify();
return success;
} else
return false;
}
/*! \overload
Removes \a item from the legend.
Returns true, if successful.
\see clearItems
*/
bool QCPLegend::removeItem(QCPAbstractLegendItem *item)
{
bool success = remove(item);
simplify();
return success;
}
/*!
Removes all items from the legend.
*/
void QCPLegend::clearItems()
{
for (int i=itemCount()-1; i>=0; --i)
removeItem(i);
}
/*!
Returns the legend items that are currently selected. If no items are selected,
the list is empty.
\see QCPAbstractLegendItem::setSelected, setSelectable
*/
QList<QCPAbstractLegendItem *> QCPLegend::selectedItems() const
{
QList<QCPAbstractLegendItem*> result;
for (int i=0; i<itemCount(); ++i)
{
if (QCPAbstractLegendItem *ali = item(i))
{
if (ali->selected())
result.append(ali);
}
}
return result;
}
/*! \internal
A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
before drawing main legend elements.
This is the antialiasing state the painter passed to the \ref draw method is in by default.
This function takes into account the local setting of the antialiasing flag as well as the
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
\see setAntialiased
*/
void QCPLegend::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend);
}
/*! \internal
Returns the pen used to paint the border of the legend, taking into account the selection state
of the legend box.
*/
QPen QCPLegend::getBorderPen() const
{
return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen;
}
/*! \internal
Returns the brush used to paint the background of the legend, taking into account the selection
state of the legend box.
*/
QBrush QCPLegend::getBrush() const
{
return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush;
}
/*! \internal
Draws the legend box with the provided \a painter. The individual legend items are layerables
themselves, thus are drawn independently.
*/
void QCPLegend::draw(QCPPainter *painter)
{
// draw background rect:
painter->setBrush(getBrush());
painter->setPen(getBorderPen());
painter->drawRect(mOuterRect);
}
/* inherits documentation from base class */
double QCPLegend::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
if (!mParentPlot) return -1;
if (onlySelectable && !mSelectableParts.testFlag(spLegendBox))
return -1;
if (mOuterRect.contains(pos.toPoint()))
{
if (details) details->setValue(spLegendBox);
return mParentPlot->selectionTolerance()*0.99;
}
return -1;
}
/* inherits documentation from base class */
void QCPLegend::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
Q_UNUSED(event)
mSelectedParts = selectedParts(); // in case item selection has changed
if (details.value<SelectablePart>() == spLegendBox && mSelectableParts.testFlag(spLegendBox))
{
SelectableParts selBefore = mSelectedParts;
setSelectedParts(additive ? mSelectedParts^spLegendBox : mSelectedParts|spLegendBox); // no need to unset spItems in !additive case, because they will be deselected by QCustomPlot (they're normal QCPLayerables with own deselectEvent)
if (selectionStateChanged)
*selectionStateChanged = mSelectedParts != selBefore;
}
}
/* inherits documentation from base class */
void QCPLegend::deselectEvent(bool *selectionStateChanged)
{
mSelectedParts = selectedParts(); // in case item selection has changed
if (mSelectableParts.testFlag(spLegendBox))
{
SelectableParts selBefore = mSelectedParts;
setSelectedParts(selectedParts() & ~spLegendBox);
if (selectionStateChanged)
*selectionStateChanged = mSelectedParts != selBefore;
}
}
/* inherits documentation from base class */
QCP::Interaction QCPLegend::selectionCategory() const
{
return QCP::iSelectLegend;
}
/* inherits documentation from base class */
QCP::Interaction QCPAbstractLegendItem::selectionCategory() const
{
return QCP::iSelectLegend;
}
/* inherits documentation from base class */
void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot)
{
Q_UNUSED(parentPlot)
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPPlotTitle
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPPlotTitle
\brief A layout element displaying a plot title text
The text may be specified with \ref setText, theformatting can be controlled with \ref setFont
and \ref setTextColor.
A plot title can be added as follows:
\code
customPlot->plotLayout()->insertRow(0); // inserts an empty row above the default axis rect
customPlot->plotLayout()->addElement(0, 0, new QCPPlotTitle(customPlot, "Your Plot Title"));
\endcode
Since a plot title is a common requirement, QCustomPlot offers specialized selection signals for
easy interaction with QCPPlotTitle. If a layout element of type QCPPlotTitle is clicked, the
signal \ref QCustomPlot::titleClick is emitted. A double click emits the \ref
QCustomPlot::titleDoubleClick signal.
*/
/* start documentation of signals */
/*! \fn void QCPPlotTitle::selectionChanged(bool selected)
This signal is emitted when the selection state has changed to \a selected, either by user
interaction or by a direct call to \ref setSelected.
\see setSelected, setSelectable
*/
/* end documentation of signals */
/*!
Creates a new QCPPlotTitle instance and sets default values. The initial text is empty (\ref setText).
To set the title text in the constructor, rather use \ref QCPPlotTitle(QCustomPlot *parentPlot, const QString &text).
*/
QCPPlotTitle::QCPPlotTitle(QCustomPlot *parentPlot) :
QCPLayoutElement(parentPlot),
mFont(QFont("sans serif", 13*1.5, QFont::Bold)),
mTextColor(Qt::black),
mSelectedFont(QFont("sans serif", 13*1.6, QFont::Bold)),
mSelectedTextColor(Qt::blue),
mSelectable(false),
mSelected(false)
{
if (parentPlot)
{
setLayer(parentPlot->currentLayer());
mFont = QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.5, QFont::Bold);
mSelectedFont = QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.6, QFont::Bold);
}
setMargins(QMargins(5, 5, 5, 0));
}
/*! \overload
Creates a new QCPPlotTitle instance and sets default values. The initial text is set to \a text.
*/
QCPPlotTitle::QCPPlotTitle(QCustomPlot *parentPlot, const QString &text) :
QCPLayoutElement(parentPlot),
mText(text),
mFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.5, QFont::Bold)),
mTextColor(Qt::black),
mSelectedFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.6, QFont::Bold)),
mSelectedTextColor(Qt::blue),
mSelectable(false),
mSelected(false)
{
setLayer("axes");
setMargins(QMargins(5, 5, 5, 0));
}
/*!
Sets the text that will be displayed to \a text. Multiple lines can be created by insertion of "\n".
\see setFont, setTextColor
*/
void QCPPlotTitle::setText(const QString &text)
{
mText = text;
}
/*!
Sets the \a font of the title text.
\see setTextColor, setSelectedFont
*/
void QCPPlotTitle::setFont(const QFont &font)
{
mFont = font;
}
/*!
Sets the \a color of the title text.
\see setFont, setSelectedTextColor
*/
void QCPPlotTitle::setTextColor(const QColor &color)
{
mTextColor = color;
}
/*!
Sets the \a font of the title text that will be used if the plot title is selected (\ref setSelected).
\see setFont
*/
void QCPPlotTitle::setSelectedFont(const QFont &font)
{
mSelectedFont = font;
}
/*!
Sets the \a color of the title text that will be used if the plot title is selected (\ref setSelected).
\see setTextColor
*/
void QCPPlotTitle::setSelectedTextColor(const QColor &color)
{
mSelectedTextColor = color;
}
/*!
Sets whether the user may select this plot title to \a selectable.
Note that even when \a selectable is set to <tt>false</tt>, the selection state may be changed
programmatically via \ref setSelected.
*/
void QCPPlotTitle::setSelectable(bool selectable)
{
mSelectable = selectable;
}
/*!
Sets the selection state of this plot title to \a selected. If the selection has changed, \ref
selectionChanged is emitted.
Note that this function can change the selection state independently of the current \ref
setSelectable state.
*/
void QCPPlotTitle::setSelected(bool selected)
{
if (mSelected != selected)
{
mSelected = selected;
emit selectionChanged(mSelected);
}
}
/* inherits documentation from base class */
void QCPPlotTitle::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiased, QCP::aeNone);
}
/* inherits documentation from base class */
void QCPPlotTitle::draw(QCPPainter *painter)
{
painter->setFont(mainFont());
painter->setPen(QPen(mainTextColor()));
painter->drawText(mRect, Qt::AlignCenter, mText, &mTextBoundingRect);
}
/* inherits documentation from base class */
QSize QCPPlotTitle::minimumSizeHint() const
{
QFontMetrics metrics(mFont);
QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size();
result.rwidth() += mMargins.left() + mMargins.right();
result.rheight() += mMargins.top() + mMargins.bottom();
return result;
}
/* inherits documentation from base class */
QSize QCPPlotTitle::maximumSizeHint() const
{
QFontMetrics metrics(mFont);
QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size();
result.rheight() += mMargins.top() + mMargins.bottom();
result.setWidth(QWIDGETSIZE_MAX);
return result;
}
/* inherits documentation from base class */
void QCPPlotTitle::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
Q_UNUSED(event)
Q_UNUSED(details)
if (mSelectable)
{
bool selBefore = mSelected;
setSelected(additive ? !mSelected : true);
if (selectionStateChanged)
*selectionStateChanged = mSelected != selBefore;
}
}
/* inherits documentation from base class */
void QCPPlotTitle::deselectEvent(bool *selectionStateChanged)
{
if (mSelectable)
{
bool selBefore = mSelected;
setSelected(false);
if (selectionStateChanged)
*selectionStateChanged = mSelected != selBefore;
}
}
/* inherits documentation from base class */
double QCPPlotTitle::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
return -1;
if (mTextBoundingRect.contains(pos.toPoint()))
return mParentPlot->selectionTolerance()*0.99;
else
return -1;
}
/*! \internal
Returns the main font to be used. This is mSelectedFont if \ref setSelected is set to
<tt>true</tt>, else mFont is returned.
*/
QFont QCPPlotTitle::mainFont() const
{
return mSelected ? mSelectedFont : mFont;
}
/*! \internal
Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to
<tt>true</tt>, else mTextColor is returned.
*/
QColor QCPPlotTitle::mainTextColor() const
{
return mSelected ? mSelectedTextColor : mTextColor;
}
| igodip/NetAnim | qcustomplot.cpp | C++ | apache-2.0 | 667,173 |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 org.jboss.marshalling.serial;
import java.io.Externalizable;
import java.io.ObjectOutput;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.InvalidClassException;
import java.io.ObjectStreamException;
import org.jboss.marshalling.Externalizer;
/**
* An externalized object. This wrapper allows an object that was written with an {@code Externalizer} to be read by
* standard Java serialization. Note that if an externalized object's child object graph ever refers to the original
* object, there will be an error in the reconstructed object graph such that those references will refer to this
* wrapper object rather than the properly externalized object.
*/
public final class ExternalizedObject implements Externalizable {
private static final long serialVersionUID = -7764783599281227099L;
private Externalizer externalizer;
private transient Object obj;
public ExternalizedObject() {
}
public ExternalizedObject(final Externalizer externalizer, final Object obj) {
this.externalizer = externalizer;
this.obj = obj;
}
/**
* {@inheritDoc}
*/
public void writeExternal(final ObjectOutput out) throws IOException {
out.writeObject(obj.getClass());
out.writeObject(externalizer);
externalizer.writeExternal(obj, out);
}
/**
* {@inheritDoc}
*/
public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
Class<?> subject = (Class<?>) in.readObject();
externalizer = (Externalizer) in.readObject();
final Object o = externalizer.createExternal(subject, in);
obj = o;
}
/**
* Return the externalized object after {@code readExternal()} completes.
*
* @return the externalized object
*
* @throws ObjectStreamException never
*/
protected Object readResolve() {
return obj;
}
/**
* {@inheritDoc}
*/
public <T> T create(final Class<T> clazz) throws InvalidClassException {
try {
return clazz.newInstance();
} catch (Exception e) {
final InvalidClassException ee = new InvalidClassException(clazz.getName(), e.getMessage());
ee.initCause(e);
throw ee;
}
}
}
| kohsuke/jboss-marshalling | serial/src/main/java/org/jboss/marshalling/serial/ExternalizedObject.java | Java | apache-2.0 | 3,023 |
/*
* Copyright 2014-2016 CyberVision, 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 org.kaaproject.kaa.server.common.verifier;
import java.io.IOException;
import java.text.MessageFormat;
import org.apache.avro.specific.SpecificRecordBase;
import org.kaaproject.kaa.common.avro.AvroByteArrayConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractKaaUserVerifier<T extends SpecificRecordBase> implements UserVerifier {
private static final Logger LOG = LoggerFactory.getLogger(AbstractKaaUserVerifier.class);
@Override
public void init(UserVerifierContext context) throws UserVerifierLifecycleException{
LOG.info("Initializing user verifier with {}", context);
AvroByteArrayConverter<T> converter = new AvroByteArrayConverter<>(getConfigurationClass());
try {
T configuration = converter.fromByteArray(context.getVerifierDto().getRawConfiguration());
LOG.info("Initializing user verifier {} with {}", getClassName(), configuration);
init(context, configuration);
} catch (IOException e) {
LOG.error(MessageFormat.format("Failed to initialize user verifier {0}", getClassName()), e);
throw new UserVerifierLifecycleException(e);
}
}
public abstract void init(UserVerifierContext context, T configuration) throws UserVerifierLifecycleException;
/**
* Gets the configuration class.
*
* @return the configuration class
*/
public abstract Class<T> getConfigurationClass();
private String getClassName() {
return this.getClass().getName();
}
}
| forGGe/kaa | server/common/verifier-shared/src/main/java/org/kaaproject/kaa/server/common/verifier/AbstractKaaUserVerifier.java | Java | apache-2.0 | 2,194 |
/*
* Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.spi;
import com.hazelcast.nio.serialization.DataSerializable;
/**
* {@code ServiceNamespace} is a namespace to group objects, structures, fragments within a service.
*
* @since 3.9
*/
public interface ServiceNamespace extends DataSerializable {
/**
* Name of the service
*
* @return name of the service
*/
String getServiceName();
}
| tufangorel/hazelcast | hazelcast/src/main/java/com/hazelcast/spi/ServiceNamespace.java | Java | apache-2.0 | 1,016 |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.cxx;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.util.graph.AbstractBreadthFirstTraversal;
import com.facebook.buck.core.util.immutables.BuckStyleValue;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkTarget;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkable;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
/**
* A helper class for building the included and excluded omnibus roots to pass to the omnibus
* builder.
*/
@BuckStyleValue
public abstract class OmnibusRoots {
/** @return the {@link NativeLinkTarget} roots that are included in omnibus linking. */
public abstract ImmutableMap<BuildTarget, NativeLinkTarget> getIncludedRoots();
/** @return the {@link NativeLinkable} roots that are excluded from omnibus linking. */
public abstract ImmutableMap<BuildTarget, NativeLinkable> getExcludedRoots();
public static Builder builder(
ImmutableSet<BuildTarget> excludes, ActionGraphBuilder graphBuilder) {
return new Builder(excludes, graphBuilder);
}
public static class Builder {
private final ImmutableSet<BuildTarget> excludes;
private final ActionGraphBuilder graphBuilder;
private final Map<BuildTarget, NativeLinkTarget> includedRoots = new LinkedHashMap<>();
private final Map<BuildTarget, NativeLinkable> excludedRoots = new LinkedHashMap<>();
private Builder(ImmutableSet<BuildTarget> excludes, ActionGraphBuilder graphBuilder) {
this.excludes = excludes;
this.graphBuilder = graphBuilder;
}
/** Add a root which is included in omnibus linking. */
public void addIncludedRoot(NativeLinkTarget root) {
includedRoots.put(root.getBuildTarget(), root);
}
/** Add a root which is excluded from omnibus linking. */
public void addExcludedRoot(NativeLinkable root) {
excludedRoots.put(root.getBuildTarget(), root);
}
/**
* Add a node which may qualify as either an included root, and excluded root, or neither.
*
* @return whether the node was added as a root.
*/
public void addPotentialRoot(NativeLinkable node, boolean includePrivateLinkerFlags) {
Optional<NativeLinkTarget> target =
node.getNativeLinkTarget(graphBuilder, includePrivateLinkerFlags);
if (target.isPresent()
&& !excludes.contains(node.getBuildTarget())
&& node.supportsOmnibusLinking()) {
addIncludedRoot(target.get());
} else {
addExcludedRoot(node);
}
}
private ImmutableMap<BuildTarget, NativeLinkable> buildExcluded() {
Map<BuildTarget, NativeLinkable> excluded = new LinkedHashMap<>(excludedRoots);
// Find all excluded nodes reachable from the included roots.
Map<BuildTarget, NativeLinkable> includedRootDeps = new LinkedHashMap<>();
for (NativeLinkTarget target : includedRoots.values()) {
for (NativeLinkable linkable : target.getNativeLinkTargetDeps(graphBuilder)) {
includedRootDeps.put(linkable.getBuildTarget(), linkable);
}
}
new AbstractBreadthFirstTraversal<NativeLinkable>(includedRootDeps.values()) {
@Override
public Iterable<NativeLinkable> visit(NativeLinkable linkable) throws RuntimeException {
if (!linkable.supportsOmnibusLinking()) {
excluded.put(linkable.getBuildTarget(), linkable);
return ImmutableSet.of();
}
return Iterables.concat(
linkable.getNativeLinkableDeps(graphBuilder),
linkable.getNativeLinkableExportedDeps(graphBuilder));
}
}.start();
// Prepare the final map of excluded roots, starting with the pre-defined ones.
Map<BuildTarget, NativeLinkable> updatedExcludedRoots = new LinkedHashMap<>(excludedRoots);
// Recursively expand the excluded nodes including any preloaded deps, as we'll need this full
// list to know which roots to exclude from omnibus linking.
new AbstractBreadthFirstTraversal<NativeLinkable>(excluded.values()) {
@Override
public Iterable<NativeLinkable> visit(NativeLinkable linkable) {
if (includedRoots.containsKey(linkable.getBuildTarget())) {
updatedExcludedRoots.put(linkable.getBuildTarget(), linkable);
}
return Iterables.concat(
linkable.getNativeLinkableDeps(graphBuilder),
linkable.getNativeLinkableExportedDeps(graphBuilder));
}
}.start();
return ImmutableMap.copyOf(updatedExcludedRoots);
}
private ImmutableMap<BuildTarget, NativeLinkTarget> buildIncluded(
ImmutableSet<BuildTarget> excluded) {
return ImmutableMap.copyOf(
Maps.filterKeys(includedRoots, Predicates.not(excluded::contains)));
}
public boolean isEmpty() {
return includedRoots.isEmpty() && excludedRoots.isEmpty();
}
public OmnibusRoots build() {
ImmutableMap<BuildTarget, NativeLinkable> excluded = buildExcluded();
ImmutableMap<BuildTarget, NativeLinkTarget> included = buildIncluded(excluded.keySet());
return ImmutableOmnibusRoots.of(included, excluded);
}
}
}
| facebook/buck | src/com/facebook/buck/cxx/OmnibusRoots.java | Java | apache-2.0 | 6,108 |
/*
Copyright 2016 Goldman Sachs.
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.gs.fw.common.mithra.test.domain;
public class GsDeskDatabaseObject extends GsDeskDatabaseObjectAbstract
{
}
| goldmansachs/reladomo | reladomo/src/test/java/com/gs/fw/common/mithra/test/domain/GsDeskDatabaseObject.java | Java | apache-2.0 | 716 |
/**
* Copyright 2012 International Business Machines Corp.
*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. 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.ibm.jbatch.container.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
import com.ibm.jbatch.container.exception.BatchContainerRuntimeException;
public class TCCLObjectInputStream extends ObjectInputStream {
public TCCLObjectInputStream(InputStream in) throws IOException {
super(in);
}
@Override
public Class<?> resolveClass(ObjectStreamClass desc) {
ClassLoader tccl = Thread.currentThread().getContextClassLoader();
try {
return tccl.loadClass(desc.getName());
} catch (ClassNotFoundException e) {
throw new BatchContainerRuntimeException(e);
}
}
}
| sidgoyal/standards.jsr352.jbatch | com.ibm.jbatch.container/src/main/java/com/ibm/jbatch/container/util/TCCLObjectInputStream.java | Java | apache-2.0 | 1,450 |
/*
* 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.cdc.mysql.processors;
import com.github.shyiko.mysql.binlog.BinaryLogClient;
import com.github.shyiko.mysql.binlog.event.Event;
import com.github.shyiko.mysql.binlog.event.EventHeaderV4;
import com.github.shyiko.mysql.binlog.event.EventType;
import com.github.shyiko.mysql.binlog.event.QueryEventData;
import com.github.shyiko.mysql.binlog.event.RotateEventData;
import com.github.shyiko.mysql.binlog.event.TableMapEventData;
import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.annotation.behavior.InputRequirement;
import org.apache.nifi.annotation.behavior.Stateful;
import org.apache.nifi.annotation.behavior.TriggerSerially;
import org.apache.nifi.annotation.behavior.WritesAttribute;
import org.apache.nifi.annotation.behavior.WritesAttributes;
import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.annotation.lifecycle.OnShutdown;
import org.apache.nifi.annotation.lifecycle.OnStopped;
import org.apache.nifi.cdc.CDCException;
import org.apache.nifi.cdc.event.ColumnDefinition;
import org.apache.nifi.cdc.event.RowEventException;
import org.apache.nifi.cdc.event.TableInfo;
import org.apache.nifi.cdc.event.TableInfoCacheKey;
import org.apache.nifi.cdc.event.io.EventWriter;
import org.apache.nifi.cdc.mysql.event.BeginTransactionEventInfo;
import org.apache.nifi.cdc.mysql.event.BinlogEventInfo;
import org.apache.nifi.cdc.mysql.event.BinlogEventListener;
import org.apache.nifi.cdc.mysql.event.BinlogLifecycleListener;
import org.apache.nifi.cdc.mysql.event.CommitTransactionEventInfo;
import org.apache.nifi.cdc.mysql.event.DeleteRowsEventInfo;
import org.apache.nifi.cdc.mysql.event.InsertRowsEventInfo;
import org.apache.nifi.cdc.mysql.event.RawBinlogEvent;
import org.apache.nifi.cdc.mysql.event.DDLEventInfo;
import org.apache.nifi.cdc.mysql.event.UpdateRowsEventInfo;
import org.apache.nifi.cdc.mysql.event.io.BeginTransactionEventWriter;
import org.apache.nifi.cdc.mysql.event.io.CommitTransactionEventWriter;
import org.apache.nifi.cdc.mysql.event.io.DeleteRowsWriter;
import org.apache.nifi.cdc.mysql.event.io.InsertRowsWriter;
import org.apache.nifi.cdc.mysql.event.io.DDLEventWriter;
import org.apache.nifi.cdc.mysql.event.io.UpdateRowsWriter;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.components.PropertyValue;
import org.apache.nifi.components.state.Scope;
import org.apache.nifi.components.state.StateManager;
import org.apache.nifi.components.state.StateMap;
import org.apache.nifi.distributed.cache.client.Deserializer;
import org.apache.nifi.distributed.cache.client.DistributedMapCacheClient;
import org.apache.nifi.distributed.cache.client.Serializer;
import org.apache.nifi.expression.ExpressionLanguageScope;
import org.apache.nifi.logging.ComponentLog;
import org.apache.nifi.processor.AbstractSessionFactoryProcessor;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.ProcessSessionFactory;
import org.apache.nifi.processor.Relationship;
import org.apache.nifi.processor.exception.ProcessException;
import org.apache.nifi.processor.util.StandardValidators;
import org.apache.nifi.reporting.InitializationException;
import org.apache.nifi.util.file.classloader.ClassLoaderUtils;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import static com.github.shyiko.mysql.binlog.event.EventType.DELETE_ROWS;
import static com.github.shyiko.mysql.binlog.event.EventType.EXT_DELETE_ROWS;
import static com.github.shyiko.mysql.binlog.event.EventType.EXT_WRITE_ROWS;
import static com.github.shyiko.mysql.binlog.event.EventType.FORMAT_DESCRIPTION;
import static com.github.shyiko.mysql.binlog.event.EventType.PRE_GA_DELETE_ROWS;
import static com.github.shyiko.mysql.binlog.event.EventType.PRE_GA_WRITE_ROWS;
import static com.github.shyiko.mysql.binlog.event.EventType.ROTATE;
import static com.github.shyiko.mysql.binlog.event.EventType.WRITE_ROWS;
/**
* A processor to retrieve Change Data Capture (CDC) events and send them as flow files.
*/
@TriggerSerially
@InputRequirement(InputRequirement.Requirement.INPUT_FORBIDDEN)
@Tags({"sql", "jdbc", "cdc", "mysql"})
@CapabilityDescription("Retrieves Change Data Capture (CDC) events from a MySQL database. CDC Events include INSERT, UPDATE, DELETE operations. Events "
+ "are output as individual flow files ordered by the time at which the operation occurred.")
@Stateful(scopes = Scope.CLUSTER, description = "Information such as a 'pointer' to the current CDC event in the database is stored by this processor, such "
+ "that it can continue from the same location if restarted.")
@WritesAttributes({
@WritesAttribute(attribute = EventWriter.SEQUENCE_ID_KEY, description = "A sequence identifier (i.e. strictly increasing integer value) specifying the order "
+ "of the CDC event flow file relative to the other event flow file(s)."),
@WritesAttribute(attribute = EventWriter.CDC_EVENT_TYPE_ATTRIBUTE, description = "A string indicating the type of CDC event that occurred, including (but not limited to) "
+ "'begin', 'insert', 'update', 'delete', 'ddl' and 'commit'."),
@WritesAttribute(attribute = "mime.type", description = "The processor outputs flow file content in JSON format, and sets the mime.type attribute to "
+ "application/json")
})
public class CaptureChangeMySQL extends AbstractSessionFactoryProcessor {
// Random invalid constant used as an indicator to not set the binlog position on the client (thereby using the latest available)
private static final int DO_NOT_SET = -1000;
// Relationships
public static final Relationship REL_SUCCESS = new Relationship.Builder()
.name("success")
.description("Successfully created FlowFile from SQL query result set.")
.build();
protected static Set<Relationship> relationships;
// Properties
public static final PropertyDescriptor DATABASE_NAME_PATTERN = new PropertyDescriptor.Builder()
.name("capture-change-mysql-db-name-pattern")
.displayName("Database/Schema Name Pattern")
.description("A regular expression (regex) for matching databases (or schemas, depending on your RDBMS' terminology) against the list of CDC events. The regex must match "
+ "the database name as it is stored in the RDBMS. If the property is not set, the database name will not be used to filter the CDC events. "
+ "NOTE: DDL events, even if they affect different databases, are associated with the database used by the session to execute the DDL. "
+ "This means if a connection is made to one database, but the DDL is issued against another, then the connected database will be the one matched against "
+ "the specified pattern.")
.required(false)
.addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
.build();
public static final PropertyDescriptor TABLE_NAME_PATTERN = new PropertyDescriptor.Builder()
.name("capture-change-mysql-name-pattern")
.displayName("Table Name Pattern")
.description("A regular expression (regex) for matching CDC events affecting matching tables. The regex must match the table name as it is stored in the database. "
+ "If the property is not set, no events will be filtered based on table name.")
.required(false)
.addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
.build();
public static final PropertyDescriptor CONNECT_TIMEOUT = new PropertyDescriptor.Builder()
.name("capture-change-mysql-max-wait-time")
.displayName("Max Wait Time")
.description("The maximum amount of time allowed for a connection to be established, zero means there is effectively no limit.")
.defaultValue("30 seconds")
.required(true)
.addValidator(StandardValidators.TIME_PERIOD_VALIDATOR)
.expressionLanguageSupported(ExpressionLanguageScope.VARIABLE_REGISTRY)
.build();
public static final PropertyDescriptor HOSTS = new PropertyDescriptor.Builder()
.name("capture-change-mysql-hosts")
.displayName("MySQL Hosts")
.description("A list of hostname/port entries corresponding to nodes in a MySQL cluster. The entries should be comma separated "
+ "using a colon such as host1:port,host2:port,.... For example mysql.myhost.com:3306. This processor will attempt to connect to "
+ "the hosts in the list in order. If one node goes down and failover is enabled for the cluster, then the processor will connect "
+ "to the active node (assuming its host entry is specified in this property. The default port for MySQL connections is 3306.")
.required(true)
.addValidator(StandardValidators.HOSTNAME_PORT_LIST_VALIDATOR)
.expressionLanguageSupported(ExpressionLanguageScope.VARIABLE_REGISTRY)
.build();
public static final PropertyDescriptor DRIVER_NAME = new PropertyDescriptor.Builder()
.name("capture-change-mysql-driver-class")
.displayName("MySQL Driver Class Name")
.description("The class name of the MySQL database driver class")
.defaultValue("com.mysql.jdbc.Driver")
.required(true)
.addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
.expressionLanguageSupported(ExpressionLanguageScope.VARIABLE_REGISTRY)
.build();
public static final PropertyDescriptor DRIVER_LOCATION = new PropertyDescriptor.Builder()
.name("capture-change-mysql-driver-locations")
.displayName("MySQL Driver Location(s)")
.description("Comma-separated list of files/folders and/or URLs containing the MySQL driver JAR and its dependencies (if any). "
+ "For example '/var/tmp/mysql-connector-java-5.1.38-bin.jar'")
.defaultValue(null)
.required(false)
.addValidator(StandardValidators.createListValidator(true, true, StandardValidators.createURLorFileValidator()))
.expressionLanguageSupported(ExpressionLanguageScope.VARIABLE_REGISTRY)
.build();
public static final PropertyDescriptor USERNAME = new PropertyDescriptor.Builder()
.name("capture-change-mysql-username")
.displayName("Username")
.description("Username to access the MySQL cluster")
.required(false)
.addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
.expressionLanguageSupported(ExpressionLanguageScope.VARIABLE_REGISTRY)
.build();
public static final PropertyDescriptor PASSWORD = new PropertyDescriptor.Builder()
.name("capture-change-mysql-password")
.displayName("Password")
.description("Password to access the MySQL cluster")
.required(false)
.sensitive(true)
.addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
.expressionLanguageSupported(ExpressionLanguageScope.VARIABLE_REGISTRY)
.build();
public static final PropertyDescriptor SERVER_ID = new PropertyDescriptor.Builder()
.name("capture-change-mysql-server-id")
.displayName("Server ID")
.description("The client connecting to the MySQL replication group is actually a simplified slave (server), and the Server ID value must be unique across the whole replication "
+ "group (i.e. different from any other Server ID being used by any master or slave). Thus, each instance of CaptureChangeMySQL must have a Server ID unique across "
+ "the replication group. If the Server ID is not specified, it defaults to 65535.")
.required(false)
.addValidator(StandardValidators.POSITIVE_LONG_VALIDATOR)
.expressionLanguageSupported(ExpressionLanguageScope.VARIABLE_REGISTRY)
.build();
public static final PropertyDescriptor DIST_CACHE_CLIENT = new PropertyDescriptor.Builder()
.name("capture-change-mysql-dist-map-cache-client")
.displayName("Distributed Map Cache Client")
.description("Identifies a Distributed Map Cache Client controller service to be used for keeping information about the various tables, columns, etc. "
+ "needed by the processor. If a client is not specified, the generated events will not include column type or name information.")
.identifiesControllerService(DistributedMapCacheClient.class)
.required(false)
.build();
public static final PropertyDescriptor RETRIEVE_ALL_RECORDS = new PropertyDescriptor.Builder()
.name("capture-change-mysql-retrieve-all-records")
.displayName("Retrieve All Records")
.description("Specifies whether to get all available CDC events, regardless of the current binlog filename and/or position. If binlog filename and position values are present "
+ "in the processor's State, this property's value is ignored. This allows for 4 different configurations: 1) If binlog data is available in processor State, that is used "
+ "to determine the start location and the value of Retrieve All Records is ignored. 2) If no binlog data is in processor State, then Retrieve All Records set to true "
+ "means start at the beginning of the binlog history. 3) If no binlog data is in processor State and Initial Binlog Filename/Position are not set, then "
+ "Retrieve All Records set to false means start at the end of the binlog history. 4) If no binlog data is in processor State and Initial Binlog Filename/Position "
+ "are set, then Retrieve All Records set to false means start at the specified initial binlog file/position. "
+ "To reset the behavior, clear the processor state (refer to the State Management section of the processor's documentation).")
.required(true)
.allowableValues("true", "false")
.defaultValue("true")
.addValidator(StandardValidators.BOOLEAN_VALIDATOR)
.build();
public static final PropertyDescriptor INCLUDE_BEGIN_COMMIT = new PropertyDescriptor.Builder()
.name("capture-change-mysql-include-begin-commit")
.displayName("Include Begin/Commit Events")
.description("Specifies whether to emit events corresponding to a BEGIN or COMMIT event in the binary log. Set to true if the BEGIN/COMMIT events are necessary in the downstream flow, "
+ "otherwise set to false, which suppresses generation of these events and can increase flow performance.")
.required(true)
.allowableValues("true", "false")
.defaultValue("false")
.addValidator(StandardValidators.BOOLEAN_VALIDATOR)
.build();
public static final PropertyDescriptor INCLUDE_DDL_EVENTS = new PropertyDescriptor.Builder()
.name("capture-change-mysql-include-ddl-events")
.displayName("Include DDL Events")
.description("Specifies whether to emit events corresponding to Data Definition Language (DDL) events such as ALTER TABLE, TRUNCATE TABLE, e.g. in the binary log. Set to true "
+ "if the DDL events are desired/necessary in the downstream flow, otherwise set to false, which suppresses generation of these events and can increase flow performance.")
.required(true)
.allowableValues("true", "false")
.defaultValue("false")
.addValidator(StandardValidators.BOOLEAN_VALIDATOR)
.build();
public static final PropertyDescriptor STATE_UPDATE_INTERVAL = new PropertyDescriptor.Builder()
.name("capture-change-mysql-state-update-interval")
.displayName("State Update Interval")
.description("Indicates how often to update the processor's state with binlog file/position values. A value of zero means that state will only be updated when the processor is "
+ "stopped or shutdown. If at some point the processor state does not contain the desired binlog values, the last flow file emitted will contain the last observed values, "
+ "and the processor can be returned to that state by using the Initial Binlog File, Initial Binlog Position, and Initial Sequence ID properties.")
.defaultValue("0 seconds")
.required(true)
.addValidator(StandardValidators.TIME_PERIOD_VALIDATOR)
.expressionLanguageSupported(ExpressionLanguageScope.VARIABLE_REGISTRY)
.build();
public static final PropertyDescriptor INIT_SEQUENCE_ID = new PropertyDescriptor.Builder()
.name("capture-change-mysql-init-seq-id")
.displayName("Initial Sequence ID")
.description("Specifies an initial sequence identifier to use if this processor's State does not have a current "
+ "sequence identifier. If a sequence identifier is present in the processor's State, this property is ignored. Sequence identifiers are "
+ "monotonically increasing integers that record the order of flow files generated by the processor. They can be used with the EnforceOrder "
+ "processor to guarantee ordered delivery of CDC events.")
.required(false)
.addValidator(StandardValidators.NON_NEGATIVE_INTEGER_VALIDATOR)
.expressionLanguageSupported(ExpressionLanguageScope.VARIABLE_REGISTRY)
.build();
public static final PropertyDescriptor INIT_BINLOG_FILENAME = new PropertyDescriptor.Builder()
.name("capture-change-mysql-init-binlog-filename")
.displayName("Initial Binlog Filename")
.description("Specifies an initial binlog filename to use if this processor's State does not have a current binlog filename. If a filename is present "
+ "in the processor's State, this property is ignored. This can be used along with Initial Binlog Position to \"skip ahead\" if previous events are not desired. "
+ "Note that NiFi Expression Language is supported, but this property is evaluated when the processor is configured, so FlowFile attributes may not be used. Expression "
+ "Language is supported to enable the use of the Variable Registry and/or environment properties.")
.required(false)
.addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
.expressionLanguageSupported(ExpressionLanguageScope.VARIABLE_REGISTRY)
.build();
public static final PropertyDescriptor INIT_BINLOG_POSITION = new PropertyDescriptor.Builder()
.name("capture-change-mysql-init-binlog-position")
.displayName("Initial Binlog Position")
.description("Specifies an initial offset into a binlog (specified by Initial Binlog Filename) to use if this processor's State does not have a current "
+ "binlog filename. If a filename is present in the processor's State, this property is ignored. This can be used along with Initial Binlog Filename "
+ "to \"skip ahead\" if previous events are not desired. Note that NiFi Expression Language is supported, but this property is evaluated when the "
+ "processor is configured, so FlowFile attributes may not be used. Expression Language is supported to enable the use of the Variable Registry "
+ "and/or environment properties.")
.required(false)
.addValidator(StandardValidators.NON_NEGATIVE_INTEGER_VALIDATOR)
.expressionLanguageSupported(ExpressionLanguageScope.VARIABLE_REGISTRY)
.build();
private static List<PropertyDescriptor> propDescriptors;
private volatile ProcessSession currentSession;
private BinaryLogClient binlogClient;
private BinlogEventListener eventListener;
private BinlogLifecycleListener lifecycleListener;
private volatile LinkedBlockingQueue<RawBinlogEvent> queue = new LinkedBlockingQueue<>();
private volatile String currentBinlogFile = null;
private volatile long currentBinlogPosition = 4;
// The following variables save the value of the binlog filename and position (and sequence id) at the beginning of a transaction. Used for rollback
private volatile String xactBinlogFile = null;
private volatile long xactBinlogPosition = 4;
private volatile long xactSequenceId = 0;
private volatile TableInfo currentTable = null;
private volatile String currentDatabase = null;
private volatile Pattern databaseNamePattern;
private volatile Pattern tableNamePattern;
private volatile boolean includeBeginCommit = false;
private volatile boolean includeDDLEvents = false;
private volatile boolean inTransaction = false;
private volatile boolean skipTable = false;
private AtomicBoolean doStop = new AtomicBoolean(false);
private AtomicBoolean hasRun = new AtomicBoolean(false);
private int currentHost = 0;
private String transitUri = "<unknown>";
private volatile long lastStateUpdate = 0L;
private volatile long stateUpdateInterval = -1L;
private AtomicLong currentSequenceId = new AtomicLong(0);
private volatile DistributedMapCacheClient cacheClient = null;
private final Serializer<TableInfoCacheKey> cacheKeySerializer = new TableInfoCacheKey.Serializer();
private final Serializer<TableInfo> cacheValueSerializer = new TableInfo.Serializer();
private final Deserializer<TableInfo> cacheValueDeserializer = new TableInfo.Deserializer();
private Connection jdbcConnection = null;
private final BeginTransactionEventWriter beginEventWriter = new BeginTransactionEventWriter();
private final CommitTransactionEventWriter commitEventWriter = new CommitTransactionEventWriter();
private final DDLEventWriter ddlEventWriter = new DDLEventWriter();
private final InsertRowsWriter insertRowsWriter = new InsertRowsWriter();
private final DeleteRowsWriter deleteRowsWriter = new DeleteRowsWriter();
private final UpdateRowsWriter updateRowsWriter = new UpdateRowsWriter();
static {
final Set<Relationship> r = new HashSet<>();
r.add(REL_SUCCESS);
relationships = Collections.unmodifiableSet(r);
final List<PropertyDescriptor> pds = new ArrayList<>();
pds.add(HOSTS);
pds.add(DRIVER_NAME);
pds.add(DRIVER_LOCATION);
pds.add(USERNAME);
pds.add(PASSWORD);
pds.add(SERVER_ID);
pds.add(DATABASE_NAME_PATTERN);
pds.add(TABLE_NAME_PATTERN);
pds.add(CONNECT_TIMEOUT);
pds.add(DIST_CACHE_CLIENT);
pds.add(RETRIEVE_ALL_RECORDS);
pds.add(INCLUDE_BEGIN_COMMIT);
pds.add(INCLUDE_DDL_EVENTS);
pds.add(STATE_UPDATE_INTERVAL);
pds.add(INIT_SEQUENCE_ID);
pds.add(INIT_BINLOG_FILENAME);
pds.add(INIT_BINLOG_POSITION);
propDescriptors = Collections.unmodifiableList(pds);
}
@Override
public Set<Relationship> getRelationships() {
return relationships;
}
@Override
protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
return propDescriptors;
}
public void setup(ProcessContext context) {
final ComponentLog logger = getLogger();
final StateManager stateManager = context.getStateManager();
final StateMap stateMap;
try {
stateMap = stateManager.getState(Scope.CLUSTER);
} catch (final IOException ioe) {
logger.error("Failed to retrieve observed maximum values from the State Manager. Will not attempt "
+ "connection until this is accomplished.", ioe);
context.yield();
return;
}
PropertyValue dbNameValue = context.getProperty(DATABASE_NAME_PATTERN);
databaseNamePattern = dbNameValue.isSet() ? Pattern.compile(dbNameValue.getValue()) : null;
PropertyValue tableNameValue = context.getProperty(TABLE_NAME_PATTERN);
tableNamePattern = tableNameValue.isSet() ? Pattern.compile(tableNameValue.getValue()) : null;
stateUpdateInterval = context.getProperty(STATE_UPDATE_INTERVAL).evaluateAttributeExpressions().asTimePeriod(TimeUnit.MILLISECONDS);
boolean getAllRecords = context.getProperty(RETRIEVE_ALL_RECORDS).asBoolean();
includeBeginCommit = context.getProperty(INCLUDE_BEGIN_COMMIT).asBoolean();
includeDDLEvents = context.getProperty(INCLUDE_DDL_EVENTS).asBoolean();
// Set current binlog filename to whatever is in State, falling back to the Retrieve All Records then Initial Binlog Filename if no State variable is present
currentBinlogFile = stateMap.get(BinlogEventInfo.BINLOG_FILENAME_KEY);
if (currentBinlogFile == null) {
if (!getAllRecords) {
if (context.getProperty(INIT_BINLOG_FILENAME).isSet()) {
currentBinlogFile = context.getProperty(INIT_BINLOG_FILENAME).evaluateAttributeExpressions().getValue();
}
} else {
// If we're starting from the beginning of all binlogs, the binlog filename must be the empty string (not null)
currentBinlogFile = "";
}
}
// Set current binlog position to whatever is in State, falling back to the Retrieve All Records then Initial Binlog Filename if no State variable is present
String binlogPosition = stateMap.get(BinlogEventInfo.BINLOG_POSITION_KEY);
if (binlogPosition != null) {
currentBinlogPosition = Long.valueOf(binlogPosition);
} else if (!getAllRecords) {
if (context.getProperty(INIT_BINLOG_POSITION).isSet()) {
currentBinlogPosition = context.getProperty(INIT_BINLOG_POSITION).evaluateAttributeExpressions().asLong();
} else {
currentBinlogPosition = DO_NOT_SET;
}
} else {
currentBinlogPosition = -1;
}
// Get current sequence ID from state
String seqIdString = stateMap.get(EventWriter.SEQUENCE_ID_KEY);
if (StringUtils.isEmpty(seqIdString)) {
// Use Initial Sequence ID property if none is found in state
PropertyValue seqIdProp = context.getProperty(INIT_SEQUENCE_ID);
if (seqIdProp.isSet()) {
currentSequenceId.set(seqIdProp.evaluateAttributeExpressions().asInteger());
}
} else {
currentSequenceId.set(Integer.parseInt(seqIdString));
}
// Get reference to Distributed Cache if one exists. If it does not, no enrichment (resolution of column names, e.g.) will be performed
boolean createEnrichmentConnection = false;
if (context.getProperty(DIST_CACHE_CLIENT).isSet()) {
cacheClient = context.getProperty(DIST_CACHE_CLIENT).asControllerService(DistributedMapCacheClient.class);
createEnrichmentConnection = true;
} else {
logger.warn("No Distributed Map Cache Client is specified, so no event enrichment (resolution of column names, e.g.) will be performed.");
cacheClient = null;
}
// Save off MySQL cluster and JDBC driver information, will be used to connect for event enrichment as well as for the binlog connector
try {
List<InetSocketAddress> hosts = getHosts(context.getProperty(HOSTS).evaluateAttributeExpressions().getValue());
String username = context.getProperty(USERNAME).evaluateAttributeExpressions().getValue();
String password = context.getProperty(PASSWORD).evaluateAttributeExpressions().getValue();
// BinaryLogClient expects a non-null password, so set it to the empty string if it is not provided
if (password == null) {
password = "";
}
long connectTimeout = context.getProperty(CONNECT_TIMEOUT).evaluateAttributeExpressions().asTimePeriod(TimeUnit.MILLISECONDS);
String driverLocation = context.getProperty(DRIVER_LOCATION).evaluateAttributeExpressions().getValue();
String driverName = context.getProperty(DRIVER_NAME).evaluateAttributeExpressions().getValue();
Long serverId = context.getProperty(SERVER_ID).evaluateAttributeExpressions().asLong();
connect(hosts, username, password, serverId, createEnrichmentConnection, driverLocation, driverName, connectTimeout);
} catch (IOException | IllegalStateException e) {
context.yield();
binlogClient = null;
throw new ProcessException(e.getMessage(), e);
}
}
@Override
public void onTrigger(ProcessContext context, ProcessSessionFactory sessionFactory) throws ProcessException {
// Indicate that this processor has executed at least once, so we know whether or not the state values are valid and should be updated
hasRun.set(true);
ComponentLog log = getLogger();
StateManager stateManager = context.getStateManager();
// Create a client if we don't have one
if (binlogClient == null) {
setup(context);
}
// If the client has been disconnected, try to reconnect
if (!binlogClient.isConnected()) {
Exception e = lifecycleListener.getException();
// If there's no exception, the listener callback might not have been executed yet, so try again later. Otherwise clean up and start over next time
if (e != null) {
// Communications failure, disconnect and try next time
log.error("Binlog connector communications failure: " + e.getMessage(), e);
try {
stop(stateManager);
} catch (CDCException ioe) {
throw new ProcessException(ioe);
}
}
// Try again later
context.yield();
return;
}
if (currentSession == null) {
currentSession = sessionFactory.createSession();
}
try {
outputEvents(currentSession, stateManager, log);
long now = System.currentTimeMillis();
long timeSinceLastUpdate = now - lastStateUpdate;
if (stateUpdateInterval != 0 && timeSinceLastUpdate >= stateUpdateInterval) {
updateState(stateManager, currentBinlogFile, currentBinlogPosition, currentSequenceId.get());
lastStateUpdate = now;
}
} catch (IOException ioe) {
try {
// Perform some processor-level "rollback", then rollback the session
currentBinlogFile = xactBinlogFile == null ? "" : xactBinlogFile;
currentBinlogPosition = xactBinlogPosition;
currentSequenceId.set(xactSequenceId);
inTransaction = false;
stop(stateManager);
queue.clear();
currentSession.rollback();
} catch (Exception e) {
// Not much we can recover from here
log.warn("Error occurred during rollback", e);
}
throw new ProcessException(ioe);
}
}
@OnStopped
public void onStopped(ProcessContext context) {
try {
stop(context.getStateManager());
} catch (CDCException ioe) {
throw new ProcessException(ioe);
}
}
@OnShutdown
public void onShutdown(ProcessContext context) {
try {
// In case we get shutdown while still running, save off the current state, disconnect, and shut down gracefully
stop(context.getStateManager());
} catch (CDCException ioe) {
throw new ProcessException(ioe);
}
}
/**
* Get a list of hosts from a NiFi property, e.g.
*
* @param hostsString A comma-separated list of hosts (host:port,host2:port2, etc.)
* @return List of InetSocketAddresses for the hosts
*/
private List<InetSocketAddress> getHosts(String hostsString) {
if (hostsString == null) {
return null;
}
final List<String> hostsSplit = Arrays.asList(hostsString.split(","));
List<InetSocketAddress> hostsList = new ArrayList<>();
for (String item : hostsSplit) {
String[] addresses = item.split(":");
if (addresses.length != 2) {
throw new ArrayIndexOutOfBoundsException("Not in host:port format");
}
hostsList.add(new InetSocketAddress(addresses[0].trim(), Integer.parseInt(addresses[1].trim())));
}
return hostsList;
}
protected void connect(List<InetSocketAddress> hosts, String username, String password, Long serverId, boolean createEnrichmentConnection,
String driverLocation, String driverName, long connectTimeout) throws IOException {
int connectionAttempts = 0;
final int numHosts = hosts.size();
InetSocketAddress connectedHost = null;
Exception lastConnectException = new Exception("Unknown connection error");
if (createEnrichmentConnection) {
try {
// Ensure driverLocation and driverName are correct before establishing binlog connection
// to avoid failing after binlog messages are received.
// Actual JDBC connection is created after binlog client gets started, because we need
// the connect-able host same as the binlog client.
registerDriver(driverLocation, driverName);
} catch (InitializationException e) {
throw new RuntimeException("Failed to register JDBC driver. Ensure MySQL Driver Location(s)" +
" and MySQL Driver Class Name are configured correctly. " + e, e);
}
}
while (connectedHost == null && connectionAttempts < numHosts) {
if (binlogClient == null) {
connectedHost = hosts.get(currentHost);
binlogClient = createBinlogClient(connectedHost.getHostString(), connectedHost.getPort(), username, password);
}
// Add an event listener and lifecycle listener for binlog and client events, respectively
if (eventListener == null) {
eventListener = createBinlogEventListener(binlogClient, queue);
}
eventListener.start();
binlogClient.registerEventListener(eventListener);
if (lifecycleListener == null) {
lifecycleListener = createBinlogLifecycleListener();
}
binlogClient.registerLifecycleListener(lifecycleListener);
binlogClient.setBinlogFilename(currentBinlogFile);
if (currentBinlogPosition != DO_NOT_SET) {
binlogClient.setBinlogPosition(currentBinlogPosition);
}
if (serverId != null) {
binlogClient.setServerId(serverId);
}
try {
if (connectTimeout == 0) {
connectTimeout = Long.MAX_VALUE;
}
binlogClient.connect(connectTimeout);
transitUri = "mysql://" + connectedHost.getHostString() + ":" + connectedHost.getPort();
} catch (IOException | TimeoutException te) {
// Try the next host
connectedHost = null;
transitUri = "<unknown>";
currentHost = (currentHost + 1) % numHosts;
connectionAttempts++;
lastConnectException = te;
}
}
if (!binlogClient.isConnected()) {
binlogClient.disconnect();
binlogClient = null;
throw new IOException("Could not connect binlog client to any of the specified hosts due to: " + lastConnectException.getMessage(), lastConnectException);
}
if (createEnrichmentConnection) {
try {
jdbcConnection = getJdbcConnection(driverLocation, driverName, connectedHost, username, password, null);
} catch (InitializationException | SQLException e) {
binlogClient.disconnect();
binlogClient = null;
throw new IOException("Error creating binlog enrichment JDBC connection to any of the specified hosts", e);
}
}
doStop.set(false);
}
public void outputEvents(ProcessSession session, StateManager stateManager, ComponentLog log) throws IOException {
RawBinlogEvent rawBinlogEvent;
// Drain the queue
while ((rawBinlogEvent = queue.poll()) != null && !doStop.get()) {
Event event = rawBinlogEvent.getEvent();
EventHeaderV4 header = event.getHeader();
long timestamp = header.getTimestamp();
EventType eventType = header.getEventType();
// Advance the current binlog position. This way if no more events are received and the processor is stopped, it will resume at the event about to be processed.
// We always get ROTATE and FORMAT_DESCRIPTION messages no matter where we start (even from the end), and they won't have the correct "next position" value, so only
// advance the position if it is not that type of event. ROTATE events don't generate output CDC events and have the current binlog position in a special field, which
// is filled in during the ROTATE case
if (eventType != ROTATE && eventType != FORMAT_DESCRIPTION) {
currentBinlogPosition = header.getPosition();
}
log.debug("Got message event type: {} ", new Object[]{header.getEventType().toString()});
switch (eventType) {
case TABLE_MAP:
// This is sent to inform which table is about to be changed by subsequent events
TableMapEventData data = event.getData();
// Should we skip this table? Yes if we've specified a DB or table name pattern and they don't match
skipTable = (databaseNamePattern != null && !databaseNamePattern.matcher(data.getDatabase()).matches())
|| (tableNamePattern != null && !tableNamePattern.matcher(data.getTable()).matches());
if (!skipTable) {
TableInfoCacheKey key = new TableInfoCacheKey(this.getIdentifier(), data.getDatabase(), data.getTable(), data.getTableId());
if (cacheClient != null) {
try {
currentTable = cacheClient.get(key, cacheKeySerializer, cacheValueDeserializer);
} catch (ConnectException ce) {
throw new IOException("Could not connect to Distributed Map Cache server to get table information", ce);
}
if (currentTable == null) {
// We don't have an entry for this table yet, so fetch the info from the database and populate the cache
try {
currentTable = loadTableInfo(key);
try {
cacheClient.put(key, currentTable, cacheKeySerializer, cacheValueSerializer);
} catch (ConnectException ce) {
throw new IOException("Could not connect to Distributed Map Cache server to put table information", ce);
}
} catch (SQLException se) {
// Propagate the error up, so things like rollback and logging/bulletins can be handled
throw new IOException(se.getMessage(), se);
}
}
}
} else {
// Clear the current table, to force a reload next time we get a TABLE_MAP event we care about
currentTable = null;
}
break;
case QUERY:
QueryEventData queryEventData = event.getData();
currentDatabase = queryEventData.getDatabase();
String sql = queryEventData.getSql();
// Is this the start of a transaction?
if ("BEGIN".equals(sql)) {
// If we're already in a transaction, something bad happened, alert the user
if (inTransaction) {
throw new IOException("BEGIN event received while already processing a transaction. This could indicate that your binlog position is invalid.");
}
// Mark the current binlog position in case we have to rollback the transaction (if the processor is stopped, e.g.)
xactBinlogFile = currentBinlogFile;
xactBinlogPosition = currentBinlogPosition;
xactSequenceId = currentSequenceId.get();
if (includeBeginCommit && (databaseNamePattern == null || databaseNamePattern.matcher(currentDatabase).matches())) {
BeginTransactionEventInfo beginEvent = new BeginTransactionEventInfo(currentDatabase, timestamp, currentBinlogFile, currentBinlogPosition);
currentSequenceId.set(beginEventWriter.writeEvent(currentSession, transitUri, beginEvent, currentSequenceId.get(), REL_SUCCESS));
}
inTransaction = true;
} else if ("COMMIT".equals(sql)) {
if (!inTransaction) {
throw new IOException("COMMIT event received while not processing a transaction (i.e. no corresponding BEGIN event). "
+ "This could indicate that your binlog position is invalid.");
}
// InnoDB generates XID events for "commit", but MyISAM generates Query events with "COMMIT", so handle that here
if (includeBeginCommit && (databaseNamePattern == null || databaseNamePattern.matcher(currentDatabase).matches())) {
CommitTransactionEventInfo commitTransactionEvent = new CommitTransactionEventInfo(currentDatabase, timestamp, currentBinlogFile, currentBinlogPosition);
currentSequenceId.set(commitEventWriter.writeEvent(currentSession, transitUri, commitTransactionEvent, currentSequenceId.get(), REL_SUCCESS));
}
// Commit the NiFi session
session.commit();
inTransaction = false;
currentTable = null;
} else {
// Check for DDL events (alter table, e.g.). Normalize the query to do string matching on the type of change
String normalizedQuery = sql.toLowerCase().trim().replaceAll(" {2,}", " ");
if (normalizedQuery.startsWith("alter table")
|| normalizedQuery.startsWith("alter ignore table")
|| normalizedQuery.startsWith("create table")
|| normalizedQuery.startsWith("truncate table")
|| normalizedQuery.startsWith("rename table")
|| normalizedQuery.startsWith("drop table")
|| normalizedQuery.startsWith("drop database")) {
if (includeDDLEvents && (databaseNamePattern == null || databaseNamePattern.matcher(currentDatabase).matches())) {
// If we don't have table information, we can still use the database name
TableInfo ddlTableInfo = (currentTable != null) ? currentTable : new TableInfo(currentDatabase, null, null, null);
DDLEventInfo ddlEvent = new DDLEventInfo(ddlTableInfo, timestamp, currentBinlogFile, currentBinlogPosition, sql);
currentSequenceId.set(ddlEventWriter.writeEvent(currentSession, transitUri, ddlEvent, currentSequenceId.get(), REL_SUCCESS));
}
// Remove all the keys from the cache that this processor added
if (cacheClient != null) {
cacheClient.removeByPattern(this.getIdentifier() + ".*");
}
// If not in a transaction, commit the session so the DDL event(s) will be transferred
if (includeDDLEvents && !inTransaction) {
session.commit();
}
}
}
break;
case XID:
if (!inTransaction) {
throw new IOException("COMMIT event received while not processing a transaction (i.e. no corresponding BEGIN event). "
+ "This could indicate that your binlog position is invalid.");
}
if (includeBeginCommit && (databaseNamePattern == null || databaseNamePattern.matcher(currentDatabase).matches())) {
CommitTransactionEventInfo commitTransactionEvent = new CommitTransactionEventInfo(currentDatabase, timestamp, currentBinlogFile, currentBinlogPosition);
currentSequenceId.set(commitEventWriter.writeEvent(currentSession, transitUri, commitTransactionEvent, currentSequenceId.get(), REL_SUCCESS));
}
// Commit the NiFi session
session.commit();
inTransaction = false;
currentTable = null;
currentDatabase = null;
break;
case WRITE_ROWS:
case EXT_WRITE_ROWS:
case PRE_GA_WRITE_ROWS:
case UPDATE_ROWS:
case EXT_UPDATE_ROWS:
case PRE_GA_UPDATE_ROWS:
case DELETE_ROWS:
case EXT_DELETE_ROWS:
case PRE_GA_DELETE_ROWS:
// If we are skipping this table, then don't emit any events related to its modification
if (skipTable) {
break;
}
if (!inTransaction) {
// These events should only happen inside a transaction, warn the user otherwise
log.warn("Table modification event occurred outside of a transaction.");
break;
}
if (currentTable == null && cacheClient != null) {
// No Table Map event was processed prior to this event, which should not happen, so throw an error
throw new RowEventException("No table information is available for this event, cannot process further.");
}
if (eventType == WRITE_ROWS
|| eventType == EXT_WRITE_ROWS
|| eventType == PRE_GA_WRITE_ROWS) {
InsertRowsEventInfo eventInfo = new InsertRowsEventInfo(currentTable, timestamp, currentBinlogFile, currentBinlogPosition, event.getData());
currentSequenceId.set(insertRowsWriter.writeEvent(currentSession, transitUri, eventInfo, currentSequenceId.get(), REL_SUCCESS));
} else if (eventType == DELETE_ROWS
|| eventType == EXT_DELETE_ROWS
|| eventType == PRE_GA_DELETE_ROWS) {
DeleteRowsEventInfo eventInfo = new DeleteRowsEventInfo(currentTable, timestamp, currentBinlogFile, currentBinlogPosition, event.getData());
currentSequenceId.set(deleteRowsWriter.writeEvent(currentSession, transitUri, eventInfo, currentSequenceId.get(), REL_SUCCESS));
} else {
// Update event
UpdateRowsEventInfo eventInfo = new UpdateRowsEventInfo(currentTable, timestamp, currentBinlogFile, currentBinlogPosition, event.getData());
currentSequenceId.set(updateRowsWriter.writeEvent(currentSession, transitUri, eventInfo, currentSequenceId.get(), REL_SUCCESS));
}
break;
case ROTATE:
// Update current binlog filename
RotateEventData rotateEventData = event.getData();
currentBinlogFile = rotateEventData.getBinlogFilename();
currentBinlogPosition = rotateEventData.getBinlogPosition();
break;
default:
break;
}
// Advance the current binlog position. This way if no more events are received and the processor is stopped, it will resume after the event that was just processed.
// We always get ROTATE and FORMAT_DESCRIPTION messages no matter where we start (even from the end), and they won't have the correct "next position" value, so only
// advance the position if it is not that type of event.
if (eventType != ROTATE && eventType != FORMAT_DESCRIPTION) {
currentBinlogPosition = header.getNextPosition();
}
}
}
protected void stop(StateManager stateManager) throws CDCException {
try {
if (binlogClient != null) {
binlogClient.disconnect();
}
if (eventListener != null) {
eventListener.stop();
if (binlogClient != null) {
binlogClient.unregisterEventListener(eventListener);
}
}
doStop.set(true);
if (hasRun.getAndSet(false)) {
updateState(stateManager, currentBinlogFile, currentBinlogPosition, currentSequenceId.get());
}
currentBinlogPosition = -1;
} catch (IOException e) {
throw new CDCException("Error closing CDC connection", e);
} finally {
binlogClient = null;
}
}
private void updateState(StateManager stateManager, String binlogFile, long binlogPosition, long sequenceId) throws IOException {
// Update state with latest values
if (stateManager != null) {
Map<String, String> newStateMap = new HashMap<>(stateManager.getState(Scope.CLUSTER).toMap());
// Save current binlog filename and position to the state map
if (binlogFile != null) {
newStateMap.put(BinlogEventInfo.BINLOG_FILENAME_KEY, binlogFile);
}
newStateMap.put(BinlogEventInfo.BINLOG_POSITION_KEY, Long.toString(binlogPosition));
newStateMap.put(EventWriter.SEQUENCE_ID_KEY, String.valueOf(sequenceId));
stateManager.setState(newStateMap, Scope.CLUSTER);
}
}
/**
* Creates and returns a BinlogEventListener instance, associated with the specified binlog client and event queue.
*
* @param client A reference to a BinaryLogClient. The listener is associated with the given client, such that the listener is notified when
* events are available to the given client.
* @param q A queue used to communicate events between the listener and the NiFi processor thread.
* @return A BinlogEventListener instance, which will be notified of events associated with the specified client
*/
BinlogEventListener createBinlogEventListener(BinaryLogClient client, LinkedBlockingQueue<RawBinlogEvent> q) {
return new BinlogEventListener(client, q);
}
/**
* Creates and returns a BinlogLifecycleListener instance, associated with the specified binlog client and event queue.
*
* @return A BinlogLifecycleListener instance, which will be notified of events associated with the specified client
*/
BinlogLifecycleListener createBinlogLifecycleListener() {
return new BinlogLifecycleListener();
}
BinaryLogClient createBinlogClient(String hostname, int port, String username, String password) {
return new BinaryLogClient(hostname, port, username, password);
}
/**
* Retrieves the column information for the specified database and table. The column information can be used to enrich CDC events coming from the RDBMS.
*
* @param key A TableInfoCacheKey reference, which contains the database and table names
* @return A TableInfo instance with the ColumnDefinitions provided (if retrieved successfully from the database)
*/
protected TableInfo loadTableInfo(TableInfoCacheKey key) throws SQLException {
TableInfo tableInfo = null;
if (jdbcConnection != null) {
try (Statement s = jdbcConnection.createStatement()) {
s.execute("USE " + key.getDatabaseName());
ResultSet rs = s.executeQuery("SELECT * FROM " + key.getTableName() + " LIMIT 0");
ResultSetMetaData rsmd = rs.getMetaData();
int numCols = rsmd.getColumnCount();
List<ColumnDefinition> columnDefinitions = new ArrayList<>();
for (int i = 1; i <= numCols; i++) {
// Use the column label if it exists, otherwise use the column name. We're not doing aliasing here, but it's better practice.
String columnLabel = rsmd.getColumnLabel(i);
columnDefinitions.add(new ColumnDefinition(rsmd.getColumnType(i), columnLabel != null ? columnLabel : rsmd.getColumnName(i)));
}
tableInfo = new TableInfo(key.getDatabaseName(), key.getTableName(), key.getTableId(), columnDefinitions);
}
}
return tableInfo;
}
/**
* using Thread.currentThread().getContextClassLoader(); will ensure that you are using the ClassLoader for you NAR.
*
* @throws InitializationException if there is a problem obtaining the ClassLoader
*/
protected Connection getJdbcConnection(String locationString, String drvName, InetSocketAddress host, String username, String password, Map<String, String> customProperties)
throws InitializationException, SQLException {
Properties connectionProps = new Properties();
if (customProperties != null) {
connectionProps.putAll(customProperties);
}
connectionProps.put("user", username);
connectionProps.put("password", password);
return DriverManager.getConnection("jdbc:mysql://" + host.getHostString() + ":" + host.getPort(), connectionProps);
}
protected void registerDriver(String locationString, String drvName) throws InitializationException {
if (locationString != null && locationString.length() > 0) {
try {
// Split and trim the entries
final ClassLoader classLoader = ClassLoaderUtils.getCustomClassLoader(
locationString,
this.getClass().getClassLoader(),
(dir, name) -> name != null && name.endsWith(".jar")
);
// Workaround which allows to use URLClassLoader for JDBC driver loading.
// (Because the DriverManager will refuse to use a driver not loaded by the system ClassLoader.)
final Class<?> clazz = Class.forName(drvName, true, classLoader);
if (clazz == null) {
throw new InitializationException("Can't load Database Driver " + drvName);
}
final Driver driver = (Driver) clazz.newInstance();
DriverManager.registerDriver(new DriverShim(driver));
} catch (final InitializationException e) {
throw e;
} catch (final MalformedURLException e) {
throw new InitializationException("Invalid Database Driver Jar Url", e);
} catch (final Exception e) {
throw new InitializationException("Can't load Database Driver", e);
}
}
}
private static class DriverShim implements Driver {
private Driver driver;
DriverShim(Driver d) {
this.driver = d;
}
@Override
public boolean acceptsURL(String u) throws SQLException {
return this.driver.acceptsURL(u);
}
@Override
public Connection connect(String u, Properties p) throws SQLException {
return this.driver.connect(u, p);
}
@Override
public int getMajorVersion() {
return this.driver.getMajorVersion();
}
@Override
public int getMinorVersion() {
return this.driver.getMinorVersion();
}
@Override
public DriverPropertyInfo[] getPropertyInfo(String u, Properties p) throws SQLException {
return this.driver.getPropertyInfo(u, p);
}
@Override
public boolean jdbcCompliant() {
return this.driver.jdbcCompliant();
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return driver.getParentLogger();
}
}
}
| Wesley-Lawrence/nifi | nifi-nar-bundles/nifi-cdc/nifi-cdc-mysql-bundle/nifi-cdc-mysql-processors/src/main/java/org/apache/nifi/cdc/mysql/processors/CaptureChangeMySQL.java | Java | apache-2.0 | 60,260 |
/*
* Copyright (c) 2015, 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.
*/
var pref = new gadgets.Prefs();
var node = pref.getString('node') || undefined;
var start = pref.getString('startTime') || undefined;
var end = pref.getString('endTime') || undefined;
var url = pref.getString('dataSource');
var template;
function fetchData(startTime, endTime) {
var url = pref.getString('dataSource');
var data = {
start_time: start,
end_time: end,
node: node,
action: pref.getString('appStatType')
};
var appname = pref.getString('appname');
if (appname != '') {
data.appname = appname;
}
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
data: data,
success: onDataReceived
});
}
function onDataReceived(data) {
var tableData = data.data;
var tableHeadings = data.headings;
var orderColumn = data.orderColumn;
var applist = data.applist || undefined;
var table;
var headings;
headings = getTableHeader(tableHeadings);
$('#placeholder').html(template(headings));
var dataTableOptions = {};
dataTableOptions['data'] = tableData;
dataTableOptions['order'] = [orderColumn];
if (!applist) {
dataTableOptions['aoColumns'] = [
{'sWidth': '60%'},
{'sWidth': '20%'},
{'sWidth': '20%'}
];
}
table = $('#table').dataTable(dataTableOptions);
if (applist) {
registerWebappSelect(table);
}
}
function registerWebappSelect(table) {
table.find('tbody').on('click', 'tr', function () {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
} else {
var param = '';
if (node) {
param = 'node=' + node;
}
if (start && end) {
param = param + (param == '' ? '' : '&') +
'start-time=' + moment(start, 'YYYY-MM-DD HH:mm').format('X') +
'&end-time=' + moment(end, 'YYYY-MM-DD HH:mm').format('X');
}
var webapp = table.fnGetData(this)[0];
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
var webappUrl = webapp;
if (param != '?') {
webappUrl = webappUrl + '?' + param;
}
publishRedirectUrl(webappUrl);
}
});
}
function getTableHeader(tableHeadings) {
var headingArray = [];
var row = [];
var th = {};
var rowSpan = 1;
var i, j, len, len2;
for (i = 0, len = tableHeadings.length; i < len; i++) {
if (tableHeadings[i] instanceof Object) {
rowSpan = 2;
break;
}
}
for (i = 0, len = tableHeadings.length; i < len; i++) {
th = {};
if (typeof(tableHeadings[i]) == 'string') {
th.rowSpan = rowSpan;
th.text = tableHeadings[i];
} else {
th.colSpan = tableHeadings[i]["sub"].length;
th.text = tableHeadings[i]['parent'];
}
row.push(th);
}
headingArray.push(row);
if (rowSpan > 1) {
row = [];
for (i = 0, len = tableHeadings.length; i < len; i++) {
if (tableHeadings[i] instanceof Object) {
var subHeadings = tableHeadings[i]['sub'];
for (j = 0, len2 = subHeadings.length; j < len2; j++) {
th = {};
th.text = subHeadings[j];
row.push(th);
}
}
}
headingArray.push(row);
}
return headingArray;
}
function publishRedirectUrl(url) {
gadgets.Hub.publish('wso2.as.http.dashboard.webapp.url', url);
}
$(function () {
fetchData();
Handlebars.registerHelper('generateHeadingTag', function (th) {
var properties = '';
properties += (th.rowSpan) ? " rowspan='" + th.rowSpan + "'" : '';
properties += (th.colSpan) ? " colspan='" + th.colSpan + "'" : '';
return new Handlebars.SafeString('<th' + properties + '>' + th.text + '</th>');
});
template = Handlebars.compile($('#table-template').html());
});
gadgets.HubSettings.onConnect = function () {
gadgets.Hub.subscribe('wso2.gadgets.charts.timeRangeChange',
function (topic, data, subscriberData) {
start = data.start.format('YYYY-MM-DD HH:mm');
end = data.end.format('YYYY-MM-DD HH:mm');
fetchData();
}
);
gadgets.Hub.subscribe('wso2.gadgets.charts.ipChange',
function (topic, data, subscriberData) {
node = data;
fetchData();
}
);
};
| pirinthapan/app-cloud | modules/setup-scripts/conf/wso2das-3.0.1/repository/deployment/server/jaggeryapps/monitoring/gadgets/data-table/js/data-table.js | JavaScript | apache-2.0 | 5,363 |
/*
* 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.presto.operator;
import com.facebook.airlift.http.client.HttpUriBuilder;
import com.facebook.airlift.log.Logger;
import com.facebook.presto.server.remotetask.Backoff;
import com.facebook.presto.spi.HostAddress;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.page.SerializedPage;
import com.google.common.base.Ticker;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import io.airlift.units.DataSize;
import io.airlift.units.Duration;
import org.joda.time.DateTime;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;
import java.io.Closeable;
import java.net.URI;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import static com.facebook.presto.spi.HostAddress.fromUri;
import static com.facebook.presto.spi.StandardErrorCode.REMOTE_BUFFER_CLOSE_FAILED;
import static com.facebook.presto.spi.StandardErrorCode.REMOTE_TASK_MISMATCH;
import static com.facebook.presto.spi.StandardErrorCode.SERIALIZED_PAGE_CHECKSUM_ERROR;
import static com.facebook.presto.spi.page.PagesSerdeUtil.isChecksumValid;
import static com.facebook.presto.util.Failures.REMOTE_TASK_MISMATCH_ERROR;
import static com.facebook.presto.util.Failures.WORKER_NODE_ERROR;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
@ThreadSafe
public final class PageBufferClient
implements Closeable
{
private static final Logger log = Logger.get(PageBufferClient.class);
/**
* For each request, the addPage method will be called zero or more times,
* followed by either requestComplete or clientFinished (if buffer complete). If the client is
* closed, requestComplete or bufferFinished may never be called.
* <p/>
* <b>NOTE:</b> Implementations of this interface are not allowed to perform
* blocking operations.
*/
public interface ClientCallback
{
boolean addPages(PageBufferClient client, List<SerializedPage> pages);
void requestComplete(PageBufferClient client);
void clientFinished(PageBufferClient client);
void clientFailed(PageBufferClient client, Throwable cause);
}
private final RpcShuffleClient resultClient;
private final boolean acknowledgePages;
private final URI location;
private final Optional<URI> asyncPageTransportLocation;
private final ClientCallback clientCallback;
private final ScheduledExecutorService scheduler;
private final Backoff backoff;
@GuardedBy("this")
private boolean closed;
@GuardedBy("this")
private ListenableFuture<?> future;
@GuardedBy("this")
private DateTime lastUpdate = DateTime.now();
@GuardedBy("this")
private long token;
@GuardedBy("this")
private boolean scheduled;
@GuardedBy("this")
private boolean completed;
@GuardedBy("this")
private String taskInstanceId;
private final AtomicLong rowsReceived = new AtomicLong();
private final AtomicInteger pagesReceived = new AtomicInteger();
private final AtomicLong rowsRejected = new AtomicLong();
private final AtomicInteger pagesRejected = new AtomicInteger();
private final AtomicInteger requestsScheduled = new AtomicInteger();
private final AtomicInteger requestsCompleted = new AtomicInteger();
private final AtomicInteger requestsFailed = new AtomicInteger();
private final Executor pageBufferClientCallbackExecutor;
public PageBufferClient(
RpcShuffleClient resultClient,
Duration maxErrorDuration,
boolean acknowledgePages,
URI location,
Optional<URI> asyncPageTransportLocation,
ClientCallback clientCallback,
ScheduledExecutorService scheduler,
Executor pageBufferClientCallbackExecutor)
{
this(resultClient, maxErrorDuration, acknowledgePages, location, asyncPageTransportLocation, clientCallback, scheduler, Ticker.systemTicker(), pageBufferClientCallbackExecutor);
}
public PageBufferClient(
RpcShuffleClient resultClient,
Duration maxErrorDuration,
boolean acknowledgePages,
URI location,
Optional<URI> asyncPageTransportLocation,
ClientCallback clientCallback,
ScheduledExecutorService scheduler,
Ticker ticker,
Executor pageBufferClientCallbackExecutor)
{
this.resultClient = requireNonNull(resultClient, "resultClient is null");
this.acknowledgePages = acknowledgePages;
this.location = requireNonNull(location, "location is null");
this.asyncPageTransportLocation = requireNonNull(asyncPageTransportLocation, "asyncPageTransportLocation is null");
this.clientCallback = requireNonNull(clientCallback, "clientCallback is null");
this.scheduler = requireNonNull(scheduler, "scheduler is null");
this.pageBufferClientCallbackExecutor = requireNonNull(pageBufferClientCallbackExecutor, "pageBufferClientCallbackExecutor is null");
requireNonNull(maxErrorDuration, "maxErrorDuration is null");
requireNonNull(ticker, "ticker is null");
this.backoff = new Backoff(maxErrorDuration, ticker);
}
public synchronized PageBufferClientStatus getStatus()
{
String state;
if (closed) {
state = "closed";
}
else if (future != null) {
state = "running";
}
else if (scheduled) {
state = "scheduled";
}
else if (completed) {
state = "completed";
}
else {
state = "queued";
}
long rejectedRows = rowsRejected.get();
int rejectedPages = pagesRejected.get();
return new PageBufferClientStatus(
location,
state,
lastUpdate,
rowsReceived.get(),
pagesReceived.get(),
rejectedRows == 0 ? OptionalLong.empty() : OptionalLong.of(rejectedRows),
rejectedPages == 0 ? OptionalInt.empty() : OptionalInt.of(rejectedPages),
requestsScheduled.get(),
requestsCompleted.get(),
requestsFailed.get(),
future == null ? "not scheduled" : "processing request");
}
public synchronized boolean isRunning()
{
return future != null;
}
@Override
public void close()
{
boolean shouldSendDelete;
Future<?> future;
synchronized (this) {
shouldSendDelete = !closed;
closed = true;
future = this.future;
this.future = null;
lastUpdate = DateTime.now();
}
if (future != null && !future.isDone()) {
// do not terminate if the request is already running to avoid closing pooled connections
future.cancel(false);
}
// abort the output buffer on the remote node; response of delete is ignored
if (shouldSendDelete) {
sendDelete();
}
}
public synchronized void scheduleRequest(DataSize maxResponseSize)
{
if (closed || (future != null) || scheduled) {
return;
}
scheduled = true;
// start before scheduling to include error delay
backoff.startRequest();
long delayNanos = backoff.getBackoffDelayNanos();
scheduler.schedule(() -> {
try {
initiateRequest(maxResponseSize);
}
catch (Throwable t) {
// should not happen, but be safe and fail the operator
clientCallback.clientFailed(PageBufferClient.this, t);
}
}, delayNanos, NANOSECONDS);
lastUpdate = DateTime.now();
requestsScheduled.incrementAndGet();
}
private synchronized void initiateRequest(DataSize maxResponseSize)
{
scheduled = false;
if (closed || (future != null)) {
return;
}
if (completed) {
sendDelete();
}
else {
sendGetResults(maxResponseSize);
}
lastUpdate = DateTime.now();
}
private synchronized void sendGetResults(DataSize maxResponseSize)
{
URI uriBase = asyncPageTransportLocation.orElse(location);
URI uri = HttpUriBuilder.uriBuilderFrom(uriBase).appendPath(String.valueOf(token)).build();
ListenableFuture<PagesResponse> resultFuture = resultClient.getResults(token, maxResponseSize);
future = resultFuture;
Futures.addCallback(resultFuture, new FutureCallback<PagesResponse>()
{
@Override
public void onSuccess(PagesResponse result)
{
checkNotHoldsLock(this);
backoff.success();
List<SerializedPage> pages;
try {
boolean shouldAcknowledge = false;
synchronized (PageBufferClient.this) {
if (taskInstanceId == null) {
taskInstanceId = result.getTaskInstanceId();
}
if (!isNullOrEmpty(taskInstanceId) && !result.getTaskInstanceId().equals(taskInstanceId)) {
// TODO: update error message
throw new PrestoException(REMOTE_TASK_MISMATCH, format("%s (%s)", REMOTE_TASK_MISMATCH_ERROR, fromUri(uri)));
}
if (result.getToken() == token) {
pages = result.getPages();
token = result.getNextToken();
shouldAcknowledge = pages.size() > 0;
}
else {
pages = ImmutableList.of();
}
}
if (shouldAcknowledge && acknowledgePages) {
// Acknowledge token without handling the response.
// The next request will also make sure the token is acknowledged.
// This is to fast release the pages on the buffer side.
resultClient.acknowledgeResultsAsync(result.getNextToken());
}
for (SerializedPage page : pages) {
if (!isChecksumValid(page)) {
throw new PrestoException(SERIALIZED_PAGE_CHECKSUM_ERROR, format("Received corrupted serialized page from host %s", HostAddress.fromUri(uri)));
}
}
// add pages:
// addPages must be called regardless of whether pages is an empty list because
// clientCallback can keep stats of requests and responses. For example, it may
// keep track of how often a client returns empty response and adjust request
// frequency or buffer size.
if (clientCallback.addPages(PageBufferClient.this, pages)) {
pagesReceived.addAndGet(pages.size());
rowsReceived.addAndGet(pages.stream().mapToLong(SerializedPage::getPositionCount).sum());
}
else {
pagesRejected.addAndGet(pages.size());
rowsRejected.addAndGet(pages.stream().mapToLong(SerializedPage::getPositionCount).sum());
}
}
catch (PrestoException e) {
handleFailure(e, resultFuture);
return;
}
synchronized (PageBufferClient.this) {
// client is complete, acknowledge it by sending it a delete in the next request
if (result.isClientComplete()) {
completed = true;
}
if (future == resultFuture) {
future = null;
}
lastUpdate = DateTime.now();
}
requestsCompleted.incrementAndGet();
clientCallback.requestComplete(PageBufferClient.this);
}
@Override
public void onFailure(Throwable t)
{
log.debug("Request to %s failed %s", uri, t);
checkNotHoldsLock(this);
t = resultClient.rewriteException(t);
if (!(t instanceof PrestoException) && backoff.failure()) {
String message = format("%s (%s - %s failures, failure duration %s, total failed request time %s)",
WORKER_NODE_ERROR,
uri,
backoff.getFailureCount(),
backoff.getFailureDuration().convertTo(SECONDS),
backoff.getFailureRequestTimeTotal().convertTo(SECONDS));
t = new PageTransportTimeoutException(fromUri(uri), message, t);
}
handleFailure(t, resultFuture);
}
}, pageBufferClientCallbackExecutor);
}
private synchronized void sendDelete()
{
ListenableFuture<?> resultFuture = resultClient.abortResults();
future = resultFuture;
Futures.addCallback(resultFuture, new FutureCallback<Object>()
{
@Override
public void onSuccess(@Nullable Object result)
{
checkNotHoldsLock(this);
backoff.success();
synchronized (PageBufferClient.this) {
closed = true;
if (future == resultFuture) {
future = null;
}
lastUpdate = DateTime.now();
}
requestsCompleted.incrementAndGet();
clientCallback.clientFinished(PageBufferClient.this);
}
@Override
public void onFailure(Throwable t)
{
checkNotHoldsLock(this);
log.error("Request to delete %s failed %s", location, t);
if (!(t instanceof PrestoException) && backoff.failure()) {
String message = format("Error closing remote buffer (%s - %s failures, failure duration %s, total failed request time %s)",
location,
backoff.getFailureCount(),
backoff.getFailureDuration().convertTo(SECONDS),
backoff.getFailureRequestTimeTotal().convertTo(SECONDS));
t = new PrestoException(REMOTE_BUFFER_CLOSE_FAILED, message, t);
}
handleFailure(t, resultFuture);
}
}, pageBufferClientCallbackExecutor);
}
private static void checkNotHoldsLock(Object lock)
{
checkState(!Thread.holdsLock(lock), "Cannot execute this method while holding a lock");
}
private void handleFailure(Throwable t, ListenableFuture<?> expectedFuture)
{
// Can not delegate to other callback while holding a lock on this
checkNotHoldsLock(this);
requestsFailed.incrementAndGet();
requestsCompleted.incrementAndGet();
if (t instanceof PrestoException) {
clientCallback.clientFailed(PageBufferClient.this, t);
}
synchronized (PageBufferClient.this) {
if (future == expectedFuture) {
future = null;
}
lastUpdate = DateTime.now();
}
clientCallback.requestComplete(PageBufferClient.this);
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PageBufferClient that = (PageBufferClient) o;
if (!location.equals(that.location)) {
return false;
}
return true;
}
@Override
public int hashCode()
{
return location.hashCode();
}
@Override
public String toString()
{
String state;
synchronized (this) {
if (closed) {
state = "CLOSED";
}
else if (future != null) {
state = "RUNNING";
}
else {
state = "QUEUED";
}
}
return toStringHelper(this)
.add("location", location)
.addValue(state)
.toString();
}
public static class PagesResponse
{
public static PagesResponse createPagesResponse(String taskInstanceId, long token, long nextToken, Iterable<SerializedPage> pages, boolean complete)
{
return new PagesResponse(taskInstanceId, token, nextToken, pages, complete);
}
public static PagesResponse createEmptyPagesResponse(String taskInstanceId, long token, long nextToken, boolean complete)
{
return new PagesResponse(taskInstanceId, token, nextToken, ImmutableList.of(), complete);
}
private final String taskInstanceId;
private final long token;
private final long nextToken;
private final List<SerializedPage> pages;
private final boolean clientComplete;
private PagesResponse(String taskInstanceId, long token, long nextToken, Iterable<SerializedPage> pages, boolean clientComplete)
{
this.taskInstanceId = taskInstanceId;
this.token = token;
this.nextToken = nextToken;
this.pages = ImmutableList.copyOf(pages);
this.clientComplete = clientComplete;
}
public long getToken()
{
return token;
}
public long getNextToken()
{
return nextToken;
}
public List<SerializedPage> getPages()
{
return pages;
}
public boolean isClientComplete()
{
return clientComplete;
}
public String getTaskInstanceId()
{
return taskInstanceId;
}
@Override
public String toString()
{
return toStringHelper(this)
.add("token", token)
.add("nextToken", nextToken)
.add("pagesSize", pages.size())
.add("clientComplete", clientComplete)
.toString();
}
}
}
| facebook/presto | presto-main/src/main/java/com/facebook/presto/operator/PageBufferClient.java | Java | apache-2.0 | 20,089 |
<form action="<?php echo BASEPATH_HARDCODED ?>users/add/" method="post">
<label for="email">Emailadres:</label>
<input type="text" name="email" name="email"/>
<br />
<label for="password">Paswoord:</label>
<input type="text" name="password" id="password"/>
<br />
<input type="submit" value="toevoegen">
</form>
<br/><br/>
<ol>
<?php $number = 0?>
<?php foreach ($users as $user):?>
<a class="big" href="<?php echo BASEPATH_HARDCODED ?>users/view/<?php echo $user['User']['id']?>/<?php echo strtolower(str_replace(" ","-",$user['User']['email']))?>">
<span class="item">
<?php echo $user['User']['email']?></a> - <a class="big" href="<?php echo BASEPATH_HARDCODED ?>users/delete/<?php echo $user['User']['id']?>">Verwijder gebruiker</a>
</span>
<br/>
<?php endforeach?>
</ol> | WouterSchoofs/web-backend | public/cursus/voorbeelden/voorbeeld-mvc-058/application/views/users/viewall.php | PHP | apache-2.0 | 800 |
/*
* Spine Runtimes Software License
* Version 2.3
*
* Copyright (c) 2013-2015, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable and
* non-transferable license to use, install, execute and perform the Spine
* Runtimes Software (the "Software") and derivative works solely for personal
* or internal use. Without the written permission of Esoteric Software (see
* Section 2 of the Spine Software License Agreement), you may not (a) modify,
* translate, adapt or otherwise create derivative works, improvements of the
* Software or develop new applications using the Software or (b) remove,
* delete, alter or obscure any trademarks or any copyright, trademark, patent
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.esotericsoftware.spine.attachments;
abstract public class Attachment {
final String name;
public Attachment (String name) {
if (name == null) throw new IllegalArgumentException("name cannot be null.");
this.name = name;
}
public String getName () {
return name;
}
public String toString () {
return getName();
}
}
| intrigus/VisEditor | Plugins/SpineRuntime/src/com/esotericsoftware/spine/attachments/Attachment.java | Java | apache-2.0 | 2,037 |
# ----------------------------------------------------------------
# Copyright 2016 Cisco Systems
#
# 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.
# ------------------------------------------------------------------
""" _importer.py
Merge _yang_ns for subpackage to a single _yang_ns at runtime.
"""
import importlib
import pkgutil
from ydk import models
class YangNs(object):
def __init__(self, d):
self.__dict__ = d
_yang_ns_dict = {}
exempt_keys = set(['__builtins__', '__doc__', '__file__',
'__name__', '__package__'])
try:
_yang_ns = importlib.import_module('ydk.models._yang_ns')
except ImportError:
for (importer, name, ispkg) in pkgutil.iter_modules(models.__path__):
if ispkg:
try:
mod_yang_ns = importlib.import_module('ydk.models.%s._yang_ns' % name)
except ImportError:
continue
keys = set(mod_yang_ns.__dict__) - exempt_keys
for key in keys:
if key not in _yang_ns_dict:
_yang_ns_dict[key] = mod_yang_ns.__dict__[key]
else:
if isinstance(_yang_ns_dict[key], dict):
_yang_ns_dict[key].update(mod_yang_ns.__dict__[key])
else:
# shadow old value
_yang_ns_dict[key] = mod_yang_ns.__dict__[key]
_yang_ns = YangNs(_yang_ns_dict)
| 111pontes/ydk-py | core/ydk/providers/_importer.py | Python | apache-2.0 | 1,938 |
exports.name = 'should';
exports.category = 'bdd/tdd';
exports.homepage = 'https://npmjs.org/package/should';
| ek1437/PeerTutor | www.peertutor.com/node_modules/nodeman/docs/should.meta.js | JavaScript | apache-2.0 | 110 |
/*
* 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.ec2.model.transform;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.internal.ListWithAutoConstructFlag;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;
/**
* Delete Network Acl Entry Request Marshaller
*/
public class DeleteNetworkAclEntryRequestMarshaller implements Marshaller<Request<DeleteNetworkAclEntryRequest>, DeleteNetworkAclEntryRequest> {
public Request<DeleteNetworkAclEntryRequest> marshall(DeleteNetworkAclEntryRequest deleteNetworkAclEntryRequest) {
if (deleteNetworkAclEntryRequest == null) {
throw new AmazonClientException("Invalid argument passed to marshall(...)");
}
Request<DeleteNetworkAclEntryRequest> request = new DefaultRequest<DeleteNetworkAclEntryRequest>(deleteNetworkAclEntryRequest, "AmazonEC2");
request.addParameter("Action", "DeleteNetworkAclEntry");
request.addParameter("Version", "2015-10-01");
if (deleteNetworkAclEntryRequest.getNetworkAclId() != null) {
request.addParameter("NetworkAclId", StringUtils.fromString(deleteNetworkAclEntryRequest.getNetworkAclId()));
}
if (deleteNetworkAclEntryRequest.getRuleNumber() != null) {
request.addParameter("RuleNumber", StringUtils.fromInteger(deleteNetworkAclEntryRequest.getRuleNumber()));
}
if (deleteNetworkAclEntryRequest.isEgress() != null) {
request.addParameter("Egress", StringUtils.fromBoolean(deleteNetworkAclEntryRequest.isEgress()));
}
return request;
}
}
| sdole/aws-sdk-java | aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/transform/DeleteNetworkAclEntryRequestMarshaller.java | Java | apache-2.0 | 2,365 |
/*******************************************************************************
* 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.ofbiz.base.util.collections;
import java.util.Locale;
import java.util.Map;
import org.apache.ofbiz.base.util.Debug;
/**
* Map Stack
*
*/
public class MapStack<K> extends MapContext<K, Object> {
public static final String module = MapStack.class.getName();
public static <K> MapStack<K> create() {
MapStack<K> newValue = new MapStack<K>();
// initialize with a single entry
newValue.push();
return newValue;
}
@SuppressWarnings("unchecked")
public static <K> MapStack<K> create(Map<K, Object> baseMap) {
MapStack<K> newValue = new MapStack<K>();
if (baseMap instanceof MapStack) {
newValue.stackList.addAll(((MapStack) baseMap).stackList);
} else {
newValue.stackList.add(0, baseMap);
}
return newValue;
}
/** Does a shallow copy of the internal stack of the passed MapStack; enables simultaneous stacks that share common parent Maps */
public static <K> MapStack<K> create(MapStack<K> source) {
MapStack<K> newValue = new MapStack<K>();
newValue.stackList.addAll(source.stackList);
return newValue;
}
protected MapStack() {
super();
}
/**
* Creates a MapStack object that has the same Map objects on its stack;
* meant to be used to enable a
* situation where a parent and child context are operating simultaneously
* using two different MapStack objects, but sharing the Maps in common
*/
@Override
public MapStack<K> standAloneStack() {
MapStack<K> standAlone = MapStack.create(this);
return standAlone;
}
/**
* Creates a MapStack object that has the same Map objects on its stack,
* but with a new Map pushed on the top; meant to be used to enable a
* situation where a parent and child context are operating simultaneously
* using two different MapStack objects, but sharing the Maps in common
*/
@Override
public MapStack<K> standAloneChildStack() {
MapStack<K> standAloneChild = MapStack.create(this);
standAloneChild.push();
return standAloneChild;
}
/* (non-Javadoc)
* @see java.util.Map#get(java.lang.Object)
*/
@Override
public Object get(Object key) {
if ("context".equals(key)) {
return this;
}
return super.get(key);
}
/* (non-Javadoc)
* @see org.apache.ofbiz.base.util.collections.LocalizedMap#get(java.lang.String, java.util.Locale)
*/
@Override
public Object get(String name, Locale locale) {
if ("context".equals(name)) {
return this;
}
return super.get(name, locale);
}
/* (non-Javadoc)
* @see java.util.Map#put(java.lang.Object, java.lang.Object)
*/
@Override
public Object put(K key, Object value) {
if ("context".equals(key)) {
if (value == null || this != value) {
Debug.logWarning("Putting a value in a MapStack with key [context] that is not this MapStack, will be hidden by the current MapStack self-reference: " + value, module);
}
}
return super.put(key, value);
}
}
| yuri0x7c1/ofbiz-explorer | src/test/resources/apache-ofbiz-16.11.03/framework/base/src/main/java/org/apache/ofbiz/base/util/collections/MapStack.java | Java | apache-2.0 | 4,203 |
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifdef INTEL_MKL
#include <limits>
#include <vector>
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/kernels/bounds_check.h"
#include "tensorflow/core/kernels/concat_lib.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/types.h"
#include "third_party/mkl/include/mkl_dnn_types.h"
#include "third_party/mkl/include/mkl_dnn.h"
#include "tensorflow/core/util/mkl_util.h"
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
enum AxisArgumentName { NAME_IS_AXIS, NAME_IS_CONCAT_DIM };
// TODO(intelft) Check if we can reuse existing EigenConcatOp using Mutable
// reference inputs.
// --------------------------------------------------------------------------
// Eigen Concat Op
// --------------------------------------------------------------------------
template <typename Device, typename T, AxisArgumentName AxisArgName>
class EigenConcatBaseOp : public OpKernel {
public:
typedef std::vector<std::unique_ptr<typename TTypes<T, 2>::ConstMatrix>>
ConstMatrixVector;
explicit EigenConcatBaseOp(OpKernelConstruction* c) : OpKernel(c) {}
// Although, we modify Compute for this call to accept one extra param,
// we need to have empty Compute because Compute is pure virtual function.
void Compute(OpKernelContext* c) {}
void Compute(OpKernelContext* c, const std::vector<Tensor>& values) {
const Tensor* concat_dim_tensor;
const char* axis_attribute_name =
AxisArgName == NAME_IS_AXIS
? "axis"
: AxisArgName == NAME_IS_CONCAT_DIM ? "concat_dim" : "<invalid>";
OP_REQUIRES_OK(c, c->input(axis_attribute_name, &concat_dim_tensor));
OP_REQUIRES(c, IsLegacyScalar(concat_dim_tensor->shape()),
errors::InvalidArgument(
axis_attribute_name,
" tensor should be a scalar integer, but got shape ",
concat_dim_tensor->shape().DebugString()));
const int32 concat_dim =
internal::SubtleMustCopy(concat_dim_tensor->scalar<int32>()());
// Instead of accessing values from context, we use input to Compute.
const int N = values.size();
const int input_dims = values[0].dims();
const TensorShape& input_shape = values[0].shape();
int32 axis = concat_dim < 0 ? concat_dim + input_dims : concat_dim;
OP_REQUIRES(c, (0 <= axis && axis < input_dims) ||
(allow_legacy_scalars() && concat_dim == 0),
errors::InvalidArgument(
"ConcatOp : Expected concatenating dimensions in the range "
"[",
-input_dims, ", ", input_dims, "), but got ", concat_dim));
// Note that we reduce the concat of n-dimensional tensors into a two
// dimensional concat. Assuming the dimensions of any input/output
// tensor are {x0, x1,...,xn-1, y0, y1,...,ym-1}, where the concat is along
// the dimension indicated with size y0, we flatten it to {x, y}, where y =
// Prod_i(yi) and x = ((n > 0) ? Prod_i(xi) : 1).
ConstMatrixVector inputs_flat;
inputs_flat.reserve(N);
int64 inputs_flat_dim0 = 1;
for (int d = 0; d < axis; ++d) {
inputs_flat_dim0 *= input_shape.dim_size(d);
}
int64 output_concat_dim = 0;
const bool input_is_scalar = IsLegacyScalar(input_shape);
for (int i = 0; i < N; ++i) {
const auto in = values[i];
const bool in_is_scalar = IsLegacyScalar(in.shape());
OP_REQUIRES(
c, in.dims() == input_dims || (input_is_scalar && in_is_scalar),
errors::InvalidArgument(
"ConcatOp : Ranks of all input tensors should match: shape[0] = ",
input_shape.DebugString(), " vs. shape[", i, "] = ",
in.shape().DebugString()));
for (int j = 0; j < input_dims; ++j) {
if (j == axis) {
continue;
}
OP_REQUIRES(
c, in.dim_size(j) == input_shape.dim_size(j),
errors::InvalidArgument(
"ConcatOp : Dimensions of inputs should match: shape[0] = ",
input_shape.DebugString(), " vs. shape[", i, "] = ",
in.shape().DebugString()));
}
if (in.NumElements() > 0) {
int64 inputs_flat_dim1 = in.NumElements() / inputs_flat_dim0;
inputs_flat.emplace_back(new typename TTypes<T, 2>::ConstMatrix(
in.shaped<T, 2>({inputs_flat_dim0, inputs_flat_dim1})));
}
// TODO(irving): Remove check once !allow_legacy_scalars().
output_concat_dim += in.dims() > 0 ? in.dim_size(axis) : 1;
}
TensorShape output_shape(input_shape);
// TODO(irving): Remove rank 0 case once !allow_legacy_scalars().
if (output_shape.dims() == 0) {
output_shape.AddDim(output_concat_dim);
} else {
output_shape.set_dim(axis, output_concat_dim);
}
Tensor* output = nullptr;
OP_REQUIRES_OK(c, c->allocate_output(0, output_shape, &output));
if (output->NumElements() > 0) {
int64 output_dim1 = output->NumElements() / inputs_flat_dim0;
auto output_flat = output->shaped<T, 2>({inputs_flat_dim0, output_dim1});
ConcatCPU<T>(c->device(), inputs_flat, &output_flat);
}
}
};
// --------------------------------------------------------------------------
// Mkl Concat Op
// --------------------------------------------------------------------------
template <typename Device, typename T, AxisArgumentName AxisArgName>
class MklConcatOp : public OpKernel {
private:
TensorFormat data_format_;
EigenConcatBaseOp<Device, T, AxisArgName> eigen_concat_op_;
public:
typedef std::vector<std::unique_ptr<typename TTypes<T, 2>::ConstMatrix>>
ConstMatrixVector;
explicit MklConcatOp(OpKernelConstruction* c) : OpKernel(c),
eigen_concat_op_(c) {}
void Compute(OpKernelContext* context) override {
MklConcatOpContext mkl_context;
// Get input tensors.
OpInputList input_tensors;
GetMklInputList(context, "values", &input_tensors);
const int N = input_tensors.size();
// Get MKL shapes.
MklShapeList input_shapes(N);
GetMklShapeList(context, "values", &input_shapes);
// If this is Concat, then concat_dim is 0th input.
// If this is ConcatV2, then axis is Nth input.
const Tensor& concat_dim_tensor = AxisArgName == NAME_IS_CONCAT_DIM ?
MklGetInput(context, 0) :
MklGetInput(context, N);
// Sanity checks
OP_REQUIRES(
context, IsLegacyScalar(concat_dim_tensor.shape()),
errors::InvalidArgument(
"Concat dim tensor should be a scalar integer, but got shape ",
concat_dim_tensor.shape().DebugString()));
int32 concat_dim =
internal::SubtleMustCopy(concat_dim_tensor.scalar<int32>()());
MklShape& inpshape0 = input_shapes[0];
// Check that all tensors are Mkl, if not we call Eigen version.
bool invoke_eigen = false;
bool is_concat_dim_channel = true;
if (!AreAllMklTensors(input_shapes)) {
invoke_eigen = true;
}
// Check that total number of dimensions is 4, if not call Eigen.
if (!invoke_eigen) {
for (auto& s : input_shapes) {
if (s.GetDimension() != 4) {
invoke_eigen = true;
break;
}
}
}
// check that concat_dim is channel, if not call Eigen version.
if (!invoke_eigen) {
for (auto& s : input_shapes) {
if (!s.IsMklChannelDim(concat_dim)) {
invoke_eigen = true;
is_concat_dim_channel = false;
break;
}
}
}
if (invoke_eigen) {
string msg = std::string("Invoking Eigen version of Concat. Reason:") +
(!is_concat_dim_channel ?
std::string("Concat dimension is not channel") :
std::string("Not all tensors are in Mkl layout"));
VLOG(1) << "MklConcatOp: " << msg;
CallEigenVersion(context, input_tensors, input_shapes);
return;
}
// For MKL format, the channel is dimension number 2.
// So if we are concating over channel and _all_ inputs are in MKL
// format, then we set concat_dim to 2.
// Since we have reached till here, it means we are concating
// over channel.
concat_dim = MklDims::C;
// One more sanity check: check that ranks of all tensors match
// and that their shapes match except for concat_dim.
int i = 0;
for (auto& s : input_shapes) {
size_t exp_dims = inpshape0.GetDimension();
OP_REQUIRES(
context, s.GetDimension() == exp_dims,
errors::InvalidArgument(
"MklConcatOp : Ranks of all input tensors should match:"
" input dimensions = ", s.GetDimension(),
" vs. expected rank = ", exp_dims));
for (int d = 0; d < exp_dims; ++d) {
if (d == concat_dim) {
continue;
}
size_t exp_size = inpshape0.GetSizes()[d];
OP_REQUIRES(context, exp_size == s.GetSizes()[d],
errors::InvalidArgument("MklConcatOp : Dimensions of inputs"
"should match: shape[0][", d, "]= ", exp_size, " vs. shape[",
i, "][", d, "] = ", s.GetSizes()[d]));
}
++i;
}
// Use input MKL layout instead of creating new layouts.
int64 output_concat_dim_size = 0;
for (auto& s : input_shapes) {
output_concat_dim_size += s.GetDimension() > 0 ?
s.GetSizes()[concat_dim] : 1;
}
mkl_context.MklCreateInputLayouts(context, input_shapes);
CHECK_EQ(dnnConcatCreate_F32(&mkl_context.prim_concat, NULL, N,
&mkl_context.lt_inputs[0]),
E_SUCCESS);
// Calculate output sizes and strides
TensorFormat data_format;
if (inpshape0.IsTensorInNHWCFormat()) {
data_format = FORMAT_NHWC;
} else {
OP_REQUIRES(context, inpshape0.IsTensorInNCHWFormat(),
errors::InvalidArgument(
"MklConcat only supports all inputs in NCHW or NHWC format "));
data_format = FORMAT_NCHW;
}
// Since all tensors are in Mkl layout, we copy sizes from input tensor.
mkl_context.out_sizes[MklDims::W] = inpshape0.GetSizes()[MklDims::W];
mkl_context.out_sizes[MklDims::H] = inpshape0.GetSizes()[MklDims::H];
mkl_context.out_sizes[MklDims::C] = output_concat_dim_size;
mkl_context.out_sizes[MklDims::N] = inpshape0.GetSizes()[MklDims::N];
GetStridesFromSizes(data_format, mkl_context.out_strides,
mkl_context.out_sizes);
// Set output Mkl shape.
int64 dim = 4;
MklShape mkl_output_mkl_shape;
mkl_output_mkl_shape.SetMklTensor(true);
mkl_output_mkl_shape.SetMklLayout(mkl_context.prim_concat, dnnResourceDst);
mkl_output_mkl_shape.SetTfLayout(dim, mkl_context.out_sizes,
mkl_context.out_strides);
mkl_output_mkl_shape.SetTfDimOrder(dim, inpshape0.GetTfToMklDimMap());
TensorShape mkl_output_tf_shape;
mkl_output_tf_shape.AddDim(1);
mkl_output_tf_shape.AddDim(dnnLayoutGetMemorySize_F32(
static_cast<dnnLayout_t>(mkl_output_mkl_shape.GetMklLayout()))/sizeof(T));
Tensor* output = nullptr;
AllocateOutputSetMklShape(context, 0, &output, mkl_output_tf_shape,
mkl_output_mkl_shape);
// Set destination resource.
mkl_context.concat_res[dnnResourceDst] = const_cast<void*>(
static_cast<const void*>(output->flat<T>().data()));
mkl_context.mkl_tmp_tensors.resize(N);
mkl_context.MklPrepareConcatInputs(context, input_tensors);
// Execute primitive.
CHECK_EQ(dnnExecute_F32(mkl_context.prim_concat, mkl_context.concat_res),
E_SUCCESS);
mkl_context.MklCleanup();
}
private:
typedef struct {
TensorFormat data_format;
size_t out_sizes[4];
size_t out_strides[4];
dnnPrimitive_t prim_concat;
void *concat_res[dnnResourceNumber];
std::vector<dnnLayout_t> lt_inputs;
std::vector<Tensor> mkl_tmp_tensors;
// Create MKL dnnLayout_t objects for tensors coming into the layer
// We only support case where input tensors are all in Mkl layout.
void MklCreateInputLayouts(OpKernelContext* context,
MklShapeList& input_shapes) {
for (auto& is : input_shapes) {
CHECK_EQ(is.IsMklTensor(), true);
lt_inputs.push_back((dnnLayout_t) is.GetCurLayout());
}
}
void MklPrepareConcatInputs(OpKernelContext* context,
OpInputList& input_tensors) {
CHECK_EQ(lt_inputs.size(), mkl_tmp_tensors.size());
for (int i = 0; i < lt_inputs.size(); ++i) {
dnnPrimitive_t mkl_prim_convert_input;
dnnLayout_t mkl_lt_internal_input;
void* mkl_buf_convert_input = nullptr;
CHECK_EQ(dnnLayoutCreateFromPrimitive_F32(&mkl_lt_internal_input,
prim_concat,
(dnnResourceType_t)
(dnnResourceMultipleSrc + i)),
E_SUCCESS);
if (!dnnLayoutCompare_F32(lt_inputs[i], mkl_lt_internal_input)) {
CHECK_EQ(dnnConversionCreate_F32(&mkl_prim_convert_input,
lt_inputs[i],
mkl_lt_internal_input),
E_SUCCESS);
AllocTmpBuffer(context, &mkl_tmp_tensors[i],
mkl_lt_internal_input,
&mkl_buf_convert_input);
CHECK_EQ(dnnConversionExecute_F32(mkl_prim_convert_input,
const_cast<void*>(static_cast<const void*>(
input_tensors[i].flat<T>().data())),
mkl_buf_convert_input),
E_SUCCESS);
concat_res[dnnResourceMultipleSrc + i] = mkl_buf_convert_input;
CHECK_EQ(dnnDelete_F32(mkl_prim_convert_input), E_SUCCESS);
} else {
concat_res[dnnResourceMultipleSrc + i] = const_cast<void*>(
static_cast<const void*>(
input_tensors[i].flat<T>().data()));
}
CHECK_EQ(dnnLayoutDelete_F32(mkl_lt_internal_input), E_SUCCESS);
}
}
void MklCleanup() {
for (auto& lt : lt_inputs) {
lt = nullptr;
}
CHECK_EQ(dnnDelete_F32(prim_concat), E_SUCCESS);
}
} MklConcatOpContext;
void CallEigenVersion(OpKernelContext* context, const OpInputList& values,
const MklShapeList& input_shapes) {
// Before calling Eigen version, we need to convert Mkl tensors to TF.
// First check that the number of input tensors and the number of Mkl
// shapes match.
CHECK_EQ(values.size(), input_shapes.size());
std::vector<Tensor> converted_values;
for (int i = 0; i < input_shapes.size(); i++) {
if (input_shapes[i].IsMklTensor()) {
// If input tensor is Mkl, then do the conversion.
Tensor tmp_tensor = ConvertMklToTF<T>(context,
values[i],
input_shapes[i]);
converted_values.push_back(tmp_tensor);
} else {
// If input tensor is TF already, then we do not need any conversion.
converted_values.push_back(values[i]);
}
}
// Call Eigen concat.
eigen_concat_op_.Compute(context, converted_values);
// Set dummy Mkl tensor as output Mkl tensor for this op.
MklShape mkl_tensor_mkl_shape;
mkl_tensor_mkl_shape.SetMklTensor(false);
mkl_tensor_mkl_shape.SetDimensions(4);
mkl_tensor_mkl_shape.SetTfDimOrder(4); // Dimensions
Tensor* mkl_tensor = nullptr;
TensorShape mkl_tensor_tf_shape;
mkl_tensor_tf_shape.AddDim(SIZE_OF_MKL_SERIAL_DATA(
mkl_tensor_mkl_shape.GetDimension()));
int tf_output_index = 0;
context->allocate_output(GetTensorMetaDataIndex(tf_output_index,
context->num_outputs()),
mkl_tensor_tf_shape, &mkl_tensor);
mkl_tensor_mkl_shape.SerializeMklShape(
mkl_tensor->flat<uint8>().data(),
mkl_tensor->flat<uint8>().size() * sizeof(uint8));
}
};
/* Use optimized concat for float type only */
#define REGISTER_MKL_CPU(type) \
REGISTER_KERNEL_BUILDER(Name("MklConcat") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.HostMemory("concat_dim") \
.Label(mkl_op_registry::kMklOpLabel), \
MklConcatOp<CPUDevice, type, NAME_IS_CONCAT_DIM>) \
REGISTER_KERNEL_BUILDER(Name("MklConcatV2") \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<int32>("Tidx") \
.HostMemory("axis") \
.Label(mkl_op_registry::kMklOpLabel), \
MklConcatOp<CPUDevice, type, NAME_IS_AXIS>)
TF_CALL_float(REGISTER_MKL_CPU);
#undef REGISTER_CONCAT_MKL
} // namespace tensorflow
#endif // INTEL_MKL
| SnakeJenny/TensorFlow | tensorflow/core/kernels/mkl_concat_op.cc | C++ | apache-2.0 | 18,576 |
/*
* $Id: Login.java 471756 2006-11-06 15:01:43Z husted $
*
* 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 mailreader2;
import org.apache.struts.apps.mailreader.dao.User;
import org.apache.struts.apps.mailreader.dao.ExpiredPasswordException;
/**
* <p> Validate a user login. </p>
*/
public final class Login extends MailreaderSupport {
public String execute() throws ExpiredPasswordException {
User user = findUser(getUsername(), getPassword());
if (user != null) {
setUser(user);
}
if (hasErrors()) {
return INPUT;
}
return SUCCESS;
}
}
| WillJiang/WillJiang | src/apps/mailreader/src/main/java/mailreader2/Login.java | Java | apache-2.0 | 1,397 |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
const models = require('./index');
/**
* Model class for event details of a VMwareAzureV2 event.
*
* @extends models['EventProviderSpecificDetails']
*/
class InMageAzureV2EventDetails extends models['EventProviderSpecificDetails'] {
/**
* Create a InMageAzureV2EventDetails.
* @member {string} [eventType] InMage Event type. Takes one of the values of
* {InMageDataContract.InMageMonitoringEventType}.
* @member {string} [category] InMage Event Category.
* @member {string} [component] InMage Event Component.
* @member {string} [correctiveAction] Corrective Action string for the
* event.
* @member {string} [details] InMage Event Details.
* @member {string} [summary] InMage Event Summary.
* @member {string} [siteName] VMware Site name.
*/
constructor() {
super();
}
/**
* Defines the metadata of InMageAzureV2EventDetails
*
* @returns {object} metadata of InMageAzureV2EventDetails
*
*/
mapper() {
return {
required: false,
serializedName: 'InMageAzureV2',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: 'instanceType',
clientName: 'instanceType'
},
uberParent: 'EventProviderSpecificDetails',
className: 'InMageAzureV2EventDetails',
modelProperties: {
instanceType: {
required: true,
serializedName: 'instanceType',
isPolymorphicDiscriminator: true,
type: {
name: 'String'
}
},
eventType: {
required: false,
serializedName: 'eventType',
type: {
name: 'String'
}
},
category: {
required: false,
serializedName: 'category',
type: {
name: 'String'
}
},
component: {
required: false,
serializedName: 'component',
type: {
name: 'String'
}
},
correctiveAction: {
required: false,
serializedName: 'correctiveAction',
type: {
name: 'String'
}
},
details: {
required: false,
serializedName: 'details',
type: {
name: 'String'
}
},
summary: {
required: false,
serializedName: 'summary',
type: {
name: 'String'
}
},
siteName: {
required: false,
serializedName: 'siteName',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = InMageAzureV2EventDetails;
| xingwu1/azure-sdk-for-node | lib/services/recoveryServicesSiteRecoveryManagement/lib/models/inMageAzureV2EventDetails.js | JavaScript | apache-2.0 | 3,153 |
define({
root: ({
appTitle: 'Dojo Bootstrap Map',
navBasemaps: 'Basemaps',
navAbout: 'About',
sidebarTitle: 'Legend',
modalAboutTitle: 'About',
modalAboutContent: 'The goal of this application boilerplate is to demonstrate how to build a mapping application that utilizes the best parts of Dojo (AMD modules, classes and widgets, promises, i18n, routing, etc) along with the responsive UI of Bootstrap.',
modalAboutMoreInfo: 'More...',
widgets : {
geocoder : {
placeholder : 'Address or Location'
}
}
}),
fr: true,
es: true,
it: true,
de: true
// TODO: define other locales as needed
});
| tsamaya/talking-code-esri-github | exemples/dojo-bootstrap-map-js/src/app/layout/nls/strings.js | JavaScript | apache-2.0 | 658 |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = formatDistance;
// Source: https://www.unicode.org/cldr/charts/32/summary/te.html
var formatDistanceLocale = {
lessThanXSeconds: {
standalone: {
one: 'సెకను కన్నా తక్కువ',
other: '{{count}} సెకన్ల కన్నా తక్కువ'
},
withPreposition: {
one: 'సెకను',
other: '{{count}} సెకన్ల'
}
},
xSeconds: {
standalone: {
one: 'ఒక సెకను',
// CLDR #1314
other: '{{count}} సెకన్ల'
},
withPreposition: {
one: 'ఒక సెకను',
other: '{{count}} సెకన్ల'
}
},
halfAMinute: {
standalone: 'అర నిమిషం',
withPreposition: 'అర నిమిషం'
},
lessThanXMinutes: {
standalone: {
one: 'ఒక నిమిషం కన్నా తక్కువ',
other: '{{count}} నిమిషాల కన్నా తక్కువ'
},
withPreposition: {
one: 'ఒక నిమిషం',
other: '{{count}} నిమిషాల'
}
},
xMinutes: {
standalone: {
one: 'ఒక నిమిషం',
// CLDR #1311
other: '{{count}} నిమిషాలు'
},
withPreposition: {
one: 'ఒక నిమిషం',
// CLDR #1311
other: '{{count}} నిమిషాల'
}
},
aboutXHours: {
standalone: {
one: 'సుమారు ఒక గంట',
other: 'సుమారు {{count}} గంటలు'
},
withPreposition: {
one: 'సుమారు ఒక గంట',
other: 'సుమారు {{count}} గంటల'
}
},
xHours: {
standalone: {
one: 'ఒక గంట',
// CLDR #1308
other: '{{count}} గంటలు'
},
withPreposition: {
one: 'ఒక గంట',
other: '{{count}} గంటల'
}
},
xDays: {
standalone: {
one: 'ఒక రోజు',
// CLDR #1292
other: '{{count}} రోజులు'
},
withPreposition: {
one: 'ఒక రోజు',
other: '{{count}} రోజుల'
}
},
aboutXMonths: {
standalone: {
one: 'సుమారు ఒక నెల',
other: 'సుమారు {{count}} నెలలు'
},
withPreposition: {
one: 'సుమారు ఒక నెల',
other: 'సుమారు {{count}} నెలల'
}
},
xMonths: {
standalone: {
one: 'ఒక నెల',
// CLDR #1281
other: '{{count}} నెలలు'
},
withPreposition: {
one: 'ఒక నెల',
other: '{{count}} నెలల'
}
},
aboutXYears: {
standalone: {
one: 'సుమారు ఒక సంవత్సరం',
other: 'సుమారు {{count}} సంవత్సరాలు'
},
withPreposition: {
one: 'సుమారు ఒక సంవత్సరం',
other: 'సుమారు {{count}} సంవత్సరాల'
}
},
xYears: {
standalone: {
one: 'ఒక సంవత్సరం',
// CLDR #1275
other: '{{count}} సంవత్సరాలు'
},
withPreposition: {
one: 'ఒక సంవత్సరం',
other: '{{count}} సంవత్సరాల'
}
},
overXYears: {
standalone: {
one: 'ఒక సంవత్సరం పైగా',
other: '{{count}} సంవత్సరాలకు పైగా'
},
withPreposition: {
one: 'ఒక సంవత్సరం',
other: '{{count}} సంవత్సరాల'
}
},
almostXYears: {
standalone: {
one: 'దాదాపు ఒక సంవత్సరం',
other: 'దాదాపు {{count}} సంవత్సరాలు'
},
withPreposition: {
one: 'దాదాపు ఒక సంవత్సరం',
other: 'దాదాపు {{count}} సంవత్సరాల'
}
}
};
function formatDistance(token, count, options) {
options = options || {};
var usageGroup = options.addSuffix ? formatDistanceLocale[token].withPreposition : formatDistanceLocale[token].standalone;
var result;
if (typeof usageGroup === 'string') {
result = usageGroup;
} else if (count === 1) {
result = usageGroup.one;
} else {
result = usageGroup.other.replace('{{count}}', count);
}
if (options.addSuffix) {
if (options.comparison > 0) {
return result + 'లో';
} else {
return result + ' క్రితం';
}
}
return result;
}
module.exports = exports.default; | BigBoss424/portfolio | v8/development/node_modules/date-fns/locale/te/_lib/formatDistance/index.js | JavaScript | apache-2.0 | 4,724 |
/*
TUIO C++ Library
Copyright (c) 2005-2014 Martin Kaltenbrunner <martin@tuio.org>
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 3.0 of the License, 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library.
*/
#include "OscReceiver.h"
using namespace TUIO;
using namespace osc;
void OscReceiver::ProcessMessage( const ReceivedMessage& msg, const IpEndpointName& remoteEndpoint) {
for (std::list<TuioClient*>::iterator client=clientList.begin(); client!= clientList.end(); client++)
(*client)->processOSC(msg);
}
void OscReceiver::ProcessBundle( const ReceivedBundle& b, const IpEndpointName& remoteEndpoint) {
try {
for( ReceivedBundle::const_iterator i = b.ElementsBegin(); i != b.ElementsEnd(); ++i ){
if( i->IsBundle() )
ProcessBundle( ReceivedBundle(*i), remoteEndpoint);
else
ProcessMessage( ReceivedMessage(*i), remoteEndpoint);
}
} catch (MalformedBundleException& e) {
std::cerr << "malformed OSC bundle: " << e.what() << std::endl;
}
}
void OscReceiver::ProcessPacket( const char *data, int size, const IpEndpointName& remoteEndpoint ) {
try {
ReceivedPacket p( data, size );
if(p.IsBundle()) ProcessBundle( ReceivedBundle(p), remoteEndpoint);
else ProcessMessage( ReceivedMessage(p), remoteEndpoint);
} catch (MalformedBundleException& e) {
std::cerr << "malformed OSC bundle: " << e.what() << std::endl;
}
}
bool OscReceiver::isConnected() {
return connected;
}
void OscReceiver::addTuioClient(TuioClient *client) {
clientList.push_back(client);
}
| portaloffreedom/robot-baby | robot_localization/TUIO/OscReceiver.cpp | C++ | apache-2.0 | 1,990 |
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* 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.intellij.psi.impl.source.xml;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiReference;
import com.intellij.psi.impl.source.tree.TreeElement;
import com.intellij.psi.meta.PsiMetaData;
import com.intellij.psi.meta.PsiMetaOwner;
import com.intellij.psi.xml.XmlElement;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.IncorrectOperationException;
import com.intellij.xml.XmlElementDescriptor;
import com.intellij.xml.XmlExtension;
import com.intellij.xml.impl.schema.AnyXmlElementDescriptor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class TagNameReference implements PsiReference {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.xml.TagNameReference");
protected final boolean myStartTagFlag;
private final ASTNode myNameElement;
public TagNameReference(ASTNode nameElement, boolean startTagFlag) {
myStartTagFlag = startTagFlag;
myNameElement = nameElement;
}
@NotNull
@Override
public PsiElement getElement() {
PsiElement element = myNameElement.getPsi();
final PsiElement parent = element.getParent();
return parent instanceof XmlTag ? parent : element;
}
@Nullable
protected XmlTag getTagElement() {
final PsiElement element = getElement();
if(element == myNameElement.getPsi()) return null;
return (XmlTag)element;
}
@NotNull
@Override
public TextRange getRangeInElement() {
final ASTNode nameElement = getNameElement();
if (nameElement == null){
return TextRange.EMPTY_RANGE;
}
int colon = getPrefixIndex(nameElement.getText()) + 1;
if (myStartTagFlag) {
final int parentOffset = ((TreeElement)nameElement).getStartOffsetInParent();
return new TextRange(parentOffset + colon, parentOffset + nameElement.getTextLength());
}
else {
final PsiElement element = getElement();
if (element == myNameElement) return new TextRange(colon, myNameElement.getTextLength());
final int elementLength = element.getTextLength();
int diffFromEnd = 0;
for(ASTNode node = element.getNode().getLastChildNode(); node != nameElement && node != null; node = node.getTreePrev()) {
diffFromEnd += node.getTextLength();
}
final int nameEnd = elementLength - diffFromEnd;
return new TextRange(nameEnd - nameElement.getTextLength() + colon, nameEnd);
}
}
protected int getPrefixIndex(@NotNull String name) {
return name.indexOf(":");
}
public ASTNode getNameElement() {
return myNameElement;
}
@Override
public PsiElement resolve() {
final XmlTag tag = getTagElement();
final XmlElementDescriptor descriptor = tag != null ? tag.getDescriptor():null;
if (LOG.isDebugEnabled()) {
LOG.debug("Descriptor for tag " +
(tag != null ? tag.getName() : "NULL") +
" is " +
(descriptor != null ? (descriptor.toString() + ": " + descriptor.getClass().getCanonicalName()) : "NULL"));
}
if (descriptor != null){
return descriptor instanceof AnyXmlElementDescriptor ? tag : descriptor.getDeclaration();
}
return null;
}
@Override
@NotNull
public String getCanonicalText() {
return getNameElement().getText();
}
@Override
@Nullable
public PsiElement handleElementRename(@NotNull String newElementName) throws IncorrectOperationException {
final XmlTag element = getTagElement();
if (element == null || !myStartTagFlag) return element;
if (getPrefixIndex(newElementName) == -1) {
final String namespacePrefix = element.getNamespacePrefix();
final int index = newElementName.lastIndexOf('.');
if (index != -1) {
final PsiElement psiElement = resolve();
if (psiElement instanceof PsiFile || (psiElement != null && psiElement.isEquivalentTo(psiElement.getContainingFile()))) {
newElementName = newElementName.substring(0, index);
}
}
newElementName = prependNamespacePrefix(newElementName, namespacePrefix);
}
element.setName(newElementName);
return element;
}
protected String prependNamespacePrefix(String newElementName, String namespacePrefix) {
newElementName = (!namespacePrefix.isEmpty() ? namespacePrefix + ":":namespacePrefix) + newElementName;
return newElementName;
}
@Override
public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException {
PsiMetaData metaData = null;
if (element instanceof PsiMetaOwner){
final PsiMetaOwner owner = (PsiMetaOwner)element;
metaData = owner.getMetaData();
if (metaData instanceof XmlElementDescriptor){
return getTagElement().setName(metaData.getName(getElement())); // TODO: need to evaluate new ns prefix
}
} else if (element instanceof PsiFile) {
final XmlTag tagElement = getTagElement();
if (tagElement == null || !myStartTagFlag) return tagElement;
String newElementName = ((PsiFile)element).getName();
final int index = newElementName.lastIndexOf('.');
// TODO: need to evaluate new ns prefix
newElementName = prependNamespacePrefix(newElementName.substring(0, index), tagElement.getNamespacePrefix());
return getTagElement().setName(newElementName);
}
final XmlTag tag = getTagElement();
throw new IncorrectOperationException("Cant bind to not a xml element definition!"+element+","+metaData + "," + tag + "," + (tag != null ? tag.getDescriptor() : "unknown descriptor"));
}
@Override
public boolean isReferenceTo(@NotNull PsiElement element) {
return getElement().getManager().areElementsEquivalent(element, resolve());
}
@Override
public boolean isSoft() {
return false;
}
@Nullable
static TagNameReference createTagNameReference(XmlElement element, @NotNull ASTNode nameElement, boolean startTagFlag) {
final XmlExtension extension = XmlExtension.getExtensionByElement(element);
return extension == null ? null : extension.createTagNameReference(nameElement, startTagFlag);
}
public boolean isStartTagFlag() {
return myStartTagFlag;
}
}
| goodwinnk/intellij-community | xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/TagNameReference.java | Java | apache-2.0 | 6,957 |
"""Update a task in maniphest.
you can use the 'task id' output from the 'arcyon task-create' command as input
to this command.
usage examples:
update task '99' with a new title, only show id:
$ arcyon task-update 99 -t 'title' --format-id
99
"""
# =============================================================================
# CONTENTS
# -----------------------------------------------------------------------------
# aoncmd_taskupdate
#
# Public Functions:
# getFromfilePrefixChars
# setupParser
# process
#
# -----------------------------------------------------------------------------
# (this contents block is generated, edits will be lost)
# =============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import textwrap
import phlcon_maniphest
import phlcon_project
import phlcon_user
import phlsys_makeconduit
def getFromfilePrefixChars():
return ""
def setupParser(parser):
# make a list of priority names in increasing order of importance
priority_name_list = phlcon_maniphest.PRIORITIES.keys()
priority_name_list.sort(
key=lambda x: phlcon_maniphest.PRIORITIES[x])
priorities = parser.add_argument_group(
'optional priority arguments',
'use any of ' + textwrap.fill(
str(priority_name_list)))
output_group = parser.add_argument_group(
'Output format arguments',
'Mutually exclusive, defaults to "--format-summary"')
output = output_group.add_mutually_exclusive_group()
opt = parser.add_argument_group(
'Optional task arguments',
'You can supply these later via the web interface if you wish')
priorities.add_argument(
'--priority',
'-p',
choices=priority_name_list,
metavar="PRIORITY",
default=None,
type=str,
help="the priority or importance of the task")
parser.add_argument(
'id',
metavar='INT',
help='the id of the task',
type=str)
parser.add_argument(
'--title',
'-t',
metavar='STRING',
help='the short title of the task',
default=None,
type=str)
opt.add_argument(
'--description',
'-d',
metavar='STRING',
help='the long description of the task',
default=None,
type=str)
opt.add_argument(
'--owner',
'-o',
metavar='USER',
help='the username of the owner',
type=str)
opt.add_argument(
'--ccs',
'-c',
nargs="*",
metavar='USER',
help='a list of usernames to cc on the task',
type=str)
opt.add_argument(
'--projects',
nargs="*",
metavar='PROJECT',
default=[],
help='a list of project names to add the task to',
type=str)
opt.add_argument(
'--comment',
'-m',
metavar='STRING',
help='an optional comment to make on the task',
default=None,
type=str)
output.add_argument(
'--format-summary',
action='store_true',
help='will print a human-readable summary of the result.')
output.add_argument(
'--format-id',
action='store_true',
help='will print just the id of the new task, for scripting.')
output.add_argument(
'--format-url',
action='store_true',
help='will print just the url of the new task, for scripting.')
phlsys_makeconduit.add_argparse_arguments(parser)
def process(args):
if args.title and not args.title.strip():
print('you must supply a non-empty title', file=sys.stderr)
return 1
conduit = phlsys_makeconduit.make_conduit(
args.uri, args.user, args.cert, args.act_as_user)
# create_task expects an integer
priority = None
if args.priority is not None:
priority = phlcon_maniphest.PRIORITIES[args.priority]
# conduit expects PHIDs not plain usernames
user_phids = phlcon_user.UserPhidCache(conduit)
if args.owner:
user_phids.add_hint(args.owner)
if args.ccs:
user_phids.add_hint_list(args.ccs)
owner = user_phids.get_phid(args.owner) if args.owner else None
ccs = [user_phids.get_phid(u) for u in args.ccs] if args.ccs else None
# conduit expects PHIDs not plain project names
projects = None
if args.projects:
project_to_phid = phlcon_project.make_project_to_phid_dict(conduit)
projects = [project_to_phid[p] for p in args.projects]
result = phlcon_maniphest.update_task(
conduit,
args.id,
args.title,
args.description,
priority,
owner,
ccs,
projects,
args.comment)
if args.format_id:
print(result.id)
elif args.format_url:
print(result.uri)
else: # args.format_summary:
message = (
"Updated task '{task_id}', you can view it at this URL:\n"
" {url}"
).format(
task_id=result.id,
url=result.uri)
print(message)
# -----------------------------------------------------------------------------
# Copyright (C) 2013-2014 Bloomberg Finance L.P.
#
# 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.
# ------------------------------ END-OF-FILE ----------------------------------
| kjedruczyk/phabricator-tools | py/aon/aoncmd_taskupdate.py | Python | apache-2.0 | 5,958 |
import logging
import terminal
INFO = logging.INFO
# between info and debug
VERBOSE = (logging.INFO + logging.DEBUG) / 2
DEBUG = logging.DEBUG
log = logging.getLogger('rdopkg')
log.setLevel(logging.INFO)
if len(log.handlers) < 1:
formatter = logging.Formatter(fmt='%(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
log.addHandler(handler)
class LogTerminal(terminal.Terminal):
@property
def warn(self):
return self.yellow
@property
def important(self):
return self.yellow_bold
@property
def error(self):
return self.red
@property
def good(self):
return self.green
@property
def cmd(self):
return self.cyan
term = LogTerminal()
def set_colors(colors):
global term
if colors == 'yes':
if not terminal.COLOR_TERMINAL:
return False
term = LogTerminal(force_styling=True)
return True
elif colors == 'no':
if not terminal.COLOR_TERMINAL:
return True
term = LogTerminal(force_styling=None)
return True
elif colors == 'auto':
term = LogTerminal()
return True
return False
def error(*args, **kwargs):
if args:
largs = list(args)
largs[0] = term.error(args[0])
args = tuple(largs)
log.error(*args, **kwargs)
def warn(*args, **kwargs):
if args:
largs = list(args)
largs[0] = term.warn(args[0])
args = tuple(largs)
log.warning(*args, **kwargs)
def success(*args, **kwargs):
if args:
largs = list(args)
largs[0] = term.good(args[0])
args = tuple(largs)
log.info(*args, **kwargs)
def info(*args, **kwargs):
log.info(*args, **kwargs)
def verbose(*args, **kwargs):
log.log(VERBOSE, *args, **kwargs)
def debug(*args, **kwargs):
log.debug(*args, **kwargs)
def command(*args, **kwargs):
log.info(*args, **kwargs)
| ktdreyer/rdopkg | rdopkg/utils/log.py | Python | apache-2.0 | 1,968 |
#
# Author:: Thomas Bishop (<bishop.thomas@gmail.com>)
# Copyright:: Copyright (c) 2011 Thomas Bishop
# License:: Apache License, Version 2.0
#
# 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.
#
require 'spec_helper'
describe Chef::Knife::ClientShow do
before(:each) do
@knife = Chef::Knife::ClientShow.new
@knife.name_args = [ 'adam' ]
@client_mock = double('client_mock')
end
describe 'run' do
it 'should list the client' do
Chef::ApiClient.should_receive(:load).with('adam').and_return(@client_mock)
@knife.should_receive(:format_for_display).with(@client_mock)
@knife.run
end
it 'should print usage and exit when a client name is not provided' do
@knife.name_args = []
@knife.should_receive(:show_usage)
@knife.ui.should_receive(:fatal)
lambda { @knife.run }.should raise_error(SystemExit)
end
end
end
| evertrue/chef | spec/unit/knife/client_show_spec.rb | Ruby | apache-2.0 | 1,383 |