prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>resources.go<|end_file_name|><|fim▁begin|>package main
<|fim▁hole|>//go:generate go tool generate_resources ../resources music resources<|fim▁end|> | |
<|file_name|>next-prev-pattern.js<|end_file_name|><|fim▁begin|>import React from "react";
import styled from 'styled-components'
import Link from './link';<|fim▁hole|>
const nextArrow = "/icons/next-arrow.png";
const prevArrow = "/icons/prev-arrow.png";
const PatternLink = styled.span`
width: 100%;
display: flex;
flex-direction: column;
padding: 1em;
float: ${props => props.previous ? 'left' : 'right'}
@media(min-width: $width-tablet) {
width: auto;
}
`;
const ImageContainer = styled.span`
height: 50px;
`;
const Image = styled.img`
height: 100%;
background-color: white;
float: ${props => props.previous ? 'right' : 'left'}
`;
const ArrowContainer = styled.div`
display: flex;
flex-direction: ${props => props.previous ? 'row-reverse' : 'row'};
align-items: center;
`;
const Name = styled.p`
padding: 10px 0;
`;
const Arrow = styled.img`
height: 10px;
flex-direction: row-reverse;
padding: ${props => props.previous ? '0 10px 0 0' : '0 0 0 10px'};
`;
const NextPrevPattern = ({pattern, direction}) => {
const previous = direction === "previous"
return (
<Link href={pattern.url}>
<PatternLink previous={previous}>
<ImageContainer>
<Image previous={previous} src={pattern.painted || pattern.lineDrawing} />
</ImageContainer>
<ArrowContainer previous={previous}>
<Name>{pattern.name}</Name>
{
(direction === "next") &&
<Arrow src={nextArrow}/>
}
{
(direction === "previous") &&
<Arrow previous src={prevArrow} />
}
</ArrowContainer>
</PatternLink>
</Link>
)
};
export default NextPrevPattern;<|fim▁end|> | |
<|file_name|>dispatcher.go<|end_file_name|><|fim▁begin|>package runner
import (
"fmt"
//"error"
//"log"
//"os"
//"io"
"github.com/go-QA/logger"
//"../logger"
//"runtime"
"time"
)
const (
MAX_WAIT_MATCH_RETURN = 3000 // Maximum time in milliseconds to wait for build return message
)
type RunId int
func (ri RunId) String() string {
return fmt.Sprintf("%d", ri)
}
type RunInfo struct {
Id RunId
Name string
LaunchType string
}
type BuildInfo struct {
Version string
Project string
Path string
BuildComplete time.Time
}
type Matcher interface {
FindMatches(buildInfo BuildInfo) []RunInfo
}
type BuildMockMatch struct {
runNum RunId
}
<|fim▁hole|> {Id: mock.runNum,
Name: fmt.Sprintf("Runplan_%d_%s", mock.runNum, buildInfo.Version),
LaunchType: "auto"},
{Id: mock.runNum + 1,
Name: fmt.Sprintf("Runplan_%d_%s", mock.runNum+1, buildInfo.Version),
LaunchType: "manual"},
{Id: mock.runNum + 2,
Name: fmt.Sprintf("Runplan_%d_%s", mock.runNum+2, buildInfo.Version),
LaunchType: "auto"},
}
}
type InternalBuildMatcher struct {
m_log *logger.GoQALog
matcher Matcher
chnBuilds chan InternalCommandInfo
chnRunplans *CommandQueue
chnExit chan int
isStopRequested bool
}
func (ibm *InternalBuildMatcher) GetBuildInfo(info InternalCommandInfo) (BuildInfo, error) {
var buildInfo BuildInfo
var err error
if info.Command == CMD_NEW_BUILD {
buildInfo = BuildInfo{Version: info.Data[0].(string),
Project: info.Data[1].(string),
Path: info.Data[2].(string)}
} else {
buildInfo = BuildInfo{}
err = &myError{mes: "No build info"}
}
return buildInfo, err
}
func (ibm *InternalBuildMatcher) CreatRunInfoMes(cmd *InternalCommandInfo, run RunInfo) {
//cmd := new(InternalCommandInfo)
cmd.Command = CMD_LAUNCH_RUN
cmd.ChnReturn = make(chan CommandInfo)
cmd.Data = []interface{}{run.Id, run.Name, run.LaunchType}
return
}
func (ibm *InternalBuildMatcher) Init(iMatch Matcher, inChn chan InternalCommandInfo, outChn *CommandQueue, chnExit chan int, log *logger.GoQALog) {
ibm.matcher = iMatch
ibm.chnBuilds = inChn
ibm.chnRunplans = outChn
ibm.chnExit = chnExit
ibm.m_log = log
ibm.isStopRequested = false
}
func (ibm *InternalBuildMatcher) Stop(mes int) bool {
return true
}
func (ibm *InternalBuildMatcher) OnMessageRecieved(nextMessage InternalCommandInfo) {
var outMes *InternalCommandInfo
nextBuild, err := ibm.GetBuildInfo(nextMessage)
if err == nil {
newRunplans := ibm.matcher.FindMatches(nextBuild)
if newRunplans != nil {
for _, run := range newRunplans {
outMes = new(InternalCommandInfo)
//ibm.m_log.LogMessage("BuildMatcher mesOut = %p", outMes)
ibm.CreatRunInfoMes(outMes, run)
*ibm.chnRunplans <- *outMes
go func(mes *InternalCommandInfo) {
select {
case resv := <-(*mes).ChnReturn:
ibm.m_log.LogMessage("BuildMatcher resv = %s %s %p", CmdName(resv.Command), resv.Data[0].(string), mes)
case <-time.After(time.Millisecond * MAX_WAIT_MATCH_RETURN):
ibm.m_log.LogMessage("BuildMatcher Timed out %v %p", mes, mes)
}
}(outMes)
}
nextMessage.ChnReturn <- GetMessageInfo(CMD_OK, fmt.Sprintf("launched %d runs", len(newRunplans)))
} else {
nextMessage.ChnReturn <- GetMessageInfo(CMD_OK, "no runs matched")
}
} else {
ibm.m_log.LogError("GetBuildInfo::%s", err)
nextMessage.ChnReturn <- GetMessageInfo(CMD_OK, "Build match err", err.Error())
}
}
func (ibm *InternalBuildMatcher) Run() {
ibm.isStopRequested = false
for ibm.isStopRequested == false {
select {
case nextMessage := <-ibm.chnBuilds:
go ibm.OnMessageRecieved(nextMessage)
case exitMessage := <-ibm.chnExit:
ibm.isStopRequested = ibm.Stop(exitMessage)
case <-time.After(time.Millisecond * LOOP_WAIT_TIMER):
}
ibm.onProcessEvents()
}
ibm.m_log.LogDebug("Out of Main loop")
}
func (ibm *InternalBuildMatcher) onProcessEvents() {
ibm.m_log.LogDebug("Matcher Process Events")
}<|fim▁end|> | func (mock *BuildMockMatch) FindMatches(buildInfo BuildInfo) []RunInfo {
return []RunInfo{
|
<|file_name|>dell_storagecenter_common.py<|end_file_name|><|fim▁begin|># Copyright 2016 Dell 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.
import eventlet
from oslo_config import cfg
from oslo_config import types
from oslo_log import log as logging
from oslo_utils import excutils
import six
from cinder import exception
from cinder.i18n import _, _LE, _LI, _LW
from cinder.objects import fields
from cinder.volume import driver
from cinder.volume.drivers.dell import dell_storagecenter_api
from cinder.volume.drivers.san.san import san_opts
from cinder.volume import volume_types
common_opts = [
cfg.IntOpt('dell_sc_ssn',
default=64702,
help='Storage Center System Serial Number'),
cfg.PortOpt('dell_sc_api_port',
default=3033,
help='Dell API port'),
cfg.StrOpt('dell_sc_server_folder',
default='openstack',
help='Name of the server folder to use on the Storage Center'),
cfg.StrOpt('dell_sc_volume_folder',
default='openstack',
help='Name of the volume folder to use on the Storage Center'),
cfg.BoolOpt('dell_sc_verify_cert',
default=False,
help='Enable HTTPS SC certificate verification'),
cfg.StrOpt('secondary_san_ip',
default='',
help='IP address of secondary DSM controller'),
cfg.StrOpt('secondary_san_login',
default='Admin',
help='Secondary DSM user name'),
cfg.StrOpt('secondary_san_password',
default='',
help='Secondary DSM user password name',
secret=True),
cfg.PortOpt('secondary_sc_api_port',
default=3033,
help='Secondary Dell API port'),
cfg.MultiOpt('excluded_domain_ip',
item_type=types.IPAddress(),
default=None,
help='Domain IP to be excluded from iSCSI returns.'),
cfg.StrOpt('dell_server_os',
default='Red Hat Linux 6.x',
help='Server OS type to use when creating a new server on the '
'Storage Center.')
]
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
CONF.register_opts(common_opts)
class DellCommonDriver(driver.ManageableVD,
driver.ManageableSnapshotsVD,
driver.BaseVD):
def __init__(self, *args, **kwargs):
super(DellCommonDriver, self).__init__(*args, **kwargs)
self.configuration.append_config_values(common_opts)
self.configuration.append_config_values(san_opts)
self.backend_name =\
self.configuration.safe_get('volume_backend_name') or 'Dell'
self.backends = self.configuration.safe_get('replication_device')
self.replication_enabled = True if self.backends else False
self.is_direct_connect = False
self.active_backend_id = kwargs.get('active_backend_id', None)
self.failed_over = True if self.active_backend_id else False
LOG.info(_LI('Loading %(name)s: Failover state is %(state)r'),
{'name': self.backend_name,
'state': self.failed_over})
self.storage_protocol = 'iSCSI'
self.failback_timeout = 60
def _bytes_to_gb(self, spacestring):
"""Space is returned in a string like ...
7.38197504E8 Bytes
Need to split that apart and convert to GB.
:returns: gbs in int form
"""
try:
n = spacestring.split(' ', 1)
fgbs = float(n[0]) / 1073741824.0
igbs = int(fgbs)
return igbs
except Exception:
# If any of that blew up it isn't in the format we
# thought so eat our error and return None
return None
def do_setup(self, context):
"""One time driver setup.
Called once by the manager after the driver is loaded.
Sets up clients, check licenses, sets up protocol
specific helpers.
"""
self._client = dell_storagecenter_api.StorageCenterApiHelper(
self.configuration, self.active_backend_id, self.storage_protocol)
def check_for_setup_error(self):
"""Validates the configuration information."""
with self._client.open_connection() as api:
api.find_sc()
self.is_direct_connect = api.is_direct_connect
if self.is_direct_connect and self.replication_enabled:
msg = _('Dell Cinder driver configuration error replication '
'not supported with direct connect.')
raise exception.InvalidHost(reason=msg)
# If we are a healthy replicated system make sure our backend
# is alive.
if self.replication_enabled and not self.failed_over:
# Check that our replication destinations are available.
for backend in self.backends:
replssn = backend['target_device_id']
try:
# Just do a find_sc on it. If it raises we catch
# that and raise with a correct exception.
api.find_sc(int(replssn))
except exception.VolumeBackendAPIException:
msg = _('Dell Cinder driver configuration error '
'replication_device %s not found') % replssn
raise exception.InvalidHost(reason=msg)
def _get_volume_extra_specs(self, obj):
"""Gets extra specs for the given object."""
type_id = obj.get('volume_type_id')
if type_id:
return volume_types.get_volume_type_extra_specs(type_id)
return {}
def _add_volume_to_consistency_group(self, api, scvolume, volume):
"""Just a helper to add a volume to a consistency group.
:param api: Dell SC API opbject.
:param scvolume: Dell SC Volume object.
:param volume: Cinder Volume object.
:returns: Nothing.
"""
if scvolume and volume.get('consistencygroup_id'):
profile = api.find_replay_profile(
volume.get('consistencygroup_id'))
if profile:
api.update_cg_volumes(profile, [volume])
def _get_replication_specs(self, specs):
"""Checks if we can do replication.
Need the extra spec set and we have to be talking to EM.
:param specs: Cinder Volume or snapshot extra specs.
:return: rinfo dict.
"""
rinfo = {'enabled': False, 'sync': False,
'live': False, 'active': False,
'autofailover': False}
# Repl does not work with direct connect.
if not self.is_direct_connect:
if (not self.failed_over and
specs.get('replication_enabled') == '<is> True'):
rinfo['enabled'] = True
if specs.get('replication_type') == '<in> sync':
rinfo['sync'] = True
if specs.get('replication:livevolume') == '<is> True':
rinfo['live'] = True
if specs.get('replication:livevolume:autofailover') == '<is> True':
rinfo['autofailover'] = True
if specs.get('replication:activereplay') == '<is> True':
rinfo['active'] = True
# Some quick checks.
if rinfo['enabled']:
replication_target_count = len(self.backends)
msg = None
if replication_target_count == 0:
msg = _(
'Replication setup failure: replication has been '
'enabled but no replication target has been specified '
'for this backend.')
if rinfo['live'] and replication_target_count != 1:
msg = _('Replication setup failure: replication:livevolume'
' has been enabled but more than one replication '
'target has been specified for this backend.')
if msg:
LOG.debug(msg)
raise exception.ReplicationError(message=msg)
# Got this far. Life is good. Return our data.
return rinfo
def _is_live_vol(self, obj):
rspecs = self._get_replication_specs(self._get_volume_extra_specs(obj))
return rspecs['enabled'] and rspecs['live']
def _create_replications(self, api, volume, scvolume, extra_specs=None):
"""Creates any appropriate replications for a given volume.
:param api: Dell REST API object.
:param volume: Cinder volume object.
:param scvolume: Dell Storage Center Volume object.
:param extra_specs: Extra specs if we have them otherwise gets them
from the volume.
:return: model_update
"""
# Replication V2
# for now we assume we have an array named backends.
replication_driver_data = None
# Replicate if we are supposed to.
if not extra_specs:
extra_specs = self._get_volume_extra_specs(volume)
rspecs = self._get_replication_specs(extra_specs)
if rspecs['enabled']:
for backend in self.backends:
targetdeviceid = backend['target_device_id']
primaryqos = backend.get('qosnode', 'cinderqos')
secondaryqos = backend.get('remoteqos', 'cinderqos')
diskfolder = backend.get('diskfolder', None)
obj = None
if rspecs['live']:
# We are rolling with a live volume.
obj = api.create_live_volume(scvolume, targetdeviceid,
rspecs['active'],
rspecs['sync'],
rspecs['autofailover'],
primaryqos, secondaryqos)
else:
# Else a regular replication.
obj = api.create_replication(scvolume, targetdeviceid,
primaryqos, rspecs['sync'],
diskfolder, rspecs['active'])
# This is either a ScReplication object or a ScLiveVolume
# object. So long as it isn't None we are fine.
if not obj:
# Create replication will have printed a better error.
msg = _('Replication %(name)s to %(ssn)s failed.') % {
'name': volume['id'],
'ssn': targetdeviceid}
raise exception.VolumeBackendAPIException(data=msg)
if not replication_driver_data:
replication_driver_data = backend['target_device_id']
else:
replication_driver_data += ','
replication_driver_data += backend['target_device_id']
# If we did something return model update.
model_update = {}
if replication_driver_data:
model_update = {
'replication_status': fields.ReplicationStatus.ENABLED,
'replication_driver_data': replication_driver_data}
return model_update
@staticmethod
def _cleanup_failed_create_volume(api, volumename):
try:
api.delete_volume(volumename)
except exception.VolumeBackendAPIException as ex:
LOG.info(_LI('Non fatal cleanup error: %s.'), ex.msg)
def create_volume(self, volume):
"""Create a volume."""
model_update = {}
# We use id as our name as it is unique.
volume_name = volume.get('id')
# Look for our volume
volume_size = volume.get('size')
LOG.debug('Creating volume %(name)s of size %(size)s',
{'name': volume_name,
'size': volume_size})
scvolume = None
with self._client.open_connection() as api:
try:
# Get our extra specs.
specs = self._get_volume_extra_specs(volume)
scvolume = api.create_volume(
volume_name, volume_size,
specs.get('storagetype:storageprofile'),
specs.get('storagetype:replayprofiles'),
specs.get('storagetype:volumeqos'),
specs.get('storagetype:groupqos'),
specs.get('storagetype:datareductionprofile'))
if scvolume is None:
raise exception.VolumeBackendAPIException(
message=_('Unable to create volume %s') %
volume_name)
# Update Consistency Group
self._add_volume_to_consistency_group(api, scvolume, volume)
# Create replications. (Or not. It checks.)
model_update = self._create_replications(api, volume, scvolume)
# Save our provider_id.
model_update['provider_id'] = scvolume['instanceId']
except Exception:
# if we actually created a volume but failed elsewhere
# clean up the volume now.
self._cleanup_failed_create_volume(api, volume_name)
with excutils.save_and_reraise_exception():
LOG.error(_LE('Failed to create volume %s'),
volume_name)
if scvolume is None:
raise exception.VolumeBackendAPIException(
data=_('Unable to create volume. Backend down.'))
return model_update
def _split_driver_data(self, replication_driver_data):
"""Splits the replication_driver_data into an array of ssn strings.
:param replication_driver_data: A string of comma separated SSNs.
:returns: SSNs in an array of strings.
"""
ssnstrings = []
# We have any replication_driver_data.
if replication_driver_data:
# Split the array and wiffle through the entries.
for str in replication_driver_data.split(','):
# Strip any junk from the string.
ssnstring = str.strip()
# Anything left?
if ssnstring:
# Add it to our array.
ssnstrings.append(ssnstring)
return ssnstrings
def _delete_live_volume(self, api, volume):
"""Delete live volume associated with volume.
:param api:Dell REST API object.
:param volume: Cinder Volume object
:return: True if we actually deleted something. False for everything
else.
"""
# Live Volume was added after provider_id support. So just assume it is
# there.
replication_driver_data = volume.get('replication_driver_data')
# Do we have any replication driver data?
if replication_driver_data:
# Valid replication data?
ssnstrings = self._split_driver_data(replication_driver_data)
if ssnstrings:
ssn = int(ssnstrings[0])
sclivevolume = api.get_live_volume(volume.get('provider_id'),
volume.get('id'))
# Have we found the live volume?
if (sclivevolume and
sclivevolume.get('secondaryScSerialNumber') == ssn and
api.delete_live_volume(sclivevolume, True)):
LOG.info(_LI('%(vname)s\'s replication live volume has '
'been deleted from storage Center %(sc)s,'),
{'vname': volume.get('id'),
'sc': ssn})
return True
# If we are here either we do not have a live volume, we do not have
# one on our configured SC or we were not able to delete it.
# Either way, warn and leave.
LOG.warning(_LW('Unable to delete %s live volume.'),
volume.get('id'))
return False
def _delete_replications(self, api, volume):
"""Delete replications associated with a given volume.
We should be able to roll through the replication_driver_data list
of SSNs and delete replication objects between them and the source
volume.
:param api: Dell REST API object.
:param volume: Cinder Volume object
:return: None
"""
replication_driver_data = volume.get('replication_driver_data')
if replication_driver_data:
ssnstrings = self._split_driver_data(replication_driver_data)
volume_name = volume.get('id')
provider_id = volume.get('provider_id')
scvol = api.find_volume(volume_name, provider_id)
# This is just a string of ssns separated by commas.
# Trundle through these and delete them all.
for ssnstring in ssnstrings:
ssn = int(ssnstring)
# Are we a replication or a live volume?
if not api.delete_replication(scvol, ssn):
LOG.warning(_LW('Unable to delete replication of Volume '
'%(vname)s to Storage Center %(sc)s.'),
{'vname': volume_name,
'sc': ssnstring})
# If none of that worked or there was nothing to do doesn't matter.
# Just move on.
def delete_volume(self, volume):
deleted = False
# We use id as our name as it is unique.
volume_name = volume.get('id')
provider_id = volume.get('provider_id')
# Unless we are migrating.
if volume.get('migration_status') == 'deleting':
volume_name = volume.get('_name_id')
provider_id = None
LOG.debug('Deleting volume %s', volume_name)<|fim▁hole|> self._get_volume_extra_specs(volume))
if rspecs['enabled']:
if rspecs['live']:
self._delete_live_volume(api, volume)
else:
self._delete_replications(api, volume)
deleted = api.delete_volume(volume_name, provider_id)
except Exception:
with excutils.save_and_reraise_exception():
LOG.error(_LE('Failed to delete volume %s'),
volume_name)
# if there was an error we will have raised an
# exception. If it failed to delete it is because
# the conditions to delete a volume were not met.
if deleted is False:
raise exception.VolumeIsBusy(volume_name=volume_name)
def create_snapshot(self, snapshot):
"""Create snapshot"""
# our volume name is the volume id
volume_name = snapshot.get('volume_id')
provider_id = snapshot.volume.get('provider_id')
snapshot_id = snapshot.get('id')
LOG.debug('Creating snapshot %(snap)s on volume %(vol)s',
{'snap': snapshot_id,
'vol': volume_name})
with self._client.open_connection() as api:
scvolume = api.find_volume(volume_name, provider_id,
self._is_live_vol(snapshot))
if scvolume is not None:
replay = api.create_replay(scvolume, snapshot_id, 0)
if replay:
return {'status': fields.SnapshotStatus.AVAILABLE,
'provider_id': scvolume['instanceId']}
else:
LOG.warning(_LW('Unable to locate volume:%s'),
volume_name)
snapshot['status'] = fields.SnapshotStatus.ERROR
msg = _('Failed to create snapshot %s') % snapshot_id
raise exception.VolumeBackendAPIException(data=msg)
def create_volume_from_snapshot(self, volume, snapshot):
"""Create new volume from other volume's snapshot on appliance."""
model_update = {}
scvolume = None
volume_name = volume.get('id')
src_provider_id = snapshot.get('provider_id')
src_volume_name = snapshot.get('volume_id')
# This snapshot could have been created on its own or as part of a
# cgsnapshot. If it was a cgsnapshot it will be identified on the Dell
# backend under cgsnapshot_id. Given the volume ID and the
# cgsnapshot_id we can find the appropriate snapshot.
# So first we look for cgsnapshot_id. If that is blank then it must
# have been a normal snapshot which will be found under snapshot_id.
snapshot_id = snapshot.get('cgsnapshot_id')
if not snapshot_id:
snapshot_id = snapshot.get('id')
LOG.debug(
'Creating new volume %(vol)s from snapshot %(snap)s '
'from vol %(src)s',
{'vol': volume_name,
'snap': snapshot_id,
'src': src_volume_name})
with self._client.open_connection() as api:
try:
srcvol = api.find_volume(src_volume_name, src_provider_id)
if srcvol is not None:
replay = api.find_replay(srcvol, snapshot_id)
if replay is not None:
# See if we have any extra specs.
specs = self._get_volume_extra_specs(volume)
scvolume = api.create_view_volume(
volume_name, replay,
specs.get('storagetype:replayprofiles'),
specs.get('storagetype:volumeqos'),
specs.get('storagetype:groupqos'),
specs.get('storagetype:datareductionprofile'))
# Extend Volume
if scvolume and (volume['size'] >
snapshot["volume_size"]):
LOG.debug('Resize the new volume to %s.',
volume['size'])
scvolume = api.expand_volume(scvolume,
volume['size'])
if scvolume is None:
raise exception.VolumeBackendAPIException(
message=_('Unable to create volume '
'%(name)s from %(snap)s.') %
{'name': volume_name,
'snap': snapshot_id})
# Update Consistency Group
self._add_volume_to_consistency_group(api,
scvolume,
volume)
# Replicate if we are supposed to.
model_update = self._create_replications(api,
volume,
scvolume)
# Save our instanceid.
model_update['provider_id'] = (
scvolume['instanceId'])
except Exception:
# Clean up after ourselves.
self._cleanup_failed_create_volume(api, volume_name)
with excutils.save_and_reraise_exception():
LOG.error(_LE('Failed to create volume %s'),
volume_name)
if scvolume is not None:
LOG.debug('Volume %(vol)s created from %(snap)s',
{'vol': volume_name,
'snap': snapshot_id})
else:
msg = _('Failed to create volume %s') % volume_name
raise exception.VolumeBackendAPIException(data=msg)
return model_update
def create_cloned_volume(self, volume, src_vref):
"""Creates a clone of the specified volume."""
model_update = {}
scvolume = None
src_volume_name = src_vref.get('id')
src_provider_id = src_vref.get('provider_id')
volume_name = volume.get('id')
LOG.debug('Creating cloned volume %(clone)s from volume %(vol)s',
{'clone': volume_name,
'vol': src_volume_name})
with self._client.open_connection() as api:
try:
srcvol = api.find_volume(src_volume_name, src_provider_id)
if srcvol is not None:
# Get our specs.
specs = self._get_volume_extra_specs(volume)
# Create our volume
scvolume = api.create_cloned_volume(
volume_name, srcvol,
specs.get('storagetype:storageprofile'),
specs.get('storagetype:replayprofiles'),
specs.get('storagetype:volumeqos'),
specs.get('storagetype:groupqos'),
specs.get('storagetype:datareductionprofile'))
# Extend Volume
if scvolume and volume['size'] > src_vref['size']:
LOG.debug('Resize the volume to %s.', volume['size'])
scvolume = api.expand_volume(scvolume, volume['size'])
# If either of those didn't work we bail.
if scvolume is None:
raise exception.VolumeBackendAPIException(
message=_('Unable to create volume '
'%(name)s from %(vol)s.') %
{'name': volume_name,
'vol': src_volume_name})
# Update Consistency Group
self._add_volume_to_consistency_group(api,
scvolume,
volume)
# Replicate if we are supposed to.
model_update = self._create_replications(api,
volume,
scvolume)
# Save our provider_id.
model_update['provider_id'] = scvolume['instanceId']
except Exception:
# Clean up after ourselves.
self._cleanup_failed_create_volume(api, volume_name)
with excutils.save_and_reraise_exception():
LOG.error(_LE('Failed to create volume %s'),
volume_name)
if scvolume is not None:
LOG.debug('Volume %(vol)s cloned from %(src)s',
{'vol': volume_name,
'src': src_volume_name})
else:
msg = _('Failed to create volume %s') % volume_name
raise exception.VolumeBackendAPIException(data=msg)
return model_update
def delete_snapshot(self, snapshot):
"""delete_snapshot"""
volume_name = snapshot.get('volume_id')
snapshot_id = snapshot.get('id')
provider_id = snapshot.get('provider_id')
LOG.debug('Deleting snapshot %(snap)s from volume %(vol)s',
{'snap': snapshot_id,
'vol': volume_name})
with self._client.open_connection() as api:
scvolume = api.find_volume(volume_name, provider_id)
if scvolume and api.delete_replay(scvolume, snapshot_id):
return
# if we are here things went poorly.
snapshot['status'] = fields.SnapshotStatus.ERROR_DELETING
msg = _('Failed to delete snapshot %s') % snapshot_id
raise exception.VolumeBackendAPIException(data=msg)
def create_export(self, context, volume, connector):
"""Create an export of a volume.
The volume exists on creation and will be visible on
initialize connection. So nothing to do here.
"""
pass
def ensure_export(self, context, volume):
"""Ensure an export of a volume.
Per the eqlx driver we just make sure that the volume actually
exists where we think it does.
"""
scvolume = None
volume_name = volume.get('id')
provider_id = volume.get('provider_id')
LOG.debug('Checking existence of volume %s', volume_name)
with self._client.open_connection() as api:
try:
scvolume = api.find_volume(volume_name, provider_id,
self._is_live_vol(volume))
except Exception:
with excutils.save_and_reraise_exception():
LOG.error(_LE('Failed to ensure export of volume %s'),
volume_name)
if scvolume is None:
msg = _('Unable to find volume %s') % volume_name
raise exception.VolumeBackendAPIException(data=msg)
def remove_export(self, context, volume):
"""Remove an export of a volume.
We do nothing here to match the nothing we do in create export. Again
we do everything in initialize and terminate connection.
"""
pass
def extend_volume(self, volume, new_size):
"""Extend the size of the volume."""
volume_name = volume.get('id')
provider_id = volume.get('provider_id')
LOG.debug('Extending volume %(vol)s to %(size)s',
{'vol': volume_name,
'size': new_size})
if volume is not None:
with self._client.open_connection() as api:
scvolume = api.find_volume(volume_name, provider_id)
if api.expand_volume(scvolume, new_size) is not None:
return
# If we are here nothing good happened.
msg = _('Unable to extend volume %s') % volume_name
raise exception.VolumeBackendAPIException(data=msg)
def get_volume_stats(self, refresh=False):
"""Get volume status.
If 'refresh' is True, run update the stats first.
"""
if refresh:
self._update_volume_stats()
# Take this opportunity to report our failover state.
if self.failed_over:
LOG.debug('%(source)s has been failed over to %(dest)s',
{'source': self.backend_name,
'dest': self.active_backend_id})
return self._stats
def _update_volume_stats(self):
"""Retrieve stats info from volume group."""
with self._client.open_connection() as api:
# Static stats.
data = {}
data['volume_backend_name'] = self.backend_name
data['vendor_name'] = 'Dell'
data['driver_version'] = self.VERSION
data['storage_protocol'] = self.storage_protocol
data['reserved_percentage'] = 0
data['consistencygroup_support'] = True
data['thin_provisioning_support'] = True
data['QoS_support'] = False
data['replication_enabled'] = self.replication_enabled
if self.replication_enabled:
data['replication_type'] = ['async', 'sync']
data['replication_count'] = len(self.backends)
replication_targets = []
# Trundle through our backends.
for backend in self.backends:
target_device_id = backend.get('target_device_id')
if target_device_id:
replication_targets.append(target_device_id)
data['replication_targets'] = replication_targets
# Get our capacity.
storageusage = api.get_storage_usage()
if storageusage:
# Get actual stats.
totalcapacity = storageusage.get('availableSpace')
totalcapacitygb = self._bytes_to_gb(totalcapacity)
data['total_capacity_gb'] = totalcapacitygb
freespace = storageusage.get('freeSpace')
freespacegb = self._bytes_to_gb(freespace)
data['free_capacity_gb'] = freespacegb
else:
# Soldier on. Just return 0 for this iteration.
LOG.error(_LE('Unable to retrieve volume stats.'))
data['total_capacity_gb'] = 0
data['free_capacity_gb'] = 0
self._stats = data
LOG.debug('Total cap %(total)s Free cap %(free)s',
{'total': data['total_capacity_gb'],
'free': data['free_capacity_gb']})
def update_migrated_volume(self, ctxt, volume, new_volume,
original_volume_status):
"""Return model update for migrated volume.
:param volume: The original volume that was migrated to this backend
:param new_volume: The migration volume object that was created on
this backend as part of the migration process
:param original_volume_status: The status of the original volume
:returns: model_update to update DB with any needed changes
"""
# We use id as our volume name so we need to rename the backend
# volume to the original volume name.
original_volume_name = volume.get('id')
current_name = new_volume.get('id')
# We should have this. If we don't we'll set it below.
provider_id = new_volume.get('provider_id')
LOG.debug('update_migrated_volume: %(current)s to %(original)s',
{'current': current_name,
'original': original_volume_name})
if original_volume_name:
with self._client.open_connection() as api:
# todo(tswanson): Delete old volume repliations/live volumes
# todo(tswanson): delete old volume?
scvolume = api.find_volume(current_name, provider_id)
if (scvolume and
api.rename_volume(scvolume, original_volume_name)):
# Replicate if we are supposed to.
model_update = self._create_replications(api,
new_volume,
scvolume)
model_update['_name_id'] = None
model_update['provider_id'] = scvolume['instanceId']
return model_update
# The world was horrible to us so we should error and leave.
LOG.error(_LE('Unable to rename the logical volume for volume: %s'),
original_volume_name)
return {'_name_id': new_volume['_name_id'] or new_volume['id']}
def create_consistencygroup(self, context, group):
"""This creates a replay profile on the storage backend.
:param context: the context of the caller.
:param group: the dictionary of the consistency group to be created.
:returns: Nothing on success.
:raises: VolumeBackendAPIException
"""
gid = group['id']
with self._client.open_connection() as api:
cgroup = api.create_replay_profile(gid)
if cgroup:
LOG.info(_LI('Created Consistency Group %s'), gid)
return
msg = _('Unable to create consistency group %s') % gid
raise exception.VolumeBackendAPIException(data=msg)
def delete_consistencygroup(self, context, group, volumes):
"""Delete the Dell SC profile associated with this consistency group.
:param context: the context of the caller.
:param group: the dictionary of the consistency group to be created.
:returns: Updated model_update, volumes.
"""
gid = group['id']
with self._client.open_connection() as api:
profile = api.find_replay_profile(gid)
if profile:
api.delete_replay_profile(profile)
# If we are here because we found no profile that should be fine
# as we are trying to delete it anyway.
# Trundle through the list deleting the volumes.
volume_updates = []
for volume in volumes:
self.delete_volume(volume)
volume_updates.append({'id': volume['id'],
'status': 'deleted'})
model_update = {'status': group['status']}
return model_update, volume_updates
def update_consistencygroup(self, context, group,
add_volumes=None, remove_volumes=None):
"""Updates a consistency group.
:param context: the context of the caller.
:param group: the dictionary of the consistency group to be updated.
:param add_volumes: a list of volume dictionaries to be added.
:param remove_volumes: a list of volume dictionaries to be removed.
:returns: model_update, add_volumes_update, remove_volumes_update
model_update is a dictionary that the driver wants the manager
to update upon a successful return. If None is returned, the manager
will set the status to 'available'.
add_volumes_update and remove_volumes_update are lists of dictionaries
that the driver wants the manager to update upon a successful return.
Note that each entry requires a {'id': xxx} so that the correct
volume entry can be updated. If None is returned, the volume will
remain its original status. Also note that you cannot directly
assign add_volumes to add_volumes_update as add_volumes is a list of
cinder.db.sqlalchemy.models.Volume objects and cannot be used for
db update directly. Same with remove_volumes.
If the driver throws an exception, the status of the group as well as
those of the volumes to be added/removed will be set to 'error'.
"""
gid = group['id']
with self._client.open_connection() as api:
profile = api.find_replay_profile(gid)
if not profile:
LOG.error(_LE('Cannot find Consistency Group %s'), gid)
elif api.update_cg_volumes(profile,
add_volumes,
remove_volumes):
LOG.info(_LI('Updated Consistency Group %s'), gid)
# we need nothing updated above us so just return None.
return None, None, None
# Things did not go well so throw.
msg = _('Unable to update consistency group %s') % gid
raise exception.VolumeBackendAPIException(data=msg)
def create_cgsnapshot(self, context, cgsnapshot, snapshots):
"""Takes a snapshot of the consistency group.
:param context: the context of the caller.
:param cgsnapshot: Information about the snapshot to take.
:param snapshots: List of snapshots for this cgsnapshot.
:returns: Updated model_update, snapshots.
:raises: VolumeBackendAPIException.
"""
cgid = cgsnapshot['consistencygroup_id']
snapshotid = cgsnapshot['id']
with self._client.open_connection() as api:
profile = api.find_replay_profile(cgid)
if profile:
LOG.debug('profile %s replayid %s', profile, snapshotid)
if api.snap_cg_replay(profile, snapshotid, 0):
snapshot_updates = []
for snapshot in snapshots:
snapshot_updates.append({
'id': snapshot.id,
'status': fields.SnapshotStatus.AVAILABLE
})
model_update = {'status': fields.SnapshotStatus.AVAILABLE}
return model_update, snapshot_updates
# That didn't go well. Tell them why. Then bomb out.
LOG.error(_LE('Failed to snap Consistency Group %s'), cgid)
else:
LOG.error(_LE('Cannot find Consistency Group %s'), cgid)
msg = _('Unable to snap Consistency Group %s') % cgid
raise exception.VolumeBackendAPIException(data=msg)
def delete_cgsnapshot(self, context, cgsnapshot, snapshots):
"""Deletes a cgsnapshot.
If profile isn't found return success. If failed to delete the
replay (the snapshot) then raise an exception.
:param context: the context of the caller.
:param cgsnapshot: Information about the snapshot to delete.
:returns: Updated model_update, snapshots.
:raises: VolumeBackendAPIException.
"""
cgid = cgsnapshot['consistencygroup_id']
snapshotid = cgsnapshot['id']
with self._client.open_connection() as api:
profile = api.find_replay_profile(cgid)
if profile:
LOG.info(_LI('Deleting snapshot %(ss)s from %(pro)s'),
{'ss': snapshotid,
'pro': profile})
if not api.delete_cg_replay(profile, snapshotid):
msg = (_('Unable to delete Consistency Group snapshot %s')
% snapshotid)
raise exception.VolumeBackendAPIException(data=msg)
snapshot_updates = []
for snapshot in snapshots:
snapshot_updates.append(
{'id': snapshot['id'],
'status': fields.SnapshotStatus.DELETED})
model_update = {'status': fields.SnapshotStatus.DELETED}
return model_update, snapshot_updates
def manage_existing(self, volume, existing_ref):
"""Brings an existing backend storage object under Cinder management.
existing_ref is passed straight through from the API request's
manage_existing_ref value, and it is up to the driver how this should
be interpreted. It should be sufficient to identify a storage object
that the driver should somehow associate with the newly-created cinder
volume structure.
There are two ways to do this:
1. Rename the backend storage object so that it matches the,
volume['name'] which is how drivers traditionally map between a
cinder volume and the associated backend storage object.
2. Place some metadata on the volume, or somewhere in the backend, that
allows other driver requests (e.g. delete, clone, attach, detach...)
to locate the backend storage object when required.
If the existing_ref doesn't make sense, or doesn't refer to an existing
backend storage object, raise a ManageExistingInvalidReference
exception.
The volume may have a volume_type, and the driver can inspect that and
compare against the properties of the referenced backend storage
object. If they are incompatible, raise a
ManageExistingVolumeTypeMismatch, specifying a reason for the failure.
:param volume: Cinder volume to manage
:param existing_ref: Driver-specific information used to identify a
volume
"""
if existing_ref.get('source-name') or existing_ref.get('source-id'):
with self._client.open_connection() as api:
api.manage_existing(volume['id'], existing_ref)
# Replicate if we are supposed to.
volume_name = volume.get('id')
provider_id = volume.get('provider_id')
scvolume = api.find_volume(volume_name, provider_id)
model_update = self._create_replications(api, volume, scvolume)
if model_update:
return model_update
else:
msg = _('Must specify source-name or source-id.')
raise exception.ManageExistingInvalidReference(
existing_ref=existing_ref, reason=msg)
# Only return a model_update if we have replication info to add.
return None
def manage_existing_get_size(self, volume, existing_ref):
"""Return size of volume to be managed by manage_existing.
When calculating the size, round up to the next GB.
:param volume: Cinder volume to manage
:param existing_ref: Driver-specific information used to identify a
volume
"""
if existing_ref.get('source-name') or existing_ref.get('source-id'):
with self._client.open_connection() as api:
return api.get_unmanaged_volume_size(existing_ref)
else:
msg = _('Must specify source-name or source-id.')
raise exception.ManageExistingInvalidReference(
existing_ref=existing_ref, reason=msg)
def unmanage(self, volume):
"""Removes the specified volume from Cinder management.
Does not delete the underlying backend storage object.
For most drivers, this will not need to do anything. However, some
drivers might use this call as an opportunity to clean up any
Cinder-specific configuration that they have associated with the
backend storage object.
:param volume: Cinder volume to unmanage
"""
with self._client.open_connection() as api:
volume_name = volume.get('id')
provider_id = volume.get('provider_id')
scvolume = api.find_volume(volume_name, provider_id)
if scvolume:
api.unmanage(scvolume)
def _get_retype_spec(self, diff, volume_name, specname, spectype):
"""Helper function to get current and requested spec.
:param diff: A difference dictionary.
:param volume_name: The volume name we are working with.
:param specname: The pretty name of the parameter.
:param spectype: The actual spec string.
:return: current, requested spec.
:raises: VolumeBackendAPIException
"""
spec = (diff['extra_specs'].get(spectype))
if spec:
if len(spec) != 2:
msg = _('Unable to retype %(specname)s, expected to receive '
'current and requested %(spectype)s values. Value '
'received: %(spec)s') % {'specname': specname,
'spectype': spectype,
'spec': spec}
LOG.error(msg)
raise exception.VolumeBackendAPIException(data=msg)
current = spec[0]
requested = spec[1]
if current != requested:
LOG.debug('Retyping volume %(vol)s to use %(specname)s '
'%(spec)s.',
{'vol': volume_name,
'specname': specname,
'spec': requested})
return current, requested
else:
LOG.info(_LI('Retype was to same Storage Profile.'))
return None, None
def _retype_replication(self, api, volume, scvolume, new_type, diff):
model_update = None
ret = True
# Replication.
current, requested = (
self._get_retype_spec(diff, volume.get('id'),
'replication_enabled',
'replication_enabled'))
# We only toggle at the repl level.
if current != requested:
# If we are changing to on...
if requested == '<is> True':
# We create our replication using our new type's extra specs.
model_update = self._create_replications(
api, volume, scvolume,
new_type.get('extra_specs'))
elif current == '<is> True':
# If we are killing replication we have to see if we currently
# have live volume enabled or not.
if self._is_live_vol(volume):
ret = self._delete_live_volume(api, volume)
else:
self._delete_replications(api, volume)
model_update = {'replication_status':
fields.ReplicationStatus.DISABLED,
'replication_driver_data': ''}
# TODO(tswanson): Add support for changing replication options.
return ret, model_update
def retype(self, ctxt, volume, new_type, diff, host):
"""Convert the volume to be of the new type.
Returns a boolean indicating whether the retype occurred.
:param ctxt: Context
:param volume: A dictionary describing the volume to migrate
:param new_type: A dictionary describing the volume type to convert to
:param diff: A dictionary with the difference between the two types
:param host: A dictionary describing the host to migrate to, where
host['host'] is its name, and host['capabilities'] is a
dictionary of its reported capabilities (Not Used).
:returns: Boolean or Boolean, model_update tuple.
"""
LOG.info(_LI('retype: volume_name: %(name)s new_type: %(newtype)s '
'diff: %(diff)s host: %(host)s'),
{'name': volume.get('id'), 'newtype': new_type,
'diff': diff, 'host': host})
model_update = None
# Any spec changes?
if diff['extra_specs']:
volume_name = volume.get('id')
provider_id = volume.get('provider_id')
with self._client.open_connection() as api:
try:
# Get our volume
scvolume = api.find_volume(volume_name, provider_id)
if scvolume is None:
LOG.error(_LE('Retype unable to find volume %s.'),
volume_name)
return False
# Check our specs.
# Storage profiles.
current, requested = (
self._get_retype_spec(diff, volume_name,
'Storage Profile',
'storagetype:storageprofile'))
# if there is a change and it didn't work fast fail.
if (current != requested and not
api.update_storage_profile(scvolume, requested)):
LOG.error(_LE('Failed to update storage profile'))
return False
# Replay profiles.
current, requested = (
self._get_retype_spec(diff, volume_name,
'Replay Profiles',
'storagetype:replayprofiles'))
# if there is a change and it didn't work fast fail.
if requested and not api.update_replay_profiles(scvolume,
requested):
LOG.error(_LE('Failed to update replay profiles'))
return False
# Volume QOS profiles.
current, requested = (
self._get_retype_spec(diff, volume_name,
'Volume QOS Profile',
'storagetype:volumeqos'))
if current != requested:
if not api.update_qos_profile(scvolume, requested):
LOG.error(_LE('Failed to update volume '
'qos profile'))
# Group QOS profiles.
current, requested = (
self._get_retype_spec(diff, volume_name,
'Group QOS Profile',
'storagetype:groupqos'))
if current != requested:
if not api.update_qos_profile(scvolume, requested,
True):
LOG.error(_LE('Failed to update group '
'qos profile'))
return False
# Data reduction profiles.
current, requested = (
self._get_retype_spec(
diff, volume_name, 'Data Reduction Profile',
'storagetype:datareductionprofile'))
if current != requested:
if not api.update_datareduction_profile(scvolume,
requested):
LOG.error(_LE('Failed to update data reduction '
'profile'))
return False
# Active Replay
current, requested = (
self._get_retype_spec(diff, volume_name,
'Replicate Active Replay',
'replication:activereplay'))
if current != requested and not (
api.update_replicate_active_replay(
scvolume, requested == '<is> True')):
LOG.error(_LE('Failed to apply '
'replication:activereplay setting'))
return False
# Deal with replication.
ret, model_update = self._retype_replication(
api, volume, scvolume, new_type, diff)
if not ret:
return False
except exception.VolumeBackendAPIException:
# We do nothing with this. We simply return failure.
return False
# If we have something to send down...
if model_update:
return True, model_update
return True
def _parse_secondary(self, api, secondary):
"""Find the replication destination associated with secondary.
:param api: Dell StorageCenterApi
:param secondary: String indicating the secondary to failover to.
:return: Destination SSN for the given secondary.
"""
LOG.debug('_parse_secondary. Looking for %s.', secondary)
destssn = None
# Trundle through these looking for our secondary.
for backend in self.backends:
ssnstring = backend['target_device_id']
# If they list a secondary it has to match.
# If they do not list a secondary we return the first
# replication on a working system.
if not secondary or secondary == ssnstring:
# Is a string. Need an int.
ssn = int(ssnstring)
# Without the source being up we have no good
# way to pick a destination to failover to. So just
# look for one that is just up.
try:
# If the SC ssn exists use it.
if api.find_sc(ssn):
destssn = ssn
break
except exception.VolumeBackendAPIException:
LOG.warning(_LW('SSN %s appears to be down.'), ssn)
LOG.info(_LI('replication failover secondary is %(ssn)s'),
{'ssn': destssn})
return destssn
def _update_backend(self, active_backend_id):
# Mark for failover or undo failover.
LOG.debug('active_backend_id: %s', active_backend_id)
if active_backend_id:
self.active_backend_id = six.text_type(active_backend_id)
self.failed_over = True
else:
self.active_backend_id = None
self.failed_over = False
self._client.active_backend_id = self.active_backend_id
def _get_qos(self, targetssn):
# Find our QOS.
qosnode = None
for backend in self.backends:
if int(backend['target_device_id']) == targetssn:
qosnode = backend.get('qosnode', 'cinderqos')
return qosnode
def _parse_extraspecs(self, volume):
# Digest our extra specs for replication.
extraspecs = {}
specs = self._get_volume_extra_specs(volume)
if specs.get('replication_type') == '<in> sync':
extraspecs['replicationtype'] = 'Synchronous'
else:
extraspecs['replicationtype'] = 'Asynchronous'
if specs.get('replication:activereplay') == '<is> True':
extraspecs['activereplay'] = True
else:
extraspecs['activereplay'] = False
extraspecs['storage_profile'] = specs.get('storagetype:storageprofile')
extraspecs['replay_profile_string'] = (
specs.get('storagetype:replayprofiles'))
return extraspecs
def _wait_for_replication(self, api, items):
# Wait for our replications to resync with their original volumes.
# We wait for completion, errors or timeout.
deadcount = 5
lastremain = 0.0
# The big wait loop.
while True:
# We run until all volumes are synced or in error.
done = True
currentremain = 0.0
# Run the list.
for item in items:
# If we have one cooking.
if item['status'] == 'inprogress':
# Is it done?
synced, remain = api.replication_progress(item['screpl'])
currentremain += remain
if synced:
# It is! Get our volumes.
cvol = api.get_volume(item['cvol'])
nvol = api.get_volume(item['nvol'])
# Flip replication.
if (cvol and nvol and api.flip_replication(
cvol, nvol, item['volume']['id'],
item['specs']['replicationtype'],
item['qosnode'],
item['specs']['activereplay'])):
# rename the original. Doesn't matter if it
# succeeded as we should have the provider_id
# of the new volume.
ovol = api.get_volume(item['ovol'])
if not ovol or not api.rename_volume(
ovol, 'org:' + ovol['name']):
# Not a reason to fail but will possibly
# cause confusion so warn.
LOG.warning(_LW('Unable to locate and rename '
'original volume: %s'),
item['ovol'])
item['status'] = 'synced'
else:
item['status'] = 'error'
elif synced is None:
# Couldn't get info on this one. Call it baked.
item['status'] = 'error'
else:
# Miles to go before we're done.
done = False
# done? then leave.
if done:
break
# Confirm we are or are not still making progress.
if lastremain == currentremain:
# One chance down. Warn user.
deadcount -= 1
LOG.warning(_LW('Waiting for replications to complete. '
'No progress for %(timeout)d seconds. '
'deadcount = %(cnt)d'),
{'timeout': self.failback_timeout,
'cnt': deadcount})
else:
# Reset
lastremain = currentremain
deadcount = 5
# If we've used up our 5 chances we error and log..
if deadcount == 0:
LOG.error(_LE('Replication progress has stopped: '
'%f remaining.'), currentremain)
for item in items:
if item['status'] == 'inprogress':
LOG.error(_LE('Failback failed for volume: %s. '
'Timeout waiting for replication to '
'sync with original volume.'),
item['volume']['id'])
item['status'] = 'error'
break
# This is part of an async call so we should be good sleeping here.
# Have to balance hammering the backend for no good reason with
# the max timeout for the unit tests. Yeah, silly.
eventlet.sleep(self.failback_timeout)
def _reattach_remaining_replications(self, api, items):
# Wiffle through our backends and reattach any remaining replication
# targets.
for item in items:
if item['status'] == 'synced':
svol = api.get_volume(item['nvol'])
# assume it went well. Will error out if not.
item['status'] = 'reattached'
# wiffle through our backends and kick off replications.
for backend in self.backends:
rssn = int(backend['target_device_id'])
if rssn != api.ssn:
rvol = api.find_repl_volume(item['volume']['id'],
rssn, None)
# if there is an old replication whack it.
api.delete_replication(svol, rssn, False)
if api.start_replication(
svol, rvol,
item['specs']['replicationtype'],
self._get_qos(rssn),
item['specs']['activereplay']):
# Save our replication_driver_data.
item['rdd'] += ','
item['rdd'] += backend['target_device_id']
else:
# No joy. Bail
item['status'] = 'error'
def _fixup_types(self, api, items):
# Update our replay profiles.
for item in items:
if item['status'] == 'reattached':
# Re-apply any appropriate replay profiles.
item['status'] = 'available'
rps = item['specs']['replay_profile_string']
if rps:
svol = api.get_volume(item['nvol'])
if not api.update_replay_profiles(svol, rps):
item['status'] = 'error'
def _volume_updates(self, items):
# Update our volume updates.
volume_updates = []
for item in items:
# Set our status for our replicated volumes
model_update = {'provider_id': item['nvol'],
'replication_driver_data': item['rdd']}
# These are simple. If the volume reaches available then,
# since we were replicating it, replication status must
# be good. Else error/error.
if item['status'] == 'available':
model_update['status'] = 'available'
model_update['replication_status'] = (
fields.ReplicationStatus.ENABLED)
else:
model_update['status'] = 'error'
model_update['replication_status'] = (
fields.ReplicationStatus.ERROR)
volume_updates.append({'volume_id': item['volume']['id'],
'updates': model_update})
return volume_updates
def _failback_replication(self, api, volume, qosnode):
"""Sets up the replication failback.
:param api: Dell SC API.
:param volume: Cinder Volume
:param qosnode: Dell QOS node object.
:return: replitem dict.
"""
LOG.info(_LI('failback_volumes: replicated volume'))
# Get our current volume.
cvol = api.find_volume(volume['id'], volume['provider_id'])
# Original volume on the primary.
ovol = api.find_repl_volume(volume['id'], api.primaryssn,
None, True, False)
# Delete our current mappings.
api.remove_mappings(cvol)
# If there is a replication to delete do so.
api.delete_replication(ovol, api.ssn, False)
# Replicate to a common replay.
screpl = api.replicate_to_common(cvol, ovol, 'tempqos')
# We made it this far. Update our status.
screplid = None
status = ''
if screpl:
screplid = screpl['instanceId']
nvolid = screpl['destinationVolume']['instanceId']
status = 'inprogress'
else:
LOG.error(_LE('Unable to restore %s'), volume['id'])
screplid = None
nvolid = None
status = 'error'
# Save some information for the next step.
# nvol is the new volume created by replicate_to_common.
# We also grab our extra specs here.
replitem = {
'volume': volume,
'specs': self._parse_extraspecs(volume),
'qosnode': qosnode,
'screpl': screplid,
'cvol': cvol['instanceId'],
'ovol': ovol['instanceId'],
'nvol': nvolid,
'rdd': six.text_type(api.ssn),
'status': status}
return replitem
def _failback_live_volume(self, api, id, provider_id):
"""failback the live volume to its original
:param api: Dell SC API
:param id: Volume ID
:param provider_id: Dell Instance ID
:return: model_update dict
"""
model_update = {}
# We do not search by name. Only failback if we have a complete
# LV object.
sclivevolume = api.get_live_volume(provider_id)
# TODO(tswanson): Check swapped state first.
if sclivevolume and api.swap_roles_live_volume(sclivevolume):
LOG.info(_LI('Success swapping sclivevolume roles %s'), id)
model_update = {
'status': 'available',
'replication_status': fields.ReplicationStatus.ENABLED,
'provider_id':
sclivevolume['secondaryVolume']['instanceId']}
else:
LOG.info(_LI('Failure swapping roles %s'), id)
model_update = {'status': 'error'}
return model_update
def _finish_failback(self, api, replitems):
# Wait for replication to complete.
# This will also flip replication.
self._wait_for_replication(api, replitems)
# Replications are done. Attach to any additional replication
# backends.
self._reattach_remaining_replications(api, replitems)
self._fixup_types(api, replitems)
return self._volume_updates(replitems)
def failback_volumes(self, volumes):
"""This is a generic volume failback.
:param volumes: List of volumes that need to be failed back.
:return: volume_updates for the list of volumes.
"""
LOG.info(_LI('failback_volumes'))
with self._client.open_connection() as api:
# Get our qosnode. This is a good way to make sure the backend
# is still setup so that we can do this.
qosnode = self._get_qos(api.ssn)
if not qosnode:
raise exception.VolumeBackendAPIException(
message=_('Unable to failback. Backend is misconfigured.'))
volume_updates = []
replitems = []
# Trundle through the volumes. Update non replicated to alive again
# and reverse the replications for the remaining volumes.
for volume in volumes:
LOG.info(_LI('failback_volumes: starting volume: %s'), volume)
model_update = {}
if volume.get('replication_driver_data'):
rspecs = self._get_replication_specs(
self._get_volume_extra_specs(volume))
if rspecs['live']:
model_update = self._failback_live_volume(
api, volume['id'], volume['provider_id'])
else:
replitem = self._failback_replication(api, volume,
qosnode)
# Save some information for the next step.
# nvol is the new volume created by
# replicate_to_common. We also grab our
# extra specs here.
replitems.append(replitem)
else:
# Not replicated. Just set it to available.
model_update = {'status': 'available'}
# Save our update
if model_update:
volume_updates.append({'volume_id': volume['id'],
'updates': model_update})
# Let's do up to 5 replications at once.
if len(replitems) == 5:
volume_updates += self._finish_failback(api, replitems)
replitems = []
# Finish any leftover items
if replitems:
volume_updates += self._finish_failback(api, replitems)
# Set us back to a happy state.
# The only way this doesn't happen is if the primary is down.
self._update_backend(None)
return volume_updates
def _failover_replication(self, api, id, provider_id, destssn):
rvol = api.break_replication(id, provider_id, destssn)
model_update = {}
if rvol:
LOG.info(_LI('Success failing over volume %s'), id)
model_update = {'replication_status':
fields.ReplicationStatus.FAILED_OVER,
'provider_id': rvol['instanceId']}
else:
LOG.info(_LI('Failed failing over volume %s'), id)
model_update = {'status': 'error'}
return model_update
def _failover_live_volume(self, api, id, provider_id):
model_update = {}
# Search for volume by id if we have to.
sclivevolume = api.get_live_volume(provider_id, id)
if sclivevolume:
swapped = api.is_swapped(provider_id, sclivevolume)
# If we aren't swapped try it. If fail error out.
if not swapped and not api.swap_roles_live_volume(sclivevolume):
LOG.info(_LI('Failure swapping roles %s'), id)
model_update = {'status': 'error'}
return model_update
LOG.info(_LI('Success swapping sclivevolume roles %s'), id)
sclivevolume = api.get_live_volume(provider_id)
model_update = {
'replication_status':
fields.ReplicationStatus.FAILED_OVER,
'provider_id':
sclivevolume['primaryVolume']['instanceId']}
# Error and leave.
return model_update
def failover_host(self, context, volumes, secondary_id=None):
"""Failover to secondary.
:param context: security context
:param secondary_id: Specifies rep target to fail over to
:param volumes: List of volumes serviced by this backend.
:returns: destssn, volume_updates data structure
Example volume_updates data structure:
.. code-block:: json
[{'volume_id': <cinder-uuid>,
'updates': {'provider_id': 8,
'replication_status': 'failed-over',
'replication_extended_status': 'whatever',...}},]
"""
LOG.debug('failover-host')
LOG.debug(self.failed_over)
LOG.debug(self.active_backend_id)
LOG.debug(self.replication_enabled)
if self.failed_over:
if secondary_id == 'default':
LOG.debug('failing back')
return 'default', self.failback_volumes(volumes)
raise exception.InvalidReplicationTarget(
reason=_('Already failed over'))
LOG.info(_LI('Failing backend to %s'), secondary_id)
# basic check
if self.replication_enabled:
with self._client.open_connection() as api:
# Look for the specified secondary.
destssn = self._parse_secondary(api, secondary_id)
if destssn:
# We roll through trying to break replications.
# Is failing here a complete failure of failover?
volume_updates = []
for volume in volumes:
model_update = {}
if volume.get('replication_driver_data'):
rspecs = self._get_replication_specs(
self._get_volume_extra_specs(volume))
if rspecs['live']:
model_update = self._failover_live_volume(
api, volume['id'],
volume.get('provider_id'))
else:
model_update = self._failover_replication(
api, volume['id'],
volume.get('provider_id'), destssn)
else:
# Not a replicated volume. Try to unmap it.
scvolume = api.find_volume(
volume['id'], volume.get('provider_id'))
api.remove_mappings(scvolume)
model_update = {'status': 'error'}
# Either we are failed over or our status is now error.
volume_updates.append({'volume_id': volume['id'],
'updates': model_update})
# this is it.
self._update_backend(destssn)
LOG.debug('after update backend')
LOG.debug(self.failed_over)
LOG.debug(self.active_backend_id)
LOG.debug(self.replication_enabled)
return destssn, volume_updates
else:
raise exception.InvalidReplicationTarget(reason=(
_('replication_failover failed. %s not found.') %
secondary_id))
# I don't think we should ever get here.
raise exception.VolumeBackendAPIException(message=(
_('replication_failover failed. '
'Backend not configured for failover')))
def _get_unmanaged_replay(self, api, volume_name, provider_id,
existing_ref):
replay_name = None
if existing_ref:
replay_name = existing_ref.get('source-name')
if not replay_name:
msg = _('_get_unmanaged_replay: Must specify source-name.')
LOG.error(msg)
raise exception.ManageExistingInvalidReference(
existing_ref=existing_ref, reason=msg)
# Find our volume.
scvolume = api.find_volume(volume_name, provider_id)
if not scvolume:
# Didn't find it.
msg = (_('_get_unmanaged_replay: Cannot find volume id %s')
% volume_name)
LOG.error(msg)
raise exception.VolumeBackendAPIException(data=msg)
# Find our replay.
screplay = api.find_replay(scvolume, replay_name)
if not screplay:
# Didn't find it. Reference must be invalid.
msg = (_('_get_unmanaged_replay: Cannot '
'find snapshot named %s') % replay_name)
LOG.error(msg)
raise exception.ManageExistingInvalidReference(
existing_ref=existing_ref, reason=msg)
return screplay
def manage_existing_snapshot(self, snapshot, existing_ref):
"""Brings an existing backend storage object under Cinder management.
existing_ref is passed straight through from the API request's
manage_existing_ref value, and it is up to the driver how this should
be interpreted. It should be sufficient to identify a storage object
that the driver should somehow associate with the newly-created cinder
snapshot structure.
There are two ways to do this:
1. Rename the backend storage object so that it matches the
snapshot['name'] which is how drivers traditionally map between a
cinder snapshot and the associated backend storage object.
2. Place some metadata on the snapshot, or somewhere in the backend,
that allows other driver requests (e.g. delete) to locate the
backend storage object when required.
If the existing_ref doesn't make sense, or doesn't refer to an existing
backend storage object, raise a ManageExistingInvalidReference
exception.
"""
with self._client.open_connection() as api:
# Find our unmanaged snapshot. This will raise on error.
volume_name = snapshot.get('volume_id')
provider_id = snapshot.get('provider_id')
snapshot_id = snapshot.get('id')
screplay = self._get_unmanaged_replay(api, volume_name,
provider_id, existing_ref)
# Manage means update description and update expiration.
if not api.manage_replay(screplay, snapshot_id):
# That didn't work. Error.
msg = (_('manage_existing_snapshot: Error managing '
'existing replay %(ss)s on volume %(vol)s') %
{'ss': screplay.get('description'),
'vol': volume_name})
LOG.error(msg)
raise exception.VolumeBackendAPIException(data=msg)
# Life is good. Let the world know what we've done.
LOG.info(_LI('manage_existing_snapshot: snapshot %(exist)s on '
'volume %(volume)s has been renamed to %(id)s and is '
'now managed by Cinder.'),
{'exist': screplay.get('description'),
'volume': volume_name,
'id': snapshot_id})
return {'provider_id': screplay['createVolume']['instanceId']}
# NOTE: Can't use abstractmethod before all drivers implement it
def manage_existing_snapshot_get_size(self, snapshot, existing_ref):
"""Return size of snapshot to be managed by manage_existing.
When calculating the size, round up to the next GB.
"""
volume_name = snapshot.get('volume_id')
provider_id = snapshot.get('provider_id')
with self._client.open_connection() as api:
screplay = self._get_unmanaged_replay(api, volume_name,
provider_id, existing_ref)
sz, rem = dell_storagecenter_api.StorageCenterApi.size_to_gb(
screplay['size'])
if rem > 0:
raise exception.VolumeBackendAPIException(
data=_('Volume size must be a multiple of 1 GB.'))
return sz
# NOTE: Can't use abstractmethod before all drivers implement it
def unmanage_snapshot(self, snapshot):
"""Removes the specified snapshot from Cinder management.
Does not delete the underlying backend storage object.
NOTE: We do set the expire countdown to 1 day. Once a snapshot is
unmanaged it will expire 24 hours later.
"""
with self._client.open_connection() as api:
snapshot_id = snapshot.get('id')
# provider_id is the snapshot's parent volume's instanceId.
provider_id = snapshot.get('provider_id')
volume_name = snapshot.get('volume_id')
# Find our volume.
scvolume = api.find_volume(volume_name, provider_id)
if not scvolume:
# Didn't find it.
msg = (_('unmanage_snapshot: Cannot find volume id %s')
% volume_name)
LOG.error(msg)
raise exception.VolumeBackendAPIException(data=msg)
# Find our replay.
screplay = api.find_replay(scvolume, snapshot_id)
if not screplay:
# Didn't find it. Reference must be invalid.
msg = (_('unmanage_snapshot: Cannot find snapshot named %s')
% snapshot_id)
LOG.error(msg)
raise exception.VolumeBackendAPIException(data=msg)
# Free our snapshot.
api.unmanage_replay(screplay)
# Do not check our result.
def thaw_backend(self, context):
"""Notify the backend that it's unfrozen/thawed.
This is a gate. We do not allow the backend to be thawed if
it is still failed over.
:param context: security context
:response: True on success
:raises Invalid: if it cannot be thawed.
"""
# We shouldn't be called if we are not failed over.
if self.failed_over:
msg = _('The Dell SC array does not support thawing a failed over'
' replication. Please migrate volumes to an operational '
'back-end or resolve primary system issues and '
'fail back to reenable full functionality.')
LOG.error(msg)
raise exception.Invalid(reason=msg)
return True<|fim▁end|> | with self._client.open_connection() as api:
try:
rspecs = self._get_replication_specs( |
<|file_name|>menubutton.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3<|fim▁hole|>
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class MenuButton(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self)
self.connect("destroy", Gtk.main_quit)
menubutton = Gtk.MenuButton("MenuButton")
self.add(menubutton)
menu = Gtk.Menu()
menubutton.set_popup(menu)
for count in range(1, 6):
menuitem = Gtk.MenuItem("Item %i" % (count))
menuitem.connect("activate", self.on_menuitem_activated)
menu.append(menuitem)
menu.show_all()
def on_menuitem_activated(self, menuitem):
print("%s Activated" % (menuitem.get_label()))
window = MenuButton()
window.show_all()
Gtk.main()<|fim▁end|> | |
<|file_name|>rest-handler.js<|end_file_name|><|fim▁begin|>var http = require('http')
var url = require('url')
var path = require('path')
var sleep = require('sleep-ref')
var Router = require("routes-router")
var concat = require('concat-stream')
var ldj = require('ldjson-stream')
var manifest = require('level-manifest')
var multilevel = require('multilevel')
var extend = require('extend')
var prettyBytes = require('pretty-bytes')
var jsonStream = require('JSONStream')
var prebuiltEditor = require('dat-editor-prebuilt')
var debug = require('debug')('rest-handler')
var auth = require('./auth.js')
var pump = require('pump')
var zlib = require('zlib')
var through = require('through2')
module.exports = RestHandler
function RestHandler(dat) {
if (!(this instanceof RestHandler)) return new RestHandler(dat)
this.dat = dat
this.auth = auth(dat.options)
this.router = this.createRoutes()
this.sleep = sleep(function(opts) {
opts.decode = true
if (opts.live === 'true') opts.live = true
if (opts.tail === 'true') opts.tail = true
return dat.createChangesReadStream(opts)
}, {style: 'newline'})
}
RestHandler.prototype.createRoutes = function() {
var router = Router()
router.addRoute("/", this.dataTable.bind(this))
router.addRoute("/api/session", this.session.bind(this))
router.addRoute("/api/login", this.login.bind(this))
router.addRoute("/api/logout", this.logout.bind(this))
router.addRoute("/api/pull", this.pull.bind(this))
router.addRoute("/api/push", this.push.bind(this))
router.addRoute("/api/changes", this.changes.bind(this))
router.addRoute("/api/stats", this.stats.bind(this))
router.addRoute("/api/bulk", this.bulk.bind(this))
router.addRoute("/api/metadata", this.package.bind(this))
router.addRoute("/api/manifest", this.manifest.bind(this))
router.addRoute("/api/rpc", this.rpc.bind(this))
router.addRoute("/api/csv", this.exportCsv.bind(this))
router.addRoute("/api", this.hello.bind(this))
router.addRoute("/api/rows", this.document.bind(this))
router.addRoute("/api/rows/:key", this.document.bind(this))
router.addRoute("/api/rows/:key/:filename", this.blob.bind(this))
router.addRoute("/api/blobs/:key", this.blobs.bind(this))
router.addRoute("*", this.notFound.bind(this))
return router
}
RestHandler.prototype.session = function(req, res) {
var self = this
this.auth.handle(req, res, function(err, session) {
debug('session', [err, session])
var data = {}
if (err) return self.auth.error(req, res)
if (session) data.session = session
else data.loggedOut = true
self.json(res, data)
})
}
RestHandler.prototype.login = function(req, res) {
var self = this
this.auth.handle(req, res, function(err, session) {
debug('login', [err, session])
if (err) {
res.setHeader("WWW-Authenticate", "Basic realm=\"Secure Area\"")
self.auth.error(req, res)
return
}
self.json(res, {session: session})
})
}
RestHandler.prototype.logout = function(req, res) {
return this.auth.error(req, res)
}
RestHandler.prototype.blob = function(req, res, opts) {
var self = this
if (req.method === 'GET') {
var key = opts.key
var blob = self.dat.createBlobReadStream(opts.key, opts.filename, opts)
blob.on('error', function(err) {
return self.error(res, 404, {"error": "Not Found"})
})
pump(blob, res)
return
}
if (req.method === "POST") {
var reqUrl = url.parse(req.url, true)
var qs = reqUrl.query
var doc = {
key: opts.key,
version: qs.version
}
self.auth.handle(req, res, function(err) {
if (err) return self.auth.error(req, res)
var key = doc.key
self.dat.get(key, { version: doc.version }, function(err, existing) {
if (existing) {
doc = existing
}
var ws = self.dat.createBlobWriteStream(opts.filename, doc, function(err, updated) {
if (err) return self.error(res, 500, err)
self.json(res, updated)
})
pump(req, ws)
})
return
})
return
}
self.error(res, 405, {error: 'method not supported'})
}
RestHandler.prototype.blobs = function(req, res, opts) {
var self = this
if (req.method === 'HEAD') {
var key = opts.key<|fim▁hole|> res.end()
})
return
}
if (req.method === 'GET') {
res.statusCode = 200
return pump(self.dat.blobs.backend.createReadStream(opts), res)
}
self.error(res, 405, {error: 'method not supported'})
}
var unzip = function(req) {
return req.headers['content-encoding'] === 'gzip' ? zlib.createGunzip() : through()
}
var zip = function(req, res) {
if (!/gzip/.test(req.headers['accept-encoding'] || '')) return through()
res.setHeader('Content-Encoding', 'gzip')
return zlib.createGzip()
}
RestHandler.prototype.push = function(req, res) {
var self = this
this.auth.handle(req, res, function(err) {
if (err) return self.auth.error(req, res)
pump(req, unzip(req), self.dat.replicator.receive(), function(err) {
if (err) {
res.statusCode = err.status || 500
res.end(err.message)
return
}
res.end()
})
})
}
RestHandler.prototype.pull = function(req, res) {
var reqUrl = url.parse(req.url, true)
var qs = reqUrl.query
var send = this.dat.replicator.send({
since: parseInt(qs.since, 10) || 0,
blobs: qs.blobs !== 'false',
live: !!qs.live
})
pump(send, zip(req, res), res)
}
RestHandler.prototype.changes = function(req, res) {
this.sleep.httpHandler(req, res)
}
RestHandler.prototype.stats = function(req, res) {
var statsStream = this.dat.createStatsStream()
statsStream.on('error', function(err) {
var errObj = {
type: 'statsStreamError',
message: err.message
}
res.statusCode = 400
serializer.write(errObj)
serializer.end()
})
var serializer = ldj.serialize()
pump(statsStream, serializer, res)
}
RestHandler.prototype.package = function(req, res) {
var meta = {changes: this.dat.storage.change, liveBackup: this.dat.supportsLiveBackup()}
meta.columns = this.dat.schema.headers()
this.json(res, meta)
}
RestHandler.prototype.manifest = function(req, res) {
this.json(res, manifest(this.dat.storage))
}
RestHandler.prototype.rpc = function(req, res) {
var self = this
this.auth.handle(req, res, function(err) {
if (err) return self.auth.error(req, res)
var mserver = multilevel.server(self.dat.storage)
pump(req, mserver, res)
})
}
RestHandler.prototype.exportCsv = function(req, res) {
var reqUrl = url.parse(req.url, true)
var qs = reqUrl.query
qs.csv = true
var readStream = this.dat.createReadStream(qs)
res.writeHead(200, {'content-type': 'text/csv'})
pump(readStream, res)
}
RestHandler.prototype.exportJson = function(req, res) {
var reqUrl = url.parse(req.url, true)
var qs = reqUrl.query
if (typeof qs.limit === 'undefined') qs.limit = 50
else qs.limit = +qs.limit
var readStream = this.dat.createReadStream(qs)
res.writeHead(200, {'content-type': 'application/json'})
pump(readStream, jsonStream.stringify('{"rows": [\n', '\n,\n', '\n]}\n'), res)
}
RestHandler.prototype.handle = function(req, res) {
debug(req.connection.remoteAddress + ' - ' + req.method + ' - ' + req.url + ' - ')
this.router(req, res)
}
RestHandler.prototype.error = function(res, status, message) {
if (!status) status = res.statusCode
if (message) {
if (message.status) status = message.status
if (typeof message === "object") message.status = status
if (typeof message === "string") message = {error: status, message: message}
}
res.statusCode = status || 500
this.json(res, message)
}
RestHandler.prototype.notFound = function(req, res) {
this.error(res, 404, {"error": "Not Found"})
}
RestHandler.prototype.hello = function(req, res) {
var self = this
var stats = {
"dat": "Hello",
"version": this.dat.version,
"changes": this.dat.storage.change,
"name": this.dat.options.name
}
this.dat.storage.stat(function(err, stat) {
if (err) return self.json(res, stats)
stats.rows = stat.rows
self.dat.storage.approximateSize(function(err, size) {
if (err) return self.json(res, stats)
stats.approximateSize = { rows: prettyBytes(size) }
self.json(res, stats)
})
})
}
RestHandler.prototype.dataTable = function(req, res) {
res.setHeader('content-type', 'text/html; charset=utf-8')
res.end(prebuiltEditor)
}
RestHandler.prototype.json = function(res, json) {
res.setHeader('content-type', 'application/json')
res.end(JSON.stringify(json) + '\n')
}
RestHandler.prototype.get = function(req, res, opts) {
var self = this
this.dat.get(opts.key, url.parse(req.url, true).query || {}, function(err, json) {
if (err && err.message === 'range not found') return self.error(res, 404, {error: "Not Found"})
if (err) return self.error(res, 500, err.message)
if (json === null) return self.error(res, 404, {error: "Not Found"})
self.json(res, json)
})
}
RestHandler.prototype.post = function(req, res) {
var self = this
self.bufferJSON(req, function(err, json) {
if (err) return self.error(res, 500, err)
if (!json) json = {}
self.dat.put(json, function(err, stored) {
if (err) {
if (err.conflict) return self.error(res, 409, {conflict: true, error: "Document update conflict. Invalid version"})
return self.error(res, 500, err)
}
res.statusCode = 201
self.json(res, stored)
})
})
}
RestHandler.prototype.delete = function(req, res, opts) {
var self = this
self.dat.delete(opts.key, function(err, stored) {
if (err) return self.error(res, 500, err)
self.json(res, {deleted: true})
})
}
RestHandler.prototype.bulk = function(req, res) {
var self = this
var opts = {}
var ct = req.headers['content-type']
if (ct === 'application/json') opts.json = true
else if (ct === 'text/csv') opts.csv = true
else return self.error(res, 400, {error: 'missing or unsupported content-type'})
opts.results = true
debug('/api/bulk', opts)
this.auth.handle(req, res, function(err) {
if (err) return self.auth.error(req, res)
var writeStream = self.dat.createWriteStream(opts)
writeStream.on('error', function(writeErr) {
var errObj = {
type: 'writeStreamError',
message: writeErr.message
}
res.statusCode = 400
serializer.write(errObj)
serializer.end()
})
var serializer = ldj.serialize()
pump(req, writeStream, serializer, res)
})
}
RestHandler.prototype.document = function(req, res, opts) {
var self = this
if (req.method === "GET" || req.method === "HEAD") {
if (opts.key) return this.get(req, res, opts)
else return this.exportJson(req, res)
}
this.auth.handle(req, res, function(err) {
if (err) return self.auth.error(req, res)
if (req.method === "POST") return self.post(req, res, opts)
if (req.method === "DELETE") return self.delete(req, res, opts)
self.error(res, 405, {error: 'method not supported'})
})
}
RestHandler.prototype.bufferJSON = function(req, cb) {
var self = this
req.on('error', function(err) {
cb(err)
})
req.pipe(concat(function(buff) {
var json
if (buff && buff.length === 0) return cb()
if (buff) {
try {
json = JSON.parse(buff)
} catch(err) {
return cb(err)
}
}
if (!json) return cb(err)
cb(null, json)
}))
}<|fim▁end|> | var blob = self.dat.blobs.backend.exists(opts, function(err, exists) {
res.statusCode = exists ? 200 : 404
res.setHeader('content-length', 0) |
<|file_name|>CmdArgs.cpp<|end_file_name|><|fim▁begin|>/*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 GPL Source Code ("Doom 3 Source Code").
Doom 3 Source Code 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.
Doom 3 Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#include "precompiled.h"
/*
============
idCmdArgs::operator=
============
*/
void idCmdArgs::operator=( const idCmdArgs &args )
{
int i;
argc = args.argc;
memcpy( tokenized, args.tokenized, MAX_COMMAND_STRING );
for( i = 0; i < argc; i++ )
{
argv[ i ] = tokenized + ( args.argv[ i ] - args.tokenized );
}
}
/*
============
idCmdArgs::Args
============
*/
const char *idCmdArgs::Args( int start, int end, bool escapeArgs ) const
{
static char cmd_args[MAX_COMMAND_STRING];
int i;
if( end < 0 )
{
end = argc - 1;
}
else if( end >= argc )
{
end = argc - 1;
}
cmd_args[0] = '\0';
if( escapeArgs )
{
strcat( cmd_args, "\"" );
}
for( i = start; i <= end; i++ )
{
if( i > start )
{
if( escapeArgs )
{
strcat( cmd_args, "\" \"" );
}
else
{
strcat( cmd_args, " " );
}
}
if( escapeArgs && strchr( argv[i], '\\' ) )
{
char *p = argv[i];
while( *p != '\0' )
{
if( *p == '\\' )
{
strcat( cmd_args, "\\\\" );
}
else
{
int l = strlen( cmd_args );
cmd_args[ l ] = *p;
cmd_args[ l + 1 ] = '\0';
}
p++;
}
}
else
{
strcat( cmd_args, argv[i] );
}
}
if( escapeArgs )
{
strcat( cmd_args, "\"" );
}
return cmd_args;
}
/*
============
idCmdArgs::TokenizeString
Parses the given string into command line tokens.
The text is copied to a separate buffer and 0 characters
are inserted in the appropriate place. The argv array
will point into this temporary buffer.
============
*/
void idCmdArgs::TokenizeString( const char *text, bool keepAsStrings )
{
idLexer lex;
idToken token, number;
int len, totalLen;
// clear previous args
argc = 0;
if( !text )
{
return;
}
lex.LoadMemory( text, strlen( text ), "idCmdSystemLocal::TokenizeString" );
lex.SetFlags( LEXFL_NOERRORS
| LEXFL_NOWARNINGS
| LEXFL_NOSTRINGCONCAT
| LEXFL_ALLOWPATHNAMES
| LEXFL_NOSTRINGESCAPECHARS
| LEXFL_ALLOWIPADDRESSES | ( keepAsStrings ? LEXFL_ONLYSTRINGS : 0 ) );
totalLen = 0;
while( 1 )
{
if( argc == MAX_COMMAND_ARGS )
{
return; // this is usually something malicious
}
if( !lex.ReadToken( &token ) )
{
return;
}
// check for negative numbers
if( !keepAsStrings && ( token == "-" ) )
{
if( lex.CheckTokenType( TT_NUMBER, 0, &number ) )
{
token = "-" + number;
}
}
// check for cvar expansion
if( token == "$" )
{
if( !lex.ReadToken( &token ) )
{
return;
}
if( idLib::cvarSystem )
{
token = idLib::cvarSystem->GetCVarString( token.c_str() );
}
else
{
token = "<unknown>";
}
}
len = token.Length();
if( totalLen + len + 1 > sizeof( tokenized ) )
{
return; // this is usually something malicious
}
// regular token
argv[argc] = tokenized + totalLen;
argc++;
idStr::Copynz( tokenized + totalLen, token.c_str(), sizeof( tokenized ) - totalLen );
totalLen += len + 1;
}
}
/*
============
idCmdArgs::AppendArg
============
*/
void idCmdArgs::AppendArg( const char *text )
{
if( !argc )
{<|fim▁hole|> argc = 1;
argv[ 0 ] = tokenized;
idStr::Copynz( tokenized, text, sizeof( tokenized ) );
}
else
{
argv[ argc ] = argv[ argc - 1 ] + strlen( argv[ argc - 1 ] ) + 1;
idStr::Copynz( argv[ argc ], text, sizeof( tokenized ) - ( argv[ argc ] - tokenized ) );
argc++;
}
}
/*
============
idCmdArgs::GetArgs
============
*/
const char **idCmdArgs::GetArgs( int *_argc )
{
*_argc = argc;
return ( const char ** )&argv[0];
}<|fim▁end|> | |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2016 Google 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<|fim▁hole|><|fim▁end|> | # limitations under the License.
"""A helper library for the runtime_configs command group.""" |
<|file_name|>PlainView.js<|end_file_name|><|fim▁begin|><|fim▁hole|> // define the (default) controller type for this View
getControllerName: function() {
return "my.own.controller";
},
// defines the UI of this View
createContent: function(oController) {
// button text is bound to Model, "press" action is bound to Controller's event handler
return;
}
});<|fim▁end|> | sap.ui.jsview(ui5nameSpace, {
|
<|file_name|>PasswordManagerRegistration.java<|end_file_name|><|fim▁begin|>package view;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.Font;
public class PasswordManagerRegistration {
JPanel regpanel;
private JTextField txtUsername;
private JPasswordField txtPass1;
private JPasswordField txtPass2;
private PasswordManagerGUI gui;
public PasswordManagerRegistration(PasswordManagerGUI gui) {
this.gui = gui;
regpanel = new JPanel();
regpanel.setLayout(new BorderLayout(0, 0));
JPanel panel_1 = new JPanel();
regpanel.add(panel_1, BorderLayout.NORTH);
JLabel lblRegistration = new JLabel(Labels.REG_REGISTRATION);
lblRegistration.setFont(new Font("Tahoma", Font.PLAIN, 38));
panel_1.add(lblRegistration);
JPanel panel_2 = new JPanel();
regpanel.add(panel_2, BorderLayout.CENTER);
panel_2.setLayout(null);
JLabel lblUsername = new JLabel(Labels.REG_USERNAME);
lblUsername.setBounds(74, 92, 132, 16);
panel_2.add(lblUsername);
JLabel lblPassword = new JLabel(Labels.REG_PASSWORD);
lblPassword.setBounds(74, 149, 173, 16);
panel_2.add(lblPassword);
JLabel lblPasswordAgain = new JLabel(Labels.REG_RE_PASSWORD);
lblPasswordAgain.setBounds(74, 204, 173, 16);
panel_2.add(lblPasswordAgain);
txtUsername = new JTextField();
txtUsername.setBounds(252, 89, 380, 22);
panel_2.add(txtUsername);
txtUsername.setColumns(10);
txtPass1 = new JPasswordField();
txtPass1.setBounds(252, 146, 380, 22);
panel_2.add(txtPass1);
txtPass2 = new JPasswordField();
txtPass2.setBounds(252, 201, 380, 22);
txtPass1.addActionListener(gui.getController());
txtPass1.setActionCommand(Labels.REG_PASS1FIELD);
txtPass2.addActionListener(gui.getController());
txtPass2.setActionCommand(Labels.REG_PASS2FIELD);
txtUsername.addActionListener(gui.getController());
txtUsername.setActionCommand(Labels.REG_USERFIELD);
panel_2.add(txtPass2);
JButton btnRegistration = new JButton(Labels.REG_REGBUTTON);
btnRegistration.addActionListener(gui.getController());
btnRegistration.setBounds(278, 288, 151, 25);
panel_2.add(btnRegistration);
}
public JTextField getTxtUsername() {
return txtUsername;
}
public JPasswordField getTxtPass1() {
return txtPass1;
}
public JPasswordField getTxtPass2() {
return txtPass2;<|fim▁hole|><|fim▁end|> | }
} |
<|file_name|>script.py<|end_file_name|><|fim▁begin|>from __future__ import print_function
import shutil
import os, sys
import time
import logging
from .loaders import PythonLoader, YAMLLoader
from .bundle import get_all_bundle_files
from .exceptions import BuildError
from .updater import TimestampUpdater
from .merge import MemoryHunk
from .version import get_manifest
from .cache import FilesystemCache
from .utils import set, StringIO
__all__ = ('CommandError', 'CommandLineEnvironment', 'main')
# logging has WARNING as default level, for the CLI we want INFO. Set this
# as early as possible, so that user customizations will not be overwritten.
logging.getLogger('webassets.script').setLevel(logging.INFO)
class CommandError(Exception):
pass
class Command(object):
"""Base-class for a command used by :class:`CommandLineEnvironment`.
Each command being a class opens up certain possibilities with respect to
subclassing and customizing the default CLI.
"""
def __init__(self, cmd_env):
self.cmd = cmd_env
def __getattr__(self, name):
# Make stuff from cmd environment easier to access
return getattr(self.cmd, name)
def __call__(self, *args, **kwargs):
raise NotImplementedError()
class BuildCommand(Command):
def __call__(self, bundles=None, output=None, directory=None, no_cache=None,
manifest=None, production=None):
"""Build assets.
``bundles``
A list of bundle names. If given, only this list of bundles
should be built.
``output``
List of (bundle, filename) 2-tuples. If given, only these
bundles will be built, using the custom output filenames.
Cannot be used with ``bundles``.
``directory``
Custom output directory to use for the bundles. The original
basenames defined in the bundle ``output`` attribute will be
used. If the ``output`` of the bundles are pointing to different
directories, they will be offset by their common prefix.
Cannot be used with ``output``.
``no_cache``
If set, a cache (if one is configured) will not be used.
``manifest``
If set, the given manifest instance will be used, instead of
any that might have been configured in the Environment. The value
passed will be resolved through ``get_manifest()``. If this fails,
a file-based manifest will be used using the given value as the
filename.
``production``
If set to ``True``, then :attr:`Environment.debug`` will forcibly
be disabled (set to ``False``) during the build.
"""
# Validate arguments
if bundles and output:
raise CommandError(
'When specifying explicit output filenames you must '
'do so for all bundles you want to build.')
if directory and output:
raise CommandError('A custom output directory cannot be '
'combined with explicit output filenames '
'for individual bundles.')
if production:
# TODO: Reset again (refactor commands to be classes)
self.environment.debug = False
# TODO: Oh how nice it would be to use the future options stack.
if manifest is not None:
try:
manifest = get_manifest(manifest, env=self.environment)
except ValueError:
manifest = get_manifest(
# abspath() is important, or this will be considered
# relative to Environment.directory.
"file:%s" % os.path.abspath(manifest),
env=self.environment)
self.environment.manifest = manifest
# Use output as a dict.
if output:
output = dict(output)
# Validate bundle names
bundle_names = bundles if bundles else (output.keys() if output else [])
for name in bundle_names:
if not name in self.environment:
raise CommandError(
'I do not know a bundle name named "%s".' % name)
# Make a list of bundles to build, and the filename to write to.
if bundle_names:
# TODO: It's not ok to use an internal property here.
bundles = [(n,b) for n, b in self.environment._named_bundles.items()
if n in bundle_names]
else:
# Includes unnamed bundles as well.
bundles = [(None, b) for b in self.environment]
# Determine common prefix for use with ``directory`` option.
if directory:
prefix = os.path.commonprefix(
[os.path.normpath(b.resolve_output())
for _, b in bundles if b.output])
# dirname() gives the right value for a single file.
prefix = os.path.dirname(prefix)
to_build = []
for name, bundle in bundles:
# TODO: We really should support this. This error here
# is just in place of a less understandable error that would
# otherwise occur.
if bundle.is_container and directory:
raise CommandError(
'A custom output directory cannot currently be '
'used with container bundles.')
# Determine which filename to use, if not the default.
overwrite_filename = None
if output:
overwrite_filename = output[name]
elif directory:
offset = os.path.normpath(
bundle.resolve_output())[len(prefix)+1:]
overwrite_filename = os.path.join(directory, offset)
to_build.append((bundle, overwrite_filename, name,))
# Build.
built = []
for bundle, overwrite_filename, name in to_build:
if name:
# A name is not necessary available of the bundle was
# registered without one.
self.log.info("Building bundle: %s (to %s)" % (
name, overwrite_filename or bundle.output))
else:
self.log.info("Building bundle: %s" % bundle.output)
try:
if not overwrite_filename:
with bundle.bind(self.environment):
bundle.build(force=True, disable_cache=no_cache)
else:
# TODO: Rethink how we deal with container bundles here.
# As it currently stands, we write all child bundles
# to the target output, merged (which is also why we
# create and force writing to a StringIO instead of just
# using the ``Hunk`` objects that build() would return
# anyway.
output = StringIO()
with bundle.bind(self.environment):
bundle.build(force=True, output=output,
disable_cache=no_cache)
if directory:
# Only auto-create directories in this mode.
output_dir = os.path.dirname(overwrite_filename)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
MemoryHunk(output.getvalue()).save(overwrite_filename)
built.append(bundle)
except BuildError as e:
self.log.error("Failed, error was: %s" % e)
if len(built):
self.event_handlers['post_build']()
if len(built) != len(to_build):
return 2
class WatchCommand(Command):
def __call__(self, loop=None):
"""Watch assets for changes.
``loop``
A callback, taking no arguments, to be called once every loop
iteration. Can be useful to integrate the command with other code.
If not specified, the loop wil call ``time.sleep()``.
"""
# TODO: This should probably also restart when the code changes.
mtimes = {}
try:
# Before starting to watch for changes, also recognize changes
# made while we did not run, and apply those immediately.
for bundle in self.environment:
print('Bringing up to date: %s' % bundle.output)
bundle.build(force=False)
self.log.info("Watching %d bundles for changes..." %
len(self.environment))
while True:
changed_bundles = self.check_for_changes(mtimes)
built = []
for bundle in changed_bundles:
print("Building bundle: %s ..." % bundle.output, end=' ')
sys.stdout.flush()
try:
bundle.build(force=True)
built.append(bundle)
except BuildError as e:
print("")
print("Failed: %s" % e)
else:
print("done")
if len(built):
self.event_handlers['post_build']()
do_end = loop() if loop else time.sleep(0.1)
if do_end:
break
except KeyboardInterrupt:
pass
def check_for_changes(self, mtimes):
# Do not update original mtimes dict right away, so that we detect
# all bundle changes if a file is in multiple bundles.
_new_mtimes = mtimes.copy()
changed_bundles = set()
# TODO: An optimization was lost here, skipping a bundle once
# a single file has been found to have changed. Bring back.
for filename, bundles_to_update in self.yield_files_to_watch():
stat = os.stat(filename)
mtime = stat.st_mtime
if sys.platform == "win32":
mtime -= stat.st_ctime
if mtimes.get(filename, mtime) != mtime:
if callable(bundles_to_update):
# Hook for when file has changed
try:
bundles_to_update = bundles_to_update()
except EnvironmentError:
# EnvironmentError is what the hooks is allowed to
# raise for a temporary problem, like an invalid config
import traceback
traceback.print_exc()
# Don't update anything, wait for another change
bundles_to_update = set()
if bundles_to_update is True:
# Indicates all bundles should be rebuilt for the change
bundles_to_update = set(self.environment)
changed_bundles |= bundles_to_update
_new_mtimes[filename] = mtime
_new_mtimes[filename] = mtime
mtimes.update(_new_mtimes)
return changed_bundles
def yield_files_to_watch(self):
for bundle in self.environment:
for filename in get_all_bundle_files(bundle):
yield filename, set([bundle])
class CleanCommand(Command):
def __call__(self):
"""Delete generated assets.
"""
self.log.info('Cleaning generated assets...')
for bundle in self.environment:
if not bundle.output:
continue
file_path = bundle.resolve_output(self.environment)
if os.path.exists(file_path):
os.unlink(file_path)
self.log.info("Deleted asset: %s" % bundle.output)
if isinstance(self.environment.cache, FilesystemCache):
shutil.rmtree(self.environment.cache.directory)
class CheckCommand(Command):
def __call__(self):
"""Check to see if assets need to be rebuilt.
A non-zero exit status will be returned if any of the input files are
newer (based on mtime) than their output file. This is intended to be
used in pre-commit hooks.
"""
needsupdate = False
updater = self.environment.updater
if not updater:
self.log.debug('no updater configured, using TimestampUpdater')
updater = TimestampUpdater()
for bundle in self.environment:
self.log.info('Checking asset: %s', bundle.output)
if updater.needs_rebuild(bundle, self.environment):
self.log.info(' needs update')
needsupdate = True
if needsupdate:
sys.exit(-1)
class CommandLineEnvironment(object):
"""Implements the core functionality for a command line frontend to
``webassets``, abstracted in a way to allow frameworks to integrate the
functionality into their own tools, for example, as a Django management
command, or a command for ``Flask-Script``.
"""
def __init__(self, env, log, post_build=None, commands=None):
self.environment = env
self.log = log
self.event_handlers = dict(post_build=lambda: True)
if callable(post_build):
self.event_handlers['post_build'] = post_build
# Instantiate each command
command_def = self.DefaultCommands.copy()
command_def.update(commands or {})
self.commands = {}
for name, construct in command_def.items():
if not construct:
continue
if not isinstance(construct, (list, tuple)):
construct = [construct, (), {}]
self.commands[name] = construct[0](
self, *construct[1], **construct[2])
def __getattr__(self, item):
# Allow method-like access to commands.
if item in self.commands:
return self.commands[item]
raise AttributeError(item)
def invoke(self, command, args):
"""Invoke ``command``, or throw a CommandError.
This is essentially a simple validation mechanism. Feel free
to call the individual command methods manually.
"""
try:
function = self.commands[command]
except KeyError as e:
raise CommandError('unknown command: %s' % e)
else:
return function(**args)
# List of commands installed
DefaultCommands = {
'build': BuildCommand,
'watch': WatchCommand,
'clean': CleanCommand,
'check': CheckCommand
}
class GenericArgparseImplementation(object):
"""Generic command line utility to interact with an webassets environment.
This is effectively a reference implementation of a command line utility
based on the ``CommandLineEnvironment`` class. Implementers may find it
feasible to simple base their own command line utility on this, rather than
implementing something custom on top of ``CommandLineEnvironment``. In
fact, if that is possible, you are encouraged to do so for greater
consistency across implementations.
"""
class WatchCommand(WatchCommand):
"""Extended watch command that also looks at the config file itself."""
def __init__(self, cmd_env, argparse_ns):
WatchCommand.__init__(self, cmd_env)
self.ns = argparse_ns
def yield_files_to_watch(self):
for result in WatchCommand.yield_files_to_watch(self):
yield result
# If the config changes, rebuild all bundles
if getattr(self.ns, 'config', None):
yield self.ns.config, self.reload_config
def reload_config(self):
try:
self.cmd.environment = YAMLLoader(self.ns.config).load_environment()
except Exception as e:
raise EnvironmentError(e)
return True
def __init__(self, env=None, log=None, prog=None, no_global_options=False):
try:
import argparse
except ImportError:
raise RuntimeError(
'The webassets command line now requires the '
'"argparse" library on Python versions <= 2.6.')
else:
self.argparse = argparse
self.env = env
self.log = log
self._construct_parser(prog, no_global_options)
def _construct_parser(self, prog=None, no_global_options=False):
self.parser = parser = self.argparse.ArgumentParser(
description="Manage assets.",
prog=prog)
if not no_global_options:
# Start with the base arguments that are valid for any command.
# XXX: Add those to the subparser?
parser.add_argument("-v", dest="verbose", action="store_true",
help="be verbose")
parser.add_argument("-q", action="store_true", dest="quiet",
help="be quiet")
if self.env is None:
loadenv = parser.add_mutually_exclusive_group()
loadenv.add_argument("-c", "--config", dest="config",
help="read environment from a YAML file")
loadenv.add_argument("-m", "--module", dest="module",
help="read environment from a Python module")
# Add subparsers.
subparsers = parser.add_subparsers(dest='command')
for command in CommandLineEnvironment.DefaultCommands.keys():
command_parser = subparsers.add_parser(command)
maker = getattr(self, 'make_%s_parser' % command, False)
if maker:
maker(command_parser)
@staticmethod
def make_build_parser(parser):
parser.add_argument(
'bundles', nargs='*', metavar='BUNDLE',
help='Optional bundle names to process. If none are '
'specified, then all known bundles will be built.')
parser.add_argument(
'--output', '-o', nargs=2, action='append',
metavar=('BUNDLE', 'FILE'),
help='Build the given bundle, and use a custom output '
'file. Can be given multiple times.')
parser.add_argument(
'--directory', '-d',
help='Write built files to this directory, using the '
'basename defined by the bundle. Will offset '
'the original bundle output paths on their common '
'prefix. Cannot be used with --output.')
parser.add_argument(
'--no-cache', action='store_true',
help='Do not use a cache that might be configured.')
parser.add_argument(
'--manifest',
help='Write a manifest to the given file. Also supports '
'the id:arg format, if you want to use a different '
'manifest implementation.')
parser.add_argument(
'--production', action='store_true',
help='Forcably turn off debug mode for the build. This '
'only has an effect if debug is set to "merge".')
def _setup_logging(self, ns):
if self.log:
log = self.log
else:
log = logging.getLogger('webassets.script')
if not log.handlers:
# In theory, this could run multiple times (e.g. tests)
handler = logging.StreamHandler()
log.addHandler(handler)
# Note that setting the level filter at the handler level is
# better than the logger level, since this is "our" handler,
# we create it, for the purposes of having a default output.
# The logger itself the user may be modifying.
handler.setLevel(logging.DEBUG if ns.verbose else (
logging.WARNING if ns.quiet else logging.INFO))
return log
def _setup_assets_env(self, ns, log):
env = self.env<|fim▁hole|> if ns.module:
env = PythonLoader(ns.module).load_environment()
if ns.config:
env = YAMLLoader(ns.config).load_environment()
return env
def _setup_cmd_env(self, assets_env, log, ns):
return CommandLineEnvironment(assets_env, log, commands={
'watch': (GenericArgparseImplementation.WatchCommand, (ns,), {})
})
def _prepare_command_args(self, ns):
# Prepare a dict of arguments cleaned of values that are not
# command-specific, and which the command method would not accept.
args = vars(ns).copy()
for action in self.parser._actions:
dest = action.dest
if dest in args:
del args[dest]
return args
def run_with_ns(self, ns):
log = self._setup_logging(ns)
env = self._setup_assets_env(ns, log)
if env is None:
raise CommandError(
"Error: No environment given or found. Maybe use -m?")
cmd = self._setup_cmd_env(env, log, ns)
# Run the selected command
args = self._prepare_command_args(ns)
return cmd.invoke(ns.command, args)
def run_with_argv(self, argv):
try:
ns = self.parser.parse_args(argv)
except SystemExit as e:
# We do not want the main() function to exit the program.
# See run() instead.
return e.args[0]
return self.run_with_ns(ns)
def main(self, argv):
"""Parse the given command line.
The commandline is expected to NOT including what would be sys.argv[0].
"""
try:
return self.run_with_argv(argv)
except CommandError as e:
print(e)
return 1
def main(argv, env=None):
"""Execute the generic version of the command line interface.
You only need to work directly with ``GenericArgparseImplementation`` if
you desire to customize things.
If no environment is given, additional arguments will be supported to allow
the user to specify/construct the environment on the command line.
"""
return GenericArgparseImplementation(env).main(argv)
def run():
"""Runs the command line interface via ``main``, then exits the process
with a proper return code."""
sys.exit(main(sys.argv[1:]) or 0)
if __name__ == '__main__':
run()<|fim▁end|> | if env is None:
assert not (ns.module and ns.config) |
<|file_name|>worker.py<|end_file_name|><|fim▁begin|># vim: expandtab sw=4 ts=4 sts=4:
#
# Copyright © 2003 - 2018 Michal Čihař <[email protected]>
#
# This file is part of python-gammu <https://wammu.eu/python-gammu/>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
"""
Asynchronous communication to phone.
Mostly you should use only L{GammuWorker} class, others are only helpers
which are used by this class.
"""
import queue
import threading
import gammu
class InvalidCommand(Exception):
"""
Exception indicating invalid command.
"""
def __init__(self, value):
"""
Initializes exception.
@param value: Name of wrong command.
@type value: string
"""
super().__init__()
self.value = value
def __str__(self):
"""
Returns textual representation of exception.
"""
return f'Invalid command: "{self.value}"'
def check_worker_command(command):
"""
Checks whether command is valid.
@param command: Name of command.
@type command: string
"""
if hasattr(gammu.StateMachine, command):
return
raise InvalidCommand(command)
class GammuCommand:
"""
Storage of single command for gammu.
"""
def __init__(self, command, params=None, percentage=100):
"""
Creates single command instance.
"""
check_worker_command(command)
self._command = command
self._params = params
self._percentage = percentage
def get_command(self):
"""
Returns command name.
"""
return self._command
def get_params(self):
"""
Returns command params.
"""
return self._params
def get_percentage(self):
"""
Returns percentage of current task.
"""
return self._percentage
def __str__(self):
"""
Returns textual representation.
"""
if self._params is not None:
return f"{self._command} {self._params}"
else:
return f"{self._command} ()"
class GammuTask:
"""
Storage of taks for gammu.
"""
def __init__(self, name, commands):
"""
Creates single command instance.
@param name: Name of task.
@type name: string
@param commands: List of commands to execute.
@type commands: list of tuples or strings
"""
self._name = name
self._list = []
self._pointer = 0
for i in range(len(commands)):
if isinstance(commands[i], tuple):
cmd = commands[i][0]
try:
params = commands[i][1]
except IndexError:
params = None
else:
cmd = commands[i]
params = None
percents = round(100 * (i + 1) / len(commands))
self._list.append(GammuCommand(cmd, params, percents))
def get_next(self):
"""
Returns next command to be executed as L{GammuCommand}.
"""
result = self._list[self._pointer]
self._pointer += 1
return result
def get_name(self):
"""
Returns task name.
"""
return self._name
def gammu_pull_device(state_machine):
state_machine.ReadDevice()
class GammuThread(threading.Thread):
"""
Thread for phone communication.
"""
def __init__(self, queue, config, callback, pull_func=gammu_pull_device):
"""
Initialises thread data.
@param queue: Queue with events.
@type queue: queue.Queue object.
@param config: Gammu configuration, same as
L{StateMachine.SetConfig} accepts.
@type config: hash
@param callback: Function which will be called upon operation
completing.
@type callback: Function, needs to accept four params: name of
completed operation, result of it, error code and percentage of
overall operation. This callback is called from different
thread, so please take care of various threading issues in other
modules you use.
"""
super().__init__()
self._kill = False
self._terminate = False
self._sm = gammu.StateMachine()
self._callback = callback
self._queue = queue
self._sm.SetConfig(0, config)
self._pull_func = pull_func
def _do_command(self, name, cmd, params, percentage=100):
"""
Executes single command on phone.
"""
func = getattr(self._sm, cmd)
error = "ERR_NONE"
result = None
try:
if params is None:
result = func()
elif isinstance(params, dict):
result = func(**params)
else:
result = func(*params)
except gammu.GSMError as info:
errcode = info.args[0]["Code"]
error = gammu.ErrorNumbers[errcode]
self._callback(name, result, error, percentage)
def run(self):
"""
Thread body, which handles phone communication. This should not
be used from outside.<|fim▁hole|> start = True
while not self._kill:
try:
if start:
task = GammuTask("Init", ["Init"])
start = False
else:
# Wait at most ten seconds for next command
task = self._queue.get(True, 10)
try:
while True:
cmd = task.get_next()
self._do_command(
task.get_name(),
cmd.get_command(),
cmd.get_params(),
cmd.get_percentage(),
)
except IndexError:
try:
if task.get_name() != "Init":
self._queue.task_done()
except (AttributeError, ValueError):
pass
except queue.Empty:
if self._terminate:
break
# Read the device to catch possible incoming events
try:
self._pull_func(self._sm)
except Exception as ex:
self._callback("ReadDevice", None, ex, 0)
def kill(self):
"""
Forces thread end without emptying queue.
"""
self._kill = True
def join(self, timeout=None):
"""
Terminates thread and waits for it.
"""
self._terminate = True
super().join(timeout)
class GammuWorker:
"""
Wrapper class for asynchronous communication with Gammu. It spaws
own thread and then passes all commands to this thread. When task is
done, caller is notified via callback.
"""
def __init__(self, callback, pull_func=gammu_pull_device):
"""
Initializes worker class.
@param callback: See L{GammuThread.__init__} for description.
"""
self._thread = None
self._callback = callback
self._config = {}
self._lock = threading.Lock()
self._queue = queue.Queue()
self._pull_func = pull_func
def enqueue_command(self, command, params):
"""
Enqueues command.
@param command: Command(s) to execute. Each command is tuple
containing function name and it's parameters.
@type command: tuple of list of tuples
@param params: Parameters to command.
@type params: tuple or string
"""
self._queue.put(GammuTask(command, [(command, params)]))
def enqueue_task(self, command, commands):
"""
Enqueues task.
@param command: Command(s) to execute. Each command is tuple
containing function name and it's parameters.
@type command: tuple of list of tuples
@param commands: List of commands to execute.
@type commands: list of tuples or strings
"""
self._queue.put(GammuTask(command, commands))
def enqueue(self, command, params=None, commands=None):
"""
Enqueues command or task.
@param command: Command(s) to execute. Each command is tuple
containing function name and it's parameters.
@type command: tuple of list of tuples
@param params: Parameters to command.
@type params: tuple or string
@param commands: List of commands to execute. When this is not
none, params are ignored and command is taken as task name.
@type commands: list of tuples or strings
"""
if commands is not None:
self.enqueue_task(command, commands)
else:
self.enqueue_command(command, params)
def configure(self, config):
"""
Configures gammu instance according to config.
@param config: Gammu configuration, same as
L{StateMachine.SetConfig} accepts.
@type config: hash
"""
self._config = config
def abort(self):
"""
Aborts any remaining operations.
"""
raise NotImplementedError
def initiate(self):
"""
Connects to phone.
"""
self._thread = GammuThread(
self._queue, self._config, self._callback, self._pull_func
)
self._thread.start()
def terminate(self, timeout=None):
"""
Terminates phone connection.
"""
self.enqueue("Terminate")
self._thread.join(timeout)
self._thread = None<|fim▁end|> | """ |
<|file_name|>filters.py<|end_file_name|><|fim▁begin|>from rest_framework.filters import (
FilterSet
)
from trialscompendium.trials.models import Treatment
class TreatmentListFilter(FilterSet):
"""
Filter query list from treatment database table
"""
class Meta:
model = Treatment
fields = {'id': ['exact', 'in'],
'no_replicate': ['exact', 'in', 'gte', 'lte'],
'nitrogen_treatment': ['iexact', 'in', 'icontains'],
'phosphate_treatment': ['iexact', 'in', 'icontains'],
'tillage_practice': ['iexact', 'in', 'icontains'],
'cropping_system': ['iexact', 'in', 'icontains'],<|fim▁hole|> 'crops_grown': ['iexact', 'in', 'icontains'],
'farm_yard_manure': ['iexact', 'in', 'icontains'],
'farm_residue': ['iexact', 'in', 'icontains'],
}
order_by = ['tillage_practice', 'cropping_system', 'crops_grown']<|fim▁end|> | |
<|file_name|>ore-sponge-versions.tester.js<|end_file_name|><|fim▁begin|>import joiModule from 'joi'
import { createServiceTester } from '../tester.js'
const Joi = joiModule.extend(joi => ({
base: joi.array(),
coerce: (value, helpers) => ({<|fim▁hole|> }),
type: 'versionArray',
}))
const isDottedVersionAtLeastOne = Joi.string().regex(/\d+(\.\d+)?(\.\d+)?$/)
export const t = await createServiceTester()
t.create('Nucleus (pluginId nucleus)')
.get('/nucleus.json')
.expectBadge({
label: 'sponge',
message: Joi.versionArray().items(isDottedVersionAtLeastOne),
})
t.create('Invalid Plugin (pluginId 1)').get('/1.json').expectBadge({
label: 'sponge',
message: 'not found',
})<|fim▁end|> | value: value.split ? value.split(' | ') : value, |
<|file_name|>20190711074029-streaks-and-reached_goals.ts<|end_file_name|><|fim▁begin|>export const up = async function(db: any): Promise<any> {
return db.runSql(
`
CREATE TABLE streaks (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
client_id CHAR(36) NOT NULL,
locale_id INT NOT NULL,
started_at DATETIME,
last_activity_at DATETIME,
FOREIGN KEY (client_id) REFERENCES user_clients (client_id) ON DELETE CASCADE,
FOREIGN KEY (locale_id) REFERENCES locales (id) ON DELETE CASCADE,
UNIQUE KEY (client_id, locale_id)
);
CREATE TABLE reached_goals (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
type ENUM('streak', 'clips', 'votes') NOT NULL,
count SMALLINT UNSIGNED NOT NULL,
client_id CHAR(36) NOT NULL,
locale_id INT NOT NULL,
reached_at DATETIME NOT NULL,
FOREIGN KEY (client_id) REFERENCES user_clients (client_id),
FOREIGN KEY (locale_id) REFERENCES locales (id),
UNIQUE(count, type, client_id, locale_id)
);
`
);
};
export const down = function(): Promise<any> {<|fim▁hole|> return null;
};<|fim▁end|> | |
<|file_name|>ItFlys.java<|end_file_name|><|fim▁begin|><|fim▁hole|> */
public class ItFlys implements Flys {
@Override
public String fly() {
return "Flying high!";
}
}<|fim▁end|> | package com.fifino.patterns.strategy;
/**
* Created by porfiriopartida on 2/13/16. |
<|file_name|>gulpfile.js<|end_file_name|><|fim▁begin|>var gulp = require('gulp'),
jshint = require('gulp-jshint'),
mocha = require('gulp-mocha'),
cover = require('gulp-coverage'),
jscs = require('gulp-jscs');
gulp.task('default', ['jscs', 'lint', 'test'], function () {
});
gulp.task('lint', function () {
return gulp.src(['./lib/*.js', './test/*.js'])
.pipe(jshint())
.pipe(jshint.reporter('default', {verbose: true}));
});
gulp.task('test', ['jscs', 'lint'], function () {
return gulp.src('./test', {read: false})
.pipe(cover.instrument({
pattern: ['*lib/*.js'],<|fim▁hole|> .pipe(cover.format())
.pipe(gulp.dest('reports'));
});
gulp.task('jscs', function () {
return gulp.src(['./lib/*.js', './test/*.js'])
.pipe(jscs());
});<|fim▁end|> | debugDirectory: 'debug'
}))
.pipe(mocha({reporter: 'nyan'}))
.pipe(cover.gather()) |
<|file_name|>test_microbench_uorb.cpp<|end_file_name|><|fim▁begin|>/****************************************************************************
*
* Copyright (C) 2018-2019 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* 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 OWNER 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.
*
****************************************************************************/
/**
* @file test_microbench_uorb.cpp
* Tests for microbench uORB functionality.
*/
#include <unit_test.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <drivers/drv_hrt.h>
#include <perf/perf_counter.h>
#include <px4_platform_common/px4_config.h>
#include <px4_platform_common/micro_hal.h>
#include <uORB/Subscription.hpp>
#include <uORB/topics/sensor_accel.h>
#include <uORB/topics/sensor_gyro.h>
#include <uORB/topics/sensor_gyro_fifo.h>
#include <uORB/topics/vehicle_local_position.h>
#include <uORB/topics/vehicle_status.h>
namespace MicroBenchORB
{
#ifdef __PX4_NUTTX
#include <nuttx/irq.h>
static irqstate_t flags;
#endif
void lock()
{
#ifdef __PX4_NUTTX
flags = px4_enter_critical_section();
#endif
}
void unlock()
{
#ifdef __PX4_NUTTX
px4_leave_critical_section(flags);
#endif
}
#define PERF(name, op, count) do { \
px4_usleep(1000); \
reset(); \
perf_counter_t p = perf_alloc(PC_ELAPSED, name); \
for (int i = 0; i < count; i++) { \
px4_usleep(1); \
lock(); \
perf_begin(p); \
op; \
perf_end(p); \
unlock(); \
reset(); \
} \
perf_print_counter(p); \
perf_free(p); \
} while (0)
class MicroBenchORB : public UnitTest
{
public:
virtual bool run_tests();
private:
bool time_px4_uorb();
bool time_px4_uorb_direct();
void reset();
vehicle_status_s status;
vehicle_local_position_s lpos;
sensor_gyro_s gyro;
sensor_gyro_fifo_s gyro_fifo;
};
bool MicroBenchORB::run_tests()
{
ut_run_test(time_px4_uorb);
ut_run_test(time_px4_uorb_direct);
return (_tests_failed == 0);
}
template<typename T>
T random(T min, T max)
{
const T scale = rand() / (T) RAND_MAX; /* [0, 1.0] */
return min + scale * (max - min); /* [min, max] */
}
void MicroBenchORB::reset()
{
srand(time(nullptr));
// initialize with random data
status.timestamp = rand();
status.mission_failure = rand();
lpos.timestamp = rand();
lpos.dist_bottom_valid = rand();
gyro.timestamp = rand();
gyro_fifo.timestamp = rand();
}
ut_declare_test_c(test_microbench_uorb, MicroBenchORB)
bool MicroBenchORB::time_px4_uorb()
{
int fd_status = orb_subscribe(ORB_ID(vehicle_status));
int fd_lpos = orb_subscribe(ORB_ID(vehicle_local_position));
int fd_gyro = orb_subscribe(ORB_ID(sensor_gyro));
int fd_gyro_fifo = orb_subscribe(ORB_ID(sensor_gyro_fifo));
int ret = 0;
bool updated = false;
uint64_t time = 0;
PERF("orb_check vehicle_status", ret = orb_check(fd_status, &updated), 100);
PERF("orb_copy vehicle_status", ret = orb_copy(ORB_ID(vehicle_status), fd_status, &status), 100);
printf("\n");
PERF("orb_check vehicle_local_position", ret = orb_check(fd_lpos, &updated), 100);
PERF("orb_copy vehicle_local_position", ret = orb_copy(ORB_ID(vehicle_local_position), fd_lpos, &lpos), 100);
printf("\n");
PERF("orb_check sensor_gyro", ret = orb_check(fd_gyro, &updated), 100);
PERF("orb_copy sensor_gyro", ret = orb_copy(ORB_ID(sensor_gyro), fd_gyro, &gyro), 100);
printf("\n");
PERF("orb_check sensor_gyro_fifo", ret = orb_check(fd_gyro_fifo, &updated), 100);
PERF("orb_copy sensor_gyro_fifo", ret = orb_copy(ORB_ID(sensor_gyro_fifo), fd_gyro_fifo, &gyro_fifo), 100);
printf("\n");
PERF("orb_exists sensor_accel 0", ret = orb_exists(ORB_ID(sensor_accel), 0), 100);
PERF("orb_exists sensor_accel 1", ret = orb_exists(ORB_ID(sensor_accel), 1), 100);
PERF("orb_exists sensor_accel 2", ret = orb_exists(ORB_ID(sensor_accel), 2), 100);
PERF("orb_exists sensor_accel 3", ret = orb_exists(ORB_ID(sensor_accel), 3), 100);
PERF("orb_exists sensor_accel 4", ret = orb_exists(ORB_ID(sensor_accel), 4), 100);
PERF("orb_exists sensor_accel 5", ret = orb_exists(ORB_ID(sensor_accel), 5), 100);
PERF("orb_exists sensor_accel 6", ret = orb_exists(ORB_ID(sensor_accel), 6), 100);
PERF("orb_exists sensor_accel 7", ret = orb_exists(ORB_ID(sensor_accel), 7), 100);
PERF("orb_exists sensor_accel 8", ret = orb_exists(ORB_ID(sensor_accel), 8), 100);
PERF("orb_exists sensor_accel 9", ret = orb_exists(ORB_ID(sensor_accel), 9), 100);
PERF("orb_exists sensor_accel 10", ret = orb_exists(ORB_ID(sensor_accel), 10), 100);
orb_unsubscribe(fd_status);
orb_unsubscribe(fd_lpos);
orb_unsubscribe(fd_gyro);
orb_unsubscribe(fd_gyro_fifo);
return true;
}
bool MicroBenchORB::time_px4_uorb_direct()
{
bool ret = false;
bool updated = false;
uint64_t time = 0;
uORB::Subscription vstatus{ORB_ID(vehicle_status)};<|fim▁hole|> PERF("uORB::Subscription orb_copy vehicle_status", ret = vstatus.copy(&status), 100);
printf("\n");
uORB::Subscription local_pos{ORB_ID(vehicle_local_position)};
PERF("uORB::Subscription orb_check vehicle_local_position", ret = local_pos.updated(), 100);
PERF("uORB::Subscription orb_copy vehicle_local_position", ret = local_pos.copy(&lpos), 100);
{
printf("\n");
uORB::Subscription sens_gyro0{ORB_ID(sensor_gyro), 0};
PERF("uORB::Subscription orb_check sensor_gyro:0", ret = sens_gyro0.updated(), 100);
PERF("uORB::Subscription orb_copy sensor_gyro:0", ret = sens_gyro0.copy(&gyro), 100);
}
{
printf("\n");
uORB::Subscription sens_gyro1{ORB_ID(sensor_gyro), 1};
PERF("uORB::Subscription orb_check sensor_gyro:1", ret = sens_gyro1.updated(), 100);
PERF("uORB::Subscription orb_copy sensor_gyro:1", ret = sens_gyro1.copy(&gyro), 100);
}
{
printf("\n");
uORB::Subscription sens_gyro2{ORB_ID(sensor_gyro), 2};
PERF("uORB::Subscription orb_check sensor_gyro:2", ret = sens_gyro2.updated(), 100);
PERF("uORB::Subscription orb_copy sensor_gyro:2", ret = sens_gyro2.copy(&gyro), 100);
}
{
printf("\n");
uORB::Subscription sens_gyro3{ORB_ID(sensor_gyro), 3};
PERF("uORB::Subscription orb_check sensor_gyro:3", ret = sens_gyro3.updated(), 100);
PERF("uORB::Subscription orb_copy sensor_gyro:3", ret = sens_gyro3.copy(&gyro), 100);
}
{
printf("\n");
uORB::Subscription sens_gyro_fifo0{ORB_ID(sensor_gyro_fifo), 0};
PERF("uORB::Subscription orb_check sensor_gyro_fifo:0", ret = sens_gyro_fifo0.updated(), 100);
PERF("uORB::Subscription orb_copy sensor_gyro_fifo:0", ret = sens_gyro_fifo0.copy(&gyro_fifo), 100);
}
return true;
}
} // namespace MicroBenchORB<|fim▁end|> | PERF("uORB::Subscription orb_check vehicle_status", ret = vstatus.updated(), 100); |
<|file_name|>test_blogpost.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
import os.path
import pytest
import abclinuxuapi
from abclinuxuapi import shared
@pytest.fixture
def bp_url():
return "http://www.abclinuxu.cz/blog/bystroushaak/2015/2/bolest-proxy"
@pytest.fixture
def do_that_fucking_monkey_patch(monkeypatch):
def mock_download(*args, **kwargs):
fn = os.path.join(os.path.dirname(__file__), "mock_data/blogpost.html")
with open(fn) as f:
return f.read()
monkeypatch.setattr(abclinuxuapi.blogpost, "download", mock_download)
def setup_module(do_that_fucking_monkey_patch):
"""
It is not possiblel to import monkeypatch from pytest. You have to use it
as fixture.<|fim▁hole|>
BPOST = abclinuxuapi.Blogpost(bp_url(), lazy=False)
@pytest.fixture
def bpost():
"""
This may seem a little bit crazy, but this speeds up the testing 6x.
I don't need new object for each test.
"""
return BPOST
def test_constructor(bp_url):
bp = abclinuxuapi.Blogpost(bp_url)
assert bp.url == bp_url
assert bp.uid is None
assert bp.title is None
assert bp.intro is None
assert bp.text is None
assert bp.rating is None
assert bp.comments == []
assert bp.comments_n == -1
assert bp.created_ts is None
assert bp.last_modified_ts is None
assert bp.object_ts > 0
def test_constructor_multi_params(bp_url):
bp = abclinuxuapi.Blogpost(
url=bp_url,
uid="uid",
title="title",
intro="intro",
text="text",
rating="rating",
comments="comments",
comments_n="comments_n",
created_ts="created_ts",
last_modified_ts="last_modified_ts",
object_ts="object_ts"
)
assert bp.url == bp_url
assert bp.uid == "uid"
assert bp.title == "title"
assert bp.intro == "intro"
assert bp.text == "text"
assert bp.rating == "rating"
assert bp.comments == "comments"
assert bp.comments_n == "comments_n"
assert bp.created_ts == "created_ts"
assert bp.last_modified_ts == "last_modified_ts"
assert bp.object_ts == "object_ts"
def test_constructor_wrong_params(bp_url):
with pytest.raises(TypeError):
bp = abclinuxuapi.Blogpost(bp_url, azgabash=True)
def test_get_title(bpost):
assert bpost.title == "Bolest proxy"
def test_get_text(bpost):
assert bpost.text.startswith("<h2>Bolest proxy</h2>")
assert "Written in CherryTree" in bpost.text
assert "bystrousak:" in bpost.text
def test_Tag():
tag = abclinuxuapi.Tag("hello", norm="_hello_")
assert tag == "hello"
assert tag.norm == "_hello_"
assert tag.url.startswith("http")
def test_tags(bpost):
assert bpost.tags
assert "proxy" in bpost.tags
# try to add and remove tag
new_tag = abclinuxuapi.Tag("nábytek", "nabytek")
bpost.remove_tag(new_tag, throw=False)
assert new_tag not in bpost.tags
bpost.add_tag(new_tag)
assert new_tag in bpost.tags
bpost.remove_tag(new_tag, throw=False)
def test_get_uid(bpost):
assert bpost.uid == 400957
def test_get_rating(bpost):
assert bpost.rating
assert bpost.rating.rating == 100
assert bpost.rating.base == 15
def test_meta_parsing(bpost):
assert bpost.has_tux
assert bpost.created_ts == 1423587660.0
assert bpost.last_modified_ts >= 1423591140.0
assert bpost.readed >= 1451
def test_get_image_urls(bpost):
assert bpost.get_image_urls()
assert bpost.get_image_urls()[0] == (
"https://www.abclinuxu.cz/images/screenshots/0/9/"
"210590-bolest-proxy-6017333664768008869.png"
)
def test_different_date_parsing():
abclinuxuapi.Blogpost(
"http://abclinuxu.cz/clanky/yubikey.-co-to-je-a-co-to-umi-1",
lazy=False
)
abclinuxuapi.Blogpost(
"http://abclinuxu.cz/clanky/bezpecnost/ssl-je-vase-bezpecne-pripojeni-opravdu-zabezpecene",
lazy=False
)
abclinuxuapi.Blogpost(
"http://abclinuxu.cz/blog/jarasa/2016/10/i-pejsek-musi-jist-kvalitne",
lazy=False
)
abclinuxuapi.Blogpost(
"http://abclinuxu.cz/blog/msk/2016/8/hlada-sa-linux-embedded-vyvojar",
lazy=False
)
blog = abclinuxuapi.Blogpost(
"http://abclinuxu.cz/blog/Strider_BSD_koutek/2006/8/objevil-jsem-ameriku",
lazy=False
)
assert len(blog.comments) == 0
blog = abclinuxuapi.Blogpost(
"http://www.abclinuxu.cz/blog/tucnak_viktor/2005/1/zdravim-nahodne-navstevniky",
lazy=False
)
blog = abclinuxuapi.Blogpost(
"https://www.abclinuxu.cz/blog/luv/2016/4/mockgeofix-mock-geolokace-kompatibilni-s-android-emulatorem",
lazy=False
)
assert len(blog.comments) == 0<|fim▁end|> | """ |
<|file_name|>GameObject.cpp<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "Common.h"
#include "QuestDef.h"
#include "GameObject.h"
#include "ObjectMgr.h"
#include "PoolMgr.h"
#include "SpellMgr.h"
#include "Spell.h"
#include "UpdateMask.h"
#include "Opcodes.h"
#include "WorldPacket.h"
#include "World.h"
#include "DatabaseEnv.h"
#include "LootMgr.h"
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "CellImpl.h"
#include "InstanceScript.h"
#include "Battleground.h"
#include "Util.h"
#include "OutdoorPvPMgr.h"
#include "BattlegroundAV.h"
#include "ScriptMgr.h"
GameObject::GameObject() : WorldObject(), m_goValue(new GameObjectValue)
{
m_objectType |= TYPEMASK_GAMEOBJECT;
m_objectTypeId = TYPEID_GAMEOBJECT;
m_updateFlag = (UPDATEFLAG_HAS_POSITION | UPDATEFLAG_POSITION | UPDATEFLAG_ROTATION);
m_valuesCount = GAMEOBJECT_END;
m_respawnTime = 0;
m_respawnDelayTime = 300;
m_lootState = GO_NOT_READY;
m_spawnedByDefault = true;
m_usetimes = 0;
m_spellId = 0;
m_cooldownTime = 0;
m_goInfo = NULL;
m_ritualOwner = NULL;
m_goData = NULL;
m_DBTableGuid = 0;
m_rotation = 0;
m_groupLootTimer = 0;
lootingGroupLowGUID = 0;
ResetLootMode(); // restore default loot mode
}
GameObject::~GameObject()
{
delete m_goValue;
//if (m_uint32Values) // field array can be not exist if GameOBject not loaded
// CleanupsBeforeDelete();
}
void GameObject::CleanupsBeforeDelete(bool /*finalCleanup*/)
{
if (IsInWorld())
RemoveFromWorld();
if (m_uint32Values) // field array can be not exist if GameOBject not loaded
{
// Possible crash at access to deleted GO in Unit::m_gameobj
if (uint64 owner_guid = GetOwnerGUID())
{
Unit* owner = ObjectAccessor::GetUnit(*this,owner_guid);
if (owner)
owner->RemoveGameObject(this,false);
else
{
const char * ownerType = "creature";
if (IS_PLAYER_GUID(owner_guid))
ownerType = "player";
else if (IS_PET_GUID(owner_guid))
ownerType = "pet";
sLog.outError("Delete GameObject (GUID: %u Entry: %u SpellId %u LinkedGO %u) that lost references to owner (GUID %u Type '%s') GO list. Crash possible later.",
GetGUIDLow(), GetGOInfo()->id, m_spellId, GetGOInfo()->GetLinkedGameObjectEntry(), GUID_LOPART(owner_guid), ownerType);
}
}
}
}
void GameObject::AddToWorld()
{
///- Register the gameobject for guid lookup
if (!IsInWorld())
{
if (m_zoneScript)
m_zoneScript->OnGameObjectCreate(this, true);
sObjectAccessor.AddObject(this);
WorldObject::AddToWorld();
}
}
void GameObject::RemoveFromWorld()
{
///- Remove the gameobject from the accessor<|fim▁hole|>
// Possible crash at access to deleted GO in Unit::m_gameobj
if (uint64 owner_guid = GetOwnerGUID())
{
if (Unit * owner = GetOwner())
owner->RemoveGameObject(this,false);
else
sLog.outError("Delete GameObject (GUID: %u Entry: %u) that have references in not found creature %u GO list. Crash possible later.",GetGUIDLow(),GetGOInfo()->id,GUID_LOPART(owner_guid));
}
WorldObject::RemoveFromWorld();
sObjectAccessor.RemoveObject(this);
}
}
bool GameObject::Create(uint32 guidlow, uint32 name_id, Map *map, uint32 phaseMask, float x, float y, float z, float ang, float rotation0, float rotation1, float rotation2, float rotation3, uint32 animprogress, GOState go_state, uint32 artKit)
{
ASSERT(map);
SetMap(map);
Relocate(x,y,z,ang);
if (!IsPositionValid())
{
sLog.outError("Gameobject (GUID: %u Entry: %u) not created. Suggested coordinates isn't valid (X: %f Y: %f)",guidlow,name_id,x,y);
return false;
}
SetPhaseMask(phaseMask,false);
SetZoneScript();
if (m_zoneScript)
{
name_id = m_zoneScript->GetGameObjectEntry(guidlow, name_id);
if (!name_id)
return false;
}
GameObjectInfo const* goinfo = sObjectMgr.GetGameObjectInfo(name_id);
if (!goinfo)
{
sLog.outErrorDb("Gameobject (GUID: %u Entry: %u) not created: it have not exist entry in `gameobject_template`. Map: %u (X: %f Y: %f Z: %f) ang: %f rotation0: %f rotation1: %f rotation2: %f rotation3: %f",guidlow, name_id, map->GetId(), x, y, z, ang, rotation0, rotation1, rotation2, rotation3);
return false;
}
Object::_Create(guidlow, goinfo->id, HIGHGUID_GAMEOBJECT);
m_goInfo = goinfo;
if (goinfo->type >= MAX_GAMEOBJECT_TYPE)
{
sLog.outErrorDb("Gameobject (GUID: %u Entry: %u) not created: it have not exist GO type '%u' in `gameobject_template`. It's will crash client if created.",guidlow,name_id,goinfo->type);
return false;
}
SetFloatValue(GAMEOBJECT_PARENTROTATION+0, rotation0);
SetFloatValue(GAMEOBJECT_PARENTROTATION+1, rotation1);
UpdateRotationFields(rotation2,rotation3); // GAMEOBJECT_FACING, GAMEOBJECT_ROTATION, GAMEOBJECT_PARENTROTATION+2/3
SetFloatValue(OBJECT_FIELD_SCALE_X, goinfo->size);
SetUInt32Value(GAMEOBJECT_FACTION, goinfo->faction);
SetUInt32Value(GAMEOBJECT_FLAGS, goinfo->flags);
SetEntry(goinfo->id);
SetUInt32Value(GAMEOBJECT_DISPLAYID, goinfo->displayId);
// GAMEOBJECT_BYTES_1, index at 0, 1, 2 and 3
SetGoState(go_state);
SetGoType(GameobjectTypes(goinfo->type));
SetGoArtKit(0); // unknown what this is
SetByteValue(GAMEOBJECT_BYTES_1, 2, artKit);
switch(goinfo->type)
{
case GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING:
m_goValue->building.health = goinfo->building.intactNumHits + goinfo->building.damagedNumHits;
SetGoAnimProgress(255);
break;
case GAMEOBJECT_TYPE_TRANSPORT:
SetUInt32Value(GAMEOBJECT_LEVEL, goinfo->transport.pause);
if (goinfo->transport.startOpen)
SetGoState(GO_STATE_ACTIVE);
SetGoAnimProgress(animprogress);
break;
case GAMEOBJECT_TYPE_FISHINGNODE:
SetGoAnimProgress(0);
break;
default:
SetGoAnimProgress(animprogress);
break;
}
LastUsedScriptID = GetGOInfo()->ScriptId;
return true;
}
void GameObject::Update(uint32 diff)
{
if (IS_MO_TRANSPORT(GetGUID()))
{
//((Transport*)this)->Update(p_time);
return;
}
switch (m_lootState)
{
case GO_NOT_READY:
{
switch(GetGoType())
{
case GAMEOBJECT_TYPE_TRAP:
{
// Arming Time for GAMEOBJECT_TYPE_TRAP (6)
GameObjectInfo const* goInfo = GetGOInfo();
// Bombs
if (goInfo->trap.charges == 2)
m_cooldownTime = time(NULL) + 10; // Hardcoded tooltip value
else if (Unit* owner = GetOwner())
{
if (owner->isInCombat())
m_cooldownTime = time(NULL) + goInfo->trap.startDelay;
}
m_lootState = GO_READY;
break;
}
case GAMEOBJECT_TYPE_FISHINGNODE:
{
// fishing code (bobber ready)
if (time(NULL) > m_respawnTime - FISHING_BOBBER_READY_TIME)
{
// splash bobber (bobber ready now)
Unit* caster = GetOwner();
if (caster && caster->GetTypeId() == TYPEID_PLAYER)
{
SetGoState(GO_STATE_ACTIVE);
SetUInt32Value(GAMEOBJECT_FLAGS, GO_FLAG_NODESPAWN);
UpdateData udata;
udata.m_map = uint16(GetMapId());
WorldPacket packet;
BuildValuesUpdateBlockForPlayer(&udata,caster->ToPlayer());
udata.BuildPacket(&packet);
caster->ToPlayer()->GetSession()->SendPacket(&packet);
SendCustomAnim();
}
m_lootState = GO_READY; // can be successfully open with some chance
}
return;
}
default:
m_lootState = GO_READY; // for other GOis same switched without delay to GO_READY
break;
}
// NO BREAK for switch (m_lootState)
}
case GO_READY:
{
if (m_respawnTime > 0) // timer on
{
if (m_respawnTime <= time(NULL)) // timer expired
{
m_respawnTime = 0;
m_SkillupList.clear();
m_usetimes = 0;
switch (GetGoType())
{
case GAMEOBJECT_TYPE_FISHINGNODE: // can't fish now
{
Unit* caster = GetOwner();
if (caster && caster->GetTypeId() == TYPEID_PLAYER)
{
caster->FinishSpell(CURRENT_CHANNELED_SPELL);
WorldPacket data(SMSG_FISH_ESCAPED,0);
caster->ToPlayer()->GetSession()->SendPacket(&data);
}
// can be delete
m_lootState = GO_JUST_DEACTIVATED;
return;
}
case GAMEOBJECT_TYPE_DOOR:
case GAMEOBJECT_TYPE_BUTTON:
//we need to open doors if they are closed (add there another condition if this code breaks some usage, but it need to be here for battlegrounds)
if (GetGoState() != GO_STATE_READY)
ResetDoorOrButton();
//flags in AB are type_button and we need to add them here so no break!
default:
if (!m_spawnedByDefault) // despawn timer
{
// can be despawned or destroyed
SetLootState(GO_JUST_DEACTIVATED);
return;
}
// respawn timer
uint32 poolid = GetDBTableGUIDLow() ? sPoolMgr.IsPartOfAPool<GameObject>(GetDBTableGUIDLow()) : 0;
if (poolid)
sPoolMgr.UpdatePool<GameObject>(poolid, GetDBTableGUIDLow());
else
GetMap()->Add(this);
break;
}
}
}
if (isSpawned())
{
// traps can have time and can not have
GameObjectInfo const* goInfo = GetGOInfo();
if (goInfo->type == GAMEOBJECT_TYPE_TRAP)
{
if (m_cooldownTime >= time(NULL))
return;
// Type 2 - Bomb (will go away after casting it's spell)
if (goInfo->trap.charges == 2)
{
if (goInfo->trap.spellId)
CastSpell(NULL, goInfo->trap.spellId); // FIXME: null target won't work for target type 1
SetLootState(GO_JUST_DEACTIVATED);
break;
}
// Type 0 and 1 - trap (type 0 will not get removed after casting a spell)
Unit* owner = GetOwner();
Unit* ok = NULL; // pointer to appropriate target if found any
bool IsBattlegroundTrap = false;
//FIXME: this is activation radius (in different casting radius that must be selected from spell data)
//TODO: move activated state code (cast itself) to GO_ACTIVATED, in this place only check activating and set state
float radius = (float)(goInfo->trap.radius)/2; // TODO rename radius to diameter (goInfo->trap.radius) should be (goInfo->trap.diameter)
if (!radius)
{
if (goInfo->trap.cooldown != 3) // cast in other case (at some triggering/linked go/etc explicit call)
return;
else
{
if (m_respawnTime > 0)
break;
radius = (float)goInfo->trap.cooldown; // battlegrounds gameobjects has data2 == 0 && data5 == 3
IsBattlegroundTrap = true;
if (!radius)
return;
}
}
// Note: this hack with search required until GO casting not implemented
// search unfriendly creature
if (owner) // hunter trap
{
Trinity::AnyUnfriendlyNoTotemUnitInObjectRangeCheck checker(this, owner, radius);
Trinity::UnitSearcher<Trinity::AnyUnfriendlyNoTotemUnitInObjectRangeCheck> searcher(this, ok, checker);
VisitNearbyGridObject(radius, searcher);
if (!ok) VisitNearbyWorldObject(radius, searcher);
}
else // environmental trap
{
// environmental damage spells already have around enemies targeting but this not help in case not existed GO casting support
// affect only players
Player* player = NULL;
Trinity::AnyPlayerInObjectRangeCheck checker(this, radius);
Trinity::PlayerSearcher<Trinity::AnyPlayerInObjectRangeCheck> searcher(this, player, checker);
VisitNearbyWorldObject(radius, searcher);
ok = player;
}
if (ok)
{
// some traps do not have spell but should be triggered
if (goInfo->trap.spellId)
CastSpell(ok, goInfo->trap.spellId);
m_cooldownTime = time(NULL) + 4; // 4 seconds
if (owner) // || goInfo->trap.charges == 1)
SetLootState(GO_JUST_DEACTIVATED);
if (IsBattlegroundTrap && ok->GetTypeId() == TYPEID_PLAYER)
{
//Battleground gameobjects case
if (ok->ToPlayer()->InBattleground())
if (Battleground *bg = ok->ToPlayer()->GetBattleground())
bg->HandleTriggerBuff(GetGUID());
}
}
}
else if (uint32 max_charges = goInfo->GetCharges())
{
if (m_usetimes >= max_charges)
{
m_usetimes = 0;
SetLootState(GO_JUST_DEACTIVATED); // can be despawned or destroyed
}
}
}
break;
}
case GO_ACTIVATED:
{
switch(GetGoType())
{
case GAMEOBJECT_TYPE_DOOR:
case GAMEOBJECT_TYPE_BUTTON:
if (GetGOInfo()->GetAutoCloseTime() && (m_cooldownTime < time(NULL)))
ResetDoorOrButton();
break;
case GAMEOBJECT_TYPE_GOOBER:
if (m_cooldownTime < time(NULL))
{
RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE);
SetLootState(GO_JUST_DEACTIVATED);
m_cooldownTime = 0;
}
break;
case GAMEOBJECT_TYPE_CHEST:
if (m_groupLootTimer)
{
if (m_groupLootTimer <= diff)
{
Group* group = sObjectMgr.GetGroupByGUID(lootingGroupLowGUID);
if (group)
group->EndRoll(&loot);
m_groupLootTimer = 0;
lootingGroupLowGUID = 0;
}
else m_groupLootTimer -= diff;
}
default:
break;
}
break;
}
case GO_JUST_DEACTIVATED:
{
//if Gameobject should cast spell, then this, but some GOs (type = 10) should be destroyed
if (GetGoType() == GAMEOBJECT_TYPE_GOOBER)
{
uint32 spellId = GetGOInfo()->goober.spellId;
if (spellId)
{
std::set<uint32>::const_iterator it = m_unique_users.begin();
std::set<uint32>::const_iterator end = m_unique_users.end();
for (; it != end; ++it)
{
if (Unit* owner = Unit::GetUnit(*this, uint64(*it)))
owner->CastSpell(owner, spellId, false);
}
m_unique_users.clear();
m_usetimes = 0;
}
SetGoState(GO_STATE_READY);
//any return here in case battleground traps
}
if (GetOwnerGUID())
{
if (Unit* owner = GetOwner())
{
owner->RemoveGameObject(this, false);
SetRespawnTime(0);
Delete();
}
return;
}
//burning flags in some battlegrounds, if you find better condition, just add it
if (GetGOInfo()->IsDespawnAtAction() || GetGoAnimProgress() > 0)
{
SendObjectDeSpawnAnim(GetGUID());
//reset flags
SetUInt32Value(GAMEOBJECT_FLAGS, GetGOInfo()->flags);
}
loot.clear();
SetLootState(GO_READY);
if (!m_respawnDelayTime)
return;
if (!m_spawnedByDefault)
{
m_respawnTime = 0;
UpdateObjectVisibility();
return;
}
m_respawnTime = time(NULL) + m_respawnDelayTime;
// if option not set then object will be saved at grid unload
if (sWorld.getBoolConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATELY))
SaveRespawnTime();
UpdateObjectVisibility();
break;
}
}
sScriptMgr.OnGameObjectUpdate(this, diff);
}
void GameObject::Refresh()
{
// not refresh despawned not casted GO (despawned casted GO destroyed in all cases anyway)
if (m_respawnTime > 0 && m_spawnedByDefault)
return;
if (isSpawned())
GetMap()->Add(this);
}
void GameObject::AddUniqueUse(Player* player)
{
AddUse();
m_unique_users.insert(player->GetGUIDLow());
}
void GameObject::Delete()
{
SetLootState(GO_NOT_READY);
if (GetOwnerGUID())
if (Unit * owner = GetOwner())
owner->RemoveGameObject(this, false);
ASSERT (!GetOwnerGUID());
SendObjectDeSpawnAnim(GetGUID());
SetGoState(GO_STATE_READY);
SetUInt32Value(GAMEOBJECT_FLAGS, GetGOInfo()->flags);
uint32 poolid = GetDBTableGUIDLow() ? sPoolMgr.IsPartOfAPool<GameObject>(GetDBTableGUIDLow()) : 0;
if (poolid)
sPoolMgr.UpdatePool<GameObject>(poolid, GetDBTableGUIDLow());
else
AddObjectToRemoveList();
}
void GameObject::getFishLoot(Loot *fishloot, Player* loot_owner)
{
fishloot->clear();
uint32 zone, subzone;
GetZoneAndAreaId(zone,subzone);
// if subzone loot exist use it
if (!fishloot->FillLoot(subzone, LootTemplates_Fishing, loot_owner, true, true))
// else use zone loot (must exist in like case)
fishloot->FillLoot(zone, LootTemplates_Fishing, loot_owner,true);
}
void GameObject::SaveToDB()
{
// this should only be used when the gameobject has already been loaded
// preferably after adding to map, because mapid may not be valid otherwise
GameObjectData const *data = sObjectMgr.GetGOData(m_DBTableGuid);
if (!data)
{
sLog.outError("GameObject::SaveToDB failed, cannot get gameobject data!");
return;
}
SaveToDB(GetMapId(), data->spawnMask, data->phaseMask);
}
void GameObject::SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask)
{
const GameObjectInfo *goI = GetGOInfo();
if (!goI)
return;
if (!m_DBTableGuid)
m_DBTableGuid = GetGUIDLow();
// update in loaded data (changing data only in this place)
GameObjectData& data = sObjectMgr.NewGOData(m_DBTableGuid);
// data->guid = guid don't must be update at save
data.id = GetEntry();
data.mapid = mapid;
data.phaseMask = phaseMask;
data.posX = GetPositionX();
data.posY = GetPositionY();
data.posZ = GetPositionZ();
data.orientation = GetOrientation();
data.rotation0 = GetFloatValue(GAMEOBJECT_PARENTROTATION+0);
data.rotation1 = GetFloatValue(GAMEOBJECT_PARENTROTATION+1);
data.rotation2 = GetFloatValue(GAMEOBJECT_PARENTROTATION+2);
data.rotation3 = GetFloatValue(GAMEOBJECT_PARENTROTATION+3);
data.spawntimesecs = m_spawnedByDefault ? m_respawnDelayTime : -(int32)m_respawnDelayTime;
data.animprogress = GetGoAnimProgress();
data.go_state = GetGoState();
data.spawnMask = spawnMask;
data.artKit = GetGoArtKit();
// updated in DB
std::ostringstream ss;
ss << "INSERT INTO gameobject VALUES ("
<< m_DBTableGuid << ", "
<< GetEntry() << ", "
<< mapid << ", "
<< uint32(spawnMask) << "," // cast to prevent save as symbol
<< uint16(GetPhaseMask()) << "," // prevent out of range error
<< GetPositionX() << ", "
<< GetPositionY() << ", "
<< GetPositionZ() << ", "
<< GetOrientation() << ", "
<< GetFloatValue(GAMEOBJECT_PARENTROTATION) << ", "
<< GetFloatValue(GAMEOBJECT_PARENTROTATION+1) << ", "
<< GetFloatValue(GAMEOBJECT_PARENTROTATION+2) << ", "
<< GetFloatValue(GAMEOBJECT_PARENTROTATION+3) << ", "
<< m_respawnDelayTime << ", "
<< uint32(GetGoAnimProgress()) << ", "
<< uint32(GetGoState()) << ")";
SQLTransaction trans = WorldDatabase.BeginTransaction();
trans->PAppend("DELETE FROM gameobject WHERE guid = '%u'", m_DBTableGuid);
trans->Append(ss.str().c_str());
WorldDatabase.CommitTransaction(trans);
}
bool GameObject::LoadFromDB(uint32 guid, Map *map)
{
GameObjectData const* data = sObjectMgr.GetGOData(guid);
if (!data)
{
sLog.outErrorDb("Gameobject (GUID: %u) not found in table `gameobject`, can't load. ",guid);
return false;
}
uint32 entry = data->id;
//uint32 map_id = data->mapid; // already used before call
uint32 phaseMask = data->phaseMask;
float x = data->posX;
float y = data->posY;
float z = data->posZ;
float ang = data->orientation;
float rotation0 = data->rotation0;
float rotation1 = data->rotation1;
float rotation2 = data->rotation2;
float rotation3 = data->rotation3;
uint32 animprogress = data->animprogress;
GOState go_state = data->go_state;
uint32 artKit = data->artKit;
m_DBTableGuid = guid;
if (map->GetInstanceId() != 0) guid = sObjectMgr.GenerateLowGuid(HIGHGUID_GAMEOBJECT);
if (!Create(guid,entry, map, phaseMask, x, y, z, ang, rotation0, rotation1, rotation2, rotation3, animprogress, go_state, artKit))
return false;
if (data->spawntimesecs >= 0)
{
m_spawnedByDefault = true;
if (!GetGOInfo()->GetDespawnPossibility() && !GetGOInfo()->IsDespawnAtAction())
{
SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NODESPAWN);
m_respawnDelayTime = 0;
m_respawnTime = 0;
}
else
{
m_respawnDelayTime = data->spawntimesecs;
m_respawnTime = sObjectMgr.GetGORespawnTime(m_DBTableGuid, map->GetInstanceId());
// ready to respawn
if (m_respawnTime && m_respawnTime <= time(NULL))
{
m_respawnTime = 0;
sObjectMgr.SaveGORespawnTime(m_DBTableGuid,GetInstanceId(),0);
}
}
}
else
{
m_spawnedByDefault = false;
m_respawnDelayTime = -data->spawntimesecs;
m_respawnTime = 0;
}
m_goData = data;
return true;
}
void GameObject::DeleteFromDB()
{
sObjectMgr.SaveGORespawnTime(m_DBTableGuid,GetInstanceId(),0);
sObjectMgr.DeleteGOData(m_DBTableGuid);
WorldDatabase.PExecute("DELETE FROM gameobject WHERE guid = '%u'", m_DBTableGuid);
WorldDatabase.PExecute("DELETE FROM game_event_gameobject WHERE guid = '%u'", m_DBTableGuid);
}
GameObject* GameObject::GetGameObject(WorldObject& object, uint64 guid)
{
return object.GetMap()->GetGameObject(guid);
}
/*********************************************************/
/*** QUEST SYSTEM ***/
/*********************************************************/
bool GameObject::hasQuest(uint32 quest_id) const
{
QuestRelationBounds qr = sObjectMgr.GetGOQuestRelationBounds(GetEntry());
for (QuestRelations::const_iterator itr = qr.first; itr != qr.second; ++itr)
{
if (itr->second == quest_id)
return true;
}
return false;
}
bool GameObject::hasInvolvedQuest(uint32 quest_id) const
{
QuestRelationBounds qir = sObjectMgr.GetGOQuestInvolvedRelationBounds(GetEntry());
for (QuestRelations::const_iterator itr = qir.first; itr != qir.second; ++itr)
{
if (itr->second == quest_id)
return true;
}
return false;
}
bool GameObject::IsTransport() const
{
// If something is marked as a transport, don't transmit an out of range packet for it.
GameObjectInfo const * gInfo = GetGOInfo();
if (!gInfo) return false;
return gInfo->type == GAMEOBJECT_TYPE_TRANSPORT || gInfo->type == GAMEOBJECT_TYPE_MO_TRANSPORT;
}
// is Dynamic transport = non-stop Transport
bool GameObject::IsDynTransport() const
{
// If something is marked as a transport, don't transmit an out of range packet for it.
GameObjectInfo const * gInfo = GetGOInfo();
if (!gInfo) return false;
return gInfo->type == GAMEOBJECT_TYPE_MO_TRANSPORT || (gInfo->type == GAMEOBJECT_TYPE_TRANSPORT && !gInfo->transport.pause);
}
Unit* GameObject::GetOwner() const
{
return ObjectAccessor::GetUnit(*this, GetOwnerGUID());
}
void GameObject::SaveRespawnTime()
{
if (m_goData && m_goData->dbData && m_respawnTime > time(NULL) && m_spawnedByDefault)
sObjectMgr.SaveGORespawnTime(m_DBTableGuid,GetInstanceId(),m_respawnTime);
}
bool GameObject::isVisibleForInState(Player const* u, bool inVisibleList) const
{
// Not in world
if (!IsInWorld() || !u->IsInWorld())
return false;
// Transport always visible at this step implementation
if (IsTransport() && IsInMap(u))
return true;
// quick check visibility false cases for non-GM-mode
if (!u->isGameMaster())
{
// despawned and then not visible for non-GM in GM-mode
if (!isSpawned())
return false;
// special invisibility cases
if (GetGOInfo()->type == GAMEOBJECT_TYPE_TRAP && GetGOInfo()->trap.stealthed)
{
Unit *owner = GetOwner();
if (owner && u->IsHostileTo(owner) && !canDetectTrap(u, GetDistance(u)))
return false;
}
}
// check distance
return IsWithinDistInMap(u->m_seer,World::GetMaxVisibleDistanceForObject() +
(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), false);
}
bool GameObject::canDetectTrap(Player const* u, float distance) const
{
if (u->hasUnitState(UNIT_STAT_STUNNED))
return false;
if (distance < GetGOInfo()->size) //collision
return true;
if (!u->HasInArc(M_PI, this)) //behind
return false;
if (u->HasAuraType(SPELL_AURA_DETECT_STEALTH))
return true;
//Visible distance is modified by -Level Diff (every level diff = 0.25f in visible distance)
float visibleDistance = (int32(u->getLevel()) - int32(GetOwner()->getLevel()))* 0.25f;
//GetModifier for trap (miscvalue 1)
//35y for aura 2836
//WARNING: these values are guessed, may be not blizzlike
visibleDistance += u->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DETECT, 1)* 0.5f;
return distance < visibleDistance;
}
void GameObject::Respawn()
{
if (m_spawnedByDefault && m_respawnTime > 0)
{
m_respawnTime = time(NULL);
sObjectMgr.SaveGORespawnTime(m_DBTableGuid,GetInstanceId(),0);
}
}
bool GameObject::ActivateToQuest(Player *pTarget) const
{
if (!sObjectMgr.IsGameObjectForQuests(GetEntry()))
return false;
switch (GetGoType())
{
// scan GO chest with loot including quest items
case GAMEOBJECT_TYPE_CHEST:
{
if (LootTemplates_Gameobject.HaveQuestLootForPlayer(GetGOInfo()->GetLootId(), pTarget))
{
//TODO: fix this hack
//look for battlegroundAV for some objects which are only activated after mine gots captured by own team
if (GetEntry() == BG_AV_OBJECTID_MINE_N || GetEntry() == BG_AV_OBJECTID_MINE_S)
if (Battleground *bg = pTarget->GetBattleground())
if (bg->GetTypeID(true) == BATTLEGROUND_AV && !(((BattlegroundAV*)bg)->PlayerCanDoMineQuest(GetEntry(),pTarget->GetTeam())))
return false;
return true;
}
break;
}
case GAMEOBJECT_TYPE_GOOBER:
{
if (pTarget->GetQuestStatus(GetGOInfo()->goober.questId) == QUEST_STATUS_INCOMPLETE || GetGOInfo()->goober.questId == -1)
return true;
break;
}
default:
break;
}
return false;
}
void GameObject::TriggeringLinkedGameObject(uint32 trapEntry, Unit* target)
{
GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(trapEntry);
if (!trapInfo || trapInfo->type != GAMEOBJECT_TYPE_TRAP)
return;
SpellEntry const* trapSpell = sSpellStore.LookupEntry(trapInfo->trap.spellId);
if (!trapSpell) // checked at load already
return;
float range;
SpellRangeEntry const * srentry = sSpellRangeStore.LookupEntry(trapSpell->rangeIndex);
//get owner to check hostility of GameObject
if (GetSpellMaxRangeForHostile(srentry) == GetSpellMaxRangeForHostile(srentry))
range = GetSpellMaxRangeForHostile(srentry);
else
{
if (Unit *owner = GetOwner())
range = (float)owner->GetSpellMaxRangeForTarget(target, srentry);
else
//if no owner assume that object is hostile to target
range = GetSpellMaxRangeForHostile(srentry);
}
// search nearest linked GO
GameObject* trapGO = NULL;
{
// using original GO distance
CellPair p(Trinity::ComputeCellPair(GetPositionX(), GetPositionY()));
Cell cell(p);
cell.data.Part.reserved = ALL_DISTRICT;
Trinity::NearestGameObjectEntryInObjectRangeCheck go_check(*target,trapEntry,range);
Trinity::GameObjectLastSearcher<Trinity::NearestGameObjectEntryInObjectRangeCheck> checker(this, trapGO,go_check);
TypeContainerVisitor<Trinity::GameObjectLastSearcher<Trinity::NearestGameObjectEntryInObjectRangeCheck>, GridTypeMapContainer > object_checker(checker);
cell.Visit(p, object_checker, *GetMap(), *target, range);
}
// found correct GO
if (trapGO)
trapGO->CastSpell(target, trapInfo->trap.spellId);
}
GameObject* GameObject::LookupFishingHoleAround(float range)
{
GameObject* ok = NULL;
CellPair p(Trinity::ComputeCellPair(GetPositionX(),GetPositionY()));
Cell cell(p);
cell.data.Part.reserved = ALL_DISTRICT;
Trinity::NearestGameObjectFishingHole u_check(*this, range);
Trinity::GameObjectSearcher<Trinity::NearestGameObjectFishingHole> checker(this, ok, u_check);
TypeContainerVisitor<Trinity::GameObjectSearcher<Trinity::NearestGameObjectFishingHole>, GridTypeMapContainer > grid_object_checker(checker);
cell.Visit(p, grid_object_checker, *GetMap(), *this, range);
return ok;
}
void GameObject::ResetDoorOrButton()
{
if (m_lootState == GO_READY || m_lootState == GO_JUST_DEACTIVATED)
return;
SwitchDoorOrButton(false);
SetLootState(GO_JUST_DEACTIVATED);
m_cooldownTime = 0;
}
void GameObject::UseDoorOrButton(uint32 time_to_restore, bool alternative /* = false */)
{
if (m_lootState != GO_READY)
return;
if (!time_to_restore)
time_to_restore = GetGOInfo()->GetAutoCloseTime();
SwitchDoorOrButton(true,alternative);
SetLootState(GO_ACTIVATED);
m_cooldownTime = time(NULL) + time_to_restore;
}
void GameObject::SetGoArtKit(uint8 kit)
{
SetByteValue(GAMEOBJECT_BYTES_1, 2, kit);
GameObjectData *data = const_cast<GameObjectData*>(sObjectMgr.GetGOData(m_DBTableGuid));
if (data)
data->artKit = kit;
}
void GameObject::SetGoArtKit(uint8 artkit, GameObject *go, uint32 lowguid)
{
const GameObjectData *data = NULL;
if (go)
{
go->SetGoArtKit(artkit);
data = go->GetGOData();
}
else if (lowguid)
data = sObjectMgr.GetGOData(lowguid);
if (data)
const_cast<GameObjectData*>(data)->artKit = artkit;
}
void GameObject::SwitchDoorOrButton(bool activate, bool alternative /* = false */)
{
if (activate)
SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE);
else
RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE);
if (GetGoState() == GO_STATE_READY) //if closed -> open
SetGoState(alternative ? GO_STATE_ACTIVE_ALTERNATIVE : GO_STATE_ACTIVE);
else //if open -> close
SetGoState(GO_STATE_READY);
}
void GameObject::Use(Unit* user)
{
// by default spell caster is user
Unit* spellCaster = user;
uint32 spellId = 0;
bool triggered = false;
switch(GetGoType())
{
case GAMEOBJECT_TYPE_DOOR: //0
case GAMEOBJECT_TYPE_BUTTON: //1
//doors/buttons never really despawn, only reset to default state/flags
UseDoorOrButton();
// activate script
GetMap()->ScriptsStart(sGameObjectScripts, GetDBTableGUIDLow(), spellCaster, this);
return;
case GAMEOBJECT_TYPE_QUESTGIVER: //2
{
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
player->PrepareGossipMenu(this, GetGOInfo()->questgiver.gossipID);
player->SendPreparedGossip(this);
return;
}
//Sitting: Wooden bench, chairs enzz
case GAMEOBJECT_TYPE_CHAIR: //7
{
GameObjectInfo const* info = GetGOInfo();
if (!info)
return;
if (user->GetTypeId() != TYPEID_PLAYER)
return;
if (!ChairListSlots.size()) // this is called once at first chair use to make list of available slots
{
if (info->chair.slots > 0) // sometimes chairs in DB have error in fields and we dont know number of slots
for (uint32 i = 0; i < info->chair.slots; ++i)
ChairListSlots[i] = 0; // Last user of current slot set to 0 (none sit here yet)
else
ChairListSlots[0] = 0; // error in DB, make one default slot
}
Player* player = (Player*)user;
// a chair may have n slots. we have to calculate their positions and teleport the player to the nearest one
float lowestDist = DEFAULT_VISIBILITY_DISTANCE;
uint32 nearest_slot = 0;
float x_lowest = GetPositionX();
float y_lowest = GetPositionY();
// the object orientation + 1/2 pi
// every slot will be on that straight line
float orthogonalOrientation = GetOrientation()+M_PI*0.5f;
// find nearest slot
bool found_free_slot = false;
for (ChairSlotAndUser::iterator itr = ChairListSlots.begin(); itr != ChairListSlots.end(); ++itr)
{
// the distance between this slot and the center of the go - imagine a 1D space
float relativeDistance = (info->size*itr->first)-(info->size*(info->chair.slots-1)/2.0f);
float x_i = GetPositionX() + relativeDistance * cos(orthogonalOrientation);
float y_i = GetPositionY() + relativeDistance * sin(orthogonalOrientation);
if (itr->second)
{
if (Player* ChairUser = sObjectMgr.GetPlayer(itr->second))
if (ChairUser->IsSitState() && ChairUser->getStandState() != UNIT_STAND_STATE_SIT && ChairUser->GetExactDist2d(x_i, y_i) < 0.1f)
continue; // This seat is already occupied by ChairUser. NOTE: Not sure if the ChairUser->getStandState() != UNIT_STAND_STATE_SIT check is required.
else
itr->second = 0; // This seat is unoccupied.
else
itr->second = 0; // The seat may of had an occupant, but they're offline.
}
found_free_slot = true;
// calculate the distance between the player and this slot
float thisDistance = player->GetDistance2d(x_i, y_i);
/* debug code. It will spawn a npc on each slot to visualize them.
Creature* helper = player->SummonCreature(14496, x_i, y_i, GetPositionZ(), GetOrientation(), TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 10000);
std::ostringstream output;
output << i << ": thisDist: " << thisDistance;
helper->MonsterSay(output.str().c_str(), LANG_UNIVERSAL, 0);
*/
if (thisDistance <= lowestDist)
{
nearest_slot = itr->first;
lowestDist = thisDistance;
x_lowest = x_i;
y_lowest = y_i;
}
}
if (found_free_slot)
{
ChairSlotAndUser::iterator itr = ChairListSlots.find(nearest_slot);
if (itr != ChairListSlots.end())
{
itr->second = player->GetGUID(); //this slot in now used by player
player->TeleportTo(GetMapId(), x_lowest, y_lowest, GetPositionZ(), GetOrientation(),TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET);
player->SetStandState(UNIT_STAND_STATE_SIT_LOW_CHAIR+info->chair.height);
return;
}
}
//else
//player->GetSession()->SendNotification("There's nowhere left for you to sit.");
return;
}
//big gun, its a spell/aura
case GAMEOBJECT_TYPE_GOOBER: //10
{
GameObjectInfo const* info = GetGOInfo();
if (user->GetTypeId() == TYPEID_PLAYER)
{
Player* player = (Player*)user;
if (info->goober.pageId) // show page...
{
WorldPacket data(SMSG_GAMEOBJECT_PAGETEXT, 8);
data << GetGUID();
player->GetSession()->SendPacket(&data);
}
else if (info->goober.gossipID)
{
player->PrepareGossipMenu(this, info->goober.gossipID);
player->SendPreparedGossip(this);
}
if (info->goober.eventId)
{
sLog.outDebug("Goober ScriptStart id %u for GO entry %u (GUID %u).", info->goober.eventId, GetEntry(), GetDBTableGUIDLow());
GetMap()->ScriptsStart(sEventScripts, info->goober.eventId, player, this);
EventInform(info->goober.eventId);
}
// possible quest objective for active quests
if (info->goober.questId && sObjectMgr.GetQuestTemplate(info->goober.questId))
{
//Quest require to be active for GO using
if (player->GetQuestStatus(info->goober.questId) != QUEST_STATUS_INCOMPLETE)
break;
}
if (Battleground* bg = player->GetBattleground())
bg->EventPlayerUsedGO(player, this);
player->CastedCreatureOrGO(info->id, GetGUID(), 0);
}
if (uint32 trapEntry = info->goober.linkedTrapId)
TriggeringLinkedGameObject(trapEntry, user);
SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE);
SetLootState(GO_ACTIVATED);
uint32 time_to_restore = info->GetAutoCloseTime();
// this appear to be ok, however others exist in addition to this that should have custom (ex: 190510, 188692, 187389)
if (time_to_restore && info->goober.customAnim)
SendCustomAnim();
else
SetGoState(GO_STATE_ACTIVE);
m_cooldownTime = time(NULL) + time_to_restore;
// cast this spell later if provided
spellId = info->goober.spellId;
spellCaster = NULL;
break;
}
case GAMEOBJECT_TYPE_CAMERA: //13
{
GameObjectInfo const* info = GetGOInfo();
if (!info)
return;
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
if (info->camera.cinematicId)
player->SendCinematicStart(info->camera.cinematicId);
if (info->camera.eventID)
GetMap()->ScriptsStart(sEventScripts, info->camera.eventID, player, this);
return;
}
//fishing bobber
case GAMEOBJECT_TYPE_FISHINGNODE: //17
{
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
if (player->GetGUID() != GetOwnerGUID())
return;
switch(getLootState())
{
case GO_READY: // ready for loot
{
uint32 zone, subzone;
GetZoneAndAreaId(zone,subzone);
int32 zone_skill = sObjectMgr.GetFishingBaseSkillLevel(subzone);
if (!zone_skill)
zone_skill = sObjectMgr.GetFishingBaseSkillLevel(zone);
//provide error, no fishable zone or area should be 0
if (!zone_skill)
sLog.outErrorDb("Fishable areaId %u are not properly defined in `skill_fishing_base_level`.",subzone);
int32 skill = player->GetSkillValue(SKILL_FISHING);
int32 chance;
if (skill < zone_skill)
{
chance = int32(pow((double)skill/zone_skill,2) * 100);
if (chance < 1)
chance = 1;
}
else
chance = 100;
int32 roll = irand(1,100);
sLog.outStaticDebug("Fishing check (skill: %i zone min skill: %i chance %i roll: %i",skill,zone_skill,chance,roll);
// but you will likely cause junk in areas that require a high fishing skill (not yet implemented)
if (chance >= roll)
{
player->UpdateFishingSkill();
// prevent removing GO at spell cancel
player->RemoveGameObject(this,false);
SetOwnerGUID(player->GetGUID());
//TODO: find reasonable value for fishing hole search
GameObject* ok = LookupFishingHoleAround(20.0f + CONTACT_DISTANCE);
if (ok)
{
ok->Use(player);
SetLootState(GO_JUST_DEACTIVATED);
}
else
player->SendLoot(GetGUID(),LOOT_FISHING);
}
// TODO: else: junk
break;
}
case GO_JUST_DEACTIVATED: // nothing to do, will be deleted at next update
break;
default:
{
SetLootState(GO_JUST_DEACTIVATED);
WorldPacket data(SMSG_FISH_NOT_HOOKED, 0);
player->GetSession()->SendPacket(&data);
break;
}
}
player->FinishSpell(CURRENT_CHANNELED_SPELL);
return;
}
case GAMEOBJECT_TYPE_SUMMONING_RITUAL: //18
{
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
Unit* owner = GetOwner();
GameObjectInfo const* info = GetGOInfo();
// ritual owner is set for GO's without owner (not summoned)
if (!m_ritualOwner && !owner)
m_ritualOwner = player;
if (owner)
{
if (owner->GetTypeId() != TYPEID_PLAYER)
return;
// accept only use by player from same group as owner, excluding owner itself (unique use already added in spell effect)
if (player == owner->ToPlayer() || (info->summoningRitual.castersGrouped && !player->IsInSameRaidWith(owner->ToPlayer())))
return;
// expect owner to already be channeling, so if not...
if (!owner->GetCurrentSpell(CURRENT_CHANNELED_SPELL))
return;
// in case summoning ritual caster is GO creator
spellCaster = owner;
}
else
{
if (player != m_ritualOwner && (info->summoningRitual.castersGrouped && !player->IsInSameRaidWith(m_ritualOwner)))
return;
spellCaster = player;
}
AddUniqueUse(player);
if (info->summoningRitual.animSpell)
{
player->CastSpell(player, info->summoningRitual.animSpell, true);
// for this case, summoningRitual.spellId is always triggered
triggered = true;
}
// full amount unique participants including original summoner
if (GetUniqueUseCount() == info->summoningRitual.reqParticipants)
{
spellCaster = m_ritualOwner ? m_ritualOwner : spellCaster;
spellId = info->summoningRitual.spellId;
if (spellId == 62330) // GO store nonexistent spell, replace by expected
{
// spell have reagent and mana cost but it not expected use its
// it triggered spell in fact casted at currently channeled GO
spellId = 61993;
triggered = true;
}
// finish owners spell
if (owner)
owner->FinishSpell(CURRENT_CHANNELED_SPELL);
// can be deleted now, if
if (!info->summoningRitual.ritualPersistent)
SetLootState(GO_JUST_DEACTIVATED);
else
{
// reset ritual for this GO
m_ritualOwner = NULL;
m_unique_users.clear();
m_usetimes = 0;
}
}
else
return;
// go to end function to spell casting
break;
}
case GAMEOBJECT_TYPE_SPELLCASTER: //22
{
GameObjectInfo const* info = GetGOInfo();
if (!info)
return;
if (info->spellcaster.partyOnly)
{
Unit* caster = GetOwner();
if (!caster || caster->GetTypeId() != TYPEID_PLAYER)
return;
if (user->GetTypeId() != TYPEID_PLAYER || !user->ToPlayer()->IsInSameRaidWith(caster->ToPlayer()))
return;
}
spellId = info->spellcaster.spellId;
AddUse();
break;
}
case GAMEOBJECT_TYPE_MEETINGSTONE: //23
{
GameObjectInfo const* info = GetGOInfo();
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
Player* targetPlayer = ObjectAccessor::FindPlayer(player->GetSelection());
// accept only use by player from same raid as caster, except caster itself
if (!targetPlayer || targetPlayer == player || !targetPlayer->IsInSameRaidWith(player))
return;
//required lvl checks!
uint8 level = player->getLevel();
if (level < info->meetingstone.minLevel)
return;
level = targetPlayer->getLevel();
if (level < info->meetingstone.minLevel)
return;
if (info->id == 194097)
spellId = 61994; // Ritual of Summoning
else
spellId = 59782; // Summoning Stone Effect
break;
}
case GAMEOBJECT_TYPE_FLAGSTAND: // 24
{
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
if (player->CanUseBattlegroundObject())
{
// in battleground check
Battleground *bg = player->GetBattleground();
if (!bg)
return;
if (player->GetVehicle())
return;
// BG flag click
// AB:
// 15001
// 15002
// 15003
// 15004
// 15005
bg->EventPlayerClickedOnFlag(player, this);
return; //we don;t need to delete flag ... it is despawned!
}
break;
}
case GAMEOBJECT_TYPE_FISHINGHOLE: // 25
{
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
player->SendLoot(GetGUID(), LOOT_FISHINGHOLE);
player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT, GetGOInfo()->id);
return;
}
case GAMEOBJECT_TYPE_FLAGDROP: // 26
{
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
if (player->CanUseBattlegroundObject())
{
// in battleground check
Battleground *bg = player->GetBattleground();
if (!bg)
return;
if( player->GetVehicle())
return;
// BG flag dropped
// WS:
// 179785 - Silverwing Flag
// 179786 - Warsong Flag
// EotS:
// 184142 - Netherstorm Flag
GameObjectInfo const* info = GetGOInfo();
if (info)
{
switch(info->id)
{
case 179785: // Silverwing Flag
// check if it's correct bg
if (bg->GetTypeID(true) == BATTLEGROUND_WS)
bg->EventPlayerClickedOnFlag(player, this);
break;
case 179786: // Warsong Flag
if (bg->GetTypeID(true) == BATTLEGROUND_WS)
bg->EventPlayerClickedOnFlag(player, this);
break;
case 184142: // Netherstorm Flag
if (bg->GetTypeID(true) == BATTLEGROUND_EY)
bg->EventPlayerClickedOnFlag(player, this);
break;
}
}
//this cause to call return, all flags must be deleted here!!
spellId = 0;
Delete();
}
break;
}
case GAMEOBJECT_TYPE_BARBER_CHAIR: //32
{
GameObjectInfo const* info = GetGOInfo();
if (!info)
return;
if (user->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = (Player*)user;
// fallback, will always work
player->TeleportTo(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation(),TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET);
WorldPacket data(SMSG_ENABLE_BARBER_SHOP, 0);
player->GetSession()->SendPacket(&data);
player->SetStandState(UNIT_STAND_STATE_SIT_LOW_CHAIR+info->barberChair.chairheight);
return;
}
default:
sLog.outDebug("Unknown Object Type %u", GetGoType());
break;
}
if (!spellId)
return;
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
if (!spellInfo)
{
if (user->GetTypeId() != TYPEID_PLAYER || !sOutdoorPvPMgr.HandleCustomSpell((Player*)user,spellId,this))
sLog.outError("WORLD: unknown spell id %u at use action for gameobject (Entry: %u GoType: %u)", spellId,GetEntry(),GetGoType());
else
sLog.outDebug("WORLD: %u non-dbc spell was handled by OutdoorPvP", spellId);
return;
}
if (spellCaster)
spellCaster->CastSpell(user, spellInfo, triggered);
else
CastSpell(user, spellId);
}
void GameObject::CastSpell(Unit* target, uint32 spellId)
{
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
if (!spellInfo)
return;
bool self = false;
for (uint8 i = 0; i < 3; ++i)
{
if (spellInfo->EffectImplicitTargetA[i] == TARGET_UNIT_CASTER)
{
self = true;
break;
}
}
if (self)
{
if (target)
target->CastSpell(target, spellInfo, true);
return;
}
//summon world trigger
Creature *trigger = SummonTrigger(GetPositionX(), GetPositionY(), GetPositionZ(), 0, 1);
if (!trigger) return;
trigger->SetVisibility(VISIBILITY_OFF); //should this be true?
if (Unit *owner = GetOwner())
{
trigger->setFaction(owner->getFaction());
trigger->CastSpell(target ? target : trigger, spellInfo, true, 0, 0, owner->GetGUID());
}
else
{
trigger->setFaction(14);
// Set owner guid for target if no owner avalible - needed by trigger auras
// - trigger gets despawned and there's no caster avalible (see AuraEffect::TriggerSpell())
trigger->CastSpell(target ? target : trigger, spellInfo, true, 0, 0, target ? target->GetGUID() : 0);
}
//trigger->setDeathState(JUST_DIED);
//trigger->RemoveCorpse();
}
void GameObject::SendCustomAnim()
{
WorldPacket data(SMSG_GAMEOBJECT_CUSTOM_ANIM,8+4);
data << GetGUID();
data << uint32(GetGoAnimProgress());
SendMessageToSet(&data, true);
}
bool GameObject::IsInRange(float x, float y, float z, float radius) const
{
GameObjectDisplayInfoEntry const * info = sGameObjectDisplayInfoStore.LookupEntry(GetUInt32Value(GAMEOBJECT_DISPLAYID));
if (!info)
return IsWithinDist3d(x, y, z, radius);
float sinA = sin(GetOrientation());
float cosA = cos(GetOrientation());
float dx = x - GetPositionX();
float dy = y - GetPositionY();
float dz = z - GetPositionZ();
float dist = sqrt(dx*dx + dy*dy);
float sinB = dx / dist;
float cosB = dy / dist;
dx = dist * (cosA * cosB + sinA * sinB);
dy = dist * (cosA * sinB - sinA * cosB);
return dx < info->maxX + radius && dx > info->minX - radius
&& dy < info->maxY + radius && dy > info->minY - radius
&& dz < info->maxZ + radius && dz > info->minZ - radius;
}
void GameObject::TakenDamage(uint32 damage, Unit *who)
{
if (!m_goValue->building.health)
return;
Player* pwho = NULL;
if (who)
{
if (who->GetTypeId() == TYPEID_PLAYER)
pwho = who->ToPlayer();
else if (who->IsVehicle() && who->GetCharmerOrOwner())
pwho = who->GetCharmerOrOwner()->ToPlayer();
}
if (m_goValue->building.health > damage)
m_goValue->building.health -= damage;
else
m_goValue->building.health = 0;
if (HasFlag(GAMEOBJECT_FLAGS, GO_FLAG_DAMAGED)) // from damaged to destroyed
{
uint8 hitType = BG_OBJECT_DMG_HIT_TYPE_HIGH_DAMAGED;
if (!m_goValue->building.health)
{
RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_DAMAGED);
SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_DESTROYED);
SetUInt32Value(GAMEOBJECT_DISPLAYID, m_goInfo->building.destroyedDisplayId);
EventInform(m_goInfo->building.destroyedEvent);
if (pwho)
if (Battleground* bg = pwho->GetBattleground())
bg->DestroyGate(pwho, this, m_goInfo->building.destroyedEvent);
hitType = BG_OBJECT_DMG_HIT_TYPE_JUST_DESTROYED;
sScriptMgr.OnGameObjectDestroyed(pwho, this, m_goInfo->building.destroyedEvent);
}
if (pwho)
if (Battleground* bg = pwho->GetBattleground())
bg->EventPlayerDamagedGO(pwho, this, hitType, m_goInfo->building.destroyedEvent);
}
else // from intact to damaged
{
uint8 hitType = BG_OBJECT_DMG_HIT_TYPE_JUST_DAMAGED;
if (m_goValue->building.health + damage < m_goInfo->building.intactNumHits + m_goInfo->building.damagedNumHits)
hitType = BG_OBJECT_DMG_HIT_TYPE_DAMAGED;
if (m_goValue->building.health <= m_goInfo->building.damagedNumHits)
{
if (!m_goInfo->building.destroyedDisplayId)
m_goValue->building.health = m_goInfo->building.damagedNumHits;
else if (!m_goValue->building.health)
m_goValue->building.health = 1;
SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_DAMAGED);
SetUInt32Value(GAMEOBJECT_DISPLAYID, m_goInfo->building.damagedDisplayId);
EventInform(m_goInfo->building.damagedEvent);
hitType = BG_OBJECT_DMG_HIT_TYPE_JUST_HIGH_DAMAGED;
}
if (pwho)
if (Battleground* bg = pwho->GetBattleground())
bg->EventPlayerDamagedGO(pwho, this, hitType, m_goInfo->building.destroyedEvent);
}
SetGoAnimProgress(m_goValue->building.health*255/(m_goInfo->building.intactNumHits + m_goInfo->building.damagedNumHits));
}
void GameObject::Rebuild()
{
RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_DAMAGED + GO_FLAG_DESTROYED);
SetUInt32Value(GAMEOBJECT_DISPLAYID, m_goInfo->displayId);
m_goValue->building.health = m_goInfo->building.intactNumHits + m_goInfo->building.damagedNumHits;
EventInform(m_goInfo->building.rebuildingEvent);
}
void GameObject::EventInform(uint32 eventId)
{
if (eventId && m_zoneScript)
m_zoneScript->ProcessEvent(this, eventId);
}
// overwrite WorldObject function for proper name localization
const char* GameObject::GetNameForLocaleIdx(LocaleConstant loc_idx) const
{
if (loc_idx != DEFAULT_LOCALE)
{
uint8 uloc_idx = uint8(loc_idx);
if (GameObjectLocale const *cl = sObjectMgr.GetGameObjectLocale(GetEntry()))
if (cl->Name.size() > uloc_idx && !cl->Name[uloc_idx].empty())
return cl->Name[uloc_idx].c_str();
}
return GetName();
}
void GameObject::UpdateRotationFields(float rotation2 /*=0.0f*/, float rotation3 /*=0.0f*/)
{
static double const atan_pow = atan(pow(2.0f, -20.0f));
double f_rot1 = sin(GetOrientation() / 2.0f);
double f_rot2 = cos(GetOrientation() / 2.0f);
int64 i_rot1 = int64(f_rot1 / atan_pow *(f_rot2 >= 0 ? 1.0f : -1.0f));
int64 rotation = (i_rot1 << 43 >> 43) & 0x00000000001FFFFF;
//float f_rot2 = sin(0.0f / 2.0f);
//int64 i_rot2 = f_rot2 / atan(pow(2.0f, -20.0f));
//rotation |= (((i_rot2 << 22) >> 32) >> 11) & 0x000003FFFFE00000;
//float f_rot3 = sin(0.0f / 2.0f);
//int64 i_rot3 = f_rot3 / atan(pow(2.0f, -21.0f));
//rotation |= (i_rot3 >> 42) & 0x7FFFFC0000000000;
m_rotation = rotation;
if (rotation2 == 0.0f && rotation3 == 0.0f)
{
rotation2 = (float)f_rot1;
rotation3 = (float)f_rot2;
}
SetFloatValue(GAMEOBJECT_PARENTROTATION+2, rotation2);
SetFloatValue(GAMEOBJECT_PARENTROTATION+3, rotation3);
}<|fim▁end|> | if (IsInWorld())
{
if (m_zoneScript)
m_zoneScript->OnGameObjectCreate(this, false); |
<|file_name|>dht.go<|end_file_name|><|fim▁begin|>package commands
import (
"bytes"
"errors"
"fmt"
"io"
"time"
key "github.com/ipfs/go-ipfs/blocks/key"
cmds "github.com/ipfs/go-ipfs/commands"
notif "github.com/ipfs/go-ipfs/notifications"
path "github.com/ipfs/go-ipfs/path"
ipdht "github.com/ipfs/go-ipfs/routing/dht"
u "github.com/ipfs/go-ipfs/util"
peer "gx/ipfs/QmUBogf4nUefBjmYjn6jfsfPJRkmDGSeMhNj4usRKq69f4/go-libp2p/p2p/peer"
)
var ErrNotDHT = errors.New("routing service is not a DHT")
var DhtCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Issue commands directly through the DHT.",
ShortDescription: ``,<|fim▁hole|> "query": queryDhtCmd,
"findprovs": findProvidersDhtCmd,
"findpeer": findPeerDhtCmd,
"get": getValueDhtCmd,
"put": putValueDhtCmd,
},
}
var queryDhtCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Run a 'findClosestPeers' query through the DHT.",
ShortDescription: ``,
},
Arguments: []cmds.Argument{
cmds.StringArg("peerID", true, true, "The peerID to run the query against."),
},
Options: []cmds.Option{
cmds.BoolOption("verbose", "v", "Write extra information."),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
dht, ok := n.Routing.(*ipdht.IpfsDHT)
if !ok {
res.SetError(ErrNotDHT, cmds.ErrNormal)
return
}
events := make(chan *notif.QueryEvent)
ctx := notif.RegisterForQueryEvents(req.Context(), events)
closestPeers, err := dht.GetClosestPeers(ctx, key.Key(req.Arguments()[0]))
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
go func() {
defer close(events)
for p := range closestPeers {
notif.PublishQueryEvent(ctx, ¬if.QueryEvent{
ID: p,
Type: notif.FinalPeer,
})
}
}()
outChan := make(chan interface{})
res.SetOutput((<-chan interface{})(outChan))
go func() {
defer close(outChan)
for e := range events {
outChan <- e
}
}()
},
Marshalers: cmds.MarshalerMap{
cmds.Text: func(res cmds.Response) (io.Reader, error) {
outChan, ok := res.Output().(<-chan interface{})
if !ok {
return nil, u.ErrCast()
}
marshal := func(v interface{}) (io.Reader, error) {
obj, ok := v.(*notif.QueryEvent)
if !ok {
return nil, u.ErrCast()
}
verbose, _, _ := res.Request().Option("v").Bool()
buf := new(bytes.Buffer)
printEvent(obj, buf, verbose, nil)
return buf, nil
}
return &cmds.ChannelMarshaler{
Channel: outChan,
Marshaler: marshal,
Res: res,
}, nil
},
},
Type: notif.QueryEvent{},
}
var findProvidersDhtCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Run a 'FindProviders' query through the DHT.",
ShortDescription: `
FindProviders will return a list of peers who are able to provide the value requested.
`,
},
Arguments: []cmds.Argument{
cmds.StringArg("key", true, true, "The key to find providers for."),
},
Options: []cmds.Option{
cmds.BoolOption("verbose", "v", "Write extra information."),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
dht, ok := n.Routing.(*ipdht.IpfsDHT)
if !ok {
res.SetError(ErrNotDHT, cmds.ErrNormal)
return
}
numProviders := 20
outChan := make(chan interface{})
res.SetOutput((<-chan interface{})(outChan))
events := make(chan *notif.QueryEvent)
ctx := notif.RegisterForQueryEvents(req.Context(), events)
pchan := dht.FindProvidersAsync(ctx, key.B58KeyDecode(req.Arguments()[0]), numProviders)
go func() {
defer close(outChan)
for e := range events {
outChan <- e
}
}()
go func() {
defer close(events)
for p := range pchan {
np := p
notif.PublishQueryEvent(ctx, ¬if.QueryEvent{
Type: notif.Provider,
Responses: []*peer.PeerInfo{&np},
})
}
}()
},
Marshalers: cmds.MarshalerMap{
cmds.Text: func(res cmds.Response) (io.Reader, error) {
outChan, ok := res.Output().(<-chan interface{})
if !ok {
return nil, u.ErrCast()
}
verbose, _, _ := res.Request().Option("v").Bool()
pfm := pfuncMap{
notif.FinalPeer: func(obj *notif.QueryEvent, out io.Writer, verbose bool) {
if verbose {
fmt.Fprintf(out, "* closest peer %s\n", obj.ID)
}
},
notif.Provider: func(obj *notif.QueryEvent, out io.Writer, verbose bool) {
prov := obj.Responses[0]
if verbose {
fmt.Fprintf(out, "provider: ")
}
fmt.Fprintf(out, "%s\n", prov.ID.Pretty())
if verbose {
for _, a := range prov.Addrs {
fmt.Fprintf(out, "\t%s\n", a)
}
}
},
}
marshal := func(v interface{}) (io.Reader, error) {
obj, ok := v.(*notif.QueryEvent)
if !ok {
return nil, u.ErrCast()
}
buf := new(bytes.Buffer)
printEvent(obj, buf, verbose, pfm)
return buf, nil
}
return &cmds.ChannelMarshaler{
Channel: outChan,
Marshaler: marshal,
Res: res,
}, nil
},
},
Type: notif.QueryEvent{},
}
var findPeerDhtCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Run a 'FindPeer' query through the DHT.",
ShortDescription: ``,
},
Arguments: []cmds.Argument{
cmds.StringArg("peerID", true, true, "The peer to search for."),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
dht, ok := n.Routing.(*ipdht.IpfsDHT)
if !ok {
res.SetError(ErrNotDHT, cmds.ErrNormal)
return
}
pid, err := peer.IDB58Decode(req.Arguments()[0])
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
outChan := make(chan interface{})
res.SetOutput((<-chan interface{})(outChan))
events := make(chan *notif.QueryEvent)
ctx := notif.RegisterForQueryEvents(req.Context(), events)
go func() {
defer close(outChan)
for v := range events {
outChan <- v
}
}()
go func() {
defer close(events)
pi, err := dht.FindPeer(ctx, pid)
if err != nil {
notif.PublishQueryEvent(ctx, ¬if.QueryEvent{
Type: notif.QueryError,
Extra: err.Error(),
})
return
}
notif.PublishQueryEvent(ctx, ¬if.QueryEvent{
Type: notif.FinalPeer,
Responses: []*peer.PeerInfo{&pi},
})
}()
},
Marshalers: cmds.MarshalerMap{
cmds.Text: func(res cmds.Response) (io.Reader, error) {
outChan, ok := res.Output().(<-chan interface{})
if !ok {
return nil, u.ErrCast()
}
pfm := pfuncMap{
notif.FinalPeer: func(obj *notif.QueryEvent, out io.Writer, verbose bool) {
pi := obj.Responses[0]
fmt.Fprintf(out, "%s\n", pi.ID)
for _, a := range pi.Addrs {
fmt.Fprintf(out, "\t%s\n", a)
}
},
}
marshal := func(v interface{}) (io.Reader, error) {
obj, ok := v.(*notif.QueryEvent)
if !ok {
return nil, u.ErrCast()
}
buf := new(bytes.Buffer)
printEvent(obj, buf, true, pfm)
return buf, nil
}
return &cmds.ChannelMarshaler{
Channel: outChan,
Marshaler: marshal,
Res: res,
}, nil
},
},
Type: notif.QueryEvent{},
}
var getValueDhtCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Run a 'GetValue' query through the DHT.",
ShortDescription: `
GetValue will return the value stored in the dht at the given key.
`,
},
Arguments: []cmds.Argument{
cmds.StringArg("key", true, true, "The key to find a value for."),
},
Options: []cmds.Option{
cmds.BoolOption("verbose", "v", "Write extra information."),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
dht, ok := n.Routing.(*ipdht.IpfsDHT)
if !ok {
res.SetError(ErrNotDHT, cmds.ErrNormal)
return
}
outChan := make(chan interface{})
res.SetOutput((<-chan interface{})(outChan))
events := make(chan *notif.QueryEvent)
ctx := notif.RegisterForQueryEvents(req.Context(), events)
dhtkey, err := escapeDhtKey(req.Arguments()[0])
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
go func() {
defer close(outChan)
for e := range events {
outChan <- e
}
}()
go func() {
defer close(events)
val, err := dht.GetValue(ctx, dhtkey)
if err != nil {
notif.PublishQueryEvent(ctx, ¬if.QueryEvent{
Type: notif.QueryError,
Extra: err.Error(),
})
} else {
notif.PublishQueryEvent(ctx, ¬if.QueryEvent{
Type: notif.Value,
Extra: string(val),
})
}
}()
},
Marshalers: cmds.MarshalerMap{
cmds.Text: func(res cmds.Response) (io.Reader, error) {
outChan, ok := res.Output().(<-chan interface{})
if !ok {
return nil, u.ErrCast()
}
verbose, _, _ := res.Request().Option("v").Bool()
pfm := pfuncMap{
notif.Value: func(obj *notif.QueryEvent, out io.Writer, verbose bool) {
if verbose {
fmt.Fprintf(out, "got value: '%s'\n", obj.Extra)
} else {
fmt.Fprintln(out, obj.Extra)
}
},
}
marshal := func(v interface{}) (io.Reader, error) {
obj, ok := v.(*notif.QueryEvent)
if !ok {
return nil, u.ErrCast()
}
buf := new(bytes.Buffer)
printEvent(obj, buf, verbose, pfm)
return buf, nil
}
return &cmds.ChannelMarshaler{
Channel: outChan,
Marshaler: marshal,
Res: res,
}, nil
},
},
Type: notif.QueryEvent{},
}
var putValueDhtCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Run a 'PutValue' query through the DHT.",
ShortDescription: `
PutValue will store the given key value pair in the dht.
`,
},
Arguments: []cmds.Argument{
cmds.StringArg("key", true, false, "The key to store the value at."),
cmds.StringArg("value", true, false, "The value to store.").EnableStdin(),
},
Options: []cmds.Option{
cmds.BoolOption("verbose", "v", "Write extra information."),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
dht, ok := n.Routing.(*ipdht.IpfsDHT)
if !ok {
res.SetError(ErrNotDHT, cmds.ErrNormal)
return
}
outChan := make(chan interface{})
res.SetOutput((<-chan interface{})(outChan))
events := make(chan *notif.QueryEvent)
ctx := notif.RegisterForQueryEvents(req.Context(), events)
key, err := escapeDhtKey(req.Arguments()[0])
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
data := req.Arguments()[1]
go func() {
defer close(outChan)
for e := range events {
outChan <- e
}
}()
go func() {
defer close(events)
err := dht.PutValue(ctx, key, []byte(data))
if err != nil {
notif.PublishQueryEvent(ctx, ¬if.QueryEvent{
Type: notif.QueryError,
Extra: err.Error(),
})
}
}()
},
Marshalers: cmds.MarshalerMap{
cmds.Text: func(res cmds.Response) (io.Reader, error) {
outChan, ok := res.Output().(<-chan interface{})
if !ok {
return nil, u.ErrCast()
}
verbose, _, _ := res.Request().Option("v").Bool()
pfm := pfuncMap{
notif.FinalPeer: func(obj *notif.QueryEvent, out io.Writer, verbose bool) {
if verbose {
fmt.Fprintf(out, "* closest peer %s\n", obj.ID)
}
},
notif.Value: func(obj *notif.QueryEvent, out io.Writer, verbose bool) {
fmt.Fprintf(out, "storing value at %s\n", obj.ID)
},
}
marshal := func(v interface{}) (io.Reader, error) {
obj, ok := v.(*notif.QueryEvent)
if !ok {
return nil, u.ErrCast()
}
buf := new(bytes.Buffer)
printEvent(obj, buf, verbose, pfm)
return buf, nil
}
return &cmds.ChannelMarshaler{
Channel: outChan,
Marshaler: marshal,
Res: res,
}, nil
},
},
Type: notif.QueryEvent{},
}
type printFunc func(obj *notif.QueryEvent, out io.Writer, verbose bool)
type pfuncMap map[notif.QueryEventType]printFunc
func printEvent(obj *notif.QueryEvent, out io.Writer, verbose bool, override pfuncMap) {
if verbose {
fmt.Fprintf(out, "%s: ", time.Now().Format("15:04:05.000"))
}
if override != nil {
if pf, ok := override[obj.Type]; ok {
pf(obj, out, verbose)
return
}
}
switch obj.Type {
case notif.SendingQuery:
if verbose {
fmt.Fprintf(out, "* querying %s\n", obj.ID)
}
case notif.Value:
if verbose {
fmt.Fprintf(out, "got value: '%s'\n", obj.Extra)
} else {
fmt.Fprint(out, obj.Extra)
}
case notif.PeerResponse:
fmt.Fprintf(out, "* %s says use ", obj.ID)
for _, p := range obj.Responses {
fmt.Fprintf(out, "%s ", p.ID)
}
fmt.Fprintln(out)
case notif.QueryError:
fmt.Fprintf(out, "error: %s\n", obj.Extra)
case notif.DialingPeer:
if verbose {
fmt.Fprintf(out, "dialing peer: %s\n", obj.ID)
}
case notif.AddingPeer:
if verbose {
fmt.Fprintf(out, "adding peer to query: %s\n", obj.ID)
}
default:
fmt.Fprintf(out, "unrecognized event type: %d\n", obj.Type)
}
}
func escapeDhtKey(s string) (key.Key, error) {
parts := path.SplitList(s)
switch len(parts) {
case 1:
return key.B58KeyDecode(s), nil
case 3:
k := key.B58KeyDecode(parts[2])
return key.Key(path.Join(append(parts[:2], k.String()))), nil
default:
return "", errors.New("invalid key")
}
}<|fim▁end|> | },
Subcommands: map[string]*cmds.Command{ |
<|file_name|>SimulationParameters.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
.. py:currentmodule:: FileFormat.SimulationParameters
.. moduleauthor:: Hendrix Demers <[email protected]>
MCXRay simulation parameters input file.
"""
# Script information for the file.
__author__ = "Hendrix Demers ([email protected])"
__version__ = ""
__date__ = ""
__copyright__ = "Copyright (c) 2012 Hendrix Demers"
__license__ = ""
# Subversion informations for the file.
__svnRevision__ = "$Revision$"
__svnDate__ = "$Date$"
__svnId__ = "$Id$"
# Standard library modules.
import copy
# Third party modules.
# Local modules.
# Project modules
import pymcxray.FileFormat.MCXRayModel as MCXRayModel
import pymcxray.FileFormat.Version as Version
# Globals and constants variables.
KEY_BASE_FILENAME = "BaseFileName"
KEY_NUMBER_ELECTRONS = "ElectronNbr"
KEY_NUMBER_PHOTONS = "PhotonNbr"
KEY_NUMBER_WINDOWS = "WindowNbr"
KEY_NUMBER_FILMS_X = "FilmNbrX"
KEY_NUMBER_FILMS_Y = "FilmNbrY"
KEY_NUMBER_FILMS_Z = "FilmNbrZ"
KEY_NUMBER_CHANNELS = "SpectraChannel"
KEY_ENERGY_CHANNEL_WIDTH = "EnergyChannelWidth"
KEY_SPECTRA_INTERPOLATION_MODEL = "SpectraInterpolation"
KEY_VOXEL_SIMPLIFICATION = "VoxelSimplification"
KEY_ELASTIC_CROSS_SECTION_SCALING_FACTOR = "ElasticCrossSectionScalingFactor"
KEY_ENERGY_LOSS_SCALING_FACTOR = "EnergyLossScalingFactor"
class SimulationParameters(object):
def __init__(self):
self.version = copy.deepcopy(Version.CURRENT_VERSION)
self._keys = self._createKeys()
self._parameters = {}
self.defaultValues()
def _createKeys(self):
keys = []
keys.append(KEY_BASE_FILENAME)
keys.append(KEY_NUMBER_ELECTRONS)
keys.append(KEY_NUMBER_PHOTONS)
keys.append(KEY_NUMBER_WINDOWS)
keys.append(KEY_NUMBER_FILMS_X)
keys.append(KEY_NUMBER_FILMS_Y)
keys.append(KEY_NUMBER_FILMS_Z)
if self.version == Version.BEFORE_VERSION:
keys.append(KEY_NUMBER_CHANNELS)
else:
keys.append(KEY_ENERGY_CHANNEL_WIDTH)
keys.append(KEY_SPECTRA_INTERPOLATION_MODEL)
keys.append(KEY_VOXEL_SIMPLIFICATION)
if self.version >= Version.VERSION_1_4_4:
keys.append(KEY_ELASTIC_CROSS_SECTION_SCALING_FACTOR)
keys.append(KEY_ENERGY_LOSS_SCALING_FACTOR)
return keys
def defaultValues(self):
<|fim▁hole|> self.numberElectrons = 1000
self.numberPhotons = 10000
self.numberWindows = 64
self.numberFilmsX = 128
self.numberFilmsY = 128
self.numberFilmsZ = 128
self.numberChannels = 1024
self.energyChannelWidth_eV = 5.0
self.spectrumInterpolationModel = MCXRayModel.SpectrumInterpolationModel.TYPE_LINEAR_DOUBLE
self.voxelSimplification = None
self.elasticCrossSectionScalingFactor = 1.0
self.energyLossScalingFactor = 1.0
def _createExtractMethod(self):
extractMethods = {}
extractMethods[KEY_BASE_FILENAME] = str
extractMethods[KEY_NUMBER_ELECTRONS] = int
extractMethods[KEY_NUMBER_PHOTONS] = int
extractMethods[KEY_NUMBER_WINDOWS] = int
extractMethods[KEY_NUMBER_FILMS_X] = int
extractMethods[KEY_NUMBER_FILMS_Y] = int
extractMethods[KEY_NUMBER_FILMS_Z] = int
extractMethods[KEY_NUMBER_CHANNELS] = int
extractMethods[KEY_ENERGY_CHANNEL_WIDTH] = float
extractMethods[KEY_SPECTRA_INTERPOLATION_MODEL] = self._extractSpectrumInterpolationModel
extractMethods[KEY_VOXEL_SIMPLIFICATION] = bool
extractMethods[KEY_ELASTIC_CROSS_SECTION_SCALING_FACTOR] = float
extractMethods[KEY_ENERGY_LOSS_SCALING_FACTOR] = float
return extractMethods
def _createFormatMethod(self):
fromatMethods = {}
fromatMethods[KEY_BASE_FILENAME] = "%s"
fromatMethods[KEY_NUMBER_ELECTRONS] = "%i"
fromatMethods[KEY_NUMBER_PHOTONS] = "%i"
fromatMethods[KEY_NUMBER_WINDOWS] = "%i"
fromatMethods[KEY_NUMBER_FILMS_X] = "%i"
fromatMethods[KEY_NUMBER_FILMS_Y] = "%i"
fromatMethods[KEY_NUMBER_FILMS_Z] = "%i"
fromatMethods[KEY_NUMBER_CHANNELS] = "%i"
fromatMethods[KEY_ENERGY_CHANNEL_WIDTH] = "%s"
fromatMethods[KEY_SPECTRA_INTERPOLATION_MODEL] = "%s"
fromatMethods[KEY_VOXEL_SIMPLIFICATION] = "%s"
fromatMethods[KEY_ELASTIC_CROSS_SECTION_SCALING_FACTOR] = "%.5f"
fromatMethods[KEY_ENERGY_LOSS_SCALING_FACTOR] = "%.5f"
return fromatMethods
def _extractSpectrumInterpolationModel(self, text):
model = MCXRayModel.SpectrumInterpolationModel(int(text))
return model
def read(self, filepath):
self.version.readFromFile(filepath)
lines = open(filepath, 'r').readlines()
extractMethods = self._createExtractMethod()
for line in lines:
line = line.strip()
for key in self._keys:
if line.startswith(key):
items = line.split('=')
self._parameters[key] = extractMethods[key](items[-1])
def write(self, filepath):
outputFile = open(filepath, 'w')
self._writeHeader(outputFile)
self.version.writeLine(outputFile)
formatMethods = self._createFormatMethod()
keys = self._createKeys()
for key in keys:
if key == KEY_SPECTRA_INTERPOLATION_MODEL:
value = formatMethods[key] % (self._parameters[key].getModel())
else:
value = formatMethods[key] % (self._parameters[key])
if value is not None and value != "None":
line = "%s=%s\n" % (key, value)
outputFile.write(line)
def _writeHeader(self, outputFile):
if self._parameters[KEY_VOXEL_SIMPLIFICATION] is not None:
headerLines = [ "********************************************************************************",
"*** SIMULATION PARAMETERS",
"***",
"*** BaseFileName = All output files will be named using this term",
"*** ElectronNbr = Total number of electrons to simulate",
"*** PhotonNbr = Total number of photons to simulate in EDS",
"*** WindowNbr = Number of energy windows in PhiRo computations",
"*** FilmNbrX = Number of X layers in PhiRo computations",
"*** FilmNbrY = Number of Y layers in PhiRo computations",
"*** FilmNbrZ = Number of Z layers in PhiRo computations",
"*** SpectraChannel = Number of channels in spectraa",
"*** SpectraInterpolation = Interpolation type for spectras",
"*** VoxelSimplification = Use only middle voxel of trajectories to store energy",
"***",
"********************************************************************************"]
elif self.version == Version.BEFORE_VERSION:
headerLines = [ "********************************************************************************",
"*** SIMULATION PARAMETERS",
"***",
"*** BaseFileName = All output files will be named using this term",
"*** ElectronNbr = Total number of electrons to simulate",
"*** PhotonNbr = Total number of photons to simulate in EDS",
"*** WindowNbr = Number of energy windows in PhiRo computations",
"*** FilmNbrX = Number of X layers in PhiRo computations",
"*** FilmNbrY = Number of Y layers in PhiRo computations",
"*** FilmNbrZ = Number of Z layers in PhiRo computations",
"*** SpectraChannel = Number of channels in spectraa",
"*** SpectraInterpolation = Interpolation type for spectras",
"***",
"********************************************************************************"]
elif self.version >= Version.VERSION_1_4_4:
headerLines = [ "********************************************************************************",
"*** SIMULATION PARAMETERS",
"***",
"*** BaseFileName = All output files will be named using this term",
"*** ElectronNbr = Total number of electrons to simulate",
"*** PhotonNbr = Total number of photons to simulate in EDS",
"*** WindowNbr = Number of energy windows in Spectrum computations",
"*** FilmNbrX = Number of X layers in Spectrum computations",
"*** FilmNbrY = Number of Y layers in Spectrum computations",
"*** FilmNbrZ = Number of Z layers in Spectrum computations",
"*** EnergyChannelWidth in eV",
"*** SpectraInterpolation = Interpolation type for spectra",
"*** ElasticCrossSectionScalingFactor",
"*** EnergyLossScalingFactor",
"***",
"********************************************************************************"]
else:
headerLines = [ "********************************************************************************",
"*** SIMULATION PARAMETERS",
"***",
"*** BaseFileName = All output files will be named using this term",
"*** ElectronNbr = Total number of electrons to simulate",
"*** PhotonNbr = Total number of photons to simulate in EDS",
"*** WindowNbr = Number of energy windows in Spectrum computations",
"*** FilmNbrX = Number of X layers in Spectrum computations",
"*** FilmNbrY = Number of Y layers in Spectrum computations",
"*** FilmNbrZ = Number of Z layers in Spectrum computations",
"*** EnergyChannelWidth in eV",
"*** SpectraInterpolation = Interpolation type for spectra",
"***",
"********************************************************************************"]
for line in headerLines:
outputFile.write(line+'\n')
@property
def version(self):
return self._version
@version.setter
def version(self, version):
self._version = version
@property
def baseFilename(self):
return self._parameters[KEY_BASE_FILENAME]
@baseFilename.setter
def baseFilename(self, baseFilename):
self._parameters[KEY_BASE_FILENAME] = baseFilename
@property
def numberElectrons(self):
return self._parameters[KEY_NUMBER_ELECTRONS]
@numberElectrons.setter
def numberElectrons(self, numberElectrons):
self._parameters[KEY_NUMBER_ELECTRONS] = numberElectrons
@property
def numberPhotons(self):
return self._parameters[KEY_NUMBER_PHOTONS]
@numberPhotons.setter
def numberPhotons(self, numberPhotons):
self._parameters[KEY_NUMBER_PHOTONS] = numberPhotons
@property
def numberWindows(self):
return self._parameters[KEY_NUMBER_WINDOWS]
@numberWindows.setter
def numberWindows(self, numberWindows):
self._parameters[KEY_NUMBER_WINDOWS] = numberWindows
@property
def numberFilmsX(self):
return self._parameters[KEY_NUMBER_FILMS_X]
@numberFilmsX.setter
def numberFilmsX(self, numberFilmsX):
self._parameters[KEY_NUMBER_FILMS_X] = numberFilmsX
@property
def numberFilmsY(self):
return self._parameters[KEY_NUMBER_FILMS_Y]
@numberFilmsY.setter
def numberFilmsY(self, numberFilmsY):
self._parameters[KEY_NUMBER_FILMS_Y] = numberFilmsY
@property
def numberFilmsZ(self):
return self._parameters[KEY_NUMBER_FILMS_Z]
@numberFilmsZ.setter
def numberFilmsZ(self, numberFilmsZ):
self._parameters[KEY_NUMBER_FILMS_Z] = numberFilmsZ
@property
def numberChannels(self):
return self._parameters[KEY_NUMBER_CHANNELS]
@numberChannels.setter
def numberChannels(self, numberChannels):
self._parameters[KEY_NUMBER_CHANNELS] = numberChannels
@property
def energyChannelWidth_eV(self):
return self._parameters[KEY_ENERGY_CHANNEL_WIDTH]
@energyChannelWidth_eV.setter
def energyChannelWidth_eV(self, energyChannelWidth_eV):
self._parameters[KEY_ENERGY_CHANNEL_WIDTH] = energyChannelWidth_eV
@property
def spectrumInterpolationModel(self):
return self._parameters[KEY_SPECTRA_INTERPOLATION_MODEL].getModel()
@spectrumInterpolationModel.setter
def spectrumInterpolationModel(self, spectrumInterpolationModel):
self._parameters[KEY_SPECTRA_INTERPOLATION_MODEL] = MCXRayModel.SpectrumInterpolationModel(spectrumInterpolationModel)
@property
def voxelSimplification(self):
return self._parameters.get(KEY_VOXEL_SIMPLIFICATION, None)
@voxelSimplification.setter
def voxelSimplification(self, voxelSimplification):
self._parameters[KEY_VOXEL_SIMPLIFICATION] = voxelSimplification
@property
def elasticCrossSectionScalingFactor(self):
return self._parameters[KEY_ELASTIC_CROSS_SECTION_SCALING_FACTOR]
@elasticCrossSectionScalingFactor.setter
def elasticCrossSectionScalingFactor(self, elasticCrossSectionScalingFactor):
self._parameters[KEY_ELASTIC_CROSS_SECTION_SCALING_FACTOR] = elasticCrossSectionScalingFactor
@property
def energyLossScalingFactor(self):
return self._parameters[KEY_ENERGY_LOSS_SCALING_FACTOR]
@energyLossScalingFactor.setter
def energyLossScalingFactor(self, energyLossScalingFactor):
self._parameters[KEY_ENERGY_LOSS_SCALING_FACTOR] = energyLossScalingFactor<|fim▁end|> | baseFilenameRef = r"Results\McXRay"
self.baseFilename = baseFilenameRef
|
<|file_name|>fortranfile.py<|end_file_name|><|fim▁begin|># Copyright 2008-2010 Neil Martinsen-Burrell
#
# 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.
# Copyright 2018 Jo Bovy
#
# Made small changes to allow this module to be used in Python 3, but only
# to be able to read the files used in the mwdust package. Keep the same
# license as above
"""Defines a file-derived class to read/write Fortran unformatted files.
The assumption is that a Fortran unformatted file is being written by
the Fortran runtime as a sequence of records. Each record consists of
an integer (of the default size [usually 32 or 64 bits]) giving the
length of the following data in bytes, then the data itself, then the
same integer as before.
Examples
--------
To use the default endian and precision settings, one can just do::
>>> f = FortranFile('filename')
>>> x = f.readReals()
One can read arrays with varying precisions::
>>> f = FortranFile('filename')
>>> x = f.readInts('h')
>>> y = f.readInts('q')
>>> z = f.readReals('f')
Where the format codes are those used by Python's struct module.
One can change the default endian-ness and header precision::
>>> f = FortranFile('filename', endian='>', header_prec='l')
for a file with little-endian data whose record headers are long
integers.
"""
__docformat__ = "restructuredtext en"
import sys
_PY3= sys.version > '3'
if _PY3:
from io import FileIO
file= FileIO
import numpy
class FortranFile(file):
<|fim▁hole|>
def _get_header_length(self):
return numpy.dtype(self._header_prec).itemsize
_header_length = property(fget=_get_header_length)
def _set_endian(self,c):
"""Set endian to big (c='>') or little (c='<') or native (c='=')
:Parameters:
`c` : string
The endian-ness to use when reading from this file.
"""
if c in '<>@=':
if c == '@':
c = '='
self._endian = c
else:
raise ValueError('Cannot set endian-ness')
def _get_endian(self):
return self._endian
ENDIAN = property(fset=_set_endian,
fget=_get_endian,
doc="Possible endian values are '<', '>', '@', '='"
)
def _set_header_prec(self, prec):
if prec in 'hilq':
self._header_prec = prec
else:
raise ValueError('Cannot set header precision')
def _get_header_prec(self):
return self._header_prec
HEADER_PREC = property(fset=_set_header_prec,
fget=_get_header_prec,
doc="Possible header precisions are 'h', 'i', 'l', 'q'"
)
def __init__(self, fname, endian='@', header_prec='i', *args, **kwargs):
"""Open a Fortran unformatted file for writing.
Parameters
----------
endian : character, optional
Specify the endian-ness of the file. Possible values are
'>', '<', '@' and '='. See the documentation of Python's
struct module for their meanings. The deafult is '>' (native
byte order)
header_prec : character, optional
Specify the precision used for the record headers. Possible
values are 'h', 'i', 'l' and 'q' with their meanings from
Python's struct module. The default is 'i' (the system's
default integer).
"""
file.__init__(self, fname, *args, **kwargs)
self.ENDIAN = endian
self.HEADER_PREC = header_prec
def _read_exactly(self, num_bytes):
"""Read in exactly num_bytes, raising an error if it can't be done."""
if _PY3:
data = b''
else:
data = ''
while True:
l = len(data)
if l == num_bytes:
return data
else:
read_data = self.read(num_bytes - l)
if read_data == '':
raise IOError('Could not read enough data.'
' Wanted %d bytes, got %d.' % (num_bytes, l))
data += read_data
def _read_check(self):
return numpy.fromstring(self._read_exactly(self._header_length),
dtype=self.ENDIAN+self.HEADER_PREC
)[0]
def _write_check(self, number_of_bytes):
"""Write the header for the given number of bytes"""
self.write(numpy.array(number_of_bytes,
dtype=self.ENDIAN+self.HEADER_PREC,).tostring()
)
def readRecord(self):
"""Read a single fortran record"""
l = self._read_check()
data_str = self._read_exactly(l)
check_size = self._read_check()
if check_size != l:
raise IOError('Error reading record from data file')
return data_str
def writeRecord(self,s):
"""Write a record with the given bytes.
Parameters
----------
s : the string to write
"""
length_bytes = len(s)
self._write_check(length_bytes)
self.write(s)
self._write_check(length_bytes)
def readString(self):
"""Read a string."""
return self.readRecord()
def writeString(self,s):
"""Write a string
Parameters
----------
s : the string to write
"""
self.writeRecord(s)
_real_precisions = 'df'
def readReals(self, prec='f'):
"""Read in an array of real numbers.
Parameters
----------
prec : character, optional
Specify the precision of the array using character codes from
Python's struct module. Possible values are 'd' and 'f'.
"""
_numpy_precisions = {'d': numpy.float64,
'f': numpy.float32
}
if prec not in self._real_precisions:
raise ValueError('Not an appropriate precision')
data_str = self.readRecord()
return numpy.fromstring(data_str, dtype=self.ENDIAN+prec)
def writeReals(self, reals, prec='f'):
"""Write an array of floats in given precision
Parameters
----------
reals : array
Data to write
prec` : string
Character code for the precision to use in writing
"""
if prec not in self._real_precisions:
raise ValueError('Not an appropriate precision')
nums = numpy.array(reals, dtype=self.ENDIAN+prec)
self.writeRecord(nums.tostring())
_int_precisions = 'hilq'
def readInts(self, prec='i'):
"""Read an array of integers.
Parameters
----------
prec : character, optional
Specify the precision of the data to be read using
character codes from Python's struct module. Possible
values are 'h', 'i', 'l' and 'q'
"""
if prec not in self._int_precisions:
raise ValueError('Not an appropriate precision')
data_str = self.readRecord()
return numpy.fromstring(data_str, dtype=self.ENDIAN+prec)
def writeInts(self, ints, prec='i'):
"""Write an array of integers in given precision
Parameters
----------
reals : array
Data to write
prec : string
Character code for the precision to use in writing
"""
if prec not in self._int_precisions:
raise ValueError('Not an appropriate precision')
nums = numpy.array(ints, dtype=self.ENDIAN+prec)
self.writeRecord(nums.tostring())<|fim▁end|> | """File with methods for dealing with fortran unformatted data files""" |
<|file_name|>feed.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# coding=utf-8
import os
import datetime
from google.appengine.ext import webapp
from google.appengine.api import memcache
from google.appengine.ext import db
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from v2ex.babel import Member
from v2ex.babel import Counter
from v2ex.babel import Section
from v2ex.babel import Node
from v2ex.babel import Topic
from v2ex.babel import Reply
from v2ex.babel.da import *
template.register_template_library('v2ex.templatetags.filters')
<|fim▁hole|> def get(self):
site = GetSite()
output = memcache.get('feed_index')
if output is None:
template_values = {}
template_values['site'] = site
template_values['site_domain'] = site.domain
template_values['site_name'] = site.title
template_values['site_slogan'] = site.slogan
template_values['feed_url'] = 'http://' + template_values['site_domain'] + '/index.xml'
template_values['site_updated'] = datetime.datetime.now()
q = db.GqlQuery("SELECT * FROM Topic ORDER BY created DESC LIMIT 10")
template_values['topics'] = q
path = os.path.join(os.path.dirname(__file__), 'tpl', 'feed', 'index.xml')
output = template.render(path, template_values)
memcache.set('feed_index', output, 600)
self.response.out.write(output)
def main():
application = webapp.WSGIApplication([
('/index.xml', FeedHomeHandler),
('/feed/v2ex.rss', FeedHomeHandler)
],
debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()<|fim▁end|> | class FeedHomeHandler(webapp.RequestHandler):
def head(self):
self.response.out.write('')
|
<|file_name|>translate.rs<|end_file_name|><|fim▁begin|>// Copyright 2016 Mozilla
//
// 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.
extern crate edn;
extern crate mentat_core;
extern crate core_traits;
extern crate mentat_query_algebrizer;
extern crate mentat_query_projector;
extern crate mentat_sql;
use std::collections::BTreeMap;
use std::rc::Rc;
use edn::query::{
FindSpec,
Keyword,
Variable,
};
use core_traits::{
Attribute,
Entid,
TypedValue,
ValueType,
};
use mentat_core::{
Schema,
};
use mentat_query_algebrizer::{
Known,
QueryInputs,
algebrize,
algebrize_with_inputs,
parse_find_string,
};
use mentat_query_projector::{
ConstantProjector,
};
use mentat_query_projector::translate::{
ProjectedSelect,
query_to_select,
};
use mentat_sql::SQLQuery;
/// Produce the appropriate `Variable` for the provided valid ?-prefixed name.
/// This lives here because we can't re-export macros:<|fim▁hole|>macro_rules! var {
( ? $var:ident ) => {
$crate::Variable::from_valid_name(concat!("?", stringify!($var)))
};
}
fn associate_ident(schema: &mut Schema, i: Keyword, e: Entid) {
schema.entid_map.insert(e, i.clone());
schema.ident_map.insert(i.clone(), e);
}
fn add_attribute(schema: &mut Schema, e: Entid, a: Attribute) {
schema.attribute_map.insert(e, a);
}
fn query_to_sql(query: ProjectedSelect) -> SQLQuery {
match query {
ProjectedSelect::Query { query, projector: _projector } => {
query.to_sql_query().expect("to_sql_query to succeed")
},
ProjectedSelect::Constant(constant) => {
panic!("ProjectedSelect wasn't ::Query! Got constant {:#?}", constant.project_without_rows());
},
}
}
fn query_to_constant(query: ProjectedSelect) -> ConstantProjector {
match query {
ProjectedSelect::Constant(constant) => {
constant
},
_ => panic!("ProjectedSelect wasn't ::Constant!"),
}
}
fn assert_query_is_empty(query: ProjectedSelect, expected_spec: FindSpec) {
let constant = query_to_constant(query).project_without_rows().expect("constant run");
assert_eq!(*constant.spec, expected_spec);
assert!(constant.results.is_empty());
}
fn inner_translate_with_inputs(schema: &Schema, query: &'static str, inputs: QueryInputs) -> ProjectedSelect {
let known = Known::for_schema(schema);
let parsed = parse_find_string(query).expect("parse to succeed");
let algebrized = algebrize_with_inputs(known, parsed, 0, inputs).expect("algebrize to succeed");
query_to_select(schema, algebrized).expect("translate to succeed")
}
fn translate_with_inputs(schema: &Schema, query: &'static str, inputs: QueryInputs) -> SQLQuery {
query_to_sql(inner_translate_with_inputs(schema, query, inputs))
}
fn translate(schema: &Schema, query: &'static str) -> SQLQuery {
translate_with_inputs(schema, query, QueryInputs::default())
}
fn translate_with_inputs_to_constant(schema: &Schema, query: &'static str, inputs: QueryInputs) -> ConstantProjector {
query_to_constant(inner_translate_with_inputs(schema, query, inputs))
}
fn translate_to_constant(schema: &Schema, query: &'static str) -> ConstantProjector {
translate_with_inputs_to_constant(schema, query, QueryInputs::default())
}
fn prepopulated_typed_schema(foo_type: ValueType) -> Schema {
let mut schema = Schema::default();
associate_ident(&mut schema, Keyword::namespaced("foo", "bar"), 99);
add_attribute(&mut schema, 99, Attribute {
value_type: foo_type,
..Default::default()
});
associate_ident(&mut schema, Keyword::namespaced("foo", "fts"), 100);
add_attribute(&mut schema, 100, Attribute {
value_type: ValueType::String,
index: true,
fulltext: true,
..Default::default()
});
schema
}
fn prepopulated_schema() -> Schema {
prepopulated_typed_schema(ValueType::String)
}
fn make_arg(name: &'static str, value: &'static str) -> (String, Rc<mentat_sql::Value>) {
(name.to_string(), Rc::new(mentat_sql::Value::Text(value.to_string())))
}
#[test]
fn test_scalar() {
let schema = prepopulated_schema();
let query = r#"[:find ?x . :where [?x :foo/bar "yyy"]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT `datoms00`.e AS `?x` FROM `datoms` AS `datoms00` WHERE `datoms00`.a = 99 AND `datoms00`.v = $v0 LIMIT 1");
assert_eq!(args, vec![make_arg("$v0", "yyy")]);
}
#[test]
fn test_tuple() {
let schema = prepopulated_schema();
let query = r#"[:find [?x] :where [?x :foo/bar "yyy"]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT `datoms00`.e AS `?x` FROM `datoms` AS `datoms00` WHERE `datoms00`.a = 99 AND `datoms00`.v = $v0 LIMIT 1");
assert_eq!(args, vec![make_arg("$v0", "yyy")]);
}
#[test]
fn test_coll() {
let schema = prepopulated_schema();
let query = r#"[:find [?x ...] :where [?x :foo/bar "yyy"]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `datoms00`.e AS `?x` FROM `datoms` AS `datoms00` WHERE `datoms00`.a = 99 AND `datoms00`.v = $v0");
assert_eq!(args, vec![make_arg("$v0", "yyy")]);
}
#[test]
fn test_rel() {
let schema = prepopulated_schema();
let query = r#"[:find ?x :where [?x :foo/bar "yyy"]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `datoms00`.e AS `?x` FROM `datoms` AS `datoms00` WHERE `datoms00`.a = 99 AND `datoms00`.v = $v0");
assert_eq!(args, vec![make_arg("$v0", "yyy")]);
}
#[test]
fn test_limit() {
let schema = prepopulated_schema();
let query = r#"[:find ?x :where [?x :foo/bar "yyy"] :limit 5]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `datoms00`.e AS `?x` FROM `datoms` AS `datoms00` WHERE `datoms00`.a = 99 AND `datoms00`.v = $v0 LIMIT 5");
assert_eq!(args, vec![make_arg("$v0", "yyy")]);
}
#[test]
fn test_unbound_variable_limit() {
let schema = prepopulated_schema();
// We don't know the value of the limit var, so we produce an escaped SQL variable to handle
// later input.
let query = r#"[:find ?x :in ?limit-is-9-great :where [?x :foo/bar "yyy"] :limit ?limit-is-9-great]"#;
let SQLQuery { sql, args } = translate_with_inputs(&schema, query, QueryInputs::default());
assert_eq!(sql, "SELECT DISTINCT `datoms00`.e AS `?x` \
FROM `datoms` AS `datoms00` \
WHERE `datoms00`.a = 99 AND `datoms00`.v = $v0 \
LIMIT $ilimit_is_9_great");
assert_eq!(args, vec![make_arg("$v0", "yyy")]);
}
#[test]
fn test_bound_variable_limit() {
let schema = prepopulated_schema();
// We know the value of `?limit` at algebrizing time, so we substitute directly.
let query = r#"[:find ?x :in ?limit :where [?x :foo/bar "yyy"] :limit ?limit]"#;
let inputs = QueryInputs::with_value_sequence(vec![(Variable::from_valid_name("?limit"), TypedValue::Long(92))]);
let SQLQuery { sql, args } = translate_with_inputs(&schema, query, inputs);
assert_eq!(sql, "SELECT DISTINCT `datoms00`.e AS `?x` FROM `datoms` AS `datoms00` WHERE `datoms00`.a = 99 AND `datoms00`.v = $v0 LIMIT 92");
assert_eq!(args, vec![make_arg("$v0", "yyy")]);
}
#[test]
fn test_bound_variable_limit_affects_distinct() {
let schema = prepopulated_schema();
// We know the value of `?limit` at algebrizing time, so we substitute directly.
// As it's `1`, we know we don't need `DISTINCT`!
let query = r#"[:find ?x :in ?limit :where [?x :foo/bar "yyy"] :limit ?limit]"#;
let inputs = QueryInputs::with_value_sequence(vec![(Variable::from_valid_name("?limit"), TypedValue::Long(1))]);
let SQLQuery { sql, args } = translate_with_inputs(&schema, query, inputs);
assert_eq!(sql, "SELECT `datoms00`.e AS `?x` FROM `datoms` AS `datoms00` WHERE `datoms00`.a = 99 AND `datoms00`.v = $v0 LIMIT 1");
assert_eq!(args, vec![make_arg("$v0", "yyy")]);
}
#[test]
fn test_bound_variable_limit_affects_types() {
let schema = prepopulated_schema();
let known = Known::for_schema(&schema);
let query = r#"[:find ?x ?limit :in ?limit :where [?x _ ?limit] :limit ?limit]"#;
let parsed = parse_find_string(query).expect("parse failed");
let algebrized = algebrize(known, parsed).expect("algebrize failed");
// The type is known.
assert_eq!(Some(ValueType::Long),
algebrized.cc.known_type(&Variable::from_valid_name("?limit")));
let select = query_to_select(&schema, algebrized).expect("query to translate");
let SQLQuery { sql, args } = query_to_sql(select);
// TODO: this query isn't actually correct -- we don't yet algebrize for variables that are
// specified in `:in` but not provided at algebrizing time. But it shows what we care about
// at the moment: we don't project a type column, because we know it's a Long.
assert_eq!(sql, "SELECT DISTINCT `datoms00`.e AS `?x`, `datoms00`.v AS `?limit` FROM `datoms` AS `datoms00` LIMIT $ilimit");
assert_eq!(args, vec![]);
}
#[test]
fn test_unknown_attribute_keyword_value() {
let schema = Schema::default();
let query = r#"[:find ?x :where [?x _ :ab/yyy]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
// Only match keywords, not strings: tag = 13.
assert_eq!(sql, "SELECT DISTINCT `datoms00`.e AS `?x` FROM `datoms` AS `datoms00` WHERE `datoms00`.v = $v0 AND (`datoms00`.value_type_tag = 13)");
assert_eq!(args, vec![make_arg("$v0", ":ab/yyy")]);
}
#[test]
fn test_unknown_attribute_string_value() {
let schema = Schema::default();
let query = r#"[:find ?x :where [?x _ "horses"]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
// We expect all_datoms because we're querying for a string. Magic, that.
// We don't want keywords etc., so tag = 10.
assert_eq!(sql, "SELECT DISTINCT `all_datoms00`.e AS `?x` FROM `all_datoms` AS `all_datoms00` WHERE `all_datoms00`.v = $v0 AND (`all_datoms00`.value_type_tag = 10)");
assert_eq!(args, vec![make_arg("$v0", "horses")]);
}
#[test]
fn test_unknown_attribute_double_value() {
let schema = Schema::default();
let query = r#"[:find ?x :where [?x _ 9.95]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
// In general, doubles _could_ be 1.0, which might match a boolean or a ref. Set tag = 5 to
// make sure we only match numbers.
assert_eq!(sql, "SELECT DISTINCT `datoms00`.e AS `?x` FROM `datoms` AS `datoms00` WHERE `datoms00`.v = 9.95e0 AND (`datoms00`.value_type_tag = 5)");
assert_eq!(args, vec![]);
}
#[test]
fn test_unknown_attribute_integer_value() {
let schema = Schema::default();
let negative = r#"[:find ?x :where [?x _ -1]]"#;
let zero = r#"[:find ?x :where [?x _ 0]]"#;
let one = r#"[:find ?x :where [?x _ 1]]"#;
let two = r#"[:find ?x :where [?x _ 2]]"#;
// Can't match boolean; no need to filter it out.
let SQLQuery { sql, args } = translate(&schema, negative);
assert_eq!(sql, "SELECT DISTINCT `datoms00`.e AS `?x` FROM `datoms` AS `datoms00` WHERE `datoms00`.v = -1");
assert_eq!(args, vec![]);
// Excludes booleans.
let SQLQuery { sql, args } = translate(&schema, zero);
assert_eq!(sql, "SELECT DISTINCT `datoms00`.e AS `?x` FROM `datoms` AS `datoms00` WHERE (`datoms00`.v = 0 AND `datoms00`.value_type_tag <> 1)");
assert_eq!(args, vec![]);
// Excludes booleans.
let SQLQuery { sql, args } = translate(&schema, one);
assert_eq!(sql, "SELECT DISTINCT `datoms00`.e AS `?x` FROM `datoms` AS `datoms00` WHERE (`datoms00`.v = 1 AND `datoms00`.value_type_tag <> 1)");
assert_eq!(args, vec![]);
// Can't match boolean; no need to filter it out.
let SQLQuery { sql, args } = translate(&schema, two);
assert_eq!(sql, "SELECT DISTINCT `datoms00`.e AS `?x` FROM `datoms` AS `datoms00` WHERE `datoms00`.v = 2");
assert_eq!(args, vec![]);
}
#[test]
fn test_unknown_ident() {
let schema = Schema::default();
let known = Known::for_schema(&schema);
let impossible = r#"[:find ?x :where [?x :db/ident :no/exist]]"#;
let parsed = parse_find_string(impossible).expect("parse failed");
let algebrized = algebrize(known, parsed).expect("algebrize failed");
// This query cannot return results: the ident doesn't resolve for a ref-typed attribute.
assert!(algebrized.is_known_empty());
// If you insist…
let select = query_to_select(&schema, algebrized).expect("query to translate");
assert_query_is_empty(select, FindSpec::FindRel(vec![var!(?x).into()]));
}
#[test]
fn test_type_required_long() {
let schema = Schema::default();
let query = r#"[:find ?x :where [?x _ ?e] [(type ?e :db.type/long)]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `datoms00`.e AS `?x` \
FROM `datoms` AS `datoms00` \
WHERE ((`datoms00`.value_type_tag = 5 AND \
(typeof(`datoms00`.v) = 'integer')))");
assert_eq!(args, vec![]);
}
#[test]
fn test_type_required_double() {
let schema = Schema::default();
let query = r#"[:find ?x :where [?x _ ?e] [(type ?e :db.type/double)]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `datoms00`.e AS `?x` \
FROM `datoms` AS `datoms00` \
WHERE ((`datoms00`.value_type_tag = 5 AND \
(typeof(`datoms00`.v) = 'real')))");
assert_eq!(args, vec![]);
}
#[test]
fn test_type_required_boolean() {
let schema = Schema::default();
let query = r#"[:find ?x :where [?x _ ?e] [(type ?e :db.type/boolean)]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `datoms00`.e AS `?x` \
FROM `datoms` AS `datoms00` \
WHERE (`datoms00`.value_type_tag = 1)");
assert_eq!(args, vec![]);
}
#[test]
fn test_type_required_string() {
let schema = Schema::default();
let query = r#"[:find ?x :where [?x _ ?e] [(type ?e :db.type/string)]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
// Note: strings should use `all_datoms` and not `datoms`.
assert_eq!(sql, "SELECT DISTINCT `all_datoms00`.e AS `?x` \
FROM `all_datoms` AS `all_datoms00` \
WHERE (`all_datoms00`.value_type_tag = 10)");
assert_eq!(args, vec![]);
}
#[test]
fn test_numeric_less_than_unknown_attribute() {
let schema = Schema::default();
let query = r#"[:find ?x :where [?x _ ?y] [(< ?y 10)]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
// Although we infer numericness from numeric predicates, we've already assigned a table to the
// first pattern, and so this is _still_ `all_datoms`.
assert_eq!(sql, "SELECT DISTINCT `all_datoms00`.e AS `?x` FROM `all_datoms` AS `all_datoms00` WHERE `all_datoms00`.v < 10");
assert_eq!(args, vec![]);
}
#[test]
fn test_numeric_gte_known_attribute() {
let schema = prepopulated_typed_schema(ValueType::Double);
let query = r#"[:find ?x :where [?x :foo/bar ?y] [(>= ?y 12.9)]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `datoms00`.e AS `?x` FROM `datoms` AS `datoms00` WHERE `datoms00`.a = 99 AND `datoms00`.v >= 1.29e1");
assert_eq!(args, vec![]);
}
#[test]
fn test_numeric_not_equals_known_attribute() {
let schema = prepopulated_typed_schema(ValueType::Long);
let query = r#"[:find ?x . :where [?x :foo/bar ?y] [(!= ?y 12)]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT `datoms00`.e AS `?x` FROM `datoms` AS `datoms00` WHERE `datoms00`.a = 99 AND `datoms00`.v <> 12 LIMIT 1");
assert_eq!(args, vec![]);
}
#[test]
fn test_compare_long_to_double_constants() {
let schema = prepopulated_typed_schema(ValueType::Double);
let query = r#"[:find ?e .
:where
[?e :foo/bar ?v]
[(< 99.0 1234512345)]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT `datoms00`.e AS `?e` FROM `datoms` AS `datoms00` \
WHERE `datoms00`.a = 99 \
AND 9.9e1 < 1234512345 \
LIMIT 1");
assert_eq!(args, vec![]);
}
#[test]
fn test_compare_long_to_double() {
let schema = prepopulated_typed_schema(ValueType::Double);
// You can compare longs to doubles.
let query = r#"[:find ?e .
:where
[?e :foo/bar ?t]
[(< ?t 1234512345)]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT `datoms00`.e AS `?e` FROM `datoms` AS `datoms00` \
WHERE `datoms00`.a = 99 \
AND `datoms00`.v < 1234512345 \
LIMIT 1");
assert_eq!(args, vec![]);
}
#[test]
fn test_compare_double_to_long() {
let schema = prepopulated_typed_schema(ValueType::Long);
// You can compare doubles to longs.
let query = r#"[:find ?e .
:where
[?e :foo/bar ?t]
[(< ?t 1234512345.0)]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT `datoms00`.e AS `?e` FROM `datoms` AS `datoms00` \
WHERE `datoms00`.a = 99 \
AND `datoms00`.v < 1.234512345e9 \
LIMIT 1");
assert_eq!(args, vec![]);
}
#[test]
fn test_simple_or_join() {
let mut schema = Schema::default();
associate_ident(&mut schema, Keyword::namespaced("page", "url"), 97);
associate_ident(&mut schema, Keyword::namespaced("page", "title"), 98);
associate_ident(&mut schema, Keyword::namespaced("page", "description"), 99);
for x in 97..100 {
add_attribute(&mut schema, x, Attribute {
value_type: ValueType::String,
..Default::default()
});
}
let query = r#"[:find [?url ?description]
:where
(or-join [?page]
[?page :page/url "http://foo.com/"]
[?page :page/title "Foo"])
[?page :page/url ?url]
[?page :page/description ?description]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT `datoms01`.v AS `?url`, `datoms02`.v AS `?description` FROM `datoms` AS `datoms00`, `datoms` AS `datoms01`, `datoms` AS `datoms02` WHERE ((`datoms00`.a = 97 AND `datoms00`.v = $v0) OR (`datoms00`.a = 98 AND `datoms00`.v = $v1)) AND `datoms01`.a = 97 AND `datoms02`.a = 99 AND `datoms00`.e = `datoms01`.e AND `datoms00`.e = `datoms02`.e LIMIT 1");
assert_eq!(args, vec![make_arg("$v0", "http://foo.com/"), make_arg("$v1", "Foo")]);
}
#[test]
fn test_complex_or_join() {
let mut schema = Schema::default();
associate_ident(&mut schema, Keyword::namespaced("page", "save"), 95);
add_attribute(&mut schema, 95, Attribute {
value_type: ValueType::Ref,
..Default::default()
});
associate_ident(&mut schema, Keyword::namespaced("save", "title"), 96);
associate_ident(&mut schema, Keyword::namespaced("page", "url"), 97);
associate_ident(&mut schema, Keyword::namespaced("page", "title"), 98);
associate_ident(&mut schema, Keyword::namespaced("page", "description"), 99);
for x in 96..100 {
add_attribute(&mut schema, x, Attribute {
value_type: ValueType::String,
..Default::default()
});
}
let query = r#"[:find [?url ?description]
:where
(or-join [?page]
[?page :page/url "http://foo.com/"]
[?page :page/title "Foo"]
(and
[?page :page/save ?save]
[?save :save/title "Foo"]))
[?page :page/url ?url]
[?page :page/description ?description]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT `datoms04`.v AS `?url`, \
`datoms05`.v AS `?description` \
FROM (SELECT `datoms00`.e AS `?page` \
FROM `datoms` AS `datoms00` \
WHERE `datoms00`.a = 97 \
AND `datoms00`.v = $v0 \
UNION \
SELECT `datoms01`.e AS `?page` \
FROM `datoms` AS `datoms01` \
WHERE `datoms01`.a = 98 \
AND `datoms01`.v = $v1 \
UNION \
SELECT `datoms02`.e AS `?page` \
FROM `datoms` AS `datoms02`, \
`datoms` AS `datoms03` \
WHERE `datoms02`.a = 95 \
AND `datoms03`.a = 96 \
AND `datoms03`.v = $v1 \
AND `datoms02`.v = `datoms03`.e) AS `c00`, \
`datoms` AS `datoms04`, \
`datoms` AS `datoms05` \
WHERE `datoms04`.a = 97 \
AND `datoms05`.a = 99 \
AND `c00`.`?page` = `datoms04`.e \
AND `c00`.`?page` = `datoms05`.e \
LIMIT 1");
assert_eq!(args, vec![make_arg("$v0", "http://foo.com/"),
make_arg("$v1", "Foo")]);
}
#[test]
fn test_complex_or_join_type_projection() {
let mut schema = Schema::default();
associate_ident(&mut schema, Keyword::namespaced("page", "title"), 98);
add_attribute(&mut schema, 98, Attribute {
value_type: ValueType::String,
..Default::default()
});
let query = r#"[:find [?y]
:where
(or
[6 :page/title ?y]
[5 _ ?y])]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT `c00`.`?y` AS `?y`, \
`c00`.`?y_value_type_tag` AS `?y_value_type_tag` \
FROM (SELECT `datoms00`.v AS `?y`, \
10 AS `?y_value_type_tag` \
FROM `datoms` AS `datoms00` \
WHERE `datoms00`.e = 6 \
AND `datoms00`.a = 98 \
UNION \
SELECT `all_datoms01`.v AS `?y`, \
`all_datoms01`.value_type_tag AS `?y_value_type_tag` \
FROM `all_datoms` AS `all_datoms01` \
WHERE `all_datoms01`.e = 5) AS `c00` \
LIMIT 1");
assert_eq!(args, vec![]);
}
#[test]
fn test_not() {
let mut schema = Schema::default();
associate_ident(&mut schema, Keyword::namespaced("page", "url"), 97);
associate_ident(&mut schema, Keyword::namespaced("page", "title"), 98);
associate_ident(&mut schema, Keyword::namespaced("page", "bookmarked"), 99);
for x in 97..99 {
add_attribute(&mut schema, x, Attribute {
value_type: ValueType::String,
..Default::default()
});
}
add_attribute(&mut schema, 99, Attribute {
value_type: ValueType::Boolean,
..Default::default()
});
let query = r#"[:find ?title
:where [?page :page/title ?title]
(not [?page :page/url "http://foo.com/"]
[?page :page/bookmarked true])]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `datoms00`.v AS `?title` FROM `datoms` AS `datoms00` WHERE `datoms00`.a = 98 AND NOT EXISTS (SELECT 1 FROM `datoms` AS `datoms01`, `datoms` AS `datoms02` WHERE `datoms01`.a = 97 AND `datoms01`.v = $v0 AND `datoms02`.a = 99 AND `datoms02`.v = 1 AND `datoms00`.e = `datoms01`.e AND `datoms00`.e = `datoms02`.e)");
assert_eq!(args, vec![make_arg("$v0", "http://foo.com/")]);
}
#[test]
fn test_not_join() {
let mut schema = Schema::default();
associate_ident(&mut schema, Keyword::namespaced("page", "url"), 97);
associate_ident(&mut schema, Keyword::namespaced("bookmarks", "page"), 98);
associate_ident(&mut schema, Keyword::namespaced("bookmarks", "date_created"), 99);
add_attribute(&mut schema, 97, Attribute {
value_type: ValueType::String,
..Default::default()
});
add_attribute(&mut schema, 98, Attribute {
value_type: ValueType::Ref,
..Default::default()
});
add_attribute(&mut schema, 99, Attribute {
value_type: ValueType::String,
..Default::default()
});
let query = r#"[:find ?url
:where [?url :page/url]
(not-join [?url]
[?page :bookmarks/page ?url]
[?page :bookmarks/date_created "4/4/2017"])]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `datoms00`.e AS `?url` FROM `datoms` AS `datoms00` WHERE `datoms00`.a = 97 AND NOT EXISTS (SELECT 1 FROM `datoms` AS `datoms01`, `datoms` AS `datoms02` WHERE `datoms01`.a = 98 AND `datoms02`.a = 99 AND `datoms02`.v = $v0 AND `datoms01`.e = `datoms02`.e AND `datoms00`.e = `datoms01`.v)");
assert_eq!(args, vec![make_arg("$v0", "4/4/2017")]);
}
#[test]
fn test_with_without_aggregate() {
let schema = prepopulated_schema();
// Known type.
let query = r#"[:find ?x :with ?y :where [?x :foo/bar ?y]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `datoms00`.e AS `?x` FROM `datoms` AS `datoms00` WHERE `datoms00`.a = 99");
assert_eq!(args, vec![]);
// Unknown type.
let query = r#"[:find ?x :with ?y :where [?x _ ?y]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `all_datoms00`.e AS `?x` FROM `all_datoms` AS `all_datoms00`");
assert_eq!(args, vec![]);
}
#[test]
fn test_order_by() {
let schema = prepopulated_schema();
// Known type.
let query = r#"[:find ?x :where [?x :foo/bar ?y] :order (desc ?y)]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `datoms00`.e AS `?x`, `datoms00`.v AS `?y` \
FROM `datoms` AS `datoms00` \
WHERE `datoms00`.a = 99 \
ORDER BY `?y` DESC");
assert_eq!(args, vec![]);
// Unknown type.
let query = r#"[:find ?x :with ?y :where [?x _ ?y] :order ?y ?x]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `all_datoms00`.e AS `?x`, `all_datoms00`.v AS `?y`, \
`all_datoms00`.value_type_tag AS `?y_value_type_tag` \
FROM `all_datoms` AS `all_datoms00` \
ORDER BY `?y_value_type_tag` ASC, `?y` ASC, `?x` ASC");
assert_eq!(args, vec![]);
}
#[test]
fn test_complex_nested_or_join_type_projection() {
let mut schema = Schema::default();
associate_ident(&mut schema, Keyword::namespaced("page", "title"), 98);
add_attribute(&mut schema, 98, Attribute {
value_type: ValueType::String,
..Default::default()
});
let input = r#"[:find [?y]
:where
(or
(or
[_ :page/title ?y])
(or
[_ :page/title ?y]))]"#;
let SQLQuery { sql, args } = translate(&schema, input);
assert_eq!(sql, "SELECT `c00`.`?y` AS `?y` \
FROM (SELECT `datoms00`.v AS `?y` \
FROM `datoms` AS `datoms00` \
WHERE `datoms00`.a = 98 \
UNION \
SELECT `datoms01`.v AS `?y` \
FROM `datoms` AS `datoms01` \
WHERE `datoms01`.a = 98) \
AS `c00` \
LIMIT 1");
assert_eq!(args, vec![]);
}
#[test]
fn test_ground_scalar() {
let schema = prepopulated_schema();
// Verify that we accept inline constants.
let query = r#"[:find ?x . :where [(ground "yyy") ?x]]"#;
let constant = translate_to_constant(&schema, query);
assert_eq!(constant.project_without_rows().unwrap()
.into_scalar().unwrap(),
Some(TypedValue::typed_string("yyy").into()));
// Verify that we accept bound input constants.
let query = r#"[:find ?x . :in ?v :where [(ground ?v) ?x]]"#;
let inputs = QueryInputs::with_value_sequence(vec![(Variable::from_valid_name("?v"), "aaa".into())]);
let constant = translate_with_inputs_to_constant(&schema, query, inputs);
assert_eq!(constant.project_without_rows().unwrap()
.into_scalar().unwrap(),
Some(TypedValue::typed_string("aaa").into()));
}
#[test]
fn test_ground_tuple() {
let schema = prepopulated_schema();
// Verify that we accept inline constants.
let query = r#"[:find ?x ?y :where [(ground [1 "yyy"]) [?x ?y]]]"#;
let constant = translate_to_constant(&schema, query);
assert_eq!(constant.project_without_rows().unwrap()
.into_rel().unwrap(),
vec![vec![TypedValue::Long(1), TypedValue::typed_string("yyy")]].into());
// Verify that we accept bound input constants.
let query = r#"[:find [?x ?y] :in ?u ?v :where [(ground [?u ?v]) [?x ?y]]]"#;
let inputs = QueryInputs::with_value_sequence(vec![(Variable::from_valid_name("?u"), TypedValue::Long(2)),
(Variable::from_valid_name("?v"), "aaa".into()),]);
let constant = translate_with_inputs_to_constant(&schema, query, inputs);
assert_eq!(constant.project_without_rows().unwrap()
.into_tuple().unwrap(),
Some(vec![TypedValue::Long(2).into(), TypedValue::typed_string("aaa").into()]));
// TODO: treat 2 as an input variable that could be bound late, rather than eagerly binding it.
// In that case the query wouldn't be constant, and would look more like:
// let SQLQuery { sql, args } = translate_with_inputs(&schema, query, inputs);
// assert_eq!(sql, "SELECT 2 AS `?x`, $v0 AS `?y` LIMIT 1");
// assert_eq!(args, vec![make_arg("$v0", "aaa"),]);
}
#[test]
fn test_ground_coll() {
let schema = prepopulated_schema();
// Verify that we accept inline constants.
let query = r#"[:find ?x :where [(ground ["xxx" "yyy"]) [?x ...]]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `c00`.`?x` AS `?x` FROM \
(SELECT 0 AS `?x` WHERE 0 UNION ALL VALUES ($v0), ($v1)) AS `c00`");
assert_eq!(args, vec![make_arg("$v0", "xxx"),
make_arg("$v1", "yyy")]);
// Verify that we accept bound input constants.
let query = r#"[:find ?x :in ?u ?v :where [(ground [?u ?v]) [?x ...]]]"#;
let inputs = QueryInputs::with_value_sequence(vec![(Variable::from_valid_name("?u"), TypedValue::Long(2)),
(Variable::from_valid_name("?v"), TypedValue::Long(3)),]);
let SQLQuery { sql, args } = translate_with_inputs(&schema, query, inputs);
// TODO: treat 2 and 3 as input variables that could be bound late, rather than eagerly binding.
assert_eq!(sql, "SELECT DISTINCT `c00`.`?x` AS `?x` FROM \
(SELECT 0 AS `?x` WHERE 0 UNION ALL VALUES (2), (3)) AS `c00`");
assert_eq!(args, vec![]);
}
#[test]
fn test_ground_rel() {
let schema = prepopulated_schema();
// Verify that we accept inline constants.
let query = r#"[:find ?x ?y :where [(ground [[1 "xxx"] [2 "yyy"]]) [[?x ?y]]]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `c00`.`?x` AS `?x`, `c00`.`?y` AS `?y` FROM \
(SELECT 0 AS `?x`, 0 AS `?y` WHERE 0 UNION ALL VALUES (1, $v0), (2, $v1)) AS `c00`");
assert_eq!(args, vec![make_arg("$v0", "xxx"),
make_arg("$v1", "yyy")]);
// Verify that we accept bound input constants.
let query = r#"[:find ?x ?y :in ?u ?v :where [(ground [[?u 1] [?v 2]]) [[?x ?y]]]]"#;
let inputs = QueryInputs::with_value_sequence(vec![(Variable::from_valid_name("?u"), TypedValue::Long(3)),
(Variable::from_valid_name("?v"), TypedValue::Long(4)),]);
let SQLQuery { sql, args } = translate_with_inputs(&schema, query, inputs);
// TODO: treat 3 and 4 as input variables that could be bound late, rather than eagerly binding.
assert_eq!(sql, "SELECT DISTINCT `c00`.`?x` AS `?x`, `c00`.`?y` AS `?y` FROM \
(SELECT 0 AS `?x`, 0 AS `?y` WHERE 0 UNION ALL VALUES (3, 1), (4, 2)) AS `c00`");
assert_eq!(args, vec![]);
}
#[test]
fn test_compound_with_ground() {
let schema = prepopulated_schema();
// Verify that we can use the resulting CCs as children in compound CCs.
let query = r#"[:find ?x :where (or [(ground "yyy") ?x]
[(ground "zzz") ?x])]"#;
let SQLQuery { sql, args } = translate(&schema, query);
// This is confusing because the computed tables (like `c00`) are numbered sequentially in each
// arm of the `or` rather than numbered globally. But SQLite scopes the names correctly, so it
// works. In the future, we might number the computed tables globally to make this more clear.
assert_eq!(sql, "SELECT DISTINCT `c00`.`?x` AS `?x` FROM (\
SELECT $v0 AS `?x` UNION \
SELECT $v1 AS `?x`) AS `c00`");
assert_eq!(args, vec![make_arg("$v0", "yyy"),
make_arg("$v1", "zzz"),]);
// Verify that we can use ground to constrain the bindings produced by earlier clauses.
let query = r#"[:find ?x . :where [_ :foo/bar ?x] [(ground "yyy") ?x]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT $v0 AS `?x` FROM `datoms` AS `datoms00` \
WHERE `datoms00`.a = 99 AND `datoms00`.v = $v0 LIMIT 1");
assert_eq!(args, vec![make_arg("$v0", "yyy")]);
// Verify that we can further constrain the bindings produced by our clause.
let query = r#"[:find ?x . :where [(ground "yyy") ?x] [_ :foo/bar ?x]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT $v0 AS `?x` FROM `datoms` AS `datoms00` \
WHERE `datoms00`.a = 99 AND `datoms00`.v = $v0 LIMIT 1");
assert_eq!(args, vec![make_arg("$v0", "yyy")]);
}
#[test]
fn test_unbound_attribute_with_ground_entity() {
let query = r#"[:find ?x ?v :where [?x _ ?v] (not [(ground 17) ?x])]"#;
let schema = prepopulated_schema();
let SQLQuery { sql, .. } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `all_datoms00`.e AS `?x`, \
`all_datoms00`.v AS `?v`, \
`all_datoms00`.value_type_tag AS `?v_value_type_tag` \
FROM `all_datoms` AS `all_datoms00` \
WHERE NOT EXISTS (SELECT 1 WHERE `all_datoms00`.e = 17)");
}
#[test]
fn test_unbound_attribute_with_ground() {
let query = r#"[:find ?x ?v :where [?x _ ?v] (not [(ground 17) ?v])]"#;
let schema = prepopulated_schema();
let SQLQuery { sql, .. } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `all_datoms00`.e AS `?x`, \
`all_datoms00`.v AS `?v`, \
`all_datoms00`.value_type_tag AS `?v_value_type_tag` \
FROM `all_datoms` AS `all_datoms00` \
WHERE NOT EXISTS (SELECT 1 WHERE `all_datoms00`.v = 17 AND \
(`all_datoms00`.value_type_tag = 5))");
}
#[test]
fn test_not_with_ground() {
let mut schema = prepopulated_schema();
associate_ident(&mut schema, Keyword::namespaced("db", "valueType"), 7);
associate_ident(&mut schema, Keyword::namespaced("db.type", "ref"), 23);
associate_ident(&mut schema, Keyword::namespaced("db.type", "bool"), 28);
associate_ident(&mut schema, Keyword::namespaced("db.type", "instant"), 29);
add_attribute(&mut schema, 7, Attribute {
value_type: ValueType::Ref,
multival: false,
..Default::default()
});
// Scalar.
// TODO: this kind of simple `not` should be implemented without the subquery. #476.
let query = r#"[:find ?x :where [?x :db/valueType ?v] (not [(ground :db.type/instant) ?v])]"#;
let SQLQuery { sql, .. } = translate(&schema, query);
assert_eq!(sql,
"SELECT DISTINCT `datoms00`.e AS `?x` FROM `datoms` AS `datoms00` WHERE `datoms00`.a = 7 AND NOT \
EXISTS (SELECT 1 WHERE `datoms00`.v = 29)");
// Coll.
// TODO: we can generate better SQL for this, too. #476.
let query = r#"[:find ?x :where [?x :db/valueType ?v] (not [(ground [:db.type/bool :db.type/instant]) [?v ...]])]"#;
let SQLQuery { sql, .. } = translate(&schema, query);
assert_eq!(sql,
"SELECT DISTINCT `datoms00`.e AS `?x` FROM `datoms` AS `datoms00` \
WHERE `datoms00`.a = 7 AND NOT EXISTS \
(SELECT 1 FROM (SELECT 0 AS `?v` WHERE 0 UNION ALL VALUES (28), (29)) AS `c00` \
WHERE `datoms00`.v = `c00`.`?v`)");
}
#[test]
fn test_fulltext() {
let schema = prepopulated_typed_schema(ValueType::Double);
let query = r#"[:find ?entity ?value ?tx ?score :where [(fulltext $ :foo/fts "needle") [[?entity ?value ?tx ?score]]]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `datoms01`.e AS `?entity`, \
`fulltext_values00`.text AS `?value`, \
`datoms01`.tx AS `?tx`, \
0e0 AS `?score` \
FROM `fulltext_values` AS `fulltext_values00`, \
`datoms` AS `datoms01` \
WHERE `datoms01`.a = 100 \
AND `datoms01`.v = `fulltext_values00`.rowid \
AND `fulltext_values00`.text MATCH $v0");
assert_eq!(args, vec![make_arg("$v0", "needle"),]);
let query = r#"[:find ?entity ?value ?tx :where [(fulltext $ :foo/fts "needle") [[?entity ?value ?tx ?score]]]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
// Observe that the computed table isn't dropped, even though `?score` isn't bound in the final conjoining clause.
assert_eq!(sql, "SELECT DISTINCT `datoms01`.e AS `?entity`, \
`fulltext_values00`.text AS `?value`, \
`datoms01`.tx AS `?tx` \
FROM `fulltext_values` AS `fulltext_values00`, \
`datoms` AS `datoms01` \
WHERE `datoms01`.a = 100 \
AND `datoms01`.v = `fulltext_values00`.rowid \
AND `fulltext_values00`.text MATCH $v0");
assert_eq!(args, vec![make_arg("$v0", "needle"),]);
let query = r#"[:find ?entity ?value ?tx :where [(fulltext $ :foo/fts "needle") [[?entity ?value ?tx _]]]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
// Observe that the computed table isn't included at all when `?score` isn't bound.
assert_eq!(sql, "SELECT DISTINCT `datoms01`.e AS `?entity`, \
`fulltext_values00`.text AS `?value`, \
`datoms01`.tx AS `?tx` \
FROM `fulltext_values` AS `fulltext_values00`, \
`datoms` AS `datoms01` \
WHERE `datoms01`.a = 100 \
AND `datoms01`.v = `fulltext_values00`.rowid \
AND `fulltext_values00`.text MATCH $v0");
assert_eq!(args, vec![make_arg("$v0", "needle"),]);
let query = r#"[:find ?entity ?value ?tx :where [(fulltext $ :foo/fts "needle") [[?entity ?value ?tx ?score]]] [?entity :foo/bar ?score]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `datoms01`.e AS `?entity`, \
`fulltext_values00`.text AS `?value`, \
`datoms01`.tx AS `?tx` \
FROM `fulltext_values` AS `fulltext_values00`, \
`datoms` AS `datoms01`, \
`datoms` AS `datoms02` \
WHERE `datoms01`.a = 100 \
AND `datoms01`.v = `fulltext_values00`.rowid \
AND `fulltext_values00`.text MATCH $v0 \
AND `datoms02`.a = 99 \
AND `datoms02`.v = 0e0 \
AND `datoms01`.e = `datoms02`.e");
assert_eq!(args, vec![make_arg("$v0", "needle"),]);
let query = r#"[:find ?entity ?value ?tx :where [?entity :foo/bar ?score] [(fulltext $ :foo/fts "needle") [[?entity ?value ?tx ?score]]]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `datoms00`.e AS `?entity`, \
`fulltext_values01`.text AS `?value`, \
`datoms02`.tx AS `?tx` \
FROM `datoms` AS `datoms00`, \
`fulltext_values` AS `fulltext_values01`, \
`datoms` AS `datoms02` \
WHERE `datoms00`.a = 99 \
AND `datoms02`.a = 100 \
AND `datoms02`.v = `fulltext_values01`.rowid \
AND `fulltext_values01`.text MATCH $v0 \
AND `datoms00`.v = 0e0 \
AND `datoms00`.e = `datoms02`.e");
assert_eq!(args, vec![make_arg("$v0", "needle"),]);
}
#[test]
fn test_fulltext_inputs() {
let schema = prepopulated_typed_schema(ValueType::String);
// Bind ?entity. We expect the output to collide.
let query = r#"[:find ?val
:in ?entity
:where [(fulltext $ :foo/fts "hello") [[?entity ?val _ _]]]]"#;
let mut types = BTreeMap::default();
types.insert(Variable::from_valid_name("?entity"), ValueType::Ref);
let inputs = QueryInputs::new(types, BTreeMap::default()).expect("valid inputs");
// Without binding the value. q_once will err if you try this!
let SQLQuery { sql, args } = translate_with_inputs(&schema, query, inputs);
assert_eq!(sql, "SELECT DISTINCT `fulltext_values00`.text AS `?val` \
FROM \
`fulltext_values` AS `fulltext_values00`, \
`datoms` AS `datoms01` \
WHERE `datoms01`.a = 100 \
AND `datoms01`.v = `fulltext_values00`.rowid \
AND `fulltext_values00`.text MATCH $v0");
assert_eq!(args, vec![make_arg("$v0", "hello"),]);
// With the value bound.
let inputs = QueryInputs::with_value_sequence(vec![(Variable::from_valid_name("?entity"), TypedValue::Ref(111))]);
let SQLQuery { sql, args } = translate_with_inputs(&schema, query, inputs);
assert_eq!(sql, "SELECT DISTINCT `fulltext_values00`.text AS `?val` \
FROM \
`fulltext_values` AS `fulltext_values00`, \
`datoms` AS `datoms01` \
WHERE `datoms01`.a = 100 \
AND `datoms01`.v = `fulltext_values00`.rowid \
AND `fulltext_values00`.text MATCH $v0 \
AND `datoms01`.e = 111");
assert_eq!(args, vec![make_arg("$v0", "hello"),]);
// Same again, but retrieving the entity.
let query = r#"[:find ?entity .
:in ?entity
:where [(fulltext $ :foo/fts "hello") [[?entity _ _]]]]"#;
let inputs = QueryInputs::with_value_sequence(vec![(Variable::from_valid_name("?entity"), TypedValue::Ref(111))]);
let SQLQuery { sql, args } = translate_with_inputs(&schema, query, inputs);
assert_eq!(sql, "SELECT 111 AS `?entity` FROM \
`fulltext_values` AS `fulltext_values00`, \
`datoms` AS `datoms01` \
WHERE `datoms01`.a = 100 \
AND `datoms01`.v = `fulltext_values00`.rowid \
AND `fulltext_values00`.text MATCH $v0 \
AND `datoms01`.e = 111 \
LIMIT 1");
assert_eq!(args, vec![make_arg("$v0", "hello"),]);
// A larger pattern.
let query = r#"[:find ?entity ?value ?friend
:in ?entity
:where
[(fulltext $ :foo/fts "hello") [[?entity ?value]]]
[?entity :foo/bar ?friend]]"#;
let inputs = QueryInputs::with_value_sequence(vec![(Variable::from_valid_name("?entity"), TypedValue::Ref(121))]);
let SQLQuery { sql, args } = translate_with_inputs(&schema, query, inputs);
assert_eq!(sql, "SELECT DISTINCT 121 AS `?entity`, \
`fulltext_values00`.text AS `?value`, \
`datoms02`.v AS `?friend` \
FROM \
`fulltext_values` AS `fulltext_values00`, \
`datoms` AS `datoms01`, \
`datoms` AS `datoms02` \
WHERE `datoms01`.a = 100 \
AND `datoms01`.v = `fulltext_values00`.rowid \
AND `fulltext_values00`.text MATCH $v0 \
AND `datoms01`.e = 121 \
AND `datoms02`.e = 121 \
AND `datoms02`.a = 99");
assert_eq!(args, vec![make_arg("$v0", "hello"),]);
}
#[test]
fn test_instant_range() {
let schema = prepopulated_typed_schema(ValueType::Instant);
let query = r#"[:find ?e
:where
[?e :foo/bar ?t]
[(> ?t #inst "2017-06-16T00:56:41.257Z")]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `datoms00`.e AS `?e` \
FROM \
`datoms` AS `datoms00` \
WHERE `datoms00`.a = 99 \
AND `datoms00`.v > 1497574601257000");
assert_eq!(args, vec![]);
}
#[test]
fn test_project_aggregates() {
let schema = prepopulated_typed_schema(ValueType::Long);
let query = r#"[:find ?e (max ?t)
:where
[?e :foo/bar ?t]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
// No outer DISTINCT: we aggregate or group by every variable.
assert_eq!(sql, "SELECT * \
FROM \
(SELECT `?e` AS `?e`, max(`?t`) AS `(max ?t)` \
FROM \
(SELECT DISTINCT \
`datoms00`.e AS `?e`, \
`datoms00`.v AS `?t` \
FROM `datoms` AS `datoms00` \
WHERE `datoms00`.a = 99) \
GROUP BY `?e`) \
WHERE `(max ?t)` IS NOT NULL");
assert_eq!(args, vec![]);
let query = r#"[:find (max ?t)
:with ?e
:where
[?e :foo/bar ?t]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT * \
FROM \
(SELECT max(`?t`) AS `(max ?t)` \
FROM \
(SELECT DISTINCT \
`datoms00`.v AS `?t`, \
`datoms00`.e AS `?e` \
FROM `datoms` AS `datoms00` \
WHERE `datoms00`.a = 99)\
) \
WHERE `(max ?t)` IS NOT NULL");
assert_eq!(args, vec![]);
// ORDER BY lifted to outer query if there is no LIMIT.
let query = r#"[:find (max ?x)
:with ?e
:where
[?e ?a ?t]
[?t :foo/bar ?x]
:order ?a]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT * \
FROM \
(SELECT max(`?x`) AS `(max ?x)`, `?a` AS `?a` \
FROM \
(SELECT DISTINCT \
`datoms01`.v AS `?x`, \
`datoms00`.a AS `?a`, \
`datoms00`.e AS `?e` \
FROM `datoms` AS `datoms00`, `datoms` AS `datoms01` \
WHERE `datoms01`.a = 99 AND `datoms00`.v = `datoms01`.e) \
GROUP BY `?a`) \
WHERE `(max ?x)` IS NOT NULL \
ORDER BY `?a` ASC");
assert_eq!(args, vec![]);
// ORDER BY duplicated in outer query if there is a LIMIT.
let query = r#"[:find (max ?x)
:with ?e
:where
[?e ?a ?t]
[?t :foo/bar ?x]
:order (desc ?a)
:limit 10]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT * \
FROM \
(SELECT max(`?x`) AS `(max ?x)`, `?a` AS `?a` \
FROM \
(SELECT DISTINCT \
`datoms01`.v AS `?x`, \
`datoms00`.a AS `?a`, \
`datoms00`.e AS `?e` \
FROM `datoms` AS `datoms00`, `datoms` AS `datoms01` \
WHERE `datoms01`.a = 99 AND `datoms00`.v = `datoms01`.e) \
GROUP BY `?a` \
ORDER BY `?a` DESC \
LIMIT 10) \
WHERE `(max ?x)` IS NOT NULL \
ORDER BY `?a` DESC");
assert_eq!(args, vec![]);
// No outer SELECT * for non-nullable aggregates.
let query = r#"[:find (count ?t)
:with ?e
:where
[?e :foo/bar ?t]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT count(`?t`) AS `(count ?t)` \
FROM \
(SELECT DISTINCT \
`datoms00`.v AS `?t`, \
`datoms00`.e AS `?e` \
FROM `datoms` AS `datoms00` \
WHERE `datoms00`.a = 99)");
assert_eq!(args, vec![]);
}
#[test]
fn test_project_the() {
let schema = prepopulated_typed_schema(ValueType::Long);
let query = r#"[:find (the ?e) (max ?t)
:where
[?e :foo/bar ?t]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
// We shouldn't NULL-check (the).
assert_eq!(sql, "SELECT * \
FROM \
(SELECT `?e` AS `?e`, max(`?t`) AS `(max ?t)` \
FROM \
(SELECT DISTINCT \
`datoms00`.e AS `?e`, \
`datoms00`.v AS `?t` \
FROM `datoms` AS `datoms00` \
WHERE `datoms00`.a = 99)) \
WHERE `(max ?t)` IS NOT NULL");
assert_eq!(args, vec![]);
}
#[test]
fn test_tx_before_and_after() {
let schema = prepopulated_typed_schema(ValueType::Long);
let query = r#"[:find ?x :where [?x _ _ ?tx] [(tx-after ?tx 12345)]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT \
`datoms00`.e AS `?x` \
FROM `datoms` AS `datoms00` \
WHERE `datoms00`.tx > 12345");
assert_eq!(args, vec![]);
let query = r#"[:find ?x :where [?x _ _ ?tx] [(tx-before ?tx 12345)]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT \
`datoms00`.e AS `?x` \
FROM `datoms` AS `datoms00` \
WHERE `datoms00`.tx < 12345");
assert_eq!(args, vec![]);
}
#[test]
fn test_tx_ids() {
let mut schema = prepopulated_typed_schema(ValueType::Double);
associate_ident(&mut schema, Keyword::namespaced("db", "txInstant"), 101);
add_attribute(&mut schema, 101, Attribute {
value_type: ValueType::Instant,
multival: false,
index: true,
..Default::default()
});
let query = r#"[:find ?tx :where [(tx-ids $ 1000 2000) [[?tx]]]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `transactions00`.tx AS `?tx` \
FROM `transactions` AS `transactions00` \
WHERE 1000 <= `transactions00`.tx \
AND `transactions00`.tx < 2000");
assert_eq!(args, vec![]);
// This is rather artificial but verifies that binding the arguments to (tx-ids) works.
let query = r#"[:find ?tx :where [?first :db/txInstant #inst "2016-01-01T11:00:00.000Z"] [?last :db/txInstant #inst "2017-01-01T11:00:00.000Z"] [(tx-ids $ ?first ?last) [?tx ...]]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `transactions02`.tx AS `?tx` \
FROM `datoms` AS `datoms00`, \
`datoms` AS `datoms01`, \
`transactions` AS `transactions02` \
WHERE `datoms00`.a = 101 \
AND `datoms00`.v = 1451646000000000 \
AND `datoms01`.a = 101 \
AND `datoms01`.v = 1483268400000000 \
AND `datoms00`.e <= `transactions02`.tx \
AND `transactions02`.tx < `datoms01`.e");
assert_eq!(args, vec![]);
// In practice the following query would be inefficient because of the filter on all_datoms.tx,
// but that is what (tx-data) is for.
let query = r#"[:find ?e ?a ?v ?tx :where [(tx-ids $ 1000 2000) [[?tx]]] [?e ?a ?v ?tx]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `all_datoms01`.e AS `?e`, \
`all_datoms01`.a AS `?a`, \
`all_datoms01`.v AS `?v`, \
`all_datoms01`.value_type_tag AS `?v_value_type_tag`, \
`transactions00`.tx AS `?tx` \
FROM `transactions` AS `transactions00`, \
`all_datoms` AS `all_datoms01` \
WHERE 1000 <= `transactions00`.tx \
AND `transactions00`.tx < 2000 \
AND `transactions00`.tx = `all_datoms01`.tx");
assert_eq!(args, vec![]);
}
#[test]
fn test_tx_data() {
let schema = prepopulated_typed_schema(ValueType::Double);
let query = r#"[:find ?e ?a ?v ?tx ?added :where [(tx-data $ 1000) [[?e ?a ?v ?tx ?added]]]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `transactions00`.e AS `?e`, \
`transactions00`.a AS `?a`, \
`transactions00`.v AS `?v`, \
`transactions00`.value_type_tag AS `?v_value_type_tag`, \
`transactions00`.tx AS `?tx`, \
`transactions00`.added AS `?added` \
FROM `transactions` AS `transactions00` \
WHERE `transactions00`.tx = 1000");
assert_eq!(args, vec![]);
// Ensure that we don't project columns that we don't need, even if they are bound to named
// variables or to placeholders.
let query = r#"[:find [?a ?v ?added] :where [(tx-data $ 1000) [[?e ?a ?v _ ?added]]]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT `transactions00`.a AS `?a`, \
`transactions00`.v AS `?v`, \
`transactions00`.value_type_tag AS `?v_value_type_tag`, \
`transactions00`.added AS `?added` \
FROM `transactions` AS `transactions00` \
WHERE `transactions00`.tx = 1000 \
LIMIT 1");
assert_eq!(args, vec![]);
// This is awkward since the transactions table is queried twice, once to list transaction IDs
// and a second time to extract data. https://github.com/mozilla/mentat/issues/644 tracks
// improving this, perhaps by optimizing certain combinations of functions and bindings.
let query = r#"[:find ?e ?a ?v ?tx ?added :where [(tx-ids $ 1000 2000) [[?tx]]] [(tx-data $ ?tx) [[?e ?a ?v _ ?added]]]]"#;
let SQLQuery { sql, args } = translate(&schema, query);
assert_eq!(sql, "SELECT DISTINCT `transactions01`.e AS `?e`, \
`transactions01`.a AS `?a`, \
`transactions01`.v AS `?v`, \
`transactions01`.value_type_tag AS `?v_value_type_tag`, \
`transactions00`.tx AS `?tx`, \
`transactions01`.added AS `?added` \
FROM `transactions` AS `transactions00`, \
`transactions` AS `transactions01` \
WHERE 1000 <= `transactions00`.tx \
AND `transactions00`.tx < 2000 \
AND `transactions01`.tx = `transactions00`.tx");
assert_eq!(args, vec![]);
}<|fim▁end|> | /// https://github.com/rust-lang/rust/issues/29638. |
<|file_name|>fstimer.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
import fstimer.fslogger
import fstimer.timer
from gi.repository import Gtk
<|fim▁hole|>def main():
pytimer = fstimer.timer.PyTimer()
Gtk.main()
if __name__ == '__main__':
main()<|fim▁end|> | |
<|file_name|>borrowck-pat-enum.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn match_ref(v: Option<int>) -> int {
match v {
Some(ref i) => {
*i
}
None => {0}
}
}
fn match_ref_unused(v: Option<int>) {
match v {
Some(_) => {}
None => {}
}
}
fn match_const_reg(v: &const Option<int>) -> int {
match *v {
Some(ref i) => {*i} //~ ERROR cannot borrow
//~^ ERROR unsafe borrow
None => {0}
}
}
fn impure(_i: int) {
}
fn match_const_reg_unused(v: &const Option<int>) {
match *v {
Some(_) => {impure(0)} // OK because nothing is captured
None => {}
}
}
fn match_const_reg_impure(v: &const Option<int>) {
match *v {
Some(ref i) => {impure(*i)} //~ ERROR cannot borrow<|fim▁hole|> None => {}
}
}
fn match_imm_reg(v: &Option<int>) {
match *v {
Some(ref i) => {impure(*i)} // OK because immutable
None => {}
}
}
fn match_mut_reg(v: &mut Option<int>) {
match *v {
Some(ref i) => {impure(*i)} // OK, frozen
None => {}
}
}
fn main() {
}<|fim▁end|> | //~^ ERROR unsafe borrow |
<|file_name|>radio.rs<|end_file_name|><|fim▁begin|>use crate::direction::Direction;
use crate::event::{Event, EventResult, Key, MouseButton, MouseEvent};
use crate::theme::ColorStyle;
use crate::view::View;
use crate::Cursive;
use crate::Vec2;
use crate::{Printer, With};
use std::cell::RefCell;
use std::rc::Rc;
struct SharedState<T> {
selection: usize,
values: Vec<Rc<T>>,
on_change: Option<Rc<dyn Fn(&mut Cursive, &T)>>,
}
impl<T> SharedState<T> {
pub fn selection(&self) -> Rc<T> {
Rc::clone(&self.values[self.selection])
}
}
/// Group to coordinate multiple radio buttons.
///
/// A `RadioGroup` is used to create and manage [`RadioButton`]s.
///
/// A `RadioGroup` can be cloned; it will keep pointing to the same group.
#[derive(Clone)]
pub struct RadioGroup<T> {
// Given to every child button
state: Rc<RefCell<SharedState<T>>>,
}
impl<T: 'static> Default for RadioGroup<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: 'static> RadioGroup<T> {
/// Creates an empty group for radio buttons.
pub fn new() -> Self {
RadioGroup {
state: Rc::new(RefCell::new(SharedState {
selection: 0,
values: Vec::new(),
on_change: None,
})),
}
}
/// Adds a new button to the group.
///
/// The button will display `label` next to it, and will embed `value`.
pub fn button<S: Into<String>>(
&mut self,
value: T,
label: S,
) -> RadioButton<T> {
let count = self.state.borrow().values.len();
self.state.borrow_mut().values.push(Rc::new(value));
RadioButton::new(Rc::clone(&self.state), count, label.into())
}
/// Returns the id of the selected button.
///
/// Buttons are indexed in the order they are created, starting from 0.
pub fn selected_id(&self) -> usize {
self.state.borrow().selection
}
/// Returns the value associated with the selected button.
pub fn selection(&self) -> Rc<T> {
self.state.borrow().selection()
}
/// Sets a callback to be used when the selection changes.
pub fn set_on_change<F: 'static + Fn(&mut Cursive, &T)>(
&mut self,
on_change: F,
) {
self.state.borrow_mut().on_change = Some(Rc::new(on_change));
}
/// Sets a callback to be used when the selection changes.
///
/// Chainable variant.
pub fn on_change<F: 'static + Fn(&mut Cursive, &T)>(
self,
on_change: F,
) -> Self {
self.with(|s| s.set_on_change(on_change))
}
}
<|fim▁hole|> text: S,
) -> RadioButton<String> {
let text = text.into();
self.button(text.clone(), text)
}
}
/// Variant of `Checkbox` arranged in group.
///
/// `RadioButton`s are managed by a [`RadioGroup`]. A single group can contain
/// several radio buttons, but only one button per group can be active at a
/// time.
///
/// `RadioButton`s are not created directly, but through
/// [`RadioGroup::button`].
///
pub struct RadioButton<T> {
state: Rc<RefCell<SharedState<T>>>,
id: usize,
enabled: bool,
label: String,
}
impl<T: 'static> RadioButton<T> {
impl_enabled!(self.enabled);
fn new(
state: Rc<RefCell<SharedState<T>>>,
id: usize,
label: String,
) -> Self {
RadioButton {
state,
id,
enabled: true,
label,
}
}
/// Returns `true` if this button is selected.
pub fn is_selected(&self) -> bool {
self.state.borrow().selection == self.id
}
/// Selects this button, un-selecting any other in the same group.
pub fn select(&mut self) -> EventResult {
let mut state = self.state.borrow_mut();
state.selection = self.id;
if let Some(ref on_change) = state.on_change {
let on_change = Rc::clone(on_change);
let value = state.selection();
EventResult::with_cb(move |s| on_change(s, &value))
} else {
EventResult::Consumed(None)
}
}
/// Selects this button, un-selecting any other in the same group.
///
/// Chainable variant.
pub fn selected(self) -> Self {
self.with(|s| {
// Ignore the potential callback here
s.select();
})
}
fn draw_internal(&self, printer: &Printer) {
printer.print((0, 0), "( )");
if self.is_selected() {
printer.print((1, 0), "X");
}
if !self.label.is_empty() {
// We want the space to be highlighted if focused
printer.print((3, 0), " ");
printer.print((4, 0), &self.label);
}
}
fn req_size(&self) -> Vec2 {
if self.label.is_empty() {
Vec2::new(3, 1)
} else {
Vec2::new(3 + 1 + self.label.len(), 1)
}
}
}
impl<T: 'static> View for RadioButton<T> {
fn required_size(&mut self, _: Vec2) -> Vec2 {
self.req_size()
}
fn take_focus(&mut self, _: Direction) -> bool {
self.enabled
}
fn draw(&self, printer: &Printer) {
if self.enabled && printer.enabled {
printer.with_selection(printer.focused, |printer| {
self.draw_internal(printer)
});
} else {
printer.with_color(ColorStyle::secondary(), |printer| {
self.draw_internal(printer)
});
}
}
fn on_event(&mut self, event: Event) -> EventResult {
if !self.enabled {
return EventResult::Ignored;
}
match event {
Event::Key(Key::Enter) | Event::Char(' ') => self.select(),
Event::Mouse {
event: MouseEvent::Release(MouseButton::Left),
position,
offset,
} if position.fits_in_rect(offset, self.req_size()) => {
self.select()
}
_ => EventResult::Ignored,
}
}
}<|fim▁end|> | impl RadioGroup<String> {
/// Adds a button, using the label itself as value.
pub fn button_str<S: Into<String>>(
&mut self, |
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls import url
from django.contrib.auth import views as auth_views
from django.views.generic import TemplateView
from . import views
app_name = 'web'
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name="front.html"), name='front'),
url(r'^index$', views.IndexView.as_view(), name='index'),
# Accounts
url('^accounts/login/',
auth_views.login,
{'template_name': 'login.html'},
name="login"),
url('^accounts/logout/', auth_views.logout, name="logout"),
url('^accounts/change/',
auth_views.password_change,
name="password_change"),
url('^accounts/register/', views.UserRegister.as_view(), name="register"),
# url('^accounts/profile/', views.UserProfile.as_view(), name="user_profile"),
# Product
url(r'^products/(\?type=.*)?$', views.ProductListView.as_view(),
name='product_list'),
url(r'^product/(?P<pk>\d+)/$', views.ProductView.as_view(),
name='product'),
url(r'^product/new/$', views.ProductCreate.as_view(),
name='product_create'),
url(r'^product/update/(?P<pk>\d+)/$', views.ProductUpdate.as_view(),
name='product_update'),
url(r'^product/delete/(?P<pk>\d+)/$', views.ProductDelete.as_view(),
name='product_delete'),
<|fim▁hole|> name='brand_list'),
url(r'^brand/(?P<pk>\d+)/$', views.BrandView.as_view(),
name='brand'),
url(r'^brand/new/$', views.BrandCreate.as_view(),
name='brand_create'),
url(r'^brand/update/(?P<pk>\d+)/$', views.BrandUpdate.as_view(),
name='brand_update'),
url(r'^brand/delete/(?P<pk>\d+)/$', views.BrandDelete.as_view(),
name='brand_delete'),
# Component
url(r'^components/$', views.ComponentListView.as_view(),
name='component_list'),
url(r'^component/(?P<pk>\d+)/$', views.ComponentView.as_view(),
name='component'),
url(r'^component/new/$', views.ComponentCreate.as_view(),
name='component_create'),
url(r'^component/update/(?P<pk>\d+)/$', views.ComponentUpdate.as_view(),
name='component_update'),
url(r'^component/delete/(?P<pk>\d+)/$', views.ComponentDelete.as_view(),
name='component_delete'),
]<|fim▁end|> | # Brand
url(r'^brands/$', views.BrandListView.as_view(), |
<|file_name|>sf2.js<|end_file_name|><|fim▁begin|>define(['js/util'], function (util) {
"use strict";
var sf2 = {};
sf2.createFromArrayBuffer = function(ab) {
var that = {
riffHeader: null,
sfbk: {}
};
var ar = util.ArrayReader(ab);
var sfGenerator = [
"startAddrsOffset", // 0
"endAddrsOffset", // 1
"startloopAddrsOffset", // 2
"endloopAddrsOffset", // 3
"startAddrsCoarseOffset", // 4
"modLfoToPitch", // 5
"vibLfoToPitch", // 6
"modEnvToPitch", // 7
"initialFilterFc", // 8
"initialFilterQ", // 9
"modLfoToFilterFc", // 10
"modEnvToFilterFc", // 11
"endAddrsCoarseOffset", // 12
"modLfoToVolume", // 13
"unused1",
"chorusEffectsSend", // 15
"reverbEffectsSend", // 16
"pan", // 17
"unused2",
"unused3",
"unused4",
"delayModLFO", // 21
"freqModLFO", // 22
"delayVibLFO", // 23
"freqVibLFO", // 24
"delayModEnv", // 25
"attackModEnv", // 26
"holdModEnv", // 27
"decayModEnv", // 28
"sustainModEnv", // 29
"releaseModEnv", // 30
"keynumToModEnvHold", // 31
"keynumToModEnvDecay", // 32
"delayVolEnv", // 33
"attackVolEnv", // 34
"holdVolEnv", // 35
"decayVolEnv", // 36
"sustainVolEnv", // 37
"releaseVolEnv", // 38
"keynumToVolEnvHold", // 39
"keynumToVolEnvDecay", // 40
"instrument", // 41: PGEN Terminator
"reserved1",
"keyRange", // 43
"velRange", // 44
"startloopAddrsCoarseOffset", // 45
"keynum", // 46
"velocity", // 47
"initialAttenuation", // 48
"reserved2",
"endloopAddrsCoarseOffset", // 50
"coarseTune", // 51
"fineTune", // 52
"sampleID", // 53: IGEN Terminator
"sampleModes", // 54
"reserved3",
"scaleTuning", // 56
"exclusiveClass", // 57
"overridingRootKey", // 58
"unused5",
"endOper"
];
that.parseHeader = function () {
// read RIFF header
that.riffHeader = parseHeader();
that.size = that.riffHeader.length + 8;
// read level1 header
ar.seek(that.riffHeader.headPosition);
that.sfbk = {};
that.sfbk.ID = ar.readStringF(4);
// read level2 header
that.sfbk.INFO = parseHeader();
// read level3 header
// 3.1 INFO
ar.seek(that.sfbk.INFO.headPosition);
that.sfbk.INFO.ID = ar.readStringF(4);
that.sfbk.INFO.child = {};
while(ar.position() < that.sfbk.INFO.headPosition + that.sfbk.INFO.length) {
var head = parseHeader();
that.sfbk.INFO.child[head.ID] = head;
}
// 3.2 sdta
ar.seek(that.sfbk.INFO.headPosition + that.sfbk.INFO.padLength);
that.sfbk.sdta = parseHeader();
ar.seek(that.sfbk.sdta.headPosition);
that.sfbk.sdta.ID = ar.readStringF(4);
that.sfbk.sdta.child = {};
while(ar.position() < that.sfbk.sdta.headPosition + that.sfbk.sdta.length) {
head = parseHeader();
that.sfbk.sdta.child[head.ID] = head;
}
// 3.3 pdta
ar.seek(that.sfbk.sdta.headPosition + that.sfbk.sdta.padLength);
that.sfbk.pdta = parseHeader();
ar.seek(that.sfbk.pdta.headPosition);
that.sfbk.pdta.ID = ar.readStringF(4);
that.sfbk.pdta.child = {};
while(ar.position() < that.sfbk.pdta.headPosition + that.sfbk.pdta.length) {
head = parseHeader();
that.sfbk.pdta.child[head.ID] = head;
}
// read level4 data
// 4.1 PHDR data
var phdr = that.sfbk.pdta.child.phdr;
phdr.data = [];
ar.seek(phdr.headPosition);
while(ar.position() < phdr.headPosition + phdr.length) {
var data = {};
data.presetName = ar.readStringF(20);
data.preset = ar.readUInt16();
data.bank = ar.readUInt16();
data.presetBagNdx = ar.readUInt16();
data.library = ar.readUInt32();
data.genre = ar.readUInt32();
data.morphology = ar.readUInt32();
phdr.data.push(data);
}
// set placeholder
that.sfbk.pdta.child.pbag.data = [];
that.sfbk.pdta.child.pgen.data = [];
that.sfbk.pdta.child.pmod.data = [];
that.sfbk.pdta.child.inst.data = [];
that.sfbk.pdta.child.ibag.data = [];
that.sfbk.pdta.child.igen.data = [];
that.sfbk.pdta.child.imod.data = [];
that.sfbk.pdta.child.shdr.data = [];
};
that.readPreset = function(n) {
var phdr = that.sfbk.pdta.child.phdr;
var pbag = that.sfbk.pdta.child.pbag;
var r = {
presetName: phdr.data[n].presetName,
preset: phdr.data[n].preset,
bank: phdr.data[n].bank,
gen: [],
mod: []
}
// PBAGs
var pgen_global = {
keyRange: { lo: 0, hi: 127 },
velRange: { lo: 1, hi: 127 }
};
var pmod_global = [];
for(var i = phdr.data[n].presetBagNdx; i < phdr.data[n + 1].presetBagNdx; i++) {
var pbag0 = parsePBAG1(ar, pbag, i);
var pbag1 = parsePBAG1(ar, pbag, i + 1);
var pmod = readPMOD1(pbag0.modNdx, pbag1.modNdx, pmod_global);
var pmod_local = Array.prototype.concat(pmod_global, pmod);
var pgen = readPGEN1(pbag0.genNdx, pbag1.genNdx, pgen_global, pmod_local);
if(pgen["instrument"] === undefined) {
pgen_global = pgen;
pmod_global = pmod;
} else {
r.gen = Array.prototype.concat(r.gen, pgen.instrument.ibag.igen);
r.mod = Array.prototype.concat(r.mod, pgen.instrument.ibag.imod);
}
// r.mod.push(readPMOD1(pbag0.modNdx, pbag1.modNdx));
}
return r;
};
that.enumPresets = function() {
var p = [];
var phdr = that.sfbk.pdta.child.phdr;
phdr.data.forEach(function(ph) { p.push(ph.presetName); });
return p;
};
that.readSDTA = function(pos) {
ar.seek(that.sfbk.sdta.child.smpl.headPosition + pos * 2);
return ar.readInt16() / 32768;
}
that.readSDTAChunk = function(b, e) {
return new Int16Array(new Uint8Array(ar.subarray(
that.sfbk.sdta.child.smpl.headPosition + b * 2,
that.sfbk.sdta.child.smpl.headPosition + e * 2
)).buffer);
}
var readPGEN1 = function(b, e, g, gm) {
var pgen = that.sfbk.pdta.child.pgen;
var global = _.O(g, true);
var global_m = _.O(gm, true);
var result = _.O(g, true);
if(b != e) {
for(var i = b; i < e; i++) {
var r = parsePGEN1(ar, pgen, i);
if(r.inst == "instrument") {
global = _.O(result, true);
result[r.inst] = readINST1(r.genAmount, global, global_m);
} else {
result[r.inst] = r.genAmount;
}
}
}
return result;
};
var readPMOD1 = function(b, e, g) {
var pmod = that.sfbk.pdta.child.pmod;
var result = _.O(g, true);
if(b != e) {
for(var i = b; i < e; i++) {
result.push(parseMOD1(ar, pmod, i));
}
}
return result;
};
var readINST1 = function(i, g, gm) {
var inst = that.sfbk.pdta.child.inst;
var ibag = that.sfbk.pdta.child.ibag;
var inst0 = parseINST1(ar, inst, i);
var inst1 = parseINST1(ar, inst, i + 1);
var r = {
"instName": inst0.instName
};
var global = _.O(g, true);
var global_m = _.O(gm, true);
// IBAGs
r.ibag = {
igen: [],<|fim▁hole|> var ibag1 = parseIBAG1(ar, ibag, i + 1);
var igen = readIGEN1(ibag0.instGenNdx, ibag1.instGenNdx, global);
var imod = readIMOD1(ibag0.instModNdx, ibag1.instModNdx, global_m);
if(igen["sampleID"] === undefined) { // global parameter
global = igen;
global_m = imod;
} else {
r.ibag.igen.push(igen);
r.ibag.imod.push(imod);
}
}
return r;
}
var readIGEN1 = function(b, e, g) {
var igen = that.sfbk.pdta.child.igen;
var result = _.O(g, true);
for(var i = b; i < e; i++) {
var r = parseIGEN1(ar, igen, i);
result[r.inst] = r.genAmount;
if(r.inst == "sampleID") {
result.shdr = readSHDR1(r.genAmount);
}
}
return result;
};
var readIMOD1 = function(b, e, g) {
var imod = that.sfbk.pdta.child.imod;
var result = _.O(g, true);
if(b != e) {
for(var i = b; i < e; i++) {
result.push(parseMOD1(ar, imod, i));
}
}
return result;
};
var readSHDR1 = function(i) {
var shdr = that.sfbk.pdta.child.shdr;
var r = parseSHDR1(ar, shdr, i);
r.end -= r.start;
r.startloop -= r.start;
r.endloop -= r.start;
r.sample = new Float32Array(r.end);
ar.seek(that.sfbk.sdta.child.smpl.headPosition + r.start * 2)
for(var j = 0; j < r.end; j++) {
r.sample[j] = ar.readInt16() / 32768;
}
r.start = 0;
return r;
};
var parseHeader = function(){
var h = {};
h.ID = ar.readStringF(4);
h.length = ar.readUInt32();
h.padLength = h.length % 2 == 1 ? h.length + 1 : h.length;
h.headPosition = ar.position();
ar.seek(ar.position() + h.padLength);
return h;
};
var parsePBAG1 = function(ar, root, i) {
ar.seek(root.headPosition + i * 4);
var data = {};
data.genNdx = ar.readUInt16();
data.modNdx = ar.readUInt16();
root.data[i] = data;
return data;
};
var parsePGEN1 = function(ar, root, i) {
ar.seek(root.headPosition + i * 4);
var data = {};
data.genOper = ar.readUInt16();
data.inst = sfGenerator[data.genOper];
if(data.inst == 'keyRange' ||
data.inst == 'velRange' ||
data.inst == 'keynum' ||
data.inst == 'velocity') {
data.genAmount = {};
data.genAmount.lo = ar.readUInt8();
data.genAmount.hi = ar.readUInt8();
} else {
data.genAmount = ar.readInt16();
}
root.data[i] = data;
return data;
};
var parseMOD1 = function(ar, root, i) {
ar.seek(root.headPosition + i * 10);
var data = {};
data.modSrcOper = { };
data.modSrcOper.index = ar.readUInt8();
data.modSrcOper.type = ar.readUInt8();
data.modDestOper = ar.readUInt16();
data.modDestInst = sfGenerator[data.modDestOper];
data.modAmount = ar.readInt16();
data.modAmtSrcOper = {};
data.modAmtSrcOper.index = ar.readUInt8();
data.modAmtSrcOper.type = ar.readUInt8();
data.modTransOper = ar.readUInt16();
root.data[i] = data;
return data;
};
var parseINST1 = function(ar, root, i) {
ar.seek(root.headPosition + i * 22);
var data = {};
data.instName = ar.readStringF(20);
data.instBagNdx = ar.readUInt16();
root.data.push(data);
return data;
};
var parseIBAG1 = function(ar, root, i) {
ar.seek(root.headPosition + i * 4);
var data = {};
data.instGenNdx = ar.readUInt16();
data.instModNdx = ar.readUInt16();
root.data.push(data);
return data;
};
var parseIGEN1 = function(ar, root, i) {
ar.seek(root.headPosition + i * 4);
var data = {};
data.genOper = ar.readUInt16();
data.inst = sfGenerator[data.genOper];
if(data.inst == 'keyRange' ||
data.inst == 'velRange' ||
data.inst == 'keynum' ||
data.inst == 'velocity') {
data.genAmount = {};
data.genAmount.lo = ar.readUInt8();
data.genAmount.hi = ar.readUInt8();
} else {
data.genAmount = ar.readInt16();
}
root.data.push(data);
return data;
};
var parseSHDR1 = function(ar, root, i) {
ar.seek(root.headPosition + i * 46);
var data = {};
data.sampleName = ar.readStringF(20);
data.start = ar.readUInt32();
data.end = ar.readUInt32();
data.startloop = ar.readUInt32();
data.endloop = ar.readUInt32();
data.sampleRate = ar.readUInt32();
data.originalPitch = ar.readUInt8();
data.pitchCorrection = ar.readInt8();
data.sampleLink = ar.readUInt16();
data.sampleType = ar.readUInt16();
root.data.push(data);
return data;
};
return that;
}
return sf2;
});<|fim▁end|> | imod: []
};
for(var i = inst0.instBagNdx; i < inst1.instBagNdx; i++) {
var ibag0 = parseIBAG1(ar, ibag, i); |
<|file_name|>uxrom.rs<|end_file_name|><|fim▁begin|>use crate::{
cart::Cart,
rom::{NesRom, CHR_BANK_SIZE, PRG_BANK_SIZE},
};
pub struct Uxrom {
prg_bank: Vec<u8>,
chr_rom: [u8; CHR_BANK_SIZE],
bank_select: u8,
last_bank: u8,
}
impl Uxrom {
pub fn new(rom: &NesRom) -> Result<Self, &'static str> {
if rom.prg.len() != PRG_BANK_SIZE * 8 {
println!("{}", rom.prg.len());
Err("Unexpected PRG ROM size")
} else if rom.chr_rom_banks > 0 && rom.chr.len() != CHR_BANK_SIZE {
Err("Unexpected CHR ROM size")
} else {
let mut cart = Uxrom {
prg_bank: vec![0; rom.prg.len()],
chr_rom: [0; CHR_BANK_SIZE],
bank_select: 0,
last_bank: rom.prg_rom_banks - 1,
};
cart.prg_bank.copy_from_slice(&rom.prg);
if rom.chr_rom_banks > 0 {
cart.chr_rom.copy_from_slice(&rom.chr);
}
Ok(cart)
}
}
}
impl Cart for Uxrom {
fn read_prg(&self, addr: u16) -> u8 {
debug_assert!(addr >= 0x8000);
let resolved_addr = resolve_prg_addr(addr, self.bank_select, self.last_bank);
self.prg_bank[resolved_addr]
}
fn write_prg(&mut self, addr: u16, value: u8) {
debug_assert!(addr >= 0x8000);
self.bank_select = value & 0x0f
}
fn read_chr(&self, addr: u16) -> u8 {
self.chr_rom[addr as usize]
}
fn write_chr(&mut self, addr: u16, value: u8) {
self.chr_rom[addr as usize] = value
}<|fim▁hole|> let normalized_addr = addr & 0x3fff;
let bank_select = bank_select as usize;
let last_bank = last_bank as usize;
if addr & 0xc000 == 0x8000 {
(bank_select << 14) | normalized_addr
} else {
(last_bank << 14) | normalized_addr
}
}
#[test]
fn test_resolve() {
let addr = resolve_prg_addr(0x8000, 0, 7);
assert_eq!(0, addr);
let addr = resolve_prg_addr(0xbfff, 0, 7);
assert_eq!(0x3fff, addr);
let addr = resolve_prg_addr(0x8000, 1, 7);
assert_eq!(0x4000, addr);
let addr = resolve_prg_addr(0xbfff, 1, 7);
assert_eq!(0x7fff, addr);
let addr = resolve_prg_addr(0x8000, 2, 7);
assert_eq!(0x8000, addr);
let addr = resolve_prg_addr(0xbfff, 2, 7);
assert_eq!(0xbfff, addr);
let addr = resolve_prg_addr(0x8000, 3, 7);
assert_eq!(0xc000, addr);
let addr = resolve_prg_addr(0xbfff, 3, 7);
assert_eq!(0xffff, addr);
let addr = resolve_prg_addr(0x8000, 4, 7);
assert_eq!(0x10000, addr);
let addr = resolve_prg_addr(0xbfff, 4, 7);
assert_eq!(0x13fff, addr);
let addr = resolve_prg_addr(0x8000, 5, 7);
assert_eq!(0x14000, addr);
let addr = resolve_prg_addr(0xbfff, 5, 7);
assert_eq!(0x17fff, addr);
let addr = resolve_prg_addr(0x8000, 6, 7);
assert_eq!(0x18000, addr);
let addr = resolve_prg_addr(0xbfff, 6, 7);
assert_eq!(0x1bfff, addr);
let addr = resolve_prg_addr(0x8000, 7, 7);
assert_eq!(0x1c000, addr);
let addr = resolve_prg_addr(0xbfff, 7, 7);
assert_eq!(0x1ffff, addr);
// Any address 0xc000 and up should always resolve to the last bank
let addr = resolve_prg_addr(0xc000, 0, 7);
assert_eq!(0x1c000, addr);
let addr = resolve_prg_addr(0xc000, 0, 6);
assert_eq!(0x18000, addr);
let addr = resolve_prg_addr(0xffff, 0, 5);
assert_eq!(0x17fff, addr);
}<|fim▁end|> | }
fn resolve_prg_addr(addr: u16, bank_select: u8, last_bank: u8) -> usize {
let addr = addr as usize; |
<|file_name|>tag_sets.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Various sets of HTML tag names, and macros for declaring them.
use string_cache::QualName;
macro_rules! declare_tag_set_impl ( ($param:ident, $b:ident, $supr:ident, $($tag:tt)+) => (
match $param {
$( qualname!(HTML, $tag) => $b, )+
p => $supr(p),
}
));
macro_rules! declare_tag_set_body (
($param:ident = $supr:ident - $($tag:tt)+)
=> ( declare_tag_set_impl!($param, false, $supr, $($tag)+) );
($param:ident = $supr:ident + $($tag:tt)+)
=> ( declare_tag_set_impl!($param, true, $supr, $($tag)+) );
($param:ident = $($tag:tt)+)
=> ( declare_tag_set_impl!($param, true, empty_set, $($tag)+) );
);
macro_rules! declare_tag_set (
(pub $name:ident = $($toks:tt)+) => (
pub fn $name(p: ::string_cache::QualName) -> bool {
declare_tag_set_body!(p = $($toks)+)
}
);
($name:ident = $($toks:tt)+) => (
fn $name(p: ::string_cache::QualName) -> bool {<|fim▁hole|> declare_tag_set_body!(p = $($toks)+)
}
);
);
#[inline(always)] pub fn empty_set(_: QualName) -> bool { false }
#[inline(always)] pub fn full_set(_: QualName) -> bool { true }
// FIXME: MathML, SVG
declare_tag_set!(pub default_scope = applet caption html table td th marquee object template);
declare_tag_set!(pub list_item_scope = default_scope + ol ul);
declare_tag_set!(pub button_scope = default_scope + button);
declare_tag_set!(pub table_scope = html table template);
declare_tag_set!(pub select_scope = full_set - optgroup option);
declare_tag_set!(pub table_body_context = tbody tfoot thead template html);
declare_tag_set!(pub table_row_context = tr template html);
declare_tag_set!(pub td_th = td th);
declare_tag_set!(pub cursory_implied_end = dd dt li option optgroup p rp rt);
declare_tag_set!(pub thorough_implied_end = cursory_implied_end
+ caption colgroup tbody td tfoot th thead tr);
declare_tag_set!(pub heading_tag = h1 h2 h3 h4 h5 h6);
declare_tag_set!(pub special_tag =
address applet area article aside base basefont bgsound blockquote body br button caption
center col colgroup dd details dir div dl dt embed fieldset figcaption figure footer form
frame frameset h1 h2 h3 h4 h5 h6 head header hgroup hr html iframe img input isindex li
link listing main marquee menu menuitem meta nav noembed noframes noscript object ol p
param plaintext pre script section select source style summary table tbody td template
textarea tfoot th thead title tr track ul wbr xmp);
//§ END<|fim▁end|> | |
<|file_name|>palindromic-substrings.js<|end_file_name|><|fim▁begin|>/**
* Palindromic Substrings
*
* Given a string, your task is to count how many palindromic substrings in this string.
*
* The substrings with different start indexes or end indexes are counted as different substrings even they consist of
* same characters.
*
* Example 1:
*
* Input: "abc"
* Output: 3
* Explanation: Three palindromic strings: "a", "b", "c".
*
* Example 2:
*<|fim▁hole|> * Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
*
* Note:
* The input string length won't exceed 1000.
*/
/**
* @param {string} s
* @return {number}
*/
const countSubstrings = s => {
const extendPalindrome = (s, left, right) => {
while (left >= 0 && right < s.length && s[left] === s[right]) {
count++;
left--;
right++;
}
};
if (!s || s.length === 0) {
return 0;
}
let count = 0;
for (let i = 0; i < s.length; i++) {
// i is the mid point
extendPalindrome(s, i, i); // odd length;
extendPalindrome(s, i, i + 1); // even length
}
return count;
};
export { countSubstrings };<|fim▁end|> | * Input: "aaa"
* Output: 6 |
<|file_name|>META.js<|end_file_name|><|fim▁begin|>import _ from 'lodash/fp'
export const TYPES = {
ADDON: 'addon',
COLLECTION: 'collection',
ELEMENT: 'element',
VIEW: 'view',
MODULE: 'module',
}
const TYPE_VALUES = _.values(TYPES)
/**
* Determine if an object qualifies as a META object.
* It must have the required keys and valid values.
* @private
* @param {Object} _meta A proposed Stardust _meta object.
* @returns {Boolean}
*/
export const isMeta = (_meta) => (
_.includes(_.get('type', _meta), TYPE_VALUES)
)
/**
* Extract the Stardust _meta object and optional key.
* Handles literal _meta objects, classes with _meta, objects with _meta
* @private
* @param {function|object} metaArg A class, a component instance, or meta object..
* @returns {object|string|undefined}
*/<|fim▁hole|> if (isMeta(metaArg)) return metaArg
// from prop
else if (isMeta(_.get('_meta', metaArg))) return metaArg._meta
// from class
else if (isMeta(_.get('constructor._meta', metaArg))) return metaArg.constructor._meta
}
const metaHasKeyValue = _.curry((key, val, metaArg) => _.flow(getMeta, _.get(key), _.eq(val))(metaArg))
export const isType = metaHasKeyValue('type')
// ----------------------------------------
// Export
// ----------------------------------------
// type
export const isAddon = isType(TYPES.ADDON)
export const isCollection = isType(TYPES.COLLECTION)
export const isElement = isType(TYPES.ELEMENT)
export const isView = isType(TYPES.VIEW)
export const isModule = isType(TYPES.MODULE)
// parent
export const isParent = _.flow(getMeta, _.has('parent'), _.eq(false))
export const isChild = _.flow(getMeta, _.has('parent'))
// other
export const isPrivate = _.flow(getMeta, _.get('name'), _.startsWith('_'))<|fim▁end|> | const getMeta = (metaArg) => {
// literal |
<|file_name|>ServerPropertiesDAO.java<|end_file_name|><|fim▁begin|>/**
* This file is part of tera-api.
*
* tera-api 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.
*
* tera-api 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 tera-api. If not, see <http://www.gnu.org/licenses/>.
*/
package com.tera.common.database.dao;
import java.util.Map;
<|fim▁hole|> * @author ATracer
*/
@Context(type = ContextType.DAO)
public interface ServerPropertiesDAO extends ContextDAO {
/**
* @param name
* @return
*/
String loadProperty(String name);
/**
* @return
*/
Map<String, String> loadProperties();
/**
* @param name
* @return
*/
boolean hasProperty(String name);
/**
* @param name
* @param value
*/
void saveProperty(String name, String value, boolean isNew);
}<|fim▁end|> | import com.tera.common.model.context.Context;
import com.tera.common.model.context.ContextType;
/**
|
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import
import datetime
from django.db import models
from django.db.models import get_model
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import smart_unicode, force_unicode
from django.template import loader, Context, TemplateDoesNotExist
from django.utils.translation import get_language, activate
from notification.models import NoticeType
from transifex.txcommon.log import logger
from .queues import log_to_queues
def _get_formatted_message(label, context):
"""
Return a message that is a rendered template with the given context using
the default language of the system.
"""
current_language = get_language()
# Setting the environment to the default language
activate(settings.LANGUAGE_CODE)
c = Context(context)
template = 'notification/%s/notice.html' % label
try:
msg = loader.get_template(template).render(c)
except TemplateDoesNotExist:
logger.error("Template '%s' doesn't exist." % template)
msg = None
# Reset environment to original language
activate(current_language)
return msg
def _user_counting(query):
"""
Get a LogEntry queryset and return a list of dictionaries with the
counting of times that the users appeared on the queryset.
Example of the resultant dictionary:
[{'user__username': u'editor', 'number': 5},
{'user__username': u'guest', 'number': 1}]
"""
query_result = query.values('user__username').annotate(
number=models.Count('user')).order_by('-number')
# Rename key from 'user__username' to 'username'
result=[]
for entry in query_result:
result.append({'username': entry['user__username'],
'number': entry['number']})
return result
def _distinct_action_time(query, limit=None):
"""
Distinct rows by the 'action_time' field, keeping in the query only the
entry with the highest 'id' for the related set of entries with equal
'action_time'.
If 'limit' is set, the function will return the 'limit'-most-recent
actionlogs.
Example:
For the following query set:
id | action_time
----+----------------------------
1 | 2010-03-11 10:55:26.32941-03
2 | 2010-03-11 10:55:26.32941-03
3 | 2010-03-11 13:48:22.202596-09
4 | 2010-03-11 13:48:53.505697-03
5 | 2010-03-11 13:48:53.505697-03
6 | 2010-03-11 13:51:09.013079-05
7 | 2010-03-11 13:51:09.013079-05
8 | 2010-03-11 13:51:09.013079-05
After passing through this function the query will be:
id | action_time
----+----------------------------
2 | 2010-03-11 10:55:26.32941-03
3 | 2010-03-11 13:48:22.202596-09
5 | 2010-03-11 13:48:53.505697-03
8 | 2010-03-11 13:51:09.013079-05
Rows with the same 'action_time' are eliminated, keeping the one with
highest 'id'.
"""
pks = query.defer('object_id', 'content_type').distinct()
if limit:
pks = pks.order_by('-id')[:limit]
else:
# For some reason, when using defer() the Meta ordering
# is not respected so we have to set it explicitly.
pks = pks.order_by('-action_time')
return pks.select_related('user')
class LogEntryManager(models.Manager):
def by_object(self, obj, limit=None):
"""Return LogEntries for a related object."""
ctype = ContentType.objects.get_for_model(obj)
q = self.filter(content_type__pk=ctype.pk, object_id=obj.pk)
return _distinct_action_time(q, limit)
def by_user(self, user, limit=None):
"""Return LogEntries for a specific user."""
q = self.filter(user__pk__exact=user.pk)
return _distinct_action_time(q, limit)
def by_object_last_week(self, obj):
"""Return LogEntries of the related object for the last week."""
last_week_date = datetime.datetime.today() - datetime.timedelta(days=7)
ctype = ContentType.objects.get_for_model(obj)
return self.filter(content_type__pk=ctype.pk, object_id=obj.pk,
action_time__gt=last_week_date)
def by_user_and_public_projects(self, user, limit=None):
"""
Return LogEntries for a specific user and his actions on public projects.
"""
# Avoiding circular import troubles. get_model didn't make it.
from transifex.projects.models import Project
ctype = ContentType.objects.get(model='project')
q = self.filter(user__pk__exact=user.pk, content_type=ctype,
object_id__in=Project.objects.filter(private=False))
return _distinct_action_time(q, limit)
def for_projects_by_user(self, user):
"""Return project LogEntries for a related user."""
ctype = ContentType.objects.get(model='project')
return self.filter(user__pk__exact=user.pk, content_type__pk=ctype.pk)
def top_submitters_by_project_content_type(self, number=10):
"""
Return a list of dicts with the ordered top submitters for the
entries of the 'project' content type.
"""
return self.top_submitters_by_content_type('projects.project', number)
def top_submitters_by_team_content_type(self, number=10):
"""
Return a list of dicts with the ordered top submitters for the
entries of the 'team' content type.
"""
return self.top_submitters_by_content_type('teams.team', number)
def top_submitters_by_language_content_type(self, number=10):
"""
Return a list of dicts with the ordered top submitters for the
entries of the 'language' content type.
"""
return self.top_submitters_by_content_type('languages.language', number)
class LogEntry(models.Model):
"""A Entry in an object's log."""
user = models.ForeignKey(User, verbose_name=_('User'), blank=True,
null=True, related_name="actionlogs")
object_id = models.IntegerField(blank=True, null=True, db_index=True)
content_type = models.ForeignKey(ContentType, blank=True, null=True,
related_name="actionlogs")
object = generic.GenericForeignKey('content_type', 'object_id')
action_type = models.ForeignKey(NoticeType, verbose_name=_('Action type'))
action_time = models.DateTimeField(_('Action time'), db_index=True)
object_name = models.CharField(blank=True, max_length=200)
message = models.TextField(blank=True, null=True)
# Managers
objects = LogEntryManager()
class Meta:
verbose_name = _('log entry')
verbose_name_plural = _('log entries')
ordering = ('-action_time',)
def __unicode__(self):
return u'%s.%s.%s' % (self.action_type, self.object_name, self.user)
def __repr__(self):
return smart_unicode("<LogEntry %d (%s)>" % (self.id,<|fim▁hole|> self.action_type.label))
def save(self, *args, **kwargs):
"""Save the object in the database."""
if self.action_time is None:
self.action_time = datetime.datetime.now()
super(LogEntry, self).save(*args, **kwargs)
def message_safe(self):
"""Return the message as HTML"""
return self.message
message_safe.allow_tags = True
message_safe.admin_order_field = 'message'
@property
def action_type_short(self):
"""
Return a shortened, generalized version of an action type.
Useful for presenting an image signifying an action type. Example::
>>> from notification.models import NoticeType
>>> nt = NoticeType(label='project_added')
>>> zlog = LogEntry(action_type=nt)
>>> nt
<NoticeType: project_added>
>>> zlog.action_type
<NoticeType: project_added>
>>> zlog.action_type_short
'added'
"""
return self.action_type.label.split('_')[-1]
def action_logging(user, object_list, action_type, message=None, context=None):
"""
Add ActionLog using a set of parameters.
user:
The user that did the action.
object_list:
A list of objects that should be created the actionlog for.
action_type:
Label of a type of action from the NoticeType model.
message:
A message to be included at the actionlog. If no message is passed
it will try do render a message using the notice.html from the
notification application.
context:
To render the message using the notification files, sometimes it is
necessary to pass some vars by using a context.
Usage::
al = 'project_added'
context = {'project': object}
action_logging(request.user, [object], al , context=context):
"""
if not getattr(settings, 'ACTIONLOG_ENABLED', None):
return
if context is None:
context = {}
if message is None:
message = _get_formatted_message(action_type, context)
action_type_obj = NoticeType.objects.get(label=action_type)
time = datetime.datetime.now()
try:
for object in object_list:
l = LogEntry(
user_id = user.pk,
content_type = ContentType.objects.get_for_model(object),
object_id = object.pk,
object_name = force_unicode(object)[:200],
action_type = action_type_obj,
action_time = time,
message = message)
l.save()
if settings.USE_REDIS:
log_to_queues(object, user, time, action_type_obj, message)
except TypeError:
raise TypeError("The 'object_list' parameter must be iterable")<|fim▁end|> | |
<|file_name|>halo_session.py<|end_file_name|><|fim▁begin|>import base64
import httplib
import json
import os
import re
import ssl
import urllib
from urlparse import urlunsplit<|fim▁hole|>
class HaloSession(object):
"""All Halo API session management happens in this object.
Args:
key(str): Halo API key
secret(str): Halo API secret
Kwargs:
api_host(str): Hostname for Halo API. Defaults to
``api.cloudpassage.com``
cert_file(str): Full path to CA file.
integration_string(str): This identifies a specific integration to the
Halo API.
"""
def __init__(self, halo_key, halo_secret, **kwargs):
self.key = halo_key
self.secret = halo_secret
self.api_host = "api.cloudpassage.com"
self.sdk_version = self.get_sdk_version()
self.sdk_version_string = "Halo-Python-SDK-slim/%s" % self.sdk_version
self.integration_string = ''
self.cert_file = None
if "api_host" in kwargs:
self.api_host = kwargs["api_host"]
if "cert_file" in kwargs:
self.cert_file = kwargs["cert_file"]
if "integration_string" in kwargs:
self.integration_string = kwargs["integration_string"]
self.user_agent = self.build_ua_string(self.sdk_version_string,
self.integration_string)
self.threads = 10
self.api_token = None
def authenticate(self):
"""Obtain and set an oauth API token."""
headers = self.build_auth_headers(self.key, self.secret)
headers["User-Agent"] = self.user_agent
params = urllib.urlencode({'grant_type': 'client_credentials'})
if self.cert_file is None:
connection = httplib.HTTPSConnection(self.api_host)
else:
ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
ctx.load_verify_locations(self.cert_file)
connection = httplib.HTTPSConnection(self.api_host,
context=ctx)
connection.request("POST", '/oauth/access_token', params, headers)
response = connection.getresponse()
code = response.status
body = response.read().decode()
if code == 401: # Bad API key...
raise CloudPassageAuthentication(json.dumps(body))
self.api_token = json.loads(body)['access_token']
return True
@classmethod
def build_auth_headers(cls, key, secret):
"""Create an auth string for Halo oauth."""
credfmt = "{key}:{secret}".format(key=key, secret=secret)
creds = base64.b64encode(credfmt)
auth_string = "Basic {creds}".format(creds=creds)
auth_header = {"Authorization": auth_string}
return auth_header
def build_header(self):
"""This builds the header, required for all API interaction."""
if self.api_token is None:
self.authenticate()
authstring = "Bearer " + self.api_token
header = {"Authorization": authstring,
"Content-Type": "application/json",
"User-Agent": self.user_agent}
return header
@classmethod
def build_ua_string(cls, sdk_version_str, integration_string):
ua = "{sdk} {integration}".format(sdk=sdk_version_str,
integration=integration_string)
return ua
def build_url(self, endpoint):
"""Build a URL from parts."""
url = urlunsplit(("https", self.api_host, endpoint, "", ""))
return url
@classmethod
def get_sdk_version(cls):
here_dir = os.path.abspath(os.path.dirname(__file__))
init_file_path = os.path.join(here_dir, "__init__.py")
raw_init_file = open(init_file_path).read()
rx_compiled = re.compile(r"\s*__version__\s*=\s*\"(\S+)\"")
version = rx_compiled.search(raw_init_file).group(1)
return version<|fim▁end|> | from exceptions import CloudPassageAuthentication
|
<|file_name|>test_operator.py<|end_file_name|><|fim▁begin|><|fim▁hole|>from numba.cuda.testing import unittest
from numba import cuda
import operator
class TestOperatorModule(unittest.TestCase):
"""
Test if operator module is supported by the CUDA target.
"""
def operator_template(self, op):
@cuda.jit
def foo(a, b):
i = 0
a[i] = op(a[i], b[i])
a = np.ones(1)
b = np.ones(1)
res = a.copy()
foo[1, 1](res, b)
np.testing.assert_equal(res, op(a, b))
def test_add(self):
self.operator_template(operator.add)
def test_sub(self):
self.operator_template(operator.sub)
def test_mul(self):
self.operator_template(operator.mul)
def test_truediv(self):
self.operator_template(operator.truediv)
if __name__ == '__main__':
unittest.main()<|fim▁end|> | from __future__ import print_function, absolute_import, division
import numpy as np |
<|file_name|>index.d.ts<|end_file_name|><|fim▁begin|>// Type definitions for parse 1.9
// Project: https://parse.com/
// Definitions by: Ullisen Media Group <http://ullisenmedia.com>, David Poetzsch-Heffter <https://github.com/dpoetzsch>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="node" />
/// <reference types="jquery" />
/// <reference types="underscore" />
declare namespace Parse {
var applicationId: string;
var javaScriptKey: string | undefined;
var masterKey: string | undefined;
var serverURL: string;
var VERSION: string;
interface SuccessOption {
success?: Function;
}
interface ErrorOption {
error?: Function;
}
interface SuccessFailureOptions extends SuccessOption, ErrorOption {
}
interface SessionTokenOption {
sessionToken?: string;
}
interface WaitOption {
/**
* Set to true to wait for the server to confirm success
* before triggering an event.
*/
wait?: boolean;
}
interface UseMasterKeyOption {
/**
* In Cloud Code and Node only, causes the Master Key to be used for this request.
*/
useMasterKey?: boolean;
}
interface ScopeOptions extends SessionTokenOption, UseMasterKeyOption {
}
interface SilentOption {
/**
* Set to true to avoid firing the event.
*/
silent?: boolean;
}
/**
* A Promise is returned by async methods as a hook to provide callbacks to be
* called when the async task is fulfilled.
*
* <p>Typical usage would be like:<pre>
* query.find().then(function(results) {
* results[0].set("foo", "bar");
* return results[0].saveAsync();
* }).then(function(result) {
* console.log("Updated " + result.id);
* });
* </pre></p>
*
* @see Parse.Promise.prototype.then
* @class
*/
interface IPromise<T> {
then<U>(resolvedCallback: (...values: T[]) => IPromise<U>, rejectedCallback?: (reason: any) => IPromise<U>): IPromise<U>;
then<U>(resolvedCallback: (...values: T[]) => U, rejectedCallback?: (reason: any) => IPromise<U>): IPromise<U>;
then<U>(resolvedCallback: (...values: T[]) => U, rejectedCallback?: (reason: any) => U): IPromise<U>;
}
class Promise<T> implements IPromise<T> {
static as<U>(resolvedValue: U): Promise<U>;
static error(error: any): Promise<any>;
static is(possiblePromise: any): Boolean;
static when(promises: IPromise<any>[]): Promise<any>;
static when(...promises: IPromise<any>[]): Promise<any>;
always(callback: Function): Promise<T>;
done(callback: Function): Promise<T>;
fail(callback: Function): Promise<T>;
reject(error: any): void;
resolve(result: any): void;
then<U>(resolvedCallback: (...values: T[]) => IPromise<U>,
rejectedCallback?: (reason: any) => IPromise<U>): IPromise<U>;
then<U>(resolvedCallback: (...values: T[]) => U,
rejectedCallback?: (reason: any) => IPromise<U>): IPromise<U>;
then<U>(resolvedCallback: (...values: T[]) => U,
rejectedCallback?: (reason: any) => U): IPromise<U>;
}
interface IBaseObject {
toJSON(): any;
}
class BaseObject implements IBaseObject {
toJSON(): any;
}
/**
* Creates a new ACL.
* If no argument is given, the ACL has no permissions for anyone.
* If the argument is a Parse.User, the ACL will have read and write
* permission for only that user.
* If the argument is any other JSON object, that object will be interpretted
* as a serialized ACL created with toJSON().
* @see Parse.Object#setACL
* @class
*
* <p>An ACL, or Access Control List can be added to any
* <code>Parse.Object</code> to restrict access to only a subset of users
* of your application.</p>
*/
class ACL extends BaseObject {
permissionsById: any;
constructor(arg1?: any);
setPublicReadAccess(allowed: boolean): void;
getPublicReadAccess(): boolean;
setPublicWriteAccess(allowed: boolean): void;
getPublicWriteAccess(): boolean;
setReadAccess(userId: User, allowed: boolean): void;
getReadAccess(userId: User): boolean;
setReadAccess(userId: string, allowed: boolean): void;
getReadAccess(userId: string): boolean;
setRoleReadAccess(role: Role, allowed: boolean): void;
setRoleReadAccess(role: string, allowed: boolean): void;
getRoleReadAccess(role: Role): boolean;
getRoleReadAccess(role: string): boolean;
setRoleWriteAccess(role: Role, allowed: boolean): void;
setRoleWriteAccess(role: string, allowed: boolean): void;
getRoleWriteAccess(role: Role): boolean;
getRoleWriteAccess(role: string): boolean;
setWriteAccess(userId: User, allowed: boolean): void;
setWriteAccess(userId: string, allowed: boolean): void;
getWriteAccess(userId: User): boolean;
getWriteAccess(userId: string): boolean;
}
/**
* A Parse.File is a local representation of a file that is saved to the Parse
* cloud.
* @class
* @param name {String} The file's name. This will be prefixed by a unique
* value once the file has finished saving. The file name must begin with
* an alphanumeric character, and consist of alphanumeric characters,
* periods, spaces, underscores, or dashes.
* @param data {Array} The data for the file, as either:
* 1. an Array of byte value Numbers, or
* 2. an Object like { base64: "..." } with a base64-encoded String.
* 3. a File object selected with a file upload control. (3) only works
* in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+.
* For example:<pre>
* var fileUploadControl = $("#profilePhotoFileUpload")[0];
* if (fileUploadControl.files.length > 0) {
* var file = fileUploadControl.files[0];
* var name = "photo.jpg";
* var parseFile = new Parse.File(name, file);
* parseFile.save().then(function() {
* // The file has been saved to Parse.
* }, function(error) {
* // The file either could not be read, or could not be saved to Parse.
* });
* }</pre>
* @param type {String} Optional Content-Type header to use for the file. If
* this is omitted, the content type will be inferred from the name's
* extension.
*/
class File {
constructor(name: string, data: any, type?: string);
name(): string;
url(): string;
save(options?: SuccessFailureOptions): Promise<File>;
}
/**
* Creates a new GeoPoint with any of the following forms:<br>
* <pre>
* new GeoPoint(otherGeoPoint)
* new GeoPoint(30, 30)
* new GeoPoint([30, 30])
* new GeoPoint({latitude: 30, longitude: 30})
* new GeoPoint() // defaults to (0, 0)
* </pre>
* @class
*
* <p>Represents a latitude / longitude point that may be associated
* with a key in a ParseObject or used as a reference point for geo queries.
* This allows proximity-based queries on the key.</p>
*
* <p>Only one key in a class may contain a GeoPoint.</p>
*
* <p>Example:<pre>
* var point = new Parse.GeoPoint(30.0, -20.0);
* var object = new Parse.Object("PlaceObject");
* object.set("location", point);
* object.save();</pre></p>
*/
class GeoPoint extends BaseObject {
latitude: number;
longitude: number;
constructor(arg1?: any, arg2?: any);
current(options?: SuccessFailureOptions): GeoPoint;
radiansTo(point: GeoPoint): number;
kilometersTo(point: GeoPoint): number;
milesTo(point: GeoPoint): number;
}
/**
* History serves as a global router (per frame) to handle hashchange
* events or pushState, match the appropriate route, and trigger
* callbacks. You shouldn't ever have to create one of these yourself
* — you should use the reference to <code>Parse.history</code>
* that will be created for you automatically if you make use of
* Routers with routes.
* @class
*
* <p>A fork of Backbone.History, provided for your convenience. If you
* use this class, you must also include jQuery, or another library
* that provides a jQuery-compatible $ function. For more information,
* see the <a href="http://documentcloud.github.com/backbone/#History">
* Backbone documentation</a>.</p>
* <p><strong><em>Available in the client SDK only.</em></strong></p>
*/
class History {
handlers: any[];
interval: number;
fragment: string;
checkUrl(e?: any): void;
getFragment(fragment?: string, forcePushState?: boolean): string;
getHash(windowOverride: Window): string;
loadUrl(fragmentOverride: any): boolean;
navigate(fragment: string, options?: any): any;
route(route: any, callback: Function): void;
start(options: any): boolean;
stop(): void;
}
/**
* A class that is used to access all of the children of a many-to-many relationship.
* Each instance of Parse.Relation is associated with a particular parent object and key.
*/
class Relation<S extends Object = Object, T extends Object = Object> extends BaseObject {
parent: S;
key: string;
targetClassName: string;
constructor(parent?: S, key?: string);
//Adds a Parse.Object or an array of Parse.Objects to the relation.
add(object: T): void;
// Returns a Parse.Query that is limited to objects in this relation.
query(): Query<T>;
// Removes a Parse.Object or an array of Parse.Objects from this relation.
remove(object: T): void;
}
/**
* Creates a new model with defined attributes. A client id (cid) is
* automatically generated and assigned for you.
*
* <p>You won't normally call this method directly. It is recommended that
* you use a subclass of <code>Parse.Object</code> instead, created by calling
* <code>extend</code>.</p>
*
* <p>However, if you don't want to use a subclass, or aren't sure which
* subclass is appropriate, you can use this form:<pre>
* var object = new Parse.Object("ClassName");
* </pre>
* That is basically equivalent to:<pre>
* var MyClass = Parse.Object.extend("ClassName");
* var object = new MyClass();
* </pre></p>
*
* @param {Object} attributes The initial set of data to store in the object.
* @param {Object} options A set of Backbone-like options for creating the
* object. The only option currently supported is "collection".
* @see Parse.Object.extend
*
* @class
*
* <p>The fundamental unit of Parse data, which implements the Backbone Model
* interface.</p>
*/
class Object extends BaseObject {
id: string;
createdAt: Date;
updatedAt: Date;
attributes: any;<|fim▁hole|> constructor(className?: string, options?: any);
constructor(attributes?: string[], options?: any);
static extend(className: string, protoProps?: any, classProps?: any): any;
static fromJSON(json: any, override: boolean): any;
static fetchAll<T extends Object>(list: T[], options: SuccessFailureOptions): Promise<T[]>;
static fetchAllIfNeeded<T extends Object>(list: T[], options: SuccessFailureOptions): Promise<T[]>;
static destroyAll<T>(list: T[], options?: Object.DestroyAllOptions): Promise<T[]>;
static saveAll<T extends Object>(list: T[], options?: Object.SaveAllOptions): Promise<T[]>;
static registerSubclass<T extends Object>(className: string, clazz: new (options?: any) => T): void;
initialize(): void;
add(attr: string, item: any): this;
addUnique(attr: string, item: any): any;
change(options: any): this;
changedAttributes(diff: any): boolean;
clear(options: any): any;
clone(): this;
destroy(options?: Object.DestroyOptions): Promise<this>;
dirty(attr?: string): boolean;
dirtyKeys(): string[];
escape(attr: string): string;
existed(): boolean;
fetch(options?: Object.FetchOptions): Promise<this>;
get(attr: string): any | undefined;
getACL(): ACL | undefined;
has(attr: string): boolean;
hasChanged(attr: string): boolean;
increment(attr: string, amount?: number): any;
isValid(): boolean;
op(attr: string): any;
previous(attr: string): any;
previousAttributes(): any;
relation(attr: string): Relation<this, Object>;
remove(attr: string, item: any): any;
save(attrs?: { [key: string]: any } | null, options?: Object.SaveOptions): Promise<this>;
save(key: string, value: any, options?: Object.SaveOptions): Promise<this>;
set(key: string, value: any, options?: Object.SetOptions): boolean;
setACL(acl: ACL, options?: SuccessFailureOptions): boolean;
unset(attr: string, options?: any): any;
validate(attrs: any, options?: SuccessFailureOptions): boolean;
}
namespace Object {
interface DestroyOptions extends SuccessFailureOptions, WaitOption, ScopeOptions { }
interface DestroyAllOptions extends SuccessFailureOptions, ScopeOptions { }
interface FetchOptions extends SuccessFailureOptions, ScopeOptions { }
interface SaveOptions extends SuccessFailureOptions, SilentOption, ScopeOptions, WaitOption { }
interface SaveAllOptions extends SuccessFailureOptions, ScopeOptions { }
interface SetOptions extends ErrorOption, SilentOption {
promise?: any;
}
}
/**
* Every Parse application installed on a device registered for
* push notifications has an associated Installation object.
*/
class Installation extends Object {
badge: any;
channels: string[];
timeZone: any;
deviceType: string;
pushType: string;
installationId: string;
deviceToken: string;
channelUris: string;
appName: string;
appVersion: string;
parseVersion: string;
appIdentifier: string;
}
/**
* Creates a new instance with the given models and options. Typically, you
* will not call this method directly, but will instead make a subclass using
* <code>Parse.Collection.extend</code>.
*
* @param {Array} models An array of instances of <code>Parse.Object</code>.
*
* @param {Object} options An optional object with Backbone-style options.
* Valid options are:<ul>
* <li>model: The Parse.Object subclass that this collection contains.
* <li>query: An instance of Parse.Query to use when fetching items.
* <li>comparator: A string property name or function to sort by.
* </ul>
*
* @see Parse.Collection.extend
*
* @class
*
* <p>Provides a standard collection class for our sets of models, ordered
* or unordered. For more information, see the
* <a href="http://documentcloud.github.com/backbone/#Collection">Backbone
* documentation</a>.</p>
*/
class Collection<T> extends Events implements IBaseObject {
model: Object;
models: Object[];
query: Query<Object>;
comparator: (object: Object) => any;
constructor(models?: Object[], options?: Collection.Options);
static extend(instanceProps: any, classProps: any): any;
initialize(): void;
add(models: any[], options?: Collection.AddOptions): Collection<T>;
at(index: number): Object;
chain(): _._Chain<Collection<T>>;
fetch(options?: Collection.FetchOptions): Promise<T>;
create(model: Object, options?: Collection.CreateOptions): Object;
get(id: string): Object;
getByCid(cid: any): any;
pluck(attr: string): any[];
remove(model: any, options?: Collection.RemoveOptions): Collection<T>;
remove(models: any[], options?: Collection.RemoveOptions): Collection<T>;
reset(models: any[], options?: Collection.ResetOptions): Collection<T>;
sort(options?: Collection.SortOptions): Collection<T>;
toJSON(): any;
}
namespace Collection {
interface Options {
model?: Object;
query?: Query<Object>;
comparator?: string;
}
interface AddOptions extends SilentOption {
/**
* The index at which to add the models.
*/
at?: number;
}
interface CreateOptions extends SuccessFailureOptions, WaitOption, SilentOption, ScopeOptions {
}
interface FetchOptions extends SuccessFailureOptions, SilentOption, ScopeOptions { }
interface RemoveOptions extends SilentOption { }
interface ResetOptions extends SilentOption { }
interface SortOptions extends SilentOption { }
}
/**
* @class
*
* <p>Parse.Events is a fork of Backbone's Events module, provided for your
* convenience.</p>
*
* <p>A module that can be mixed in to any object in order to provide
* it with custom events. You may bind callback functions to an event
* with `on`, or remove these functions with `off`.
* Triggering an event fires all callbacks in the order that `on` was
* called.
*
* <pre>
* var object = {};
* _.extend(object, Parse.Events);
* object.on('expand', function(){ alert('expanded'); });
* object.trigger('expand');</pre></p>
*
* <p>For more information, see the
* <a href="http://documentcloud.github.com/backbone/#Events">Backbone
* documentation</a>.</p>
*/
class Events {
static off(events: string[], callback?: Function, context?: any): Events;
static on(events: string[], callback?: Function, context?: any): Events;
static trigger(events: string[]): Events;
static bind(): Events;
static unbind(): Events;
on(eventName: string, callback?: Function, context?: any): Events;
off(eventName?: string | null, callback?: Function | null, context?: any): Events;
trigger(eventName: string, ...args: any[]): Events;
bind(eventName: string, callback: Function, context?: any): Events;
unbind(eventName?: string, callback?: Function, context?: any): Events;
}
/**
* Creates a new parse Parse.Query for the given Parse.Object subclass.
* @param objectClass -
* An instance of a subclass of Parse.Object, or a Parse className string.
* @class
*
* <p>Parse.Query defines a query that is used to fetch Parse.Objects. The
* most common use case is finding all objects that match a query through the
* <code>find</code> method. For example, this sample code fetches all objects
* of class <code>MyClass</code>. It calls a different function depending on
* whether the fetch succeeded or not.
*
* <pre>
* var query = new Parse.Query(MyClass);
* query.find({
* success: function(results) {
* // results is an array of Parse.Object.
* },
*
* error: function(error) {
* // error is an instance of Parse.Error.
* }
* });</pre></p>
*
* <p>A Parse.Query can also be used to retrieve a single object whose id is
* known, through the get method. For example, this sample code fetches an
* object of class <code>MyClass</code> and id <code>myId</code>. It calls a
* different function depending on whether the fetch succeeded or not.
*
* <pre>
* var query = new Parse.Query(MyClass);
* query.get(myId, {
* success: function(object) {
* // object is an instance of Parse.Object.
* },
*
* error: function(object, error) {
* // error is an instance of Parse.Error.
* }
* });</pre></p>
*
* <p>A Parse.Query can also be used to count the number of objects that match
* the query without retrieving all of those objects. For example, this
* sample code counts the number of objects of the class <code>MyClass</code>
* <pre>
* var query = new Parse.Query(MyClass);
* query.count({
* success: function(number) {
* // There are number instances of MyClass.
* },
*
* error: function(error) {
* // error is an instance of Parse.Error.
* }
* });</pre></p>
*/
class Query<T extends Object = Object> extends BaseObject {
objectClass: any;
className: string;
constructor(objectClass: string);
constructor(objectClass: new(...args: any[]) => T);
static or<U extends Object>(...var_args: Query<U>[]): Query<U>;
addAscending(key: string): Query<T>;
addAscending(key: string[]): Query<T>;
addDescending(key: string): Query<T>;
addDescending(key: string[]): Query<T>;
ascending(key: string): Query<T>;
ascending(key: string[]): Query<T>;
collection(items?: Object[], options?: Collection.Options): Collection<Object>;
containedIn(key: string, values: any[]): Query<T>;
contains(key: string, substring: string): Query<T>;
containsAll(key: string, values: any[]): Query<T>;
count(options?: Query.CountOptions): Promise<number>;
descending(key: string): Query<T>;
descending(key: string[]): Query<T>;
doesNotExist(key: string): Query<T>;
doesNotMatchKeyInQuery<U extends Object>(key: string, queryKey: string, query: Query<U>): Query<T>;
doesNotMatchQuery<U extends Object>(key: string, query: Query<U>): Query<T>;
each(callback: Function, options?: Query.EachOptions): Promise<void>;
endsWith(key: string, suffix: string): Query<T>;
equalTo(key: string, value: any): Query<T>;
exists(key: string): Query<T>;
find(options?: Query.FindOptions): Promise<T[]>;
first(options?: Query.FirstOptions): Promise<T | undefined>;
get(objectId: string, options?: Query.GetOptions): Promise<T>;
greaterThan(key: string, value: any): Query<T>;
greaterThanOrEqualTo(key: string, value: any): Query<T>;
include(key: string): Query<T>;
include(keys: string[]): Query<T>;
lessThan(key: string, value: any): Query<T>;
lessThanOrEqualTo(key: string, value: any): Query<T>;
limit(n: number): Query<T>;
matches(key: string, regex: RegExp, modifiers: any): Query<T>;
matchesKeyInQuery<U extends Object>(key: string, queryKey: string, query: Query<U>): Query<T>;
matchesQuery<U extends Object>(key: string, query: Query<U>): Query<T>;
near(key: string, point: GeoPoint): Query<T>;
notContainedIn(key: string, values: any[]): Query<T>;
notEqualTo(key: string, value: any): Query<T>;
select(...keys: string[]): Query<T>;
skip(n: number): Query<T>;
startsWith(key: string, prefix: string): Query<T>;
withinGeoBox(key: string, southwest: GeoPoint, northeast: GeoPoint): Query<T>;
withinKilometers(key: string, point: GeoPoint, maxDistance: number): Query<T>;
withinMiles(key: string, point: GeoPoint, maxDistance: number): Query<T>;
withinRadians(key: string, point: GeoPoint, maxDistance: number): Query<T>;
}
namespace Query {
interface EachOptions extends SuccessFailureOptions, ScopeOptions { }
interface CountOptions extends SuccessFailureOptions, ScopeOptions { }
interface FindOptions extends SuccessFailureOptions, ScopeOptions { }
interface FirstOptions extends SuccessFailureOptions, ScopeOptions { }
interface GetOptions extends SuccessFailureOptions, ScopeOptions { }
}
/**
* Represents a Role on the Parse server. Roles represent groupings of
* Users for the purposes of granting permissions (e.g. specifying an ACL
* for an Object). Roles are specified by their sets of child users and
* child roles, all of which are granted any permissions that the parent
* role has.
*
* <p>Roles must have a name (which cannot be changed after creation of the
* role), and must specify an ACL.</p>
* @class
* A Parse.Role is a local representation of a role persisted to the Parse
* cloud.
*/
class Role extends Object {
constructor(name: string, acl: ACL);
getRoles(): Relation<Role, Role>;
getUsers(): Relation<Role, User>;
getName(): string;
setName(name: string, options?: SuccessFailureOptions): any;
}
class Config extends Object {
static get(options?: SuccessFailureOptions): Promise<Config>;
static current(): Config;
get(attr: string): any;
escape(attr: string): any;
}
class Session extends Object {
static current(): Promise<Session>;
getSessionToken(): string;
isCurrentSessionRevocable(): boolean;
}
/**
* Routers map faux-URLs to actions, and fire events when routes are
* matched. Creating a new one sets its `routes` hash, if not set statically.
* @class
*
* <p>A fork of Backbone.Router, provided for your convenience.
* For more information, see the
* <a href="http://documentcloud.github.com/backbone/#Router">Backbone
* documentation</a>.</p>
* <p><strong><em>Available in the client SDK only.</em></strong></p>
*/
class Router extends Events {
routes: Router.RouteMap;
constructor(options?: Router.Options);
static extend(instanceProps: any, classProps: any): any;
initialize(): void;
navigate(fragment: string, options?: Router.NavigateOptions): Router;
navigate(fragment: string, trigger?: boolean): Router;
route(route: string, name: string, callback: Function): Router;
}
namespace Router {
interface Options {
routes: RouteMap;
}
interface RouteMap {
[url: string]: string;
}
interface NavigateOptions {
trigger?: boolean;
}
}
/**
* @class
*
* <p>A Parse.User object is a local representation of a user persisted to the
* Parse cloud. This class is a subclass of a Parse.Object, and retains the
* same functionality of a Parse.Object, but also extends it with various
* user specific methods, like authentication, signing up, and validation of
* uniqueness.</p>
*/
class User extends Object {
static current(): User | undefined;
static signUp(username: string, password: string, attrs: any, options?: SuccessFailureOptions): Promise<User>;
static logIn(username: string, password: string, options?: SuccessFailureOptions): Promise<User>;
static logOut(): Promise<User>;
static allowCustomUserClass(isAllowed: boolean): void;
static become(sessionToken: string, options?: SuccessFailureOptions): Promise<User>;
static requestPasswordReset(email: string, options?: SuccessFailureOptions): Promise<User>;
static extend(protoProps?: any, classProps?: any): any;
signUp(attrs: any, options?: SuccessFailureOptions): Promise<this>;
logIn(options?: SuccessFailureOptions): Promise<this>;
authenticated(): boolean;
isCurrent(): boolean;
getEmail(): string | undefined;
setEmail(email: string, options?: SuccessFailureOptions): boolean;
getUsername(): string | undefined;
setUsername(username: string, options?: SuccessFailureOptions): boolean;
setPassword(password: string, options?: SuccessFailureOptions): boolean;
getSessionToken(): string;
}
/**
* Creating a Parse.View creates its initial element outside of the DOM,
* if an existing element is not provided...
* @class
*
* <p>A fork of Backbone.View, provided for your convenience. If you use this
* class, you must also include jQuery, or another library that provides a
* jQuery-compatible $ function. For more information, see the
* <a href="http://documentcloud.github.com/backbone/#View">Backbone
* documentation</a>.</p>
* <p><strong><em>Available in the client SDK only.</em></strong></p>
*/
class View<T> extends Events {
model: any;
collection: any;
id: string;
cid: string;
className: string;
tagName: string;
el: any;
$el: JQuery;
attributes: any;
constructor(options?: View.Options);
static extend(properties: any, classProperties?: any): any;
$(selector?: string): JQuery;
setElement(element: HTMLElement, delegate?: boolean): View<T>;
setElement(element: JQuery, delegate?: boolean): View<T>;
render(): View<T>;
remove(): View<T>;
make(tagName: any, attributes?: View.Attribute[], content?: any): any;
delegateEvents(events?: any): any;
undelegateEvents(): any;
}
namespace View {
interface Options {
model?: any;
collection?: any;
el?: any;
id?: string;
className?: string;
tagName?: string;
attributes?: Attribute[];
}
interface Attribute {
[attributeName: string]: string | number | boolean;
}
}
namespace Analytics {
function track(name: string, dimensions: any): Promise<any>;
}
/**
* Provides a set of utilities for using Parse with Facebook.
* @namespace
* Provides a set of utilities for using Parse with Facebook.
*/
namespace FacebookUtils {
function init(options?: any): void;
function isLinked(user: User): boolean;
function link(user: User, permissions: any, options?: SuccessFailureOptions): void;
function logIn(permissions: any, options?: SuccessFailureOptions): void;
function unlink(user: User, options?: SuccessFailureOptions): void;
}
/**
* @namespace Contains functions for calling and declaring
* <a href="/docs/cloud_code_guide#functions">cloud functions</a>.
* <p><strong><em>
* Some functions are only available from Cloud Code.
* </em></strong></p>
*/
namespace Cloud {
interface CookieOptions {
domain?: string;
expires?: Date;
httpOnly?: boolean;
maxAge?: number;
path?: string;
secure?: boolean;
}
interface HttpResponse {
buffer?: Buffer;
cookies?: any;
data?: any;
headers?: any;
status?: number;
text?: string;
}
interface JobRequest {
params: any;
}
interface JobStatus {
error?: (response: any) => void;
message?: (response: any) => void;
success?: (response: any) => void;
}
interface FunctionRequest {
installationId?: String;
master?: boolean;
params?: any;
user?: User;
}
interface FunctionResponse {
success: (response: any) => void;
error: (response: any) => void;
}
interface Cookie {
name?: string;
options?: CookieOptions;
value?: string;
}
interface TriggerRequest {
installationId?: String;
master?: boolean;
user?: User;
object: Object;
}
interface AfterSaveRequest extends TriggerRequest {}
interface AfterDeleteRequest extends TriggerRequest {}
interface BeforeDeleteRequest extends TriggerRequest {}
interface BeforeDeleteResponse extends FunctionResponse {}
interface BeforeSaveRequest extends TriggerRequest {}
interface BeforeSaveResponse extends FunctionResponse {
success: () => void;
}
function afterDelete(arg1: any, func?: (request: AfterDeleteRequest) => void): void;
function afterSave(arg1: any, func?: (request: AfterSaveRequest) => void): void;
function beforeDelete(arg1: any, func?: (request: BeforeDeleteRequest, response: BeforeDeleteResponse) => void): void;
function beforeSave(arg1: any, func?: (request: BeforeSaveRequest, response: BeforeSaveResponse) => void): void;
function define(name: string, func?: (request: FunctionRequest, response: FunctionResponse) => void): void;
function httpRequest(options: HTTPOptions): Promise<HttpResponse>;
function job(name: string, func?: (request: JobRequest, status: JobStatus) => void): HttpResponse;
function run(name: string, data?: any, options?: RunOptions): Promise<any>;
function useMasterKey(): void;
interface RunOptions extends SuccessFailureOptions, ScopeOptions { }
/**
* To use this Cloud Module in Cloud Code, you must require 'buffer' in your JavaScript file.
*
* import Buffer = require("buffer").Buffer;
*/
var HTTPOptions: new () => HTTPOptions;
interface HTTPOptions {
/**
* The body of the request.
* If it is a JSON object, then the Content-Type set in the headers must be application/x-www-form-urlencoded or application/json.
* You can also set this to a Buffer object to send raw bytes.
* If you use a Buffer, you should also set the Content-Type header explicitly to describe what these bytes represent.
*/
body?: string | Buffer | Object;
/**
* Defaults to 'false'.
*/
followRedirects?: boolean;
/**
* The headers for the request.
*/
headers?: {
[headerName: string]: string | number | boolean;
};
/**
*The method of the request (i.e GET, POST, etc).
*/
method?: string;
/**
* The query portion of the url.
*/
params?: any;
/**
* The url to send the request to.
*/
url: string;
success?: (response: any) => void;
error?: (response: any) => void;
}
}
class Error {
code: ErrorCode;
message: string;
constructor(code: ErrorCode, message: string);
}
/*
* We need to inline the codes in order to make compilation work without this type definition as dependency.
*/
const enum ErrorCode {
OTHER_CAUSE = -1,
INTERNAL_SERVER_ERROR = 1,
CONNECTION_FAILED = 100,
OBJECT_NOT_FOUND = 101,
INVALID_QUERY = 102,
INVALID_CLASS_NAME = 103,
MISSING_OBJECT_ID = 104,
INVALID_KEY_NAME = 105,
INVALID_POINTER = 106,
INVALID_JSON = 107,
COMMAND_UNAVAILABLE = 108,
NOT_INITIALIZED = 109,
INCORRECT_TYPE = 111,
INVALID_CHANNEL_NAME = 112,
PUSH_MISCONFIGURED = 115,
OBJECT_TOO_LARGE = 116,
OPERATION_FORBIDDEN = 119,
CACHE_MISS = 120,
INVALID_NESTED_KEY = 121,
INVALID_FILE_NAME = 122,
INVALID_ACL = 123,
TIMEOUT = 124,
INVALID_EMAIL_ADDRESS = 125,
MISSING_CONTENT_TYPE = 126,
MISSING_CONTENT_LENGTH = 127,
INVALID_CONTENT_LENGTH = 128,
FILE_TOO_LARGE = 129,
FILE_SAVE_ERROR = 130,
DUPLICATE_VALUE = 137,
INVALID_ROLE_NAME = 139,
EXCEEDED_QUOTA = 140,
SCRIPT_FAILED = 141,
VALIDATION_ERROR = 142,
INVALID_IMAGE_DATA = 150,
UNSAVED_FILE_ERROR = 151,
INVALID_PUSH_TIME_ERROR = 152,
FILE_DELETE_ERROR = 153,
REQUEST_LIMIT_EXCEEDED = 155,
INVALID_EVENT_NAME = 160,
USERNAME_MISSING = 200,
PASSWORD_MISSING = 201,
USERNAME_TAKEN = 202,
EMAIL_TAKEN = 203,
EMAIL_MISSING = 204,
EMAIL_NOT_FOUND = 205,
SESSION_MISSING = 206,
MUST_CREATE_USER_THROUGH_SIGNUP = 207,
ACCOUNT_ALREADY_LINKED = 208,
INVALID_SESSION_TOKEN = 209,
LINKED_ID_MISSING = 250,
INVALID_LINKED_SESSION = 251,
UNSUPPORTED_SERVICE = 252,
AGGREGATE_ERROR = 600,
FILE_READ_ERROR = 601,
X_DOMAIN_REQUEST = 602
}
/**
* @class
* A Parse.Op is an atomic operation that can be applied to a field in a
* Parse.Object. For example, calling <code>object.set("foo", "bar")</code>
* is an example of a Parse.Op.Set. Calling <code>object.unset("foo")</code>
* is a Parse.Op.Unset. These operations are stored in a Parse.Object and
* sent to the server as part of <code>object.save()</code> operations.
* Instances of Parse.Op should be immutable.
*
* You should not create subclasses of Parse.Op or instantiate Parse.Op
* directly.
*/
namespace Op {
interface BaseOperation extends IBaseObject {
objects(): any[];
}
interface Add extends BaseOperation {
}
interface AddUnique extends BaseOperation {
}
interface Increment extends IBaseObject {
amount: number;
}
interface Relation extends IBaseObject {
added(): Object[];
removed: Object[];
}
interface Set extends IBaseObject {
value(): any;
}
interface Unset extends IBaseObject {
}
}
/**
* Contains functions to deal with Push in Parse
* @name Parse.Push
* @namespace
*/
namespace Push {
function send<T>(data: PushData, options?: SendOptions): Promise<T>;
interface PushData {
channels?: string[];
push_time?: Date;
expiration_time?: Date;
expiration_interval?: number;
where?: Query<Installation>;
data?: any;
alert?: string;
badge?: string;
sound?: string;
title?: string;
}
interface SendOptions extends UseMasterKeyOption {
success?: () => void;
error?: (error: Error) => void;
}
}
/**
* Call this method first to set up your authentication tokens for Parse.
* You can get your keys from the Data Browser on parse.com.
* @param {String} applicationId Your Parse Application ID.
* @param {String} javaScriptKey (optional) Your Parse JavaScript Key (Not needed for parse-server)
* @param {String} masterKey (optional) Your Parse Master Key. (Node.js only!)
*/
function initialize(applicationId: string, javaScriptKey?: string, masterKey?: string): void;
}
declare module "parse/node" {
export = Parse;
}
declare module "parse" {
import * as parse from "parse/node";
export = parse
}<|fim▁end|> | cid: string;
changed: boolean;
className: string;
|
<|file_name|>mir_codegen_switch.rs<|end_file_name|><|fim▁begin|><|fim▁hole|>//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
enum Abc {
A(u8),
B(i8),
C,
D,
}
fn foo(x: Abc) -> i32 {
match x {
Abc::C => 3,
Abc::D => 4,
Abc::B(_) => 2,
Abc::A(_) => 1,
}
}
fn foo2(x: Abc) -> bool {
match x {
Abc::D => true,
_ => false
}
}
fn main() {
assert_eq!(1, foo(Abc::A(42)));
assert_eq!(2, foo(Abc::B(-100)));
assert_eq!(3, foo(Abc::C));
assert_eq!(4, foo(Abc::D));
assert_eq!(false, foo2(Abc::A(1)));
assert_eq!(false, foo2(Abc::B(2)));
assert_eq!(false, foo2(Abc::C));
assert_eq!(true, foo2(Abc::D));
}<|fim▁end|> | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. |
<|file_name|>constant.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-<|fim▁hole|>GENDER = ((u'男',u'男'),(u'女',u'女'))<|fim▁end|> | |
<|file_name|>PreferencesBasedRepository.java<|end_file_name|><|fim▁begin|>package com.github.sixro.minihabits.core.infrastructure.domain;
import java.util.*;
import com.badlogic.gdx.Preferences;
import com.github.sixro.minihabits.core.domain.*;
public class PreferencesBasedRepository implements Repository {
private final Preferences prefs;
public PreferencesBasedRepository(Preferences prefs) {
super();
this.prefs = prefs;
}
@Override
public Set<MiniHabit> findAll() {
String text = prefs.getString("mini_habits");
if (text == null || text.trim().isEmpty())
return new LinkedHashSet<MiniHabit>();
return newMiniHabits(text);
}
@Override
public void add(MiniHabit miniHabit) {
Set<MiniHabit> list = findAll();
list.add(miniHabit);
prefs.putString("mini_habits", asString(list));
prefs.flush();
}
@Override
public void update(Collection<MiniHabit> list) {
Set<MiniHabit> currentList = findAll();
currentList.removeAll(list);
currentList.addAll(list);
<|fim▁hole|>
@Override
public void updateProgressDate(DateAtMidnight aDate) {
prefs.putLong("last_feedback_timestamp", aDate.getTime());
prefs.flush();
}
@Override
public DateAtMidnight lastFeedbackDate() {
long timestamp = prefs.getLong("last_feedback_timestamp");
if (timestamp == 0L)
return null;
return DateAtMidnight.from(timestamp);
}
private Set<MiniHabit> newMiniHabits(String text) {
String[] parts = text.split(",");
Set<MiniHabit> ret = new LinkedHashSet<MiniHabit>();
for (String part: parts)
ret.add(newMiniHabit(part));
return ret;
}
private MiniHabit newMiniHabit(String part) {
int indexOfColon = part.indexOf(':');
String label = part.substring(0, indexOfColon);
Integer daysInProgress = Integer.parseInt(part.substring(indexOfColon +1));
MiniHabit habit = new MiniHabit(label, daysInProgress);
return habit;
}
private String asString(Collection<MiniHabit> list) {
StringBuilder b = new StringBuilder();
int i = 0;
for (MiniHabit each: list) {
b.append(each.label() + ":" + each.daysInProgress());
if (i < list.size()-1)
b.append(',');
i++;
}
return b.toString();
}
}<|fim▁end|> | prefs.putString("mini_habits", asString(currentList));
prefs.flush();
}
|
<|file_name|>sbtview.py<|end_file_name|><|fim▁begin|>import sublime
import sublime_plugin
try:
from .sbtsettings import SBTSettings
from .util import maybe, OnePerWindow
except(ValueError):
from sbtsettings import SBTSettings
from util import maybe, OnePerWindow
import re
class SbtView(OnePerWindow):
settings = {
"line_numbers": False,
"gutter": False,
"rulers": [],
"word_wrap": False,
"draw_centered": False,
"highlight_line": False
}
@classmethod
def is_sbt_view(cls, view):
if view is not None:
for window in maybe(view.window()):
sbt_view = cls(window)
return sbt_view.panel.id() == view.id()
def __init__(self, window):<|fim▁hole|> self.window = window
self.settings = SBTSettings(window)
self.panel = self.window.get_output_panel('sbt')
self.panel.set_syntax_file("Packages/SublimeSBT/SBTOutput.hidden-tmLanguage")
for name, setting in SbtView.settings.items():
self.panel.settings().set(name, setting)
self._update_panel_colors()
self.settings.add_on_change(self._update_panel_colors)
self._output_size = 0
self._set_running(False)
def start(self):
self.clear_output()
self.show()
self._set_running(True)
def finish(self):
self.show_output('\n -- Finished --\n')
self._set_running(False)
def show(self):
self._update_panel_colors()
self.window.run_command('show_panel', {'panel': 'output.sbt'})
sublime.set_timeout(self._show_selection, 0)
def hide(self):
self.window.run_command('hide_panel', {'panel': 'output.sbt'})
def focus(self):
self.window.focus_view(self.panel)
self.panel.show(self.panel.size())
def show_output(self, output):
output = self._clean_output(output)
self.show()
self._append_output(output)
self._output_size = self.panel.size()
self.panel.show(self._output_size)
self.panel.sel().clear()
self.panel.sel().add(sublime.Region(self._output_size, self._output_size))
def clear_output(self):
self._erase_output(sublime.Region(0, self.panel.size()))
def take_input(self):
input_region = sublime.Region(self._output_size, self.panel.size())
input = self.panel.substr(input_region)
if sublime.platform() == 'windows':
self._append_output('\n')
else:
self._erase_output(input_region)
return input
def delete_left(self):
if self.panel.sel()[0].begin() > self._output_size:
self.panel.run_command('left_delete')
def delete_bol(self):
if self.panel.sel()[0].begin() >= self._output_size:
p = self.panel.sel()[-1].end()
self._erase_output(sublime.Region(self._output_size, p))
def delete_word_left(self):
if self.panel.sel()[0].begin() > self._output_size:
for r in self.panel.sel():
p = max(self.panel.word(r).begin(), self._output_size)
self.panel.sel().add(sublime.Region(p, r.end()))
self._erase_output(*self.panel.sel())
def delete_word_right(self):
if self.panel.sel()[0].begin() >= self._output_size:
for r in self.panel.sel():
p = self.panel.word(r).end()
self.panel.sel().add(sublime.Region(r.begin(), p))
self._erase_output(*self.panel.sel())
def update_writability(self):
self.panel.set_read_only(not self._running or
self.panel.sel()[0].begin() < self._output_size)
def _set_running(self, running):
self._running = running
self.update_writability()
def _append_output(self, output):
self._run_command('sbt_append_output', output=output)
def _erase_output(self, *regions):
self._run_command('sbt_erase_output',
regions=[[r.begin(), r.end()] for r in regions])
def _run_command(self, name, **kwargs):
self.panel.set_read_only(False)
self.panel.run_command(name, kwargs)
self.update_writability()
def _clean_output(self, output):
return self._strip_codes(self._normalize_lines(output))
def _normalize_lines(self, output):
return output.replace('\r\n', '\n').replace('\033M', '\r')
def _show_selection(self):
self.panel.show(self.panel.sel()[0].begin(), True)
def _strip_codes(self, output):
return re.sub(r'\033\[[0-9;]+[mK]', '', output)
def _update_panel_colors(self):
self.panel.settings().set('color_scheme', self.settings.get('color_scheme'))
class SbtAppendOutputCommand(sublime_plugin.TextCommand):
def run(self, edit, output):
for i, s in enumerate(output.split('\r')):
if i > 0:
self.view.replace(edit, self.view.line(self.view.size()), s)
else:
self.view.insert(edit, self.view.size(), s)
class SbtEraseOutputCommand(sublime_plugin.TextCommand):
def run(self, edit, regions):
for a, b in reversed(regions):
self.view.erase(edit, sublime.Region(int(a), int(b)))<|fim▁end|> | |
<|file_name|>global.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Abstractions for global scopes.
//!
//! This module contains smart pointers to global scopes, to simplify writing
//! code that works in workers as well as window scopes.
use dom::bindings::conversions::native_from_reflector_jsmanaged;
use dom::bindings::js::{JS, JSRef, Rootable, Root, Unrooted};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::workerglobalscope::{WorkerGlobalScope, WorkerGlobalScopeHelpers};
use dom::window::{self, WindowHelpers};
use devtools_traits::DevtoolsControlChan;
use script_task::{ScriptChan, ScriptPort, ScriptMsg, ScriptTask};
use msg::constellation_msg::{PipelineId, WorkerId};
use net_traits::ResourceTask;
use js::{JSCLASS_IS_GLOBAL, JSCLASS_IS_DOMJSCLASS};
use js::glue::{GetGlobalForObjectCrossCompartment};
use js::jsapi::{JSContext, JSObject};
use js::jsapi::{JS_GetClass};
use url::Url;
/// A freely-copyable reference to a rooted global object.
#[derive(Copy, Clone)]
pub enum GlobalRef<'a> {
/// A reference to a `Window` object.
Window(JSRef<'a, window::Window>),
/// A reference to a `WorkerGlobalScope` object.
Worker(JSRef<'a, WorkerGlobalScope>),
}
/// A stack-based rooted reference to a global object.
#[no_move]
pub enum GlobalRoot {
/// A root for a `Window` object.
Window(Root<window::Window>),
/// A root for a `WorkerGlobalScope` object.
Worker(Root<WorkerGlobalScope>),
}
/// A traced reference to a global object, for use in fields of traced Rust
/// structures.
#[jstraceable]
#[must_root]
pub enum GlobalField {
/// A field for a `Window` object.
Window(JS<window::Window>),
/// A field for a `WorkerGlobalScope` object.
Worker(JS<WorkerGlobalScope>),
}
/// An unrooted reference to a global object.
#[must_root]
pub enum GlobalUnrooted {
/// An unrooted reference to a `Window` object.
Window(Unrooted<window::Window>),
/// An unrooted reference to a `WorkerGlobalScope` object.
Worker(Unrooted<WorkerGlobalScope>),
}
impl<'a> GlobalRef<'a> {
/// Get the `JSContext` for the `JSRuntime` associated with the thread
/// this global object is on.
pub fn get_cx(&self) -> *mut JSContext {
match *self {
GlobalRef::Window(ref window) => window.get_cx(),
GlobalRef::Worker(ref worker) => worker.get_cx(),
}
}
/// Extract a `Window`, causing task failure if the global object is not
/// a `Window`.
pub fn as_window<'b>(&'b self) -> JSRef<'b, window::Window> {
match *self {
GlobalRef::Window(window) => window,
GlobalRef::Worker(_) => panic!("expected a Window scope"),
}
}
/// Get the `PipelineId` for this global scope.
pub fn pipeline(&self) -> PipelineId {
match *self {
GlobalRef::Window(window) => window.pipeline(),
GlobalRef::Worker(worker) => worker.pipeline(),
}
}
/// Get `DevtoolsControlChan` to send messages to Devtools
/// task when available.
pub fn devtools_chan(&self) -> Option<DevtoolsControlChan> {
match *self {
GlobalRef::Window(window) => window.devtools_chan(),
GlobalRef::Worker(worker) => worker.devtools_chan(),
}
}
/// Get the `ResourceTask` for this global scope.
pub fn resource_task(&self) -> ResourceTask {
match *self {
GlobalRef::Window(ref window) => window.resource_task().clone(),
GlobalRef::Worker(ref worker) => worker.resource_task().clone(),
}
}
/// Get next worker id.
pub fn get_next_worker_id(&self) -> WorkerId {
match *self {
GlobalRef::Window(ref window) => window.get_next_worker_id(),
GlobalRef::Worker(ref worker) => worker.get_next_worker_id()
}
}<|fim▁hole|> GlobalRef::Window(ref window) => window.get_url(),
GlobalRef::Worker(ref worker) => worker.get_url().clone(),
}
}
/// `ScriptChan` used to send messages to the event loop of this global's
/// thread.
pub fn script_chan(&self) -> Box<ScriptChan+Send> {
match *self {
GlobalRef::Window(ref window) => window.script_chan(),
GlobalRef::Worker(ref worker) => worker.script_chan(),
}
}
/// Create a new sender/receiver pair that can be used to implement an on-demand
/// event loop. Used for implementing web APIs that require blocking semantics
/// without resorting to nested event loops.
pub fn new_script_pair(&self) -> (Box<ScriptChan+Send>, Box<ScriptPort+Send>) {
match *self {
GlobalRef::Window(ref window) => window.new_script_pair(),
GlobalRef::Worker(ref worker) => worker.new_script_pair(),
}
}
/// Process a single event as if it were the next event in the task queue for
/// this global.
pub fn process_event(&self, msg: ScriptMsg) {
match *self {
GlobalRef::Window(_) => ScriptTask::process_event(msg),
GlobalRef::Worker(ref worker) => worker.process_event(msg),
}
}
}
impl<'a> Reflectable for GlobalRef<'a> {
fn reflector<'b>(&'b self) -> &'b Reflector {
match *self {
GlobalRef::Window(ref window) => window.reflector(),
GlobalRef::Worker(ref worker) => worker.reflector(),
}
}
}
impl GlobalRoot {
/// Obtain a safe reference to the global object that cannot outlive the
/// lifetime of this root.
pub fn r<'c>(&'c self) -> GlobalRef<'c> {
match *self {
GlobalRoot::Window(ref window) => GlobalRef::Window(window.r()),
GlobalRoot::Worker(ref worker) => GlobalRef::Worker(worker.r()),
}
}
}
impl GlobalField {
/// Create a new `GlobalField` from a rooted reference.
pub fn from_rooted(global: &GlobalRef) -> GlobalField {
match *global {
GlobalRef::Window(window) => GlobalField::Window(JS::from_rooted(window)),
GlobalRef::Worker(worker) => GlobalField::Worker(JS::from_rooted(worker)),
}
}
/// Create a stack-bounded root for this reference.
pub fn root(&self) -> GlobalRoot {
match *self {
GlobalField::Window(ref window) => GlobalRoot::Window(window.root()),
GlobalField::Worker(ref worker) => GlobalRoot::Worker(worker.root()),
}
}
}
impl GlobalUnrooted {
/// Create a stack-bounded root for this reference.
pub fn root(&self) -> GlobalRoot {
match *self {
GlobalUnrooted::Window(ref window) => GlobalRoot::Window(window.root()),
GlobalUnrooted::Worker(ref worker) => GlobalRoot::Worker(worker.root()),
}
}
}
/// Returns the global object of the realm that the given JS object was created in.
#[allow(unrooted_must_root)]
pub fn global_object_for_js_object(obj: *mut JSObject) -> GlobalUnrooted {
unsafe {
let global = GetGlobalForObjectCrossCompartment(obj);
let clasp = JS_GetClass(global);
assert!(((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL)) != 0);
match native_from_reflector_jsmanaged(global) {
Ok(window) => return GlobalUnrooted::Window(window),
Err(_) => (),
}
match native_from_reflector_jsmanaged(global) {
Ok(worker) => return GlobalUnrooted::Worker(worker),
Err(_) => (),
}
panic!("found DOM global that doesn't unwrap to Window or WorkerGlobalScope")
}
}<|fim▁end|> |
/// Get the URL for this global scope.
pub fn get_url(&self) -> Url {
match *self { |
<|file_name|>System_service_alert.java<|end_file_name|><|fim▁begin|>//Auto generated file
//Do not edit this file
package org.sisiya.ui.standart;
import org.sql2o.Connection;
import org.sql2o.Query;
import java.util.List;
import org.sisiya.ui.Application;
import java.util.Date;
public class System_service_alert extends Model{
//Fields
protected int id;
protected int user_id;
protected int system_id;
protected int service_id;
protected int alert_type_id;
protected int status_id;
protected int frequency;
protected boolean enabled;
protected Date last_alert_time;
private ModelHooks mh;
private Boolean isNew;
//Constructer
public System_service_alert(){
isNew = true;
//Default Constructer
fields.add(new Field("id","int","system_service_alert-id",true,true));
fields.add(new Field("user_id","int","system_service_alert-user_id",false,false));
fields.add(new Field("system_id","int","system_service_alert-system_id",false,false));
fields.add(new Field("service_id","int","system_service_alert-service_id",false,false));
fields.add(new Field("alert_type_id","int","system_service_alert-alert_type_id",false,false));
fields.add(new Field("status_id","int","system_service_alert-status_id",false,false));
fields.add(new Field("frequency","int","system_service_alert-frequency",false,false));
fields.add(new Field("enabled","boolean","system_service_alert-enabled",false,false));
fields.add(new Field("last_alert_time","Date","system_service_alert-last_alert_time",false,false));
}
public void registerHooks(ModelHooks _mh){
mh = _mh;
}
//Setters
public void setId(int _id){
id = _id;
}
public void setUser_id(int _user_id){
user_id = _user_id;
}
public void setSystem_id(int _system_id){
system_id = _system_id;
}
public void setService_id(int _service_id){
service_id = _service_id;
}
public void setAlert_type_id(int _alert_type_id){
alert_type_id = _alert_type_id;
}
public void setStatus_id(int _status_id){
status_id = _status_id;
}
public void setFrequency(int _frequency){
frequency = _frequency;
}
public void setEnabled(boolean _enabled){
enabled = _enabled;
}
public void setLast_alert_time(Date _last_alert_time){
last_alert_time = _last_alert_time;
}
public void setIsNew(boolean b){
isNew = b;
}
//Getters
public int getId(){
return id;
}
public int getUser_id(){
return user_id;
}
public int getSystem_id(){
return system_id;
}
public int getService_id(){
return service_id;
}
public int getAlert_type_id(){
return alert_type_id;
}
public int getStatus_id(){
return status_id;
}
public int getFrequency(){
return frequency;
}
public boolean getEnabled(){
return enabled;
}
public Date getLast_alert_time(){
return last_alert_time;
}
public Boolean isNew() {
return isNew;
}
//Data Access Methods
//Data Access Methods
public boolean save(Connection _connection){
return(save(_connection,true,true));
}
public boolean save(Connection _connection,boolean doValidate,boolean executeHooks){
if(doValidate){
try {
if(!mh.validate(_connection)){
return(false);
}
} catch (Exception e) {
errors.add(new Error(e.getClass().getName(), e.getMessage()));
return(false);
}
if(!isReadyToSave()){
return(false);
}
}
if(executeHooks){
try {
if(isNew()){
if(!mh.beforeInsert(_connection)){return(false);}
}else{
if(!mh.beforeUpdate(_connection)){return(false);}
}
if(!mh.beforeSave(_connection)){return(false);}
} catch (Exception e) {
errors.add(new Error(e.getClass().getName(), e.getMessage()));
return(false);
}
//Actual db update
if(isNew()){
try {
if(!insert(_connection)){return(false);}
if(!mh.afterInsert(_connection)){return(false);}
if(!mh.afterSave(_connection)){return(false);}
} catch (Exception e) {
errors.add(new Error(e.getClass().getName(), e.getMessage()));
return(false);
}
}else{
try {
if(!update(_connection)){return(false);}
if(!mh.afterUpdate(_connection)){return(false);}
if(!mh.afterSave(_connection)){return(false);}
} catch (Exception e) {
errors.add(new Error(e.getClass().getName(), e.getMessage()));
return(false);
} <|fim▁hole|> }
}else{
//Actual db operation without hooks
if(isNew()){
try {
if(!insert(_connection)){return(false);}
} catch (Exception e) {
errors.add(new Error(e.getClass().getName(), e.getMessage()));
return(false);
}
}else{
try {
if(!update(_connection)){return(false);}
} catch (Exception e) {
errors.add(new Error(e.getClass().getName(), e.getMessage()));
return(false);
}
}
}
return true;
}
public boolean destroy(Connection _connection,boolean executeHooks){
if(executeHooks){
if(!mh.beforeDestroy(_connection)){return(false);}
}
if(!delete(_connection)){return(false);}
if(executeHooks){
if(!mh.afterDestroy(_connection)){return(false);}
}
return(true);
}
public boolean destroy(Connection _connection){
return(destroy(_connection,true));
}
//Private Data Acess utility Methods
private boolean insert(Connection _connection){
Query query;
query = _connection.createQuery(insertSql(),true);
query = query.addParameter("user_idP",user_id);
query = query.addParameter("system_idP",system_id);
query = query.addParameter("service_idP",service_id);
query = query.addParameter("alert_type_idP",alert_type_id);
query = query.addParameter("status_idP",status_id);
query = query.addParameter("frequencyP",frequency);
query = query.addParameter("enabledP",enabled);
query = query.addParameter("last_alert_timeP",last_alert_time);
id = (int) query.executeUpdate().getKey();
return(true);
}
private boolean update(Connection _connection){
Query query;
query = _connection.createQuery(updateSql());
query = query.addParameter("idP",id);
query = query.addParameter("user_idP",user_id);
query = query.addParameter("system_idP",system_id);
query = query.addParameter("service_idP",service_id);
query = query.addParameter("alert_type_idP",alert_type_id);
query = query.addParameter("status_idP",status_id);
query = query.addParameter("frequencyP",frequency);
query = query.addParameter("enabledP",enabled);
query = query.addParameter("last_alert_timeP",last_alert_time);
query.executeUpdate();
return(true);
}
private boolean delete(Connection _connection){
Query query;
query = _connection.createQuery(deleteSql());
query.addParameter("idP",id);
query.executeUpdate();
return(true);
}
private String insertSql(){
String querySql = "insert into system_service_alerts( ";
querySql += "user_id,";
querySql += "system_id,";
querySql += "service_id,";
querySql += "alert_type_id,";
querySql += "status_id,";
querySql += "frequency,";
querySql += "enabled,";
querySql += "last_alert_time)";
querySql += "values (";
querySql += ":user_idP,";
querySql += ":system_idP,";
querySql += ":service_idP,";
querySql += ":alert_type_idP,";
querySql += ":status_idP,";
querySql += ":frequencyP,";
querySql += ":enabledP,";
querySql += ":last_alert_timeP)";
return querySql;
}
private String updateSql(){
String querySql = "update system_service_alerts set ";
querySql += "user_id = :user_idP, " ;
querySql += "system_id = :system_idP, " ;
querySql += "service_id = :service_idP, " ;
querySql += "alert_type_id = :alert_type_idP, " ;
querySql += "status_id = :status_idP, " ;
querySql += "frequency = :frequencyP, " ;
querySql += "enabled = :enabledP, " ;
querySql += "last_alert_time = :last_alert_timeP ";
querySql += " where id = :idP";
return querySql;
}
private String deleteSql(){
String querySql = "delete from system_service_alerts where id = :idP";
return querySql;
}
}<|fim▁end|> | |
<|file_name|>helper.go<|end_file_name|><|fim▁begin|>// Copyright 2015 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"math"
)
// RoundFloat rounds float val to the nearest integer value with float64 format, like GNU rint function.<|fim▁hole|>// so we will choose the even number if the result is midway between two representable value.
// e.g, 1.5 -> 2, 2.5 -> 2.
func RoundFloat(val float64) float64 {
v, frac := math.Modf(val)
if val >= 0.0 {
if frac > 0.5 || (frac == 0.5 && uint64(v)%2 != 0) {
v += 1.0
}
} else {
if frac < -0.5 || (frac == -0.5 && uint64(v)%2 != 0) {
v -= 1.0
}
}
return v
}
func getMaxFloat(flen int, decimal int) float64 {
intPartLen := flen - decimal
f := math.Pow10(intPartLen)
f -= math.Pow10(-decimal)
return f
}
func truncateFloat(f float64, decimal int) float64 {
pow := math.Pow10(decimal)
t := (f - math.Floor(f)) * pow
round := RoundFloat(t)
f = math.Floor(f) + round/pow
return f
}
// TruncateFloat tries to truncate f.
// If the result exceeds the max/min float that flen/decimal allowed, returns the max/min float allowed.
func TruncateFloat(f float64, flen int, decimal int) (float64, error) {
if math.IsNaN(f) {
// nan returns 0
return 0, nil
}
maxF := getMaxFloat(flen, decimal)
if !math.IsInf(f, 0) {
f = truncateFloat(f, decimal)
}
if f > maxF {
f = maxF
} else if f < -maxF {
f = -maxF
}
return f, nil
}<|fim▁end|> | // RoundFloat uses default rounding mode, see http://www.gnu.org/software/libc/manual/html_node/Rounding.html |
<|file_name|>styles.ts<|end_file_name|><|fim▁begin|>/**
* @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
*/
import * as path from 'path';
import * as webpack from 'webpack';
import {
AnyComponentStyleBudgetChecker,
PostcssCliResources,
RemoveHashPlugin,
SuppressExtractedTextChunksWebpackPlugin,
} from '../../plugins/webpack';
import { WebpackConfigOptions } from '../build-options';
import { getOutputHashFormat, normalizeExtraEntryPoints } from './utils';
const autoprefixer = require('autoprefixer');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const postcssImports = require('postcss-import');
// tslint:disable-next-line:no-big-function
export function getStylesConfig(wco: WebpackConfigOptions) {
const { root, buildOptions } = wco;
const entryPoints: { [key: string]: string[] } = {};
const globalStylePaths: string[] = [];
const extraPlugins: webpack.Plugin[] = [
new AnyComponentStyleBudgetChecker(buildOptions.budgets),
];
const cssSourceMap = buildOptions.sourceMap.styles;
// Determine hashing format.
const hashFormat = getOutputHashFormat(buildOptions.outputHashing as string);
const postcssPluginCreator = function(loader: webpack.loader.LoaderContext) {
return [
postcssImports({
resolve: (url: string) => (url.startsWith('~') ? url.substr(1) : url),
load: (filename: string) => {
return new Promise<string>((resolve, reject) => {
loader.fs.readFile(filename, (err: Error, data: Buffer) => {
if (err) {
reject(err);
return;
}
const content = data.toString();
resolve(content);
});
});
},
}),
PostcssCliResources({
baseHref: buildOptions.baseHref,
deployUrl: buildOptions.deployUrl,
resourcesOutputPath: buildOptions.resourcesOutputPath,
loader,
rebaseRootRelative: buildOptions.rebaseRootRelativeCssUrls,
filename: `[name]${hashFormat.file}.[ext]`,
emitFile: buildOptions.platform !== 'server',
}),
autoprefixer(),
];
};
// use includePaths from appConfig
const includePaths: string[] = [];
let lessPathOptions: { paths?: string[] } = {};
if (
buildOptions.stylePreprocessorOptions &&
buildOptions.stylePreprocessorOptions.includePaths &&
buildOptions.stylePreprocessorOptions.includePaths.length > 0
) {
buildOptions.stylePreprocessorOptions.includePaths.forEach((includePath: string) =>
includePaths.push(path.resolve(root, includePath)),
);
lessPathOptions = {
paths: includePaths,
};
}
// Process global styles.
if (buildOptions.styles.length > 0) {
const chunkNames: string[] = [];
normalizeExtraEntryPoints(buildOptions.styles, 'styles').forEach(style => {
const resolvedPath = path.resolve(root, style.input);
// Add style entry points.
if (entryPoints[style.bundleName]) {
entryPoints[style.bundleName].push(resolvedPath);
} else {
entryPoints[style.bundleName] = [resolvedPath];
}
// Add non injected styles to the list.
if (!style.inject) {
chunkNames.push(style.bundleName);
}
// Add global css paths.
globalStylePaths.push(resolvedPath);
});
if (chunkNames.length > 0) {
// Add plugin to remove hashes from lazy styles.
extraPlugins.push(new RemoveHashPlugin({ chunkNames, hashFormat }));
}
}
let sassImplementation: {} | undefined;
try {
// tslint:disable-next-line:no-implicit-dependencies
sassImplementation = require('node-sass');
} catch {
sassImplementation = require('sass');
}
// set base rules to derive final rules from
const baseRules: webpack.RuleSetRule[] = [
{ test: /\.css$/, use: [] },
{
test: /\.scss$|\.sass$/,
use: [
{
loader: require.resolve('resolve-url-loader'),
options: {
sourceMap: cssSourceMap,
},
},
{
loader: require.resolve('sass-loader'),
options: {
implementation: sassImplementation,
sourceMap: true,
sassOptions: {
// bootstrap-sass requires a minimum precision of 8
precision: 8,
includePaths,<|fim▁hole|> outputStyle: 'expanded',
},
},
},
],
},
{
test: /\.less$/,
use: [
{
loader: require.resolve('less-loader'),
options: {
sourceMap: cssSourceMap,
lessOptions: {
javascriptEnabled: true,
...lessPathOptions,
},
},
},
],
},
{
test: /\.styl$/,
use: [
{
loader: require.resolve('resolve-url-loader'),
options: {
sourceMap: cssSourceMap,
},
},
{
loader: require.resolve('stylus-loader'),
options: {
sourceMap: { comment: false },
paths: includePaths,
},
},
],
},
];
// load component css as raw strings
const rules: webpack.RuleSetRule[] = baseRules.map(({ test, use }) => ({
exclude: globalStylePaths,
test,
use: [
{ loader: require.resolve('raw-loader') },
{
loader: require.resolve('postcss-loader'),
options: {
ident: 'embedded',
plugins: postcssPluginCreator,
sourceMap: cssSourceMap
// Never use component css sourcemap when style optimizations are on.
// It will just increase bundle size without offering good debug experience.
&& !buildOptions.optimization.styles
// Inline all sourcemap types except hidden ones, which are the same as no sourcemaps
// for component css.
&& !buildOptions.sourceMap.hidden ? 'inline' : false,
},
},
...(use as webpack.Loader[]),
],
}));
// load global css as css files
if (globalStylePaths.length > 0) {
rules.push(
...baseRules.map(({ test, use }) => {
return {
include: globalStylePaths,
test,
use: [
buildOptions.extractCss ? MiniCssExtractPlugin.loader : require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
url: false,
sourceMap: cssSourceMap,
},
},
{
loader: require.resolve('postcss-loader'),
options: {
ident: buildOptions.extractCss ? 'extracted' : 'embedded',
plugins: postcssPluginCreator,
sourceMap:
cssSourceMap && !buildOptions.extractCss && !buildOptions.sourceMap.hidden
? 'inline'
: cssSourceMap,
},
},
...(use as webpack.Loader[]),
],
};
}),
);
}
if (buildOptions.extractCss) {
extraPlugins.push(
// extract global css from js files into own css file
new MiniCssExtractPlugin({ filename: `[name]${hashFormat.extract}.css` }),
// suppress empty .js files in css only entry points
new SuppressExtractedTextChunksWebpackPlugin(),
);
}
return {
entry: entryPoints,
module: { rules },
plugins: extraPlugins,
};
}<|fim▁end|> | // Use expanded as otherwise sass will remove comments that are needed for autoprefixer
// Ex: /* autoprefixer grid: autoplace */
// tslint:disable-next-line: max-line-length
// See: https://github.com/webpack-contrib/sass-loader/blob/45ad0be17264ceada5f0b4fb87e9357abe85c4ff/src/getSassOptions.js#L68-L70 |
<|file_name|>tcp_listen.py<|end_file_name|><|fim▁begin|><|fim▁hole|>
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 5555))
s.listen(1)
while 1:
conn, addr = s.accept()
#data = conn.recv(1024)
conn.send("blabla".encode())
conn.close()
if __name__ == '__main__':
main()<|fim▁end|> | #!/usr/bin/env python3
import socket |
<|file_name|>explorer_factory.rs<|end_file_name|><|fim▁begin|>// The MIT License (MIT)
//
// Copyright (c) 2015 dinowernli
//
// 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.
use explorer::Explorer;
use explorer::monte_carlo_explorer::MonteCarloExplorer;
use explorer::random_explorer::RandomExplorer;
use predictor::Predictor;
use random::RandomImpl;
/// An object which knows how to produce explorers.
pub trait ExplorerFactory {
fn create_monte_carlo_explorer<'a>(
&self, predictor: &'a mut Predictor) -> Box<Explorer + 'a>;
fn create_random_explorer(
&self) -> Box<Explorer>;
}
pub struct ExplorerFactoryImpl;
impl ExplorerFactoryImpl {
pub fn new() -> ExplorerFactoryImpl { ExplorerFactoryImpl }
}
impl ExplorerFactory for ExplorerFactoryImpl {<|fim▁hole|> &self, predictor: &'a mut Predictor) -> Box<Explorer + 'a> {
Box::new(MonteCarloExplorer::new(predictor))
}
fn create_random_explorer(&self) -> Box<Explorer> {
Box::new(RandomExplorer::new(Box::new(RandomImpl::create(235669))))
}
}<|fim▁end|> | fn create_monte_carlo_explorer<'a>( |
<|file_name|>skip_issue.go<|end_file_name|><|fim▁begin|>// Copyright 2018 Istio 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<|fim▁hole|>// See the License for the specific language governing permissions and
// limitations under the License.
package rules
import (
"go/ast"
"go/token"
"istio.io/tools/pkg/checker"
)
// SkipIssue requires that a `t.Skip()` call in test function should contain url to a issue.
// This helps to keep tracking of the issue that causes a test to be skipped.
// For example, this is a valid call,
// t.Skip("https://github.com/istio/istio/issues/6012")
// t.SkipNow() and t.Skipf() are not allowed.
type SkipIssue struct {
skipArgsRegex string // Defines arg in t.Skip() that should match.
}
// NewSkipByIssue creates and returns a SkipIssue object.
func NewSkipByIssue() *SkipIssue {
return &SkipIssue{
skipArgsRegex: `https:\/\/github\.com\/istio\/istio\/issues\/[0-9]+`,
}
}
// GetID returns skip_by_issue_rule.
func (lr *SkipIssue) GetID() string {
return GetCallerFileName()
}
// Check returns verifies if aNode is a valid t.Skip(), or aNode is not t.Skip(), t.SkipNow(),
// and t.Skipf(). If verification fails lrp creates a new report.
// This is an example for valid call t.Skip("https://github.com/istio/istio/issues/6012")
// These calls are not valid:
// t.Skip("https://istio.io/"),
// t.SkipNow(),
// t.Skipf("https://istio.io/%d", x).
func (lr *SkipIssue) Check(aNode ast.Node, fs *token.FileSet, lrp *checker.Report) {
if fn, isFn := aNode.(*ast.FuncDecl); isFn {
for _, bd := range fn.Body.List {
if ok, _ := matchFunc(bd, "t", "SkipNow"); ok {
lrp.AddItem(fs.Position(bd.Pos()), lr.GetID(), "Only t.Skip() is allowed and t.Skip() should contain an url to GitHub issue.")
} else if ok, _ := matchFunc(bd, "t", "Skipf"); ok {
lrp.AddItem(fs.Position(bd.Pos()), lr.GetID(), "Only t.Skip() is allowed and t.Skip() should contain an url to GitHub issue.")
} else if ok, fcall := matchFunc(bd, "t", "Skip"); ok && !matchFuncArgs(fcall, lr.skipArgsRegex) {
lrp.AddItem(fs.Position(bd.Pos()), lr.GetID(), "Only t.Skip() is allowed and t.Skip() should contain an url to GitHub issue.")
}
}
}
}<|fim▁end|> | //
// 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. |
<|file_name|>euler002.py<|end_file_name|><|fim▁begin|>T = int(raw_input())
for test in xrange(T):
N = int(raw_input())
a, b, result = 0, 1, 0
c = a+b
while c < N:
if c%2 == 0:
result += c
a,b = b,c
c = a+b<|fim▁hole|> print result<|fim▁end|> | |
<|file_name|>utility.go<|end_file_name|><|fim▁begin|>package utility
import (
"crypto/rand"
"encoding/base64"
"fmt"
"log"
"math"
"strconv"
"strings"
"time"
"encoding/binary"
"github.com/Dancapistan/gobase32"
"github.com/boatilus/peppercorn/db"
"github.com/boatilus/peppercorn/version"
"github.com/mssola/user_agent"
"github.com/spf13/viper"
)
// UserAgent is the type returned from ParseUserAgent()
type UserAgent struct {
Browser string
OS string
}
// crReplacer is used for RemoveCRs.
var crReplacer *strings.Replacer
func init() {
crReplacer = strings.NewReplacer("\r", "")
}
// Must accepts an error and, if the error is non-nil, aborts the application after logging the
// error.
func Must(err error) {
if err != nil {
log.Fatal(err)
}
}
// ObfuscateEmail accepts an email address and returns parts of it obfuscated with asterisks.
func ObfuscateEmail(address string) string {
s := strings.Split(address, "@")
// There's no ampersand present, more than one, or nothing preceding it, so we don't have a valid
// local part.
if len(s) == 1 || len(s) > 2 || len(s[0]) == 0 {
return address
}
domain := strings.Split(s[1], ".")
// There's no period present or more than one, or it does not have at least one character before
// the dot, so we don't have a valid domain.
if len(domain) == 1 || len(domain) > 2 || len(domain[0]) == 0 {
return address
}
return fmt.Sprintf("%s***@%s***.%s", string(s[0][0]), string(domain[0][0]), domain[1])
}
// ParseUserAgent accepts a User-Agent string and returns a struct filled with data we should
// display to users
func ParseUserAgent(userAgent string) *UserAgent {
ua := user_agent.New(userAgent)
browser, _ := ua.Browser() // Ignore version
osInfo := ua.OSInfo()
return &UserAgent{
Browser: browser,
OS: osInfo.Name + " " + osInfo.Version,
}
}
// FormatTime gives us a Ruby-style "X period ago"-type string from a date if the the date is
// fewer than 60 minutes earlier. Otherwise, returns a kitchen time if the post falls as the same
// date as the current time, and a full date of the format "January 2, 2006 at 3:04 PM" otherwise.
func FormatTime(t time.Time, current time.Time) string {
d := current.Sub(t)
seconds := int64(d.Seconds())
minutes := seconds / 60
if seconds < 60 {
return "less than a minute ago"
}
if seconds < 120 {
return "about a minute ago"
}
if minutes < 60 {
return fmt.Sprintf("%d minutes ago", minutes)
}
if t.Day() == current.Day() {
return t.Format("3:04 PM")
}
return t.Format("January 2, 2006 at 3:04 PM")
}
// GetVersionString returns the version as a string.
func GetVersionString() string {
return version.GetString()
}
// GetTitle returns the title string.
func GetTitle() string {
return viper.GetString("title")
}
// GetTitleWith returns the title string, with "- `appended`", or just the title if `appended`
// is blank.
func GetTitleWith(appended string) string {
if len(appended) == 0 {
return GetTitle()
}
return GetTitle() + " - " + appended
}
// CommifyCountType accepts a `db.CountType` and returns a string formtted with comma thousands
// separators (if necessary).
func CommifyCountType(n db.CountType) string {
return CommifyInt64(int64(n))
}
// CommifyInt64 accepts an `int64` and returns the commified representation of it.
func CommifyInt64(v int64) string {
if v == 0 {
return "0"
}
// We'll simply return the string-formatted value if it's non-zero and between -999 and 999
if v < 1000 && v > 0 || v > -1000 && v < 0 {
return strconv.FormatInt(v, 10)
}
// MinInt64 can't be negated to a usable value, so it has to be special-cased.
if v == math.MinInt64 {
return "-9,223,372,036,854,775,808"
}
isNegative := v < 0
if isNegative {
// Negate the value, as negativity causes issues for string formatting for our purposes.
v = -v
}
var parts [7]string
j := 6
for v > 999 {
mod := v % 1000
switch {
case mod < 10:
parts[j] = "00" + strconv.FormatInt(mod, 10)
case mod < 100:
parts[j] = "0" + strconv.FormatInt(mod, 10)
default:
parts[j] = strconv.FormatInt(mod, 10)
}
v = v / 1000
j--
}
parts[j] = strconv.FormatInt(v, 10)
if isNegative {
return "-" + strings.Join(parts[j:], ",")
}
return strings.Join(parts[j:], ",")
}
// ComputePage calculates the page number given the post number and the pagination value.
func ComputePage(postNum db.CountType, paginateEvery db.CountType) db.CountType {
pageCount := postNum / paginateEvery
pageModulo := postNum % paginateEvery
if pageModulo != 0 {
pageCount++
}
return pageCount
}
// RemoveCRs accepts a string and returns a new string with any instances of a Carriage Return
// character removed.
func RemoveCRs(s string) string {
return crReplacer.Replace(s)
}
// GetISO8601String accepts a `Time` and returns a string with an ISO8601 representation.
func GetISO8601String(t *time.Time) string {
if t == nil {
return ""
}
return t.Format("2006-01-02T15:04:05-0700")<|fim▁hole|>func GenerateRandomNonce() string {
n := 16
b := make([]byte, n)
_, err := rand.Read(b)
if err != nil {
return ""
}
return base64.StdEncoding.EncodeToString(b)
}
// GenerateRandomRecoveryCode generates a random, (hopefully) cryptographically-secure string 12
// characters in length. The string is encoded using Crockford's base32, since we can expect
// that recovery codes will be printed by the user and may need to be paper-transcribed at some
// point.
func GenerateRandomRecoveryCode() string {
b := make([]byte, 8)
_, err := rand.Read(b)
if err != nil {
log.Fatal(err)
}
n1 := binary.LittleEndian.Uint32(b[0:4])
n2 := binary.LittleEndian.Uint32(b[4:8])
b1 := base32.Encode(n1).Pad(6)
b2 := base32.Encode(n2).Pad(6)
return string(b1[0:6]) + string(b2[0:6])
}<|fim▁end|> | }
// GenerateRandomNonce creates a cryptographically-secure random base64 string 128 bits wide, for
// use as a nonce value Content-Security-Policy |
<|file_name|>auth_service.js<|end_file_name|><|fim▁begin|>// Copyright 2016 Hewlett-Packard Development Company, L.P.
//
// 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.
//
// END OF TERMS AND CONDITIONS
const nock = require('nock');
const expect = require('chai').expect;
const encryptUtil = require('./../app/routes/auth/encrypt.es6');
const fs = require('fs');
const async = require('async');
const resources = require('../app/resources/strings.es6');
// TODO: add test for TTL expiration.
// Disable eslint to allow for Nock generated objects
/* eslint-disable quote-props*/
/* eslint-disable no-unused-expressions */
/* eslint-disable no-useless-escape */
/* eslint-disable camelcase */
process.env.HE_ISSUER = "issue";
process.env.HE_AUTH_SERVICE_PORT = 0;
process.env.HE_AUTH_NO_COLLECTOR = 1;
process.env.HE_AUDIENCE = "audience";
process.env.HE_AUTH_MOCK_AUTH = "true";
process.env.HE_AUTH_SSL_PASS = "default";
process.env.JWE_SECRETS_PATH = "./test/assets/jwe_secrets_assets.pem";
process.env.VAULT_DEV_ROOT_TOKEN_ID = "default";
process.env.HE_IDENTITY_PORTAL_ENDPOINT = "http://example.com";
process.env.HE_IDENTITY_WS_ENDPOINT = "http://example.com";
process.env.JWE_TOKEN_PATH = "./test/assets/jwe_secrets_assets.pem";
process.env.JWE_TOKEN_URL_PATH = "./test/assets/jwe_secrets_assets.pem";
process.env.JWT_TOKEN_PATH = "./test/assets/jwe_secrets_assets.pem";
process.env.JWE_TOKEN_URL_PATH_PUB = "./test/assets/jwe_secrets_pub_assets.pem";
process.env.JWT_TOKEN_PATH_PUB = "./test/assets/jwe_secrets_pub_assets.pem";
process.env.HE_AUTH_SSL_KEY = "./test/assets/key.pem";
process.env.HE_AUTH_SSL_CERT = "./test/assets/cert.pem";
if (process.env.HTTP_PROXY || process.env.http_proxy) {
process.env.NO_PROXY = process.env.NO_PROXY ? process.env.NO_PROXY + ',vault' : 'vault';
process.env.no_proxy = process.env.no_proxy ? process.env.no_proxy + ',vault' : 'vault';
process.env.NO_PROXY = process.env.NO_PROXY ? process.env.NO_PROXY + ',basicauth' : 'basicauth';
process.env.no_proxy = process.env.no_proxy ? process.env.no_proxy + ',basicauth' : 'basicauth';
process.env.NO_PROXY = process.env.NO_PROXY ? process.env.NO_PROXY + ',localhost' : 'localhost';
process.env.no_proxy = process.env.no_proxy ? process.env.no_proxy + ',localhost' : 'localhost';
}
nock('http://vault:8200', {"encodedQueryParams": true})
.get('/v1/sys/init')
.reply(200, {"initialized": true}, ['Content-Type',
'application/json',
'Date',
'Tue, 01 Nov 2016 05:04:04 GMT',
'Content-Length',
'21',
'Connection',
'close']);
nock('http://vault:8200', {"encodedQueryParams": true})
.get('/v1/sys/seal-status')
.reply(200, {
"sealed": false, "t": 1,
"n": 1,
"progress": 0,
"version": "Vault v0.6.1",
"cluster_name": "vault-cluster-8ed1001e",
"cluster_id": "48a3ee1a-14fd-be4e-3cc5-bb023c56024e"
}, [
'Content-Type',
'application/json',
'Date',
'Tue, 01 Nov 2016 05:04:04 GMT',
'Content-Length',
'159',
'Connection',
'close'
]);
nock('http://vault:8200', {"encodedQueryParams": true})
.get('/v1/sys/mounts')
.reply(200, {
"secret/": {
"config": {
"default_lease_ttl": 0, "max_lease_ttl": 0
},
"description": "generic secret storage",
"type": "generic"
},
"cubbyhole/": {
"config": {
"default_lease_ttl": 0, "max_lease_ttl": 0
},
"description": "per-token private secret storage",
"type": "cubbyhole"
},
"sys/": {
"config": {
"default_lease_ttl": 0, "max_lease_ttl": 0
},
"description": "system endpoints used for control, policy and debugging",
"type": "system"
},
"request_id": "93f8c930-6ddf-6165-7989-63c598c14aac",
"lease_id": "",
"renewable": false,
"lease_duration": 0,
"data": {
"cubbyhole/": {
"config": {
"default_lease_ttl": 0, "max_lease_ttl": 0
},
"description": "per-token private secret storage",
"type": "cubbyhole"
},
"secret/": {
"config": {
"default_lease_ttl": 0, "max_lease_ttl": 0
},
"description": "generic secret storage",
"type": "generic"
},
"sys/": {
"config": {
"default_lease_ttl": 0, "max_lease_ttl": 0
},
"description": "system endpoints used for control, policy and debugging",
"type": "system"
}
},
"wrap_info": null,
"warnings": null,
"auth": null
}, [
'Content-Type',
'application/json',
'Date',
'Tue, 01 Nov 2016 05:04:04 GMT',
'Content-Length',
'961',
'Connection',
'close'
]);
nock('http://vault:8200', {"encodedQueryParams": true})
.get('/v1/sys/auth')
.reply(200, {
"token/": {
"config": {
"default_lease_ttl": 0,
"max_lease_ttl": 0
},
"description": "token based credentials",
"type": "token"
},
"request_id": "ad9b37e3-7963-3848-95b3-7915d8504202",
"lease_id": "",
"renewable": false,
"lease_duration": 0,
"data": {
"token/": {
"config": {
"default_lease_ttl": 0, "max_lease_ttl": 0
},
"description": "token based credentials",
"type": "token"
}
},
"wrap_info": null,
"warnings": null,
"auth": null
}, [
'Content-Type',
'application/json',
'Date',
'Tue, 01 Nov 2016 05:04:04 GMT',
'Content-Length',
'393',
'Connection',
'close'
]);
nock('http://vault:8200', {"encodedQueryParams": true})
.put('/v1/secret/abcd/integration', {
"integration_info": {
"name": "integration", "auth": {"type": "basic_auth"}
},
"user_info": {
"id": "abcd"
},
"secrets": {"token": "YWRtaW46YWRtaW4="}
})
.reply(204, "", ['Content-Type',
'application/json',
'Date',
'Tue, 01 Nov 2016 04:18:12 GMT',
'Connection',
'close']);
nock('http://vault:8200', {"encodedQueryParams": true})
.get('/v1/secret/abcd/integration')
.reply(200, {
"request_id": "c48cf5e1-e9c2-c16d-dfaa-847944584e20",
"lease_id": "",
"renewable": false,
"lease_duration": 2592000,
"data": {
"integration_info": {"auth": "auth", "name": "integration"},
"secrets": {"username": "admin", "password": "admin"},
"user_info": {"id": "abcd"}
},
"wrap_info": null,
"warnings": null,
"auth": null
}, ['Content-Type',
'application/json',
'Date',
'Fri, 11 Nov 2016 14:44:08 GMT',
'Content-Length',
'273',
'Connection',
'close']);
nock('http://vault:8200', {"encodedQueryParams": true})
.get('/v1/secret/DoesNotExists/integration')
.reply(404, {"errors": []}, ['Content-Type',
'application/json',
'Date',
'Fri, 11 Nov 2016 14:45:20 GMT',
'Content-Length',
'14',
'Connection',
'close']);
nock('http://vault:8200', {"encodedQueryParams": true})
.get('/v1/secret/abcd/DoesNotExists')
.reply(404, {"errors": []}, ['Content-Type',
'application/json',
'Date',
'Fri, 11 Nov 2016 14:45:20 GMT',
'Content-Length',
'14',
'Connection',
'close']);
nock('http://basicauth', {"encodedQueryParams": true})
.get('/success')
.reply(200, {"authenticated": true, "user": "admin"}, ['Server',
'nginx',
'Date',
'Sat, 12 Nov 2016 03:10:08 GMT',
'Content-Type',
'application/json',
'Content-Length',
'48',
'Connection',
'close',
'Access-Control-Allow-Origin',
'*',
'Access-Control-Allow-Credentials',
'true']);
nock('http://basicauth', {"encodedQueryParams": true})
.get('/failure')
.reply(401, {"authenticated": true, "user": "admin"}, ['Server',
'nginx',
'Date',
'Sat, 12 Nov 2016 03:10:08 GMT',
'Content-Type',
'application/json',
'Content-Length',
'48',
'Connection',
'close',
'Access-Control-Allow-Origin',
'*',
'Access-Control-Allow-Credentials',
'true']);
nock('http://vault:8200', {"encodedQueryParams": true})
.put('/v1/secret/abcd/integration', {
"integration_info": {
"name": "integration",
"auth": {
"type": "basic_auth",
"params": {
"endpoint": {
url: "http://basicauth/success",
verb: "GET"
}
}
}
},
"user_info": {
"id": "abcd"
},
"secrets": {
"token": "YWRtaW46YWRtaW4="
}
})
.reply(204, "", ['Content-Type',
'application/json',
'Date',
'Sat, 12 Nov 2016 03:10:08 GMT',
'Connection',
'close']);
nock('http://vault:8200', {"encodedQueryParams": true})
.put('/v1/secret/abcd/integration', {
"integration_info": {
"name": "integration",
"auth": {
"type": "basic_auth",
"params": {
}
}
},
"user_info": {
"id": "abcd"
},
"secrets": {
"token": "YWRtaW46YWRtaW4="
}
})
.reply(204, "", ['Content-Type',
'application/json',
'Date',
'Sat, 12 Nov 2016 03:10:08 GMT',
'Connection',
'close']);
nock('http://vault:8200', {"encodedQueryParams": true})
.put('/v1/secret/abcd/integration', {
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http:\/\/idmauth\/success",
verb: "POST"
}
}
}
},
"user_info": {
"id": "abcd"
},
"secrets": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ",
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"
}
})
.reply(204, "", ['Content-Type',
'application/json',
'Date',
'Sat, 12 Nov 2016 03:10:08 GMT',
'Connection',
'close']);
const authService = require('../server.es6');
const request = require('supertest')(authService.app);
/* eslint-disable no-undef */
let token = "";
let secret = "";
let secretPayload = {"username": "admin", "password": "admin"};
describe('Auth Service tests', function() {
this.timeout(20000);
before(function(done) {
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
});
it('should fail to yield token if fields are not properly set', function(done) {
request
.post('/token_urls')
.send({})
.expect(500, done);
});
it('should fail to yield token if url_props is not set', function(done) {
request
.post('/token_urls')
.send({
"user_info": {"id": "abcd"},
"integration_info": {"name": "integration", "auth": "auth"},
"bot_info": "xyz"
})
.expect(500, done);
});
it('should fail to yield token if bot_info is not set', function(done) {
request
.post('/token_urls')
.send({
"user_info": {"id": "abcd"},
"integration_info": {"name": "integration", "auth": "auth"},
"url_props": {"ttl": 300}
})
.expect(500, done);
});
it('should fail to yield token if integration_info is not set', function(done) {
request
.post('/token_urls')
.send({
"user_info": {"id": "abcd"},
"bot_info": "xyz",
"url_props": {"ttl": 300}
})
.expect(500, done);
});
it('should fail to yield token if user_info is not set', function(done) {
request
.post('/token_urls')
.send({
"integration_info": {"name": "integration", "auth": "auth"},
"bot_info": "xyz",
"url_props": {"ttl": 300}
})
.expect(500, done);
});
it('should fail to yield token if integration_info.name is not set', function(done) {
request
.post('/token_urls')
.send({
"integration_info": {"auth": "auth"},
"bot_info": "xyz",
"url_props": {"ttl": 300}
})
.expect(500, done);
});
it('should fail to yield token if integration_info.auth is not set', function(done) {
request
.post('/token_urls')
.send({
"integration_info": {"name": "integration"},
"bot_info": "xyz",
"url_props": {"ttl": 300}
})
.expect(500, done);
});
it('should yield valid token if body is correctly built', function(done) {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {"type": "basic_auth"}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
});
it('should return an error when posting secrets without providing a token or secret', function(done) {
request
.post('/secrets')
.send({})
.expect(500, done);
});
it('should return an error when posting secrets without providing a valid token', function(done) {
request
.post('/secrets')
.send({"secrets": secret})
.expect(500, done);
});
it('should return an error when posting secrets without providing a valid secret', function(done) {
request
.post('/secrets')
.send({"secrets": {"invalid": "secret"}, "token": token})
.expect(500, done);
});
it('should store the secret given a valid token and secret', function(done) {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(201, done);
});
it('should be able to retrieve the stored secret', function(done) {
let userID = 'abcd';
let integrationName = 'integration';
request
.get(`/secrets/${userID}/${integrationName}`)
.expect(200)
.expect(resp => {
expect(resp).to.exist;
expect(resp.body).to.exist;
expect(resp.body.secrets).to.exist;
expect(resp.body.secrets).to.be.an('object');
expect(resp.body.integration_info).to.exist;
expect(resp.body.integration_info).to.be.an('object');
expect(resp.body.integration_info.name).to.exist;
expect(resp.body.integration_info.auth).to.exist;
expect(resp.body.user_info).to.exist;
expect(resp.body.user_info).to.be.an('object');
expect(resp.body.user_info.id).to.exist;
})
.end(done);
});
it('should error out when a non-existing userID is given', function(done) {
let userID = 'DoesNotExists';
let integrationName = 'integration';
request
.get(`/secrets/${userID}/${integrationName}`)
.expect(404, done);
});
it('should error out when a non-existing integrationName is given', function(done) {
let userID = 'abcd';
let integrationName = 'DoesNotExists';
request
.get(`/secrets/${userID}/${integrationName}`)
.expect(404, done);
});
});
describe('Auth Service endpoint authentication test', function() {
it('should yield valid token with an embedded endpoint (credentials set to admin:admin)', function(done) {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "basic_auth",
"params": {
"endpoint": {
url: "http://basicauth/success",
verb: "GET"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
});
it('should store the secret given valid credentials', function(done) {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(201, done);
});
});
describe('Auth Service endpoint authentication test for failure', function() {
it('should yield valid token with an embedded endpoint (credentials set to admin:newPassword)', function(done) {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "basic_auth",
"params": {
"endpoint": {
url: "http://basicauth/failure",
verb: "GET"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
});
it('should not store the secret given invalid credentials', function(done) {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(401, done);
});
it('should not store the secret if `verb` is not specified', function(done) {
async.series([
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "basic_auth",
"params": {
"endpoint": {
url: "http://basicauth/success"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('should not store the secret if `url` is not specified', function(done) {
async.series([
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "basic_auth",
"params": {
"endpoint": {
verb: "GET"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('should store the secret if `endpoint` is not specified', function(done) {
async.series([
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "basic_auth",
"params": {
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(201, done);
});
});
});
describe('Test IDM authentication', function() {
it('Should fail if missing endpoint', function(done) {
async.series([
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('Should fail if missing url', function(done) {
async.series([
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
verb: "POST"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('Should fail if missing verb', function(done) {
async.series([
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://basicauth/success"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('Should fail if missing secrets', function(done) {
request
.post('/secrets')
.send({"token": token})
.expect(500, done);
});
it('Should fail if missing user', function(done) {
async.series([
done => {
let secretPayload = {
"tenant": {
"username": "admin",
"password": "admin"
}
};
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
},
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://basicauth/success",
verb: "POST"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('Should fail if missing username in user structure', function(done) {
async.series([
done => {
let secretPayload = {
"user": {
"password": "admin"
},
"tenant": {
"username": "admin",
"password": "admin"
}
};
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
},
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://basicauth/success",
verb: "POST"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('Should fail if missing password in user structure', function(done) {
async.series([
done => {
let secretPayload = {
"user": {
"username": "admin"
},
"tenant": {
"username": "admin",
"password": "admin"
}
};
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
},
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://basicauth/success",
verb: "POST"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('Should fail if missing tenant', function(done) {
async.series([
done => {
let secretPayload = {
"user": {
"username": "admin",
"password": "admin"
}
};
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
},
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://basicauth/success",
verb: "POST"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('Should fail if missing username in tenant structure', function(done) {
async.series([
done => {
let secretPayload = {
"user": {
"username": "admin",
"password": "admin"
},
"tenant": {
"password": "admin"
}
};
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
},
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://basicauth/success",
verb: "POST"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('Should fail if missing password in tenant structure', function(done) {
async.series([
done => {
let secretPayload = {
"user": {
"username": "admin",
"password": "admin"
},
"tenant": {
"username": "admin"
}
};
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
},
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://basicauth/success",
verb: "POST"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('Should fail if missing NAME in tenant structure', function(done) {
async.series([
done => {
let secretPayload = {
"user": {
"username": "admin",
"password": "admin"
},
"tenant": {
"username": "admin",
"password": "admin"
}
};
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
},
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://basicauth/success",
verb: "POST"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('Should fail if an unsupported http verb is given.', function(done) {
async.series([
done => {
let secretPayload = {
"user": {
"username": "admin",
"password": "admin"
},
"tenant": {
"username": "admin",
"password": "admin"
}
};
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
},
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://idmauth/success",
verb: "GET"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('Should successfully authenticate when payload is built correctly.', function(done) {
async.series([
done => {
let secretPayload = {
"user": {
"username": resources.MOCK_IDM_CREDS.username,
"password": resources.MOCK_IDM_CREDS.password
},
"tenant": {
"name": resources.MOCK_IDM_CREDS.tenantName,
"username": resources.MOCK_IDM_CREDS.tenantUsername,
"password": resources.MOCK_IDM_CREDS.tenantPassword
}
};
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
},
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://idmauth/success",
verb: "POST"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(201, done);
});
});
it('Should not allow access to an agent with incorrect user credentials.', function(done) {
async.series([
done => {
let secretPayload = {
"user": {
"username": "wrong",
"password": "wrong"
},
"tenant": {
"name": resources.MOCK_IDM_CREDS.tenantName,
"username": resources.MOCK_IDM_CREDS.tenantUsername,
"password": resources.MOCK_IDM_CREDS.tenantPassword
}
};
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
},
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://idmauth/failure",
verb: "POST"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')<|fim▁hole|> expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(401, done);
});
});
it('Should not allow access to an agent with incorrect tenant credentials.', function(done) {
async.series([
done => {
let secretPayload = {
"user": {
"username": resources.MOCK_IDM_CREDS.username,
"password": resources.MOCK_IDM_CREDS.password
},
"tenant": {
"name": resources.MOCK_IDM_CREDS.tenantName,
"username": "wrong",
"password": "wrong"
}
};
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
},
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://idmauth/failure",
verb: "POST"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(401, done);
});
});
it('Should not allow access to an agent with incorrect tenant NAME', function(done) {
async.series([
done => {
let secretPayload = {
"user": {
"username": resources.MOCK_IDM_CREDS.username,
"password": resources.MOCK_IDM_CREDS.password
},
"tenant": {
"name": "wrong",
"username": resources.MOCK_IDM_CREDS.tenantUsername,
"password": resources.MOCK_IDM_CREDS.tenantPassword
}
};
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
},
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://idmauth/failure",
verb: "POST"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(401, done);
});
});
});<|fim▁end|> | .send(payload)
.expect(201)
.expect(res => { |
<|file_name|>fake_server_verifier.cc<|end_file_name|><|fim▁begin|>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/sync/test/fake_server/fake_server_verifier.h"
#include <map>
#include <memory>
#include <set>
#include <vector>
#include "base/json/json_writer.h"
#include "components/sync/test/fake_server/fake_server.h"
using base::JSONWriter;
using std::string;
using testing::AssertionFailure;
using testing::AssertionResult;
using testing::AssertionSuccess;
namespace fake_server {
namespace {
AssertionResult DictionaryCreationAssertionFailure() {
return AssertionFailure() << "FakeServer failed to create an entities "
<< "dictionary.";
}
AssertionResult VerificationCountAssertionFailure(size_t actual_count,
size_t expected_count) {
return AssertionFailure() << "Actual count: " << actual_count << "; "
<< "Expected count: " << expected_count;
}
AssertionResult UnknownTypeAssertionFailure(const string& model_type) {
return AssertionFailure() << "Verification not attempted. Unknown ModelType: "
<< model_type;
}
AssertionResult VerifySessionsHierarchyEquality(
const SessionsHierarchy& expected,
const SessionsHierarchy& actual) {
if (expected.Equals(actual))
return AssertionSuccess() << "Sessions hierarchies are equal.";
return AssertionFailure() << "Sessions hierarchies are not equal. "
<< "FakeServer contents: " << actual.ToString()
<< "; Expected contents: " << expected.ToString();
}
// Caller maintains ownership of |entities|.
string ConvertFakeServerContentsToString(
const base::DictionaryValue& entities) {
string entities_str;
if (!JSONWriter::WriteWithOptions(entities, JSONWriter::OPTIONS_PRETTY_PRINT,
&entities_str)) {
entities_str = "Could not convert FakeServer contents to string.";
}
return "FakeServer contents:\n" + entities_str;
}
} // namespace
FakeServerVerifier::FakeServerVerifier(FakeServer* fake_server)
: fake_server_(fake_server) {}
FakeServerVerifier::~FakeServerVerifier() {}
AssertionResult FakeServerVerifier::VerifyEntityCountByType(
size_t expected_count,
syncer::ModelType model_type) const {
std::unique_ptr<base::DictionaryValue> entities =
fake_server_->GetEntitiesAsDictionaryValue();
if (!entities) {
return DictionaryCreationAssertionFailure();
}
string model_type_string = ModelTypeToString(model_type);
base::ListValue* entity_list = nullptr;
if (!entities->GetList(model_type_string, &entity_list)) {
return UnknownTypeAssertionFailure(model_type_string);
} else if (expected_count != entity_list->GetSize()) {
return VerificationCountAssertionFailure(entity_list->GetSize(),
expected_count)
<< "\n\n"
<< ConvertFakeServerContentsToString(*entities);
}
return AssertionSuccess();
}
AssertionResult FakeServerVerifier::VerifyEntityCountByTypeAndName(
size_t expected_count,
syncer::ModelType model_type,
const string& name) const {
std::unique_ptr<base::DictionaryValue> entities =
fake_server_->GetEntitiesAsDictionaryValue();
if (!entities) {
return DictionaryCreationAssertionFailure();
}
string model_type_string = ModelTypeToString(model_type);
base::ListValue* entity_list = nullptr;
size_t actual_count = 0;
if (entities->GetList(model_type_string, &entity_list)) {
base::Value name_value(name);
for (const auto& entity : *entity_list) {
if (name_value.Equals(&entity))
actual_count++;
}
}
if (!entity_list) {
return UnknownTypeAssertionFailure(model_type_string);
} else if (actual_count != expected_count) {
return VerificationCountAssertionFailure(actual_count, expected_count)
<< "; Name: " << name << "\n\n"
<< ConvertFakeServerContentsToString(*entities);
}
return AssertionSuccess();
}
AssertionResult FakeServerVerifier::VerifySessions(
const SessionsHierarchy& expected_sessions) {
std::vector<sync_pb::SyncEntity> sessions =
fake_server_->GetSyncEntitiesByModelType(syncer::SESSIONS);
// Look for the sessions entity containing a SessionHeader and cache all tab
// IDs/URLs. These will be used later to construct a SessionsHierarchy.
sync_pb::SessionHeader session_header;
std::map<int, int> tab_ids_to_window_ids;
std::map<int, std::string> tab_ids_to_urls;
std::string session_tag;
for (const auto& entity : sessions) {
sync_pb::SessionSpecifics session_specifics = entity.specifics().session();
// Ensure that all session tags match the first entity. Only one session is
// supported for verification at this time.
if (session_tag.empty()) {
session_tag = session_specifics.session_tag();
} else if (session_specifics.session_tag() != session_tag) {
return AssertionFailure() << "Multiple session tags found.";
}
if (session_specifics.has_header()) {
session_header = session_specifics.header();
} else if (session_specifics.has_tab()) {
const sync_pb::SessionTab& tab = session_specifics.tab();
const sync_pb::TabNavigation& nav =
tab.navigation(tab.current_navigation_index());
// Only read from tabs that have a title on their current navigation
// entry. This the result of an oddity around the timing of sessions
// related changes. Sometimes when opening a new window, the first
// navigation will be committed before the title has been set. Then a
// subsequent commit will go through for that same navigation. Because
// this logic is used to ensure synchronization, we are going to exclude
// partially omitted navigations. The full navigation should typically be
// committed in full immediately after we fail a check because of this.
if (nav.has_title()) {
tab_ids_to_window_ids[tab.tab_id()] = tab.window_id();
tab_ids_to_urls[tab.tab_id()] = nav.virtual_url();
}
}
}
// Create a SessionsHierarchy from the cached SyncEntity data. This loop over
// the SessionHeader also ensures its data corresponds to the data stored in
// each SessionTab.
SessionsHierarchy actual_sessions;
for (const auto& window : session_header.window()) {
std::multiset<std::string> tab_urls;<|fim▁hole|> return AssertionFailure() << "Malformed data: Tab entity not found.";
}
tab_urls.insert(tab_ids_to_urls[tab_id]);
}
actual_sessions.AddWindow(tab_urls);
}
return VerifySessionsHierarchyEquality(expected_sessions, actual_sessions);
}
} // namespace fake_server<|fim▁end|> | for (int tab_id : window.tab()) {
if (tab_ids_to_window_ids.find(tab_id) == tab_ids_to_window_ids.end()) { |
<|file_name|>bitcoin_sr.ts<|end_file_name|><|fim▁begin|><TS language="sr" version="2.1">
<context>
<name>AddressBookPage</name>
<message>
<source>Right-click to edit address or label</source>
<translation>Kliknite desnim klikom radi izmene adrese ili oznake</translation>
</message>
<message>
<source>Create a new address</source>
<translation>Napravite novu adresu</translation>
</message>
<message>
<source>&New</source>
<translation>Novo</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopirajte trenutno izabranu adresu</translation>
</message>
<message>
<source>&Copy</source>
<translation>Kopirajte</translation>
</message>
<message>
<source>C&lose</source>
<translation>Zatvorite</translation>
</message>
<message>
<source>Delete the currently selected address from the list</source>
<translation>Izbrisite trenutno izabranu adresu sa liste</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>Eksportuj podatke iz izabrane kartice u fajl</translation>
</message>
<message>
<source>&Delete</source>
<translation>&Избриши</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<source>Enter passphrase</source>
<translation>Унесите лозинку</translation>
</message>
<message>
<source>New passphrase</source>
<translation>Нова лозинка</translation>
</message>
<message>
<source>Repeat new passphrase</source>
<translation>Поновите нову лозинку</translation>
</message>
</context>
<context>
<name>BanTableModel</name>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<source>Synchronizing with network...</source>
<translation>Синхронизација са мрежом у току...</translation>
</message>
<message>
<source>&Overview</source>
<translation>&Општи преглед</translation>
</message>
<message>
<source>Show general overview of wallet</source>
<translation>Погледајте општи преглед новчаника</translation>
</message>
<message>
<source>&Transactions</source>
<translation>&Трансакције</translation>
</message>
<message>
<source>Browse transaction history</source>
<translation>Претражите историјат трансакција</translation>
</message>
<message>
<source>E&xit</source>
<translation>I&zlaz</translation>
</message>
<message>
<source>Quit application</source>
<translation>Напустите програм</translation>
</message>
<message>
<source>About &Qt</source>
<translation>О &Qt-у</translation>
</message>
<message>
<source>Show information about Qt</source>
<translation>Прегледајте информације о Qt-у</translation>
</message>
<message>
<source>&Options...</source>
<translation>П&оставке...</translation>
</message>
<message>
<source>&Encrypt Wallet...</source>
<translation>&Шифровање новчаника...</translation>
</message>
<message>
<source>&Backup Wallet...</source>
<translation>&Backup новчаника</translation>
</message>
<message>
<source>&Change Passphrase...</source>
<translation>Промени &лозинку...</translation>
</message>
<message>
<source>Send coins to a CannabisCoin address</source>
<translation>Пошаљите новац на cannabiscoin адресу</translation>
</message>
<message>
<source>Change the passphrase used for wallet encryption</source>
<translation>Мењање лозинке којом се шифрује новчаник</translation>
</message>
<message>
<source>Wallet</source>
<translation>новчаник</translation>
</message>
<message>
<source>&Send</source>
<translation>&Пошаљи</translation>
</message>
<message>
<source>&File</source>
<translation>&Фајл</translation>
</message>
<message>
<source>&Settings</source>
<translation>&Подешавања</translation>
</message>
<message>
<source>&Help</source>
<translation>П&омоћ</translation>
</message>
<message>
<source>Tabs toolbar</source>
<translation>Трака са картицама</translation>
</message>
<message>
<source>Up to date</source>
<translation>Ажурно</translation>
</message>
<message>
<source>Catching up...</source>
<translation>Ажурирање у току...</translation>
</message>
<message>
<source>Sent transaction</source>
<translation>Послана трансакција</translation>
</message>
<message>
<source>Incoming transaction</source>
<translation>Придошла трансакција</translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Новчаник јс <b>шифрован</b> и тренутно <b>откључан</b></translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Новчаник јс <b>шифрован</b> и тренутно <b>закључан</b></translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Amount:</source>
<translation>Iznos:</translation>
</message>
<message>
<source>Amount</source>
<translation>iznos</translation>
</message>
<message>
<source>Date</source>
<translation>datum</translation>
</message>
<message>
<source>Confirmed</source>
<translation>Potvrdjen</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<source>Edit Address</source>
<translation>Измени адресу</translation>
</message>
<message>
<source>&Label</source>
<translation>&Етикета</translation>
</message>
<message>
<source>&Address</source>
<translation>&Адреса</translation>
</message>
</context>
<context>
<name>FreespaceChecker</name>
</context>
<context>
<name>HelpMessageDialog</name>
<message>
<source>version</source>
<translation>верзија</translation>
</message>
<message>
<source>Usage:</source>
<translation>Korišćenje:</translation>
</message>
</context>
<context>
<name>Intro</name>
</context>
<context>
<name>OpenURIDialog</name>
</context>
<context>
<name>OptionsDialog</name>
<message>
<source>Options</source>
<translation>Поставке</translation>
</message>
<message>
<source>W&allet</source>
<translation>новчаник</translation>
</message>
<message>
<source>&Unit to show amounts in:</source>
<translation>&Јединица за приказивање износа:</translation>
</message>
<message>
<source>&OK</source>
<translation>&OK</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<source>Form</source>
<translation>Форма</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
</context>
<context>
<name>PeerTableModel</name>
</context>
<context>
<name>QObject</name>
<message>
<source>Amount</source>
<translation>iznos</translation>
</message>
</context>
<context>
<name>QRImageWidget</name>
</context>
<context>
<name>RPCConsole</name>
</context>
<context>
<name>ReceiveCoinsDialog</name>
<message>
<source>&Amount:</source>
<translation>Iznos:</translation>
</message>
<message>
<source>&Label:</source>
<translation>&Етикета</translation>
</message>
<message>
<source>&Message:</source>
<translation>Poruka:</translation>
</message>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<source>Copy &Address</source>
<translation>Kopirajte adresu</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>Send Coins</source>
<translation>Слање новца</translation>
</message>
<message>
<source>Amount:</source>
<translation>Iznos:</translation>
</message>
<message>
<source>Confirm the send action</source>
<translation>Потврди акцију слања</translation>
</message>
<message>
<source>S&end</source>
<translation>&Пошаљи</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<source>A&mount:</source>
<translation>Iznos:</translation>
</message>
<message>
<source>&Label:</source>
<translation>&Етикета</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt+</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt+П</translation>
</message>
<message>
<source>Message:</source>
<translation>Poruka:</translation>
</message>
</context>
<context>
<name>SendConfirmationDialog</name>
</context>
<context>
<name>ShutdownWindow</name>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<source>Alt+A</source>
<translation>Alt+</translation>
</message>
<message><|fim▁hole|><context>
<name>SplashScreen</name>
<message>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
</context>
<context>
<name>TransactionDesc</name>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<source>This pane shows a detailed description of the transaction</source>
<translation>Ovaj odeljak pokazuje detaljan opis transakcije</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
</context>
<context>
<name>TransactionView</name>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
</context>
<context>
<name>WalletFrame</name>
</context>
<context>
<name>WalletModel</name>
</context>
<context>
<name>WalletView</name>
</context>
<context>
<name>bitcoin-core</name>
<message>
<source>Options:</source>
<translation>Opcije</translation>
</message>
<message>
<source>Specify data directory</source>
<translation>Gde je konkretni data direktorijum </translation>
</message>
<message>
<source>Accept command line and JSON-RPC commands</source>
<translation>Prihvati komandnu liniju i JSON-RPC komande</translation>
</message>
<message>
<source>Run in the background as a daemon and accept commands</source>
<translation>Radi u pozadini kao daemon servis i prihvati komande</translation>
</message>
<message>
<source>Username for JSON-RPC connections</source>
<translation>Korisničko ime za JSON-RPC konekcije</translation>
</message>
<message>
<source>Password for JSON-RPC connections</source>
<translation>Lozinka za JSON-RPC konekcije</translation>
</message>
<message>
<source>Loading addresses...</source>
<translation>učitavam adrese....</translation>
</message>
<message>
<source>Loading block index...</source>
<translation>Učitavam blok indeksa...</translation>
</message>
<message>
<source>Loading wallet...</source>
<translation>Новчаник се учитава...</translation>
</message>
<message>
<source>Rescanning...</source>
<translation>Ponovo skeniram...</translation>
</message>
<message>
<source>Done loading</source>
<translation>Završeno učitavanje</translation>
</message>
</context>
</TS><|fim▁end|> | <source>Alt+P</source>
<translation>Alt+П</translation>
</message>
</context> |
<|file_name|>get-initial-game-state.test.js<|end_file_name|><|fim▁begin|>"use strict";
const test = require("tape");
const aceyDeuceyGameEngine = require("../");
const getInitialGameState = aceyDeuceyGameEngine.getInitialGameState;
test("getInitialGameState", t => {
t.plan(1);
const gameState = {
board: [
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},<|fim▁hole|> {isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0}
],
isPlayerOne: true,
playerOne: {
initialPieces: 15,
barPieces: 0,
winningPieces: 0
},
playerTwo: {
initialPieces: 15,
barPieces: 0,
winningPieces:0
}
};
t.deepEqual(getInitialGameState(), gameState, "returns the correct gameState object");
});<|fim▁end|> | {isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0}, |
<|file_name|>menu.module.ts<|end_file_name|><|fim▁begin|>/*
"l'Agenda Collaboratif"
Copyright (C) 2016 Valentin VIENNOT
Contact : [email protected]
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
You have to put a copy of this program's license into your project.
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.
FULL LICENSE FILE : https://github.com/misterw97/agendacollaboratif/edit/master/LICENSE
*/
import {NgModule, Component, OnInit, OnDestroy} from "@angular/core";
import {CommonModule} from "@angular/common";
import {RouterModule} from "@angular/router";
import {SyncService} from "../services/sync.service";
import {DateService} from "../services/date.service";
import {IntervalObservable} from "rxjs/observable/IntervalObservable";
import {ParseService} from "../services/parse.service";
import {Devoir} from "../concepts/devoir";
import {Section} from "../concepts/section";
import {TooltipModule} from "../../components/tooltip/tooltip";
@Component({
moduleId: module.id,
selector: 'agd-menu',
templateUrl: './menu.module.html',
providers: [
DateService,
ParseService
]
})
export class Menu implements OnInit, OnDestroy {
private interval: any;<|fim▁hole|> constructor(public _sync: SyncService,
private _date: DateService,
private _parse: ParseService) {
this.sections = [];
}
ngOnInit(): void {
this.sync();
this.interval = IntervalObservable.create(60000).subscribe((t) => this.sync());
}
ngOnDestroy(): void {
this.interval.unsubscribe();
}
private sync(): void {
console.log("Mise à jour du semainier...");
let sections = Section.getSections(this.getDevoirs(), this._date).sections;
this.sections = this.transformSections(sections);
}
private getDevoirs(): Devoir[] {
// Récupère les devoirs depuis le localStorage
return this._parse.parse("devoirs");
}
private transformSections(sections: Section[]): Section[] {
let today: number = (new Date()).getDate();
let date: Date = new Date();
let retour: Section[] = [];
let j = 0;
for (let i: number = today; i < today + 9; i++) {
if (sections[j].titre === date.getDate().toString()) {
retour.push(sections[j]);
j++;
} else {
retour.push({
titre: date.getDate().toString(),
sous_titre: this._date.getDayTiny(date),
devoirs: [],
mois: null
});
}
date.setDate(date.getDate() + 1);
}
return retour;
}
}
@NgModule({
imports: [CommonModule, RouterModule, TooltipModule],
exports: [Menu],
declarations: [Menu]
})
export class MenuAgdModule {
}<|fim▁end|> | public sections: Section[];
|
<|file_name|>Searching_Faculty.py<|end_file_name|><|fim▁begin|>import time
import os
import sys
import pickle
a=sys.argv[1]
q=open('facultysubject.txt','r')
w=open('facultydept.txt','r')
e=open('facultyprojects.txt','r')
dic1={}
dic2={}<|fim▁hole|>##print dic2.keys()
dic3=pickle.load(e)
#3print dic3.keys()
print 'NAME OF FACULTY: '+a+'\n'
print 'DETAILS AVAILABLE:- '+'\n'
print ' **************SEARACHING***************'
time.sleep(2)
if dic1.has_key(a)==True :
var1=dic1[a]
##print var1
var ='SUBJECT OF FACULTY: '+var1
print var+'\n'
if dic2.has_key(a)==True :
var2=dic2[a]
var3='DEPT. OF FACULTY: '+var2
print var3+'\n'
if dic3.has_key(a)==True :
var4=dic3[a]
var5='ONGOING PROJECTS: '+var4
print var5+'\n'
if dic1.has_key(a)==False and dic2.has_key(a)==False and dic3.has_key(a)==False :
print ' **************SEARACHING***************'
time.sleep(2)
print ' ........Sorry!No Matches Found.........'<|fim▁end|> | dic3={}
dic1=pickle.load(q)
##print dic1.keys()
dic2=pickle.load(w) |
<|file_name|>crud.py<|end_file_name|><|fim▁begin|># sql/crud.py
# Copyright (C) 2005-2016 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Functions used by compiler.py to determine the parameters rendered
within INSERT and UPDATE statements.
"""
from .. import util
from .. import exc
from . import dml
from . import elements
import operator
REQUIRED = util.symbol('REQUIRED', """
Placeholder for the value within a :class:`.BindParameter`
which is required to be present when the statement is passed
to :meth:`.Connection.execute`.
This symbol is typically used when a :func:`.expression.insert`
or :func:`.expression.update` statement is compiled without parameter
values present.
""")
ISINSERT = util.symbol('ISINSERT')
ISUPDATE = util.symbol('ISUPDATE')
ISDELETE = util.symbol('ISDELETE')
def _setup_crud_params(compiler, stmt, local_stmt_type, **kw):
restore_isinsert = compiler.isinsert
restore_isupdate = compiler.isupdate
restore_isdelete = compiler.isdelete
should_restore = (
restore_isinsert or restore_isupdate or restore_isdelete
) or len(compiler.stack) > 1
if local_stmt_type is ISINSERT:
compiler.isupdate = False
compiler.isinsert = True
elif local_stmt_type is ISUPDATE:
compiler.isupdate = True
compiler.isinsert = False
elif local_stmt_type is ISDELETE:
if not should_restore:
compiler.isdelete = True
else:
assert False, "ISINSERT, ISUPDATE, or ISDELETE expected"
try:
if local_stmt_type in (ISINSERT, ISUPDATE):
return _get_crud_params(compiler, stmt, **kw)
finally:
if should_restore:
compiler.isinsert = restore_isinsert
compiler.isupdate = restore_isupdate
compiler.isdelete = restore_isdelete
def _get_crud_params(compiler, stmt, **kw):
"""create a set of tuples representing column/string pairs for use
in an INSERT or UPDATE statement.
Also generates the Compiled object's postfetch, prefetch, and
returning column collections, used for default handling and ultimately
populating the ResultProxy's prefetch_cols() and postfetch_cols()
collections.
"""
compiler.postfetch = []
compiler.insert_prefetch = []
compiler.update_prefetch = []
compiler.returning = []
# no parameters in the statement, no parameters in the
# compiled params - return binds for all columns
if compiler.column_keys is None and stmt.parameters is None:
return [
(c, _create_bind_param(
compiler, c, None, required=True))
for c in stmt.table.columns
]
if stmt._has_multi_parameters:
stmt_parameters = stmt.parameters[0]
else:
stmt_parameters = stmt.parameters
# getters - these are normally just column.key,
# but in the case of mysql multi-table update, the rules for
# .key must conditionally take tablename into account
_column_as_key, _getattr_col_key, _col_bind_name = \
_key_getters_for_crud_column(compiler, stmt)
# if we have statement parameters - set defaults in the
# compiled params
if compiler.column_keys is None:
parameters = {}
else:
parameters = dict((_column_as_key(key), REQUIRED)
for key in compiler.column_keys
if not stmt_parameters or
key not in stmt_parameters)
# create a list of column assignment clauses as tuples
values = []
if stmt_parameters is not None:
_get_stmt_parameters_params(
compiler,
parameters, stmt_parameters, _column_as_key, values, kw)
check_columns = {}
# special logic that only occurs for multi-table UPDATE
# statements
if compiler.isupdate and stmt._extra_froms and stmt_parameters:
_get_multitable_params(
compiler, stmt, stmt_parameters, check_columns,
_col_bind_name, _getattr_col_key, values, kw)
if compiler.isinsert and stmt.select_names:
_scan_insert_from_select_cols(
compiler, stmt, parameters,
_getattr_col_key, _column_as_key,
_col_bind_name, check_columns, values, kw)
else:
_scan_cols(
compiler, stmt, parameters,
_getattr_col_key, _column_as_key,
_col_bind_name, check_columns, values, kw)
if parameters and stmt_parameters:
check = set(parameters).intersection(
_column_as_key(k) for k in stmt_parameters
).difference(check_columns)
if check:
raise exc.CompileError(
"Unconsumed column names: %s" %
(", ".join("%s" % c for c in check))
)
if stmt._has_multi_parameters:
values = _extend_values_for_multiparams(compiler, stmt, values, kw)
return values
def _create_bind_param(
compiler, col, value, process=True,
required=False, name=None, **kw):
if name is None:
name = col.key
bindparam = elements.BindParameter(
name, value, type_=col.type, required=required)
bindparam._is_crud = True
if process:
bindparam = bindparam._compiler_dispatch(compiler, **kw)
return bindparam
def _key_getters_for_crud_column(compiler, stmt):
if compiler.isupdate and stmt._extra_froms:
# when extra tables are present, refer to the columns
# in those extra tables as table-qualified, including in
# dictionaries and when rendering bind param names.
# the "main" table of the statement remains unqualified,
# allowing the most compatibility with a non-multi-table
# statement.
_et = set(stmt._extra_froms)
def _column_as_key(key):
str_key = elements._column_as_key(key)
if hasattr(key, 'table') and key.table in _et:
return (key.table.name, str_key)
else:
return str_key
def _getattr_col_key(col):
if col.table in _et:
return (col.table.name, col.key)
else:
return col.key
def _col_bind_name(col):
if col.table in _et:
return "%s_%s" % (col.table.name, col.key)
else:
return col.key
else:
_column_as_key = elements._column_as_key
_getattr_col_key = _col_bind_name = operator.attrgetter("key")
return _column_as_key, _getattr_col_key, _col_bind_name
def _scan_insert_from_select_cols(
compiler, stmt, parameters, _getattr_col_key,
_column_as_key, _col_bind_name, check_columns, values, kw):
need_pks, implicit_returning, \
implicit_return_defaults, postfetch_lastrowid = \
_get_returning_modifiers(compiler, stmt)
cols = [stmt.table.c[_column_as_key(name)]
for name in stmt.select_names]
compiler._insert_from_select = stmt.select
add_select_cols = []
if stmt.include_insert_from_select_defaults:
col_set = set(cols)
for col in stmt.table.columns:
if col not in col_set and col.default:
cols.append(col)
for c in cols:
col_key = _getattr_col_key(c)
if col_key in parameters and col_key not in check_columns:
parameters.pop(col_key)
values.append((c, None))
else:
_append_param_insert_select_hasdefault(
compiler, stmt, c, add_select_cols, kw)
if add_select_cols:
values.extend(add_select_cols)
compiler._insert_from_select = compiler._insert_from_select._generate()
compiler._insert_from_select._raw_columns = \
tuple(compiler._insert_from_select._raw_columns) + tuple(
expr for col, expr in add_select_cols)
def _scan_cols(
compiler, stmt, parameters, _getattr_col_key,
_column_as_key, _col_bind_name, check_columns, values, kw):
need_pks, implicit_returning, \
implicit_return_defaults, postfetch_lastrowid = \
_get_returning_modifiers(compiler, stmt)
if stmt._parameter_ordering:
parameter_ordering = [
_column_as_key(key) for key in stmt._parameter_ordering
]
ordered_keys = set(parameter_ordering)
cols = [
stmt.table.c[key] for key in parameter_ordering
] + [
c for c in stmt.table.c if c.key not in ordered_keys
]
else:
cols = stmt.table.columns
for c in cols:
col_key = _getattr_col_key(c)
if col_key in parameters and col_key not in check_columns:
_append_param_parameter(
compiler, stmt, c, col_key, parameters, _col_bind_name,
implicit_returning, implicit_return_defaults, values, kw)
elif compiler.isinsert:
if c.primary_key and \
need_pks and \
(
implicit_returning or
not postfetch_lastrowid or
c is not stmt.table._autoincrement_column
):
if implicit_returning:
_append_param_insert_pk_returning(
compiler, stmt, c, values, kw)
else:
_append_param_insert_pk(compiler, stmt, c, values, kw)
elif c.default is not None:
_append_param_insert_hasdefault(
compiler, stmt, c, implicit_return_defaults,
values, kw)
elif c.server_default is not None:
if implicit_return_defaults and \
c in implicit_return_defaults:
compiler.returning.append(c)
elif not c.primary_key:
compiler.postfetch.append(c)
elif implicit_return_defaults and \
c in implicit_return_defaults:
compiler.returning.append(c)
elif c.primary_key and \
c is not stmt.table._autoincrement_column and \
not c.nullable:
_warn_pk_with_no_anticipated_value(c)
elif compiler.isupdate:
_append_param_update(
compiler, stmt, c, implicit_return_defaults, values, kw)
def _append_param_parameter(
compiler, stmt, c, col_key, parameters, _col_bind_name,
implicit_returning, implicit_return_defaults, values, kw):
value = parameters.pop(col_key)
if elements._is_literal(value):
value = _create_bind_param(
compiler, c, value, required=value is REQUIRED,
name=_col_bind_name(c)
if not stmt._has_multi_parameters
else "%s_m0" % _col_bind_name(c),
**kw
)
else:
if isinstance(value, elements.BindParameter) and \
value.type._isnull:
value = value._clone()
value.type = c.type
if c.primary_key and implicit_returning:
compiler.returning.append(c)
value = compiler.process(value.self_group(), **kw)
elif implicit_return_defaults and \
c in implicit_return_defaults:
compiler.returning.append(c)
value = compiler.process(value.self_group(), **kw)
else:
compiler.postfetch.append(c)
value = compiler.process(value.self_group(), **kw)
values.append((c, value))
def _append_param_insert_pk_returning(compiler, stmt, c, values, kw):
"""Create a primary key expression in the INSERT statement and
possibly a RETURNING clause for it.
If the column has a Python-side default, we will create a bound
parameter for it and "pre-execute" the Python function. If
the column has a SQL expression default, or is a sequence,
we will add it directly into the INSERT statement and add a
RETURNING element to get the new value. If the column has a
server side default or is marked as the "autoincrement" column,
we will add a RETRUNING element to get at the value.
If all the above tests fail, that indicates a primary key column with no
noted default generation capabilities that has no parameter passed;
raise an exception.
"""
if c.default is not None:
if c.default.is_sequence:
if compiler.dialect.supports_sequences and \
(not c.default.optional or
not compiler.dialect.sequences_optional):
proc = compiler.process(c.default, **kw)
values.append((c, proc))
compiler.returning.append(c)
elif c.default.is_clause_element:
values.append(
(c, compiler.process(
c.default.arg.self_group(), **kw))
)
compiler.returning.append(c)
else:
values.append(
(c, _create_insert_prefetch_bind_param(compiler, c))
)
elif c is stmt.table._autoincrement_column or c.server_default is not None:
compiler.returning.append(c)
elif not c.nullable:
# no .default, no .server_default, not autoincrement, we have
# no indication this primary key column will have any value
_warn_pk_with_no_anticipated_value(c)
def _create_insert_prefetch_bind_param(compiler, c, process=True, name=None):
param = _create_bind_param(compiler, c, None, process=process, name=name)
compiler.insert_prefetch.append(c)
return param
def _create_update_prefetch_bind_param(compiler, c, process=True, name=None):
param = _create_bind_param(compiler, c, None, process=process, name=name)
compiler.update_prefetch.append(c)
return param
class _multiparam_column(elements.ColumnElement):
def __init__(self, original, index):
self.key = "%s_m%d" % (original.key, index + 1)
self.original = original
self.default = original.default
self.type = original.type
def __eq__(self, other):
return isinstance(other, _multiparam_column) and \
other.key == self.key and \
other.original == self.original
def _process_multiparam_default_bind(compiler, stmt, c, index, kw):
if not c.default:
raise exc.CompileError(
"INSERT value for column %s is explicitly rendered as a bound"
"parameter in the VALUES clause; "
"a Python-side value or SQL expression is required" % c)
elif c.default.is_clause_element:
return compiler.process(c.default.arg.self_group(), **kw)
else:
col = _multiparam_column(c, index)
if isinstance(stmt, dml.Insert):
return _create_insert_prefetch_bind_param(compiler, col)
else:
return _create_update_prefetch_bind_param(compiler, col)
def _append_param_insert_pk(compiler, stmt, c, values, kw):
"""Create a bound parameter in the INSERT statement to receive a
'prefetched' default value.
The 'prefetched' value indicates that we are to invoke a Python-side
default function or expliclt SQL expression before the INSERT statement
proceeds, so that we have a primary key value available.
if the column has no noted default generation capabilities, it has
no value passed in either; raise an exception.
"""
if (
(
# column has a Python-side default
c.default is not None and
(
# and it won't be a Sequence
not c.default.is_sequence or
compiler.dialect.supports_sequences
)
)
or
(
# column is the "autoincrement column"
c is stmt.table._autoincrement_column and
(
# and it's either a "sequence" or a
# pre-executable "autoincrement" sequence
compiler.dialect.supports_sequences or
compiler.dialect.preexecute_autoincrement_sequences
)
)
):
values.append(
(c, _create_insert_prefetch_bind_param(compiler, c))
)
elif c.default is None and c.server_default is None and not c.nullable:
# no .default, no .server_default, not autoincrement, we have
# no indication this primary key column will have any value
_warn_pk_with_no_anticipated_value(c)
def _append_param_insert_hasdefault(
compiler, stmt, c, implicit_return_defaults, values, kw):
if c.default.is_sequence:
if compiler.dialect.supports_sequences and \
(not c.default.optional or
not compiler.dialect.sequences_optional):
proc = compiler.process(c.default, **kw)
values.append((c, proc))
if implicit_return_defaults and \
c in implicit_return_defaults:
compiler.returning.append(c)
elif not c.primary_key:
compiler.postfetch.append(c)
elif c.default.is_clause_element:
proc = compiler.process(c.default.arg.self_group(), **kw)
values.append((c, proc))
if implicit_return_defaults and \
c in implicit_return_defaults:
compiler.returning.append(c)
elif not c.primary_key:
# don't add primary key column to postfetch
compiler.postfetch.append(c)
else:
values.append(
(c, _create_insert_prefetch_bind_param(compiler, c))
)
def _append_param_insert_select_hasdefault(
compiler, stmt, c, values, kw):
if c.default.is_sequence:
if compiler.dialect.supports_sequences and \
(not c.default.optional or
not compiler.dialect.sequences_optional):
proc = c.default
values.append((c, proc))
elif c.default.is_clause_element:
proc = c.default.arg.self_group()
values.append((c, proc))
else:
values.append(
(c, _create_insert_prefetch_bind_param(compiler, c, process=False))
)
def _append_param_update(
compiler, stmt, c, implicit_return_defaults, values, kw):
if c.onupdate is not None and not c.onupdate.is_sequence:
if c.onupdate.is_clause_element:
values.append(
(c, compiler.process(
c.onupdate.arg.self_group(), **kw))
)
if implicit_return_defaults and \
c in implicit_return_defaults:
compiler.returning.append(c)
else:
compiler.postfetch.append(c)
else:
values.append(
(c, _create_update_prefetch_bind_param(compiler, c))
)
elif c.server_onupdate is not None:
if implicit_return_defaults and \
c in implicit_return_defaults:
compiler.returning.append(c)
else:
compiler.postfetch.append(c)
elif implicit_return_defaults and \
stmt._return_defaults is not True and \
c in implicit_return_defaults:
compiler.returning.append(c)
def _get_multitable_params(
compiler, stmt, stmt_parameters, check_columns,
_col_bind_name, _getattr_col_key, values, kw):
normalized_params = dict(
(elements._clause_element_as_expr(c), param)
for c, param in stmt_parameters.items()
)
affected_tables = set()
for t in stmt._extra_froms:
for c in t.c:
if c in normalized_params:
affected_tables.add(t)
check_columns[_getattr_col_key(c)] = c
value = normalized_params[c]
if elements._is_literal(value):
value = _create_bind_param(
compiler, c, value, required=value is REQUIRED,
name=_col_bind_name(c))
else:
compiler.postfetch.append(c)
value = compiler.process(value.self_group(), **kw)
values.append((c, value))
# determine tables which are actually to be updated - process onupdate
# and server_onupdate for these
for t in affected_tables:
for c in t.c:
if c in normalized_params:
continue
elif (c.onupdate is not None and not
c.onupdate.is_sequence):
if c.onupdate.is_clause_element:
values.append(
(c, compiler.process(
c.onupdate.arg.self_group(),
**kw)
)
)
compiler.postfetch.append(c)
else:
values.append(
(c, _create_update_prefetch_bind_param(
compiler, c, name=_col_bind_name(c)))
)
elif c.server_onupdate is not None:
compiler.postfetch.append(c)
def _extend_values_for_multiparams(compiler, stmt, values, kw):
values_0 = values
values = [values]
values.extend(
[
(
c,
(_create_bind_param(
compiler, c, row[c.key],
name="%s_m%d" % (c.key, i + 1)
) if elements._is_literal(row[c.key])
else compiler.process(
row[c.key].self_group(), **kw))
if c.key in row else
_process_multiparam_default_bind(compiler, stmt, c, i, kw)
)
for (c, param) in values_0
]
for i, row in enumerate(stmt.parameters[1:])
)
return values
def _get_stmt_parameters_params(
compiler, parameters, stmt_parameters, _column_as_key, values, kw):<|fim▁hole|> else:
# a non-Column expression on the left side;
# add it to values() in an "as-is" state,
# coercing right side to bound param
if elements._is_literal(v):
v = compiler.process(
elements.BindParameter(None, v, type_=k.type),
**kw)
else:
v = compiler.process(v.self_group(), **kw)
values.append((k, v))
def _get_returning_modifiers(compiler, stmt):
need_pks = compiler.isinsert and \
not compiler.inline and \
not stmt._returning and \
not stmt._has_multi_parameters
implicit_returning = need_pks and \
compiler.dialect.implicit_returning and \
stmt.table.implicit_returning
if compiler.isinsert:
implicit_return_defaults = (implicit_returning and
stmt._return_defaults)
elif compiler.isupdate:
implicit_return_defaults = (compiler.dialect.implicit_returning and
stmt.table.implicit_returning and
stmt._return_defaults)
else:
# this line is unused, currently we are always
# isinsert or isupdate
implicit_return_defaults = False # pragma: no cover
if implicit_return_defaults:
if stmt._return_defaults is True:
implicit_return_defaults = set(stmt.table.c)
else:
implicit_return_defaults = set(stmt._return_defaults)
postfetch_lastrowid = need_pks and compiler.dialect.postfetch_lastrowid
return need_pks, implicit_returning, \
implicit_return_defaults, postfetch_lastrowid
def _warn_pk_with_no_anticipated_value(c):
msg = (
"Column '%s.%s' is marked as a member of the "
"primary key for table '%s', "
"but has no Python-side or server-side default generator indicated, "
"nor does it indicate 'autoincrement=True' or 'nullable=True', "
"and no explicit value is passed. "
"Primary key columns typically may not store NULL."
%
(c.table.fullname, c.name, c.table.fullname))
if len(c.table.primary_key) > 1:
msg += (
" Note that as of SQLAlchemy 1.1, 'autoincrement=True' must be "
"indicated explicitly for composite (e.g. multicolumn) primary "
"keys if AUTO_INCREMENT/SERIAL/IDENTITY "
"behavior is expected for one of the columns in the primary key. "
"CREATE TABLE statements are impacted by this change as well on "
"most backends.")
util.warn(msg)<|fim▁end|> | for k, v in stmt_parameters.items():
colkey = _column_as_key(k)
if colkey is not None:
parameters.setdefault(colkey, v) |
<|file_name|>ShHealOper_ChangeOrientation.cpp<|end_file_name|><|fim▁begin|>// Copyright (C) 2005 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// 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.
//
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// See http://www.salome-platform.org/ or email : [email protected]
//
//
// File: ShHealOper_ChangeOrientation.cxx
// Created: 11.07.06 11:46:45
// Author: Sergey KUUL
#include <ShHealOper_ChangeOrientation.hxx>
#include <BRep_Builder.hxx>
#include <TopoDS_Iterator.hxx>
//=======================================================================
//function : ShHealOper_ChangeOrientation()
//purpose : Constructor
//=======================================================================
ShHealOper_ChangeOrientation::ShHealOper_ChangeOrientation ( const TopoDS_Shape& theShape )
{
Init(theShape);
}
//=======================================================================
//function : Init
//purpose :
//=======================================================================
void ShHealOper_ChangeOrientation::Init(const TopoDS_Shape& theShape)
{
ShHealOper_Tool::Init(theShape);
}
//=======================================================================
//function : Perform
//purpose :
//=======================================================================
Standard_Boolean ShHealOper_ChangeOrientation::Perform()
{
BRep_Builder B;
if (myInitShape.ShapeType() == TopAbs_SHELL) {
myResultShape = myInitShape.EmptyCopied();
TopoDS_Iterator itr(myInitShape);
while (itr.More()) {
B.Add(myResultShape,itr.Value().Reversed());
itr.Next();<|fim▁hole|> }
}
else if (myInitShape.ShapeType() == TopAbs_FACE) {
myResultShape = myInitShape.EmptyCopied();
TopoDS_Iterator itr(myInitShape);
while (itr.More()) {
B.Add(myResultShape,itr.Value());
itr.Next();
}
myResultShape.Reverse();
}
else if ( myInitShape.ShapeType() == TopAbs_WIRE || myInitShape.ShapeType() == TopAbs_EDGE) {
myResultShape = myInitShape.EmptyCopied();
TopoDS_Iterator itr(myInitShape);
while (itr.More()) {
B.Add(myResultShape,itr.Value());
itr.Next();
}
myResultShape.Reverse();
}
else {
return false;
}
return true;
}<|fim▁end|> | |
<|file_name|>shape_base.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
import warnings
import numpy.core.numeric as _nx
from numpy.core.numeric import (
asarray, zeros, outer, concatenate, isscalar, array, asanyarray
)
from numpy.core.fromnumeric import product, reshape
from numpy.core import vstack, atleast_3d
__all__ = [
'column_stack', 'row_stack', 'dstack', 'array_split', 'split',
'hsplit', 'vsplit', 'dsplit', 'apply_over_axes', 'expand_dims',
'apply_along_axis', 'kron', 'tile', 'get_array_wrap'
]
def apply_along_axis(func1d, axis, arr, *args, **kwargs):
"""
Apply a function to 1-D slices along the given axis.
Execute `func1d(a, *args)` where `func1d` operates on 1-D arrays and `a`
is a 1-D slice of `arr` along `axis`.
Parameters
----------
func1d : function
This function should accept 1-D arrays. It is applied to 1-D
slices of `arr` along the specified axis.
axis : integer
Axis along which `arr` is sliced.
arr : ndarray
Input array.
args : any
Additional arguments to `func1d`.
kwargs: any
Additional named arguments to `func1d`.
.. versionadded:: 1.9.0
Returns
-------
apply_along_axis : ndarray
The output array. The shape of `outarr` is identical to the shape of
`arr`, except along the `axis` dimension, where the length of `outarr`
is equal to the size of the return value of `func1d`. If `func1d`
returns a scalar `outarr` will have one fewer dimensions than `arr`.
See Also
--------
apply_over_axes : Apply a function repeatedly over multiple axes.
Examples
--------
>>> def my_func(a):
... \"\"\"Average first and last element of a 1-D array\"\"\"
... return (a[0] + a[-1]) * 0.5
>>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> np.apply_along_axis(my_func, 0, b)
array([ 4., 5., 6.])
>>> np.apply_along_axis(my_func, 1, b)
array([ 2., 5., 8.])
For a function that doesn't return a scalar, the number of dimensions in
`outarr` is the same as `arr`.
>>> b = np.array([[8,1,7], [4,3,9], [5,2,6]])
>>> np.apply_along_axis(sorted, 1, b)
array([[1, 7, 8],
[3, 4, 9],
[2, 5, 6]])
"""
arr = asarray(arr)
nd = arr.ndim
if axis < 0:
axis += nd
if (axis >= nd):
raise ValueError("axis must be less than arr.ndim; axis=%d, rank=%d."
% (axis, nd))
ind = [0]*(nd-1)
i = zeros(nd, 'O')
indlist = list(range(nd))
indlist.remove(axis)
i[axis] = slice(None, None)
outshape = asarray(arr.shape).take(indlist)
i.put(indlist, ind)
res = func1d(arr[tuple(i.tolist())], *args, **kwargs)
# if res is a number, then we have a smaller output array
if isscalar(res):
outarr = zeros(outshape, asarray(res).dtype)
outarr[tuple(ind)] = res
Ntot = product(outshape)
k = 1
while k < Ntot:
# increment the index
ind[-1] += 1
n = -1
while (ind[n] >= outshape[n]) and (n > (1-nd)):
ind[n-1] += 1
ind[n] = 0
n -= 1
i.put(indlist, ind)
res = func1d(arr[tuple(i.tolist())], *args, **kwargs)
outarr[tuple(ind)] = res
k += 1
return outarr
else:
Ntot = product(outshape)
holdshape = outshape
outshape = list(arr.shape)
outshape[axis] = len(res)
outarr = zeros(outshape, asarray(res).dtype)
outarr[tuple(i.tolist())] = res
k = 1
while k < Ntot:
# increment the index
ind[-1] += 1
n = -1
while (ind[n] >= holdshape[n]) and (n > (1-nd)):
ind[n-1] += 1
ind[n] = 0
n -= 1
i.put(indlist, ind)
res = func1d(arr[tuple(i.tolist())], *args, **kwargs)
outarr[tuple(i.tolist())] = res
k += 1
return outarr
def apply_over_axes(func, a, axes):
"""
Apply a function repeatedly over multiple axes.
`func` is called as `res = func(a, axis)`, where `axis` is the first
element of `axes`. The result `res` of the function call must have
either the same dimensions as `a` or one less dimension. If `res`
has one less dimension than `a`, a dimension is inserted before
`axis`. The call to `func` is then repeated for each axis in `axes`,
with `res` as the first argument.
Parameters
----------
func : function
This function must take two arguments, `func(a, axis)`.
a : array_like
Input array.
axes : array_like
Axes over which `func` is applied; the elements must be integers.
Returns
-------
apply_over_axis : ndarray
The output array. The number of dimensions is the same as `a`,
but the shape can be different. This depends on whether `func`
changes the shape of its output with respect to its input.
See Also
--------
apply_along_axis :
Apply a function to 1-D slices of an array along the given axis.
Notes
------
This function is equivalent to tuple axis arguments to reorderable ufuncs
with keepdims=True. Tuple axis arguments to ufuncs have been availabe since
version 1.7.0.
Examples
--------
>>> a = np.arange(24).reshape(2,3,4)
>>> a
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
Sum over axes 0 and 2. The result has same number of dimensions
as the original array:
>>> np.apply_over_axes(np.sum, a, [0,2])
array([[[ 60],
[ 92],
[124]]])
Tuple axis arguments to ufuncs are equivalent:
>>> np.sum(a, axis=(0,2), keepdims=True)
array([[[ 60],
[ 92],
[124]]])
"""
val = asarray(a)
N = a.ndim
if array(axes).ndim == 0:
axes = (axes,)
for axis in axes:
if axis < 0:
axis = N + axis
args = (val, axis)
res = func(*args)
if res.ndim == val.ndim:
val = res
else:
res = expand_dims(res, axis)
if res.ndim == val.ndim:
val = res
else:
raise ValueError("function is not returning "
"an array of the correct shape")
return val
def expand_dims(a, axis):
"""
Expand the shape of an array.
Insert a new axis, corresponding to a given position in the array shape.
Parameters
----------
a : array_like
Input array.
axis : int
Position (amongst axes) where new axis is to be inserted.
Returns
-------
res : ndarray
Output array. The number of dimensions is one greater than that of
the input array.
See Also
--------
doc.indexing, atleast_1d, atleast_2d, atleast_3d
Examples
--------
>>> x = np.array([1,2])
>>> x.shape
(2,)
The following is equivalent to ``x[np.newaxis,:]`` or ``x[np.newaxis]``:
>>> y = np.expand_dims(x, axis=0)
>>> y
array([[1, 2]])
>>> y.shape
(1, 2)
>>> y = np.expand_dims(x, axis=1) # Equivalent to x[:,newaxis]
>>> y
array([[1],
[2]])
>>> y.shape
(2, 1)
Note that some examples may use ``None`` instead of ``np.newaxis``. These
are the same objects:
>>> np.newaxis is None
True
"""
a = asarray(a)
shape = a.shape
if axis < 0:
axis = axis + len(shape) + 1
return a.reshape(shape[:axis] + (1,) + shape[axis:])
row_stack = vstack
def column_stack(tup):
"""
Stack 1-D arrays as columns into a 2-D array.
Take a sequence of 1-D arrays and stack them as columns
to make a single 2-D array. 2-D arrays are stacked as-is,
just like with `hstack`. 1-D arrays are turned into 2-D columns
first.
Parameters
----------
tup : sequence of 1-D or 2-D arrays.
Arrays to stack. All of them must have the same first dimension.
Returns
-------
stacked : 2-D array
The array formed by stacking the given arrays.
See Also
--------
hstack, vstack, concatenate
Examples
--------
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.column_stack((a,b))
array([[1, 2],
[2, 3],
[3, 4]])
<|fim▁hole|> """
arrays = []
for v in tup:
arr = array(v, copy=False, subok=True)
if arr.ndim < 2:
arr = array(arr, copy=False, subok=True, ndmin=2).T
arrays.append(arr)
return _nx.concatenate(arrays, 1)
def dstack(tup):
"""
Stack arrays in sequence depth wise (along third axis).
Takes a sequence of arrays and stack them along the third axis
to make a single array. Rebuilds arrays divided by `dsplit`.
This is a simple way to stack 2D arrays (images) into a single
3D array for processing.
Parameters
----------
tup : sequence of arrays
Arrays to stack. All of them must have the same shape along all
but the third axis.
Returns
-------
stacked : ndarray
The array formed by stacking the given arrays.
See Also
--------
stack : Join a sequence of arrays along a new axis.
vstack : Stack along first axis.
hstack : Stack along second axis.
concatenate : Join a sequence of arrays along an existing axis.
dsplit : Split array along third axis.
Notes
-----
Equivalent to ``np.concatenate(tup, axis=2)``.
Examples
--------
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.dstack((a,b))
array([[[1, 2],
[2, 3],
[3, 4]]])
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[2],[3],[4]])
>>> np.dstack((a,b))
array([[[1, 2]],
[[2, 3]],
[[3, 4]]])
"""
return _nx.concatenate([atleast_3d(_m) for _m in tup], 2)
def _replace_zero_by_x_arrays(sub_arys):
for i in range(len(sub_arys)):
if len(_nx.shape(sub_arys[i])) == 0:
sub_arys[i] = _nx.empty(0, dtype=sub_arys[i].dtype)
elif _nx.sometrue(_nx.equal(_nx.shape(sub_arys[i]), 0)):
sub_arys[i] = _nx.empty(0, dtype=sub_arys[i].dtype)
return sub_arys
def array_split(ary, indices_or_sections, axis=0):
"""
Split an array into multiple sub-arrays.
Please refer to the ``split`` documentation. The only difference
between these functions is that ``array_split`` allows
`indices_or_sections` to be an integer that does *not* equally
divide the axis.
See Also
--------
split : Split array into multiple sub-arrays of equal size.
Examples
--------
>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
[array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7.])]
"""
try:
Ntotal = ary.shape[axis]
except AttributeError:
Ntotal = len(ary)
try:
# handle scalar case.
Nsections = len(indices_or_sections) + 1
div_points = [0] + list(indices_or_sections) + [Ntotal]
except TypeError:
# indices_or_sections is a scalar, not an array.
Nsections = int(indices_or_sections)
if Nsections <= 0:
raise ValueError('number sections must be larger than 0.')
Neach_section, extras = divmod(Ntotal, Nsections)
section_sizes = ([0] +
extras * [Neach_section+1] +
(Nsections-extras) * [Neach_section])
div_points = _nx.array(section_sizes).cumsum()
sub_arys = []
sary = _nx.swapaxes(ary, axis, 0)
for i in range(Nsections):
st = div_points[i]
end = div_points[i + 1]
sub_arys.append(_nx.swapaxes(sary[st:end], axis, 0))
# This "kludge" was introduced here to replace arrays shaped (0, 10)
# or similar with an array shaped (0,).
# There seems no need for this, so give a FutureWarning to remove later.
if sub_arys[-1].size == 0 and sub_arys[-1].ndim != 1:
warnings.warn("in the future np.array_split will retain the shape of "
"arrays with a zero size, instead of replacing them by "
"`array([])`, which always has a shape of (0,).",
FutureWarning)
sub_arys = _replace_zero_by_x_arrays(sub_arys)
return sub_arys
def split(ary,indices_or_sections,axis=0):
"""
Split an array into multiple sub-arrays.
Parameters
----------
ary : ndarray
Array to be divided into sub-arrays.
indices_or_sections : int or 1-D array
If `indices_or_sections` is an integer, N, the array will be divided
into N equal arrays along `axis`. If such a split is not possible,
an error is raised.
If `indices_or_sections` is a 1-D array of sorted integers, the entries
indicate where along `axis` the array is split. For example,
``[2, 3]`` would, for ``axis=0``, result in
- ary[:2]
- ary[2:3]
- ary[3:]
If an index exceeds the dimension of the array along `axis`,
an empty sub-array is returned correspondingly.
axis : int, optional
The axis along which to split, default is 0.
Returns
-------
sub-arrays : list of ndarrays
A list of sub-arrays.
Raises
------
ValueError
If `indices_or_sections` is given as an integer, but
a split does not result in equal division.
See Also
--------
array_split : Split an array into multiple sub-arrays of equal or
near-equal size. Does not raise an exception if
an equal division cannot be made.
hsplit : Split array into multiple sub-arrays horizontally (column-wise).
vsplit : Split array into multiple sub-arrays vertically (row wise).
dsplit : Split array into multiple sub-arrays along the 3rd axis (depth).
concatenate : Join a sequence of arrays along an existing axis.
stack : Join a sequence of arrays along a new axis.
hstack : Stack arrays in sequence horizontally (column wise).
vstack : Stack arrays in sequence vertically (row wise).
dstack : Stack arrays in sequence depth wise (along third dimension).
Examples
--------
>>> x = np.arange(9.0)
>>> np.split(x, 3)
[array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7., 8.])]
>>> x = np.arange(8.0)
>>> np.split(x, [3, 5, 6, 10])
[array([ 0., 1., 2.]),
array([ 3., 4.]),
array([ 5.]),
array([ 6., 7.]),
array([], dtype=float64)]
"""
try:
len(indices_or_sections)
except TypeError:
sections = indices_or_sections
N = ary.shape[axis]
if N % sections:
raise ValueError(
'array split does not result in an equal division')
res = array_split(ary, indices_or_sections, axis)
return res
def hsplit(ary, indices_or_sections):
"""
Split an array into multiple sub-arrays horizontally (column-wise).
Please refer to the `split` documentation. `hsplit` is equivalent
to `split` with ``axis=1``, the array is always split along the second
axis regardless of the array dimension.
See Also
--------
split : Split an array into multiple sub-arrays of equal size.
Examples
--------
>>> x = np.arange(16.0).reshape(4, 4)
>>> x
array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]])
>>> np.hsplit(x, 2)
[array([[ 0., 1.],
[ 4., 5.],
[ 8., 9.],
[ 12., 13.]]),
array([[ 2., 3.],
[ 6., 7.],
[ 10., 11.],
[ 14., 15.]])]
>>> np.hsplit(x, np.array([3, 6]))
[array([[ 0., 1., 2.],
[ 4., 5., 6.],
[ 8., 9., 10.],
[ 12., 13., 14.]]),
array([[ 3.],
[ 7.],
[ 11.],
[ 15.]]),
array([], dtype=float64)]
With a higher dimensional array the split is still along the second axis.
>>> x = np.arange(8.0).reshape(2, 2, 2)
>>> x
array([[[ 0., 1.],
[ 2., 3.]],
[[ 4., 5.],
[ 6., 7.]]])
>>> np.hsplit(x, 2)
[array([[[ 0., 1.]],
[[ 4., 5.]]]),
array([[[ 2., 3.]],
[[ 6., 7.]]])]
"""
if len(_nx.shape(ary)) == 0:
raise ValueError('hsplit only works on arrays of 1 or more dimensions')
if len(ary.shape) > 1:
return split(ary, indices_or_sections, 1)
else:
return split(ary, indices_or_sections, 0)
def vsplit(ary, indices_or_sections):
"""
Split an array into multiple sub-arrays vertically (row-wise).
Please refer to the ``split`` documentation. ``vsplit`` is equivalent
to ``split`` with `axis=0` (default), the array is always split along the
first axis regardless of the array dimension.
See Also
--------
split : Split an array into multiple sub-arrays of equal size.
Examples
--------
>>> x = np.arange(16.0).reshape(4, 4)
>>> x
array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]])
>>> np.vsplit(x, 2)
[array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.]]),
array([[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]])]
>>> np.vsplit(x, np.array([3, 6]))
[array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]]),
array([[ 12., 13., 14., 15.]]),
array([], dtype=float64)]
With a higher dimensional array the split is still along the first axis.
>>> x = np.arange(8.0).reshape(2, 2, 2)
>>> x
array([[[ 0., 1.],
[ 2., 3.]],
[[ 4., 5.],
[ 6., 7.]]])
>>> np.vsplit(x, 2)
[array([[[ 0., 1.],
[ 2., 3.]]]),
array([[[ 4., 5.],
[ 6., 7.]]])]
"""
if len(_nx.shape(ary)) < 2:
raise ValueError('vsplit only works on arrays of 2 or more dimensions')
return split(ary, indices_or_sections, 0)
def dsplit(ary, indices_or_sections):
"""
Split array into multiple sub-arrays along the 3rd axis (depth).
Please refer to the `split` documentation. `dsplit` is equivalent
to `split` with ``axis=2``, the array is always split along the third
axis provided the array dimension is greater than or equal to 3.
See Also
--------
split : Split an array into multiple sub-arrays of equal size.
Examples
--------
>>> x = np.arange(16.0).reshape(2, 2, 4)
>>> x
array([[[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.]],
[[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]]])
>>> np.dsplit(x, 2)
[array([[[ 0., 1.],
[ 4., 5.]],
[[ 8., 9.],
[ 12., 13.]]]),
array([[[ 2., 3.],
[ 6., 7.]],
[[ 10., 11.],
[ 14., 15.]]])]
>>> np.dsplit(x, np.array([3, 6]))
[array([[[ 0., 1., 2.],
[ 4., 5., 6.]],
[[ 8., 9., 10.],
[ 12., 13., 14.]]]),
array([[[ 3.],
[ 7.]],
[[ 11.],
[ 15.]]]),
array([], dtype=float64)]
"""
if len(_nx.shape(ary)) < 3:
raise ValueError('dsplit only works on arrays of 3 or more dimensions')
return split(ary, indices_or_sections, 2)
def get_array_prepare(*args):
"""Find the wrapper for the array with the highest priority.
In case of ties, leftmost wins. If no wrapper is found, return None
"""
wrappers = sorted((getattr(x, '__array_priority__', 0), -i,
x.__array_prepare__) for i, x in enumerate(args)
if hasattr(x, '__array_prepare__'))
if wrappers:
return wrappers[-1][-1]
return None
def get_array_wrap(*args):
"""Find the wrapper for the array with the highest priority.
In case of ties, leftmost wins. If no wrapper is found, return None
"""
wrappers = sorted((getattr(x, '__array_priority__', 0), -i,
x.__array_wrap__) for i, x in enumerate(args)
if hasattr(x, '__array_wrap__'))
if wrappers:
return wrappers[-1][-1]
return None
def kron(a, b):
"""
Kronecker product of two arrays.
Computes the Kronecker product, a composite array made of blocks of the
second array scaled by the first.
Parameters
----------
a, b : array_like
Returns
-------
out : ndarray
See Also
--------
outer : The outer product
Notes
-----
The function assumes that the number of dimensions of `a` and `b`
are the same, if necessary prepending the smallest with ones.
If `a.shape = (r0,r1,..,rN)` and `b.shape = (s0,s1,...,sN)`,
the Kronecker product has shape `(r0*s0, r1*s1, ..., rN*SN)`.
The elements are products of elements from `a` and `b`, organized
explicitly by::
kron(a,b)[k0,k1,...,kN] = a[i0,i1,...,iN] * b[j0,j1,...,jN]
where::
kt = it * st + jt, t = 0,...,N
In the common 2-D case (N=1), the block structure can be visualized::
[[ a[0,0]*b, a[0,1]*b, ... , a[0,-1]*b ],
[ ... ... ],
[ a[-1,0]*b, a[-1,1]*b, ... , a[-1,-1]*b ]]
Examples
--------
>>> np.kron([1,10,100], [5,6,7])
array([ 5, 6, 7, 50, 60, 70, 500, 600, 700])
>>> np.kron([5,6,7], [1,10,100])
array([ 5, 50, 500, 6, 60, 600, 7, 70, 700])
>>> np.kron(np.eye(2), np.ones((2,2)))
array([[ 1., 1., 0., 0.],
[ 1., 1., 0., 0.],
[ 0., 0., 1., 1.],
[ 0., 0., 1., 1.]])
>>> a = np.arange(100).reshape((2,5,2,5))
>>> b = np.arange(24).reshape((2,3,4))
>>> c = np.kron(a,b)
>>> c.shape
(2, 10, 6, 20)
>>> I = (1,3,0,2)
>>> J = (0,2,1)
>>> J1 = (0,) + J # extend to ndim=4
>>> S1 = (1,) + b.shape
>>> K = tuple(np.array(I) * np.array(S1) + np.array(J1))
>>> c[K] == a[I]*b[J]
True
"""
b = asanyarray(b)
a = array(a, copy=False, subok=True, ndmin=b.ndim)
ndb, nda = b.ndim, a.ndim
if (nda == 0 or ndb == 0):
return _nx.multiply(a, b)
as_ = a.shape
bs = b.shape
if not a.flags.contiguous:
a = reshape(a, as_)
if not b.flags.contiguous:
b = reshape(b, bs)
nd = ndb
if (ndb != nda):
if (ndb > nda):
as_ = (1,)*(ndb-nda) + as_
else:
bs = (1,)*(nda-ndb) + bs
nd = nda
result = outer(a, b).reshape(as_+bs)
axis = nd-1
for _ in range(nd):
result = concatenate(result, axis=axis)
wrapper = get_array_prepare(a, b)
if wrapper is not None:
result = wrapper(result)
wrapper = get_array_wrap(a, b)
if wrapper is not None:
result = wrapper(result)
return result
def tile(A, reps):
"""
Construct an array by repeating A the number of times given by reps.
If `reps` has length ``d``, the result will have dimension of
``max(d, A.ndim)``.
If ``A.ndim < d``, `A` is promoted to be d-dimensional by prepending new
axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication,
or shape (1, 1, 3) for 3-D replication. If this is not the desired
behavior, promote `A` to d-dimensions manually before calling this
function.
If ``A.ndim > d``, `reps` is promoted to `A`.ndim by pre-pending 1's to it.
Thus for an `A` of shape (2, 3, 4, 5), a `reps` of (2, 2) is treated as
(1, 1, 2, 2).
Parameters
----------
A : array_like
The input array.
reps : array_like
The number of repetitions of `A` along each axis.
Returns
-------
c : ndarray
The tiled output array.
See Also
--------
repeat : Repeat elements of an array.
Examples
--------
>>> a = np.array([0, 1, 2])
>>> np.tile(a, 2)
array([0, 1, 2, 0, 1, 2])
>>> np.tile(a, (2, 2))
array([[0, 1, 2, 0, 1, 2],
[0, 1, 2, 0, 1, 2]])
>>> np.tile(a, (2, 1, 2))
array([[[0, 1, 2, 0, 1, 2]],
[[0, 1, 2, 0, 1, 2]]])
>>> b = np.array([[1, 2], [3, 4]])
>>> np.tile(b, 2)
array([[1, 2, 1, 2],
[3, 4, 3, 4]])
>>> np.tile(b, (2, 1))
array([[1, 2],
[3, 4],
[1, 2],
[3, 4]])
"""
try:
tup = tuple(reps)
except TypeError:
tup = (reps,)
d = len(tup)
if all(x == 1 for x in tup) and isinstance(A, _nx.ndarray):
# Fixes the problem that the function does not make a copy if A is a
# numpy array and the repetitions are 1 in all dimensions
return _nx.array(A, copy=True, subok=True, ndmin=d)
else:
c = _nx.array(A, copy=False, subok=True, ndmin=d)
shape = list(c.shape)
n = max(c.size, 1)
if (d < c.ndim):
tup = (1,)*(c.ndim-d) + tup
for i, nrep in enumerate(tup):
if nrep != 1:
c = c.reshape(-1, n).repeat(nrep, 0)
dim_in = shape[i]
dim_out = dim_in*nrep
shape[i] = dim_out
n //= max(dim_in, 1)
return c.reshape(shape)<|fim▁end|> | |
<|file_name|>VisBio.java<|end_file_name|><|fim▁begin|>/*
* #%L
* VisBio application for visualization of multidimensional biological
* image data.
* %%
* Copyright (C) 2002 - 2014 Board of Regents of the University of
* Wisconsin-Madison.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
package loci.visbio;
import java.awt.Color;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import loci.visbio.util.InstanceServer;
import loci.visbio.util.SplashScreen;
/**
* VisBio is a biological visualization tool designed for easy visualization and
* analysis of multidimensional image data. This class is the main gateway into
* the application. It creates and displays a VisBioFrame via reflection, so
* that the splash screen appears as quickly as possible, before the class
* loader gets too far along.
*/
public final class VisBio extends Thread {
// -- Constants --
/** Application title. */
public static final String TITLE = "VisBio";
/** Application version (of the form "###"). */
private static final String V = "@visbio.version@";
/** Application version (of the form "#.##"). */
public static final String VERSION = V.equals("@visbio" + ".version@")
? "(internal build)" : (V.substring(0, 1) + "." + V.substring(1));
/** Application authors. */
public static final String AUTHOR = "Curtis Rueden and Abraham Sorber, LOCI";
/** Application build date. */
public static final String DATE = "@date@";
/** Port to use for communicating between application instances. */
public static final int INSTANCE_PORT = 0xabcd;
// -- Constructor --
/** Ensure this class can't be externally instantiated. */
private VisBio() {}
// -- VisBio API methods --
/** Launches the VisBio GUI with no arguments, in a separate thread. */
public static void startProgram() {
new VisBio().start();
}
/** Launches VisBio, returning the newly constructed VisBioFrame object. */
public static Object launch(final String[] args)
throws ClassNotFoundException, IllegalAccessException,
InstantiationException, InvocationTargetException, NoSuchMethodException
{
// check whether VisBio is already running
boolean isRunning = true;
try {
InstanceServer.sendArguments(args, INSTANCE_PORT);
}
catch (final IOException exc) {
isRunning = false;
}
if (isRunning) return null;
// display splash screen
final String[] msg =
{ TITLE + " " + VERSION + " - " + AUTHOR, "VisBio is starting up..." };
final SplashScreen ss =
new SplashScreen(VisBio.class.getResource("visbio-logo.png"), msg,
new Color(255, 255, 220), new Color(255, 50, 50));
ss.setVisible(true);
// toggle window decoration mode via reflection
final boolean b =
"true".equals(System.getProperty("visbio.decorateWindows"));
final Class<?> jf = Class.forName("javax.swing.JFrame");
final Method m =
jf.getMethod("setDefaultLookAndFeelDecorated",
new Class<?>[] { boolean.class });
m.invoke(null, new Object[] { new Boolean(b) });
<|fim▁hole|> final Class<?> vb = Class.forName("loci.visbio.VisBioFrame");
final Constructor<?> con =
vb.getConstructor(new Class[] { ss.getClass(), String[].class });
return con.newInstance(new Object[] { ss, args });
}
// -- Thread API methods --
/** Launches the VisBio GUI with no arguments. */
@Override
public void run() {
try {
launch(new String[0]);
}
catch (final Exception exc) {
exc.printStackTrace();
}
}
// -- Main --
/** Launches the VisBio GUI. */
public static void main(final String[] args) throws ClassNotFoundException,
IllegalAccessException, InstantiationException, InvocationTargetException,
NoSuchMethodException
{
System.setProperty("apple.laf.useScreenMenuBar", "true");
final Object o = launch(args);
if (o == null) System.out.println("VisBio is already running.");
}
}<|fim▁end|> | // construct VisBio interface via reflection |
<|file_name|>bufpool.cc<|end_file_name|><|fim▁begin|>/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
*/
/*
* bufpool.c++
*
* $Date: 2004/05/12 15:29:36 $ $Revision: 1.2 $
* $Header: /home/krh/git/sync/mesa-cvs-repo/Mesa/src/glu/sgi/libnurbs/internals/bufpool.cc,v 1.2 2004/05/12 15:29:36 brianp Exp $
*/
#include "glimports.h"
#include "myassert.h"
#include "bufpool.h"
/*-----------------------------------------------------------------------------
* Pool - allocate a new pool of buffers
*-----------------------------------------------------------------------------
*/
Pool::Pool( int _buffersize, int initpoolsize, const char *n )
{
if((unsigned)_buffersize < sizeof(Buffer))
buffersize = sizeof(Buffer);
else
buffersize = _buffersize;
initsize = initpoolsize * buffersize;
nextsize = initsize;
name = n;
magic = is_allocated;
nextblock = 0;
curblock = 0;
freelist = 0;
nextfree = 0;
}
/*-----------------------------------------------------------------------------
* ~Pool - free a pool of buffers and the pool itself
*-----------------------------------------------------------------------------
*/
Pool::~Pool( void )
{
assert( (this != 0) && (magic == is_allocated) );
while( nextblock ) {
delete [] blocklist[--nextblock];
blocklist[nextblock] = 0;
}
magic = is_free;
}
void Pool::grow( void )
{<|fim▁hole|> assert( (this != 0) && (magic == is_allocated) );
curblock = new char[nextsize];
blocklist[nextblock++] = curblock;
nextfree = nextsize;
nextsize *= 2;
}
/*-----------------------------------------------------------------------------
* Pool::clear - free buffers associated with pool but keep pool
*-----------------------------------------------------------------------------
*/
void
Pool::clear( void )
{
assert( (this != 0) && (magic == is_allocated) );
while( nextblock ) {
delete [] blocklist[--nextblock];
blocklist[nextblock] = 0;
}
curblock = 0;
freelist = 0;
nextfree = 0;
if( nextsize > initsize )
nextsize /= 2;
}<|fim▁end|> | |
<|file_name|>testutils.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import, print_function, division
from pony.py23compat import basestring
from functools import wraps
from contextlib import contextmanager
from pony.orm.core import Database
from pony.utils import import_module
def raises_exception(exc_class, msg=None):
def decorator(func):
def wrapper(self, *args, **kwargs):
try:
func(self, *args, **kwargs)
self.fail("expected exception %s wasn't raised" % exc_class.__name__)
except exc_class as e:
if not e.args: self.assertEqual(msg, None)
elif msg is not None:
self.assertEqual(e.args[0], msg, "incorrect exception message. expected '%s', got '%s'" % (msg, e.args[0]))
wrapper.__name__ = func.__name__
return wrapper
return decorator
@contextmanager
def raises_if(test, cond, exc_class, exc_msg=None):
try:
yield
except exc_class as e:
test.assertTrue(cond)
if exc_msg is None: pass
elif exc_msg.startswith('...') and exc_msg != '...':
if exc_msg.endswith('...'):
test.assertIn(exc_msg[3:-3], str(e))
else:
test.assertTrue(str(e).endswith(exc_msg[3:]))
elif exc_msg.endswith('...'):
test.assertTrue(str(e).startswith(exc_msg[:-3]))
else:
test.assertEqual(str(e), exc_msg)
else:
test.assertFalse(cond)
def flatten(x):
result = []
for el in x:
if hasattr(el, "__iter__") and not isinstance(el, basestring):
result.extend(flatten(el))
else:
result.append(el)
return result
class TestConnection(object):
def __init__(con, database):
con.database = database
if database and database.provider_name == 'postgres':
con.autocommit = True
def commit(con):
pass
def rollback(con):
pass
def cursor(con):
return test_cursor
class TestCursor(object):
def __init__(cursor):
cursor.description = []
cursor.rowcount = 0
<|fim▁hole|> pass
def fetchone(cursor):
return None
def fetchmany(cursor, size):
return []
def fetchall(cursor):
return []
test_cursor = TestCursor()
class TestPool(object):
def __init__(pool, database):
pool.database = database
def connect(pool):
return TestConnection(pool.database)
def release(pool, con):
pass
def drop(pool, con):
pass
def disconnect(pool):
pass
class TestDatabase(Database):
real_provider_name = None
raw_server_version = None
sql = None
def bind(self, provider_name, *args, **kwargs):
if self.real_provider_name is not None:
provider_name = self.real_provider_name
self.provider_name = provider_name
provider_module = import_module('pony.orm.dbproviders.' + provider_name)
provider_cls = provider_module.provider_cls
raw_server_version = self.raw_server_version
if raw_server_version is None:
if provider_name == 'sqlite': raw_server_version = '3.7.17'
elif provider_name in ('postgres', 'pygresql'): raw_server_version = '9.2'
elif provider_name == 'oracle': raw_server_version = '11.2.0.2.0'
elif provider_name == 'mysql': raw_server_version = '5.6.11'
else: assert False, provider_name # pragma: no cover
t = [ int(component) for component in raw_server_version.split('.') ]
if len(t) == 2: t.append(0)
server_version = tuple(t)
if provider_name in ('postgres', 'pygresql'):
server_version = int('%d%02d%02d' % server_version)
class TestProvider(provider_cls):
def inspect_connection(provider, connection):
pass
TestProvider.server_version = server_version
kwargs['pony_check_connection'] = False
kwargs['pony_pool_mockup'] = TestPool(self)
Database.bind(self, TestProvider, *args, **kwargs)
def _execute(database, sql, globals, locals, frame_depth):
assert False # pragma: no cover
def _exec_sql(database, sql, arguments=None, returning_id=False):
assert type(arguments) is not list and not returning_id
database.sql = sql
database.arguments = arguments
return test_cursor
def generate_mapping(database, filename=None, check_tables=True, create_tables=False):
return Database.generate_mapping(database, filename, create_tables=False)<|fim▁end|> | def execute(cursor, sql, args=None):
|
<|file_name|>SettingUpdate.cpp<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2013-2018 Team Kodi
* This file is part of Kodi - https://kodi.tv
*
* SPDX-License-Identifier: GPL-2.0-or-later
* See LICENSES/README.md for more information.
*/
#include "SettingUpdate.h"
#include "ServiceBroker.h"
#include "SettingDefinitions.h"
#include "utils/StringUtils.h"
#include "utils/XBMCTinyXML.h"
#include "utils/log.h"
CSettingUpdate::CSettingUpdate() : CStaticLoggerBase("CSettingUpdate")
{
}
bool CSettingUpdate::Deserialize(const TiXmlNode *node)
{
if (node == nullptr)
return false;
auto elem = node->ToElement();
if (elem == nullptr)
return false;
<|fim▁hole|> return false;
}
if (m_type == SettingUpdateType::Rename)
{
if (node->FirstChild() == nullptr || node->FirstChild()->Type() != TiXmlNode::TINYXML_TEXT)
{
s_logger->warn("missing or invalid setting id for rename update definition");
return false;
}
m_value = node->FirstChild()->ValueStr();
}
return true;
}
bool CSettingUpdate::setType(const std::string &type)
{
if (StringUtils::EqualsNoCase(type, "change"))
m_type = SettingUpdateType::Change;
else if (StringUtils::EqualsNoCase(type, "rename"))
m_type = SettingUpdateType::Rename;
else
return false;
return true;
}<|fim▁end|> | auto strType = elem->Attribute(SETTING_XML_ATTR_TYPE);
if (strType == nullptr || strlen(strType) <= 0 || !setType(strType))
{
s_logger->warn("missing or unknown update type definition"); |
<|file_name|>SystemCommandCall.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2010 Pablo Arrighi, Alex Concha, Miguel Lezama for version 1.
* Copyright 2013 Pablo Arrighi, Miguel Lezama, Kevin Mazet for version 2.
*
* This file is part of GOOL.
*
* GOOL is free software: you can redistribute it and/or modify it under the terms of the GNU
* General Public License as published by the Free Software Foundation, version 3.
*
* GOOL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License version 3 for more details.<|fim▁hole|>
package gool.ast.system;
import gool.ast.core.GoolCall;
import gool.ast.type.TypeVoid;
import gool.generator.GoolGeneratorController;
/**
* This class captures the invocation of a system method.
*/
public class SystemCommandCall extends GoolCall {
/**
* The constructor of a "system call" representation.
*/
public SystemCommandCall() {
super(TypeVoid.INSTANCE);
}
@Override
public String callGetCode() {
return GoolGeneratorController.generator().getCode(this);
}
}<|fim▁end|> | *
* You should have received a copy of the GNU General Public License along with GOOL,
* in the file COPYING.txt. If not, see <http://www.gnu.org/licenses/>.
*/ |
<|file_name|>sync-rwlock-read-mode-shouldnt-escape.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed<|fim▁hole|>
// error-pattern: cannot infer an appropriate lifetime
extern mod extra;
use extra::sync;
fn main() {
let x = ~sync::RWlock();
let mut y = None;
do x.write_downgrade |write_mode| {
y = Some(x.downgrade(write_mode));
}
// Adding this line causes a method unification failure instead
// do (&option::unwrap(y)).read { }
}<|fim▁end|> | // except according to those terms. |
<|file_name|>test_fixes.py<|end_file_name|><|fim▁begin|>from execnet import Group
from execnet.gateway_bootstrap import fix_pid_for_jython_popen
<|fim▁hole|> group.makegateway('popen//id=via')
group.makegateway('popen//via=via')
finally:
group.terminate(timeout=1.0)
def test_jython_bootstrap_fix():
group = Group()
gw = group.makegateway('popen')
popen = gw._io.popen
real_pid = popen.pid
try:
# nothing happens when calling it on a normal seyup
fix_pid_for_jython_popen(gw)
assert popen.pid == real_pid
# if there is no pid for a popen gw, restore
popen.pid = None
fix_pid_for_jython_popen(gw)
assert popen.pid == real_pid
# if there is no pid for other gw, ignore - they are remote
gw.spec.popen = False
popen.pid = None
fix_pid_for_jython_popen(gw)
assert popen.pid is None
finally:
popen.pid = real_pid
group.terminate(timeout=1)<|fim▁end|> |
def test_jython_bootstrap_not_on_remote():
group = Group()
try: |
<|file_name|>timedelta.py<|end_file_name|><|fim▁begin|>import datetime
from judge.utils.timedelta import nice_repr
from . import registry
@registry.filter
def timedelta(value, display='long'):
if value is None:
return value<|fim▁hole|>
@registry.filter
def timestampdelta(value, display='long'):
value = datetime.timedelta(seconds=value)
return timedelta(value, display)
@registry.filter
def seconds(timedelta):
return timedelta.total_seconds()
@registry.filter
@registry.render_with('time-remaining-fragment.html')
def as_countdown(timedelta):
return {'countdown': timedelta}<|fim▁end|> | return nice_repr(value, display) |
<|file_name|>Node.java<|end_file_name|><|fim▁begin|>/* This code is part of Freenet. It is distributed under the GNU General
* Public License, version 2 (or at your option any later version). See
* http://www.gnu.org/ for further details of the GPL. */
/* Freenet 0.7 node. */
package freenet.node;
import static freenet.node.stats.DataStoreKeyType.CHK;
import static freenet.node.stats.DataStoreKeyType.PUB_KEY;
import static freenet.node.stats.DataStoreKeyType.SSK;
import static freenet.node.stats.DataStoreType.CACHE;
import static freenet.node.stats.DataStoreType.CLIENT;
import static freenet.node.stats.DataStoreType.SLASHDOT;
import static freenet.node.stats.DataStoreType.STORE;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.Random;
import java.util.Set;
import freenet.config.*;
import freenet.node.useralerts.*;
import org.tanukisoftware.wrapper.WrapperManager;
import freenet.client.FetchContext;
import freenet.clients.fcp.FCPMessage;
import freenet.clients.fcp.FeedMessage;
import freenet.clients.http.SecurityLevelsToadlet;
import freenet.clients.http.SimpleToadletServer;
import freenet.crypt.DSAPublicKey;
import freenet.crypt.ECDH;
import freenet.crypt.MasterSecret;
import freenet.crypt.PersistentRandomSource;
import freenet.crypt.RandomSource;
import freenet.crypt.Yarrow;
import freenet.io.comm.DMT;
import freenet.io.comm.DisconnectedException;
import freenet.io.comm.FreenetInetAddress;
import freenet.io.comm.IOStatisticCollector;
import freenet.io.comm.Message;
import freenet.io.comm.MessageCore;
import freenet.io.comm.MessageFilter;
import freenet.io.comm.Peer;
import freenet.io.comm.PeerParseException;
import freenet.io.comm.ReferenceSignatureVerificationException;
import freenet.io.comm.TrafficClass;
import freenet.io.comm.UdpSocketHandler;
import freenet.io.xfer.PartiallyReceivedBlock;
import freenet.keys.CHKBlock;
import freenet.keys.CHKVerifyException;
import freenet.keys.ClientCHK;
import freenet.keys.ClientCHKBlock;
import freenet.keys.ClientKey;
import freenet.keys.ClientKeyBlock;
import freenet.keys.ClientSSK;
import freenet.keys.ClientSSKBlock;
import freenet.keys.Key;
import freenet.keys.KeyBlock;
import freenet.keys.KeyVerifyException;
import freenet.keys.NodeCHK;
import freenet.keys.NodeSSK;
import freenet.keys.SSKBlock;
import freenet.keys.SSKVerifyException;
import freenet.l10n.BaseL10n;
import freenet.l10n.NodeL10n;
import freenet.node.DarknetPeerNode.FRIEND_TRUST;
import freenet.node.DarknetPeerNode.FRIEND_VISIBILITY;
import freenet.node.NodeDispatcher.NodeDispatcherCallback;
import freenet.node.OpennetManager.ConnectionType;
import freenet.node.SecurityLevels.NETWORK_THREAT_LEVEL;
import freenet.node.SecurityLevels.PHYSICAL_THREAT_LEVEL;
import freenet.node.probe.Listener;
import freenet.node.probe.Type;
import freenet.node.stats.DataStoreInstanceType;
import freenet.node.stats.DataStoreStats;
import freenet.node.stats.NotAvailNodeStoreStats;
import freenet.node.stats.StoreCallbackStats;
import freenet.node.updater.NodeUpdateManager;
import freenet.pluginmanager.ForwardPort;
import freenet.pluginmanager.PluginDownLoaderOfficialHTTPS;
import freenet.pluginmanager.PluginManager;
import freenet.store.BlockMetadata;
import freenet.store.CHKStore;
import freenet.store.FreenetStore;
import freenet.store.KeyCollisionException;
import freenet.store.NullFreenetStore;
import freenet.store.PubkeyStore;
import freenet.store.RAMFreenetStore;
import freenet.store.SSKStore;
import freenet.store.SlashdotStore;
import freenet.store.StorableBlock;
import freenet.store.StoreCallback;
import freenet.store.caching.CachingFreenetStore;
import freenet.store.caching.CachingFreenetStoreTracker;
import freenet.store.saltedhash.ResizablePersistentIntBuffer;
import freenet.store.saltedhash.SaltedHashFreenetStore;
import freenet.support.Executor;
import freenet.support.Fields;
import freenet.support.HTMLNode;
import freenet.support.HexUtil;
import freenet.support.JVMVersion;
import freenet.support.LogThresholdCallback;
import freenet.support.Logger;
import freenet.support.Logger.LogLevel;
import freenet.support.PooledExecutor;
import freenet.support.PrioritizedTicker;
import freenet.support.ShortBuffer;
import freenet.support.SimpleFieldSet;
import freenet.support.Ticker;
import freenet.support.TokenBucket;
import freenet.support.api.BooleanCallback;
import freenet.support.api.IntCallback;
import freenet.support.api.LongCallback;
import freenet.support.api.ShortCallback;
import freenet.support.api.StringCallback;
import freenet.support.io.ArrayBucketFactory;
import freenet.support.io.Closer;
import freenet.support.io.FileUtil;
import freenet.support.io.NativeThread;
import freenet.support.math.MersenneTwister;
import freenet.support.transport.ip.HostnameSyntaxException;
/**
* @author amphibian
*/
public class Node implements TimeSkewDetectorCallback {
public class MigrateOldStoreData implements Runnable {
private final boolean clientCache;
public MigrateOldStoreData(boolean clientCache) {
this.clientCache = clientCache;
if(clientCache) {
oldCHKClientCache = chkClientcache;
oldPKClientCache = pubKeyClientcache;
oldSSKClientCache = sskClientcache;
} else {
oldCHK = chkDatastore;
oldPK = pubKeyDatastore;
oldSSK = sskDatastore;
oldCHKCache = chkDatastore;
oldPKCache = pubKeyDatastore;
oldSSKCache = sskDatastore;
}
}
@Override
public void run() {
System.err.println("Migrating old "+(clientCache ? "client cache" : "datastore"));
if(clientCache) {
migrateOldStore(oldCHKClientCache, chkClientcache, true);
StoreCallback<? extends StorableBlock> old;
synchronized(Node.this) {
old = oldCHKClientCache;
oldCHKClientCache = null;
}
closeOldStore(old);
migrateOldStore(oldPKClientCache, pubKeyClientcache, true);
synchronized(Node.this) {
old = oldPKClientCache;
oldPKClientCache = null;
}
closeOldStore(old);
migrateOldStore(oldSSKClientCache, sskClientcache, true);
synchronized(Node.this) {
old = oldSSKClientCache;
oldSSKClientCache = null;
}
closeOldStore(old);
} else {
migrateOldStore(oldCHK, chkDatastore, false);
oldCHK = null;
migrateOldStore(oldPK, pubKeyDatastore, false);
oldPK = null;
migrateOldStore(oldSSK, sskDatastore, false);
oldSSK = null;
migrateOldStore(oldCHKCache, chkDatacache, false);
oldCHKCache = null;
migrateOldStore(oldPKCache, pubKeyDatacache, false);
oldPKCache = null;
migrateOldStore(oldSSKCache, sskDatacache, false);
oldSSKCache = null;
}
System.err.println("Finished migrating old "+(clientCache ? "client cache" : "datastore"));
}
}
volatile CHKStore oldCHK;
volatile PubkeyStore oldPK;
volatile SSKStore oldSSK;
volatile CHKStore oldCHKCache;
volatile PubkeyStore oldPKCache;
volatile SSKStore oldSSKCache;
volatile CHKStore oldCHKClientCache;
volatile PubkeyStore oldPKClientCache;
volatile SSKStore oldSSKClientCache;
private <T extends StorableBlock> void migrateOldStore(StoreCallback<T> old, StoreCallback<T> newStore, boolean canReadClientCache) {
FreenetStore<T> store = old.getStore();
if(store instanceof RAMFreenetStore) {
RAMFreenetStore<T> ramstore = (RAMFreenetStore<T>)store;
try {
ramstore.migrateTo(newStore, canReadClientCache);
} catch (IOException e) {
Logger.error(this, "Caught migrating old store: "+e, e);
}
ramstore.clear();
} else if(store instanceof SaltedHashFreenetStore) {
Logger.error(this, "Migrating from from a saltedhashstore not fully supported yet: will not keep old keys");
}
}
public <T extends StorableBlock> void closeOldStore(StoreCallback<T> old) {
FreenetStore<T> store = old.getStore();
if(store instanceof SaltedHashFreenetStore) {
SaltedHashFreenetStore<T> saltstore = (SaltedHashFreenetStore<T>) store;
saltstore.close();
saltstore.destruct();
}
}
private static volatile boolean logMINOR;
private static volatile boolean logDEBUG;
static {
Logger.registerLogThresholdCallback(new LogThresholdCallback(){
@Override
public void shouldUpdate(){
logMINOR = Logger.shouldLog(LogLevel.MINOR, this);
logDEBUG = Logger.shouldLog(LogLevel.DEBUG, this);
}
});
}
private static MeaningfulNodeNameUserAlert nodeNameUserAlert;
private static TimeSkewDetectedUserAlert timeSkewDetectedUserAlert;
public class NodeNameCallback extends StringCallback {
NodeNameCallback() {
}
@Override
public String get() {
String name;
synchronized(this) {
name = myName;
}
if(name.startsWith("Node id|")|| name.equals("MyFirstFreenetNode") || name.startsWith("Freenet node with no name #")){
clientCore.alerts.register(nodeNameUserAlert);
}else{
clientCore.alerts.unregister(nodeNameUserAlert);
}
return name;
}
@Override
public void set(String val) throws InvalidConfigValueException {
if(get().equals(val)) return;
else if(val.length() > 128)
throw new InvalidConfigValueException("The given node name is too long ("+val+')');
else if("".equals(val))
val = "~none~";
synchronized(this) {
myName = val;
}
// We'll broadcast the new name to our connected darknet peers via a differential node reference
SimpleFieldSet fs = new SimpleFieldSet(true);
fs.putSingle("myName", myName);
peers.locallyBroadcastDiffNodeRef(fs, true, false);
// We call the callback once again to ensure MeaningfulNodeNameUserAlert
// has been unregistered ... see #1595
get();
}
}
private class StoreTypeCallback extends StringCallback implements EnumerableOptionCallback {
@Override
public String get() {
synchronized(Node.this) {
return storeType;
}
}
@Override
public void set(String val) throws InvalidConfigValueException, NodeNeedRestartException {
boolean found = false;
for (String p : getPossibleValues()) {
if (p.equals(val)) {
found = true;
break;
}
}
if (!found)
throw new InvalidConfigValueException("Invalid store type");
String type;
synchronized(Node.this) {
type = storeType;
}
if(type.equals("ram")) {
synchronized(this) { // Serialise this part.
makeStore(val);
}
} else {
synchronized(Node.this) {
storeType = val;
}
throw new NodeNeedRestartException("Store type cannot be changed on the fly");
}
}
@Override
public String[] getPossibleValues() {
return new String[] { "salt-hash", "ram" };
}
}
private class ClientCacheTypeCallback extends StringCallback implements EnumerableOptionCallback {
@Override
public String get() {
synchronized(Node.this) {
return clientCacheType;
}
}
@Override
public void set(String val) throws InvalidConfigValueException, NodeNeedRestartException {
boolean found = false;
for (String p : getPossibleValues()) {
if (p.equals(val)) {
found = true;
break;
}
}
if (!found)
throw new InvalidConfigValueException("Invalid store type");
synchronized(this) { // Serialise this part.
String suffix = getStoreSuffix();
if (val.equals("salt-hash")) {
byte[] key;
try {
synchronized(Node.this) {
if(keys == null) throw new MasterKeysWrongPasswordException();
key = keys.clientCacheMasterKey;
clientCacheType = val;
}
} catch (MasterKeysWrongPasswordException e1) {
setClientCacheAwaitingPassword();
throw new InvalidConfigValueException("You must enter the password");
}
try {
initSaltHashClientCacheFS(suffix, true, key);
} catch (NodeInitException e) {
Logger.error(this, "Unable to create new store", e);
System.err.println("Unable to create new store: "+e);
e.printStackTrace();
// FIXME l10n both on the NodeInitException and the wrapper message
throw new InvalidConfigValueException("Unable to create new store: "+e);
}
} else if(val.equals("ram")) {
initRAMClientCacheFS();
} else /*if(val.equals("none")) */{
initNoClientCacheFS();
}
synchronized(Node.this) {
clientCacheType = val;
}
}
}
@Override
public String[] getPossibleValues() {
return new String[] { "salt-hash", "ram", "none" };
}
}
private static class L10nCallback extends StringCallback implements EnumerableOptionCallback {
@Override
public String get() {
return NodeL10n.getBase().getSelectedLanguage().fullName;
}
@Override
public void set(String val) throws InvalidConfigValueException {
if(val == null || get().equalsIgnoreCase(val)) return;
try {
NodeL10n.getBase().setLanguage(BaseL10n.LANGUAGE.mapToLanguage(val));
} catch (MissingResourceException e) {
throw new InvalidConfigValueException(e.getLocalizedMessage());
}
PluginManager.setLanguage(NodeL10n.getBase().getSelectedLanguage());
}
@Override
public String[] getPossibleValues() {
return BaseL10n.LANGUAGE.valuesWithFullNames();
}
}
/** Encryption key for client.dat.crypt or client.dat.bak.crypt */
private DatabaseKey databaseKey;
/** Encryption keys, if loaded, null if waiting for a password. We must be able to write them,
* and they're all used elsewhere anyway, so there's no point trying not to keep them in memory. */
private MasterKeys keys;
/** Stats */
public final NodeStats nodeStats;
/** Config object for the whole node. */
public final PersistentConfig config;
// Static stuff related to logger
/** Directory to log to */
static File logDir;
/** Maximum size of gzipped logfiles */
static long maxLogSize;
/** Log config handler */
public static LoggingConfigHandler logConfigHandler;
public static final int PACKETS_IN_BLOCK = 32;
public static final int PACKET_SIZE = 1024;
public static final double DECREMENT_AT_MIN_PROB = 0.25;
public static final double DECREMENT_AT_MAX_PROB = 0.5;
// Send keepalives every 7-14 seconds. Will be acked and if necessary resent.
// Old behaviour was keepalives every 14-28. Even that was adequate for a 30 second
// timeout. Most nodes don't need to send keepalives because they are constantly busy,
// this is only an issue for disabled darknet connections, very quiet private networks
// etc.
public static final long KEEPALIVE_INTERVAL = SECONDS.toMillis(7);
// If no activity for 30 seconds, node is dead
// 35 seconds allows plenty of time for resends etc even if above is 14 sec as it is on older nodes.
public static final long MAX_PEER_INACTIVITY = SECONDS.toMillis(35);
/** Time after which a handshake is assumed to have failed. */
public static final int HANDSHAKE_TIMEOUT = (int) MILLISECONDS.toMillis(4800); // Keep the below within the 30 second assumed timeout.
// Inter-handshake time must be at least 2x handshake timeout
public static final int MIN_TIME_BETWEEN_HANDSHAKE_SENDS = HANDSHAKE_TIMEOUT*2; // 10-20 secs
public static final int RANDOMIZED_TIME_BETWEEN_HANDSHAKE_SENDS = HANDSHAKE_TIMEOUT*2; // avoid overlap when the two handshakes are at the same time
public static final int MIN_TIME_BETWEEN_VERSION_PROBES = HANDSHAKE_TIMEOUT*4;
public static final int RANDOMIZED_TIME_BETWEEN_VERSION_PROBES = HANDSHAKE_TIMEOUT*2; // 20-30 secs
public static final int MIN_TIME_BETWEEN_VERSION_SENDS = HANDSHAKE_TIMEOUT*4;
public static final int RANDOMIZED_TIME_BETWEEN_VERSION_SENDS = HANDSHAKE_TIMEOUT*2; // 20-30 secs
public static final int MIN_TIME_BETWEEN_BURSTING_HANDSHAKE_BURSTS = HANDSHAKE_TIMEOUT*24; // 2-5 minutes
public static final int RANDOMIZED_TIME_BETWEEN_BURSTING_HANDSHAKE_BURSTS = HANDSHAKE_TIMEOUT*36;
public static final int MIN_BURSTING_HANDSHAKE_BURST_SIZE = 1; // 1-4 handshake sends per burst
public static final int RANDOMIZED_BURSTING_HANDSHAKE_BURST_SIZE = 3;
// If we don't receive any packets at all in this period, from any node, tell the user
public static final long ALARM_TIME = MINUTES.toMillis(1);
static final long MIN_INTERVAL_BETWEEN_INCOMING_SWAP_REQUESTS = MILLISECONDS.toMillis(900);
static final long MIN_INTERVAL_BETWEEN_INCOMING_PROBE_REQUESTS = MILLISECONDS.toMillis(1000);
public static final int SYMMETRIC_KEY_LENGTH = 32; // 256 bits - note that this isn't used everywhere to determine it
/** Datastore directory */
private final ProgramDirectory storeDir;
/** Datastore properties */
private String storeType;
private boolean storeUseSlotFilters;
private boolean storeSaltHashResizeOnStart;
/** Minimum total datastore size */
static final long MIN_STORE_SIZE = 32 * 1024 * 1024;
/** Default datastore size (must be at least MIN_STORE_SIZE) */
static final long DEFAULT_STORE_SIZE = 32 * 1024 * 1024;
/** Minimum client cache size */
static final long MIN_CLIENT_CACHE_SIZE = 0;
/** Default client cache size (must be at least MIN_CLIENT_CACHE_SIZE) */
static final long DEFAULT_CLIENT_CACHE_SIZE = 10 * 1024 * 1024;
/** Minimum slashdot cache size */
static final long MIN_SLASHDOT_CACHE_SIZE = 0;
/** Default slashdot cache size (must be at least MIN_SLASHDOT_CACHE_SIZE) */
static final long DEFAULT_SLASHDOT_CACHE_SIZE = 10 * 1024 * 1024;
/** The number of bytes per key total in all the different datastores. All the datastores
* are always the same size in number of keys. */
public static final int sizePerKey = CHKBlock.DATA_LENGTH + CHKBlock.TOTAL_HEADERS_LENGTH +
DSAPublicKey.PADDED_SIZE + SSKBlock.DATA_LENGTH + SSKBlock.TOTAL_HEADERS_LENGTH;
/** The maximum number of keys stored in each of the datastores, cache and store combined. */
private long maxTotalKeys;
long maxCacheKeys;
long maxStoreKeys;
/** The maximum size of the datastore. Kept to avoid rounding turning 5G into 5368698672 */
private long maxTotalDatastoreSize;
/** If true, store shrinks occur immediately even if they are over 10% of the store size. If false,
* we just set the storeSize and do an offline shrink on the next startup. Online shrinks do not
* preserve the most recently used data so are not recommended. */
private boolean storeForceBigShrinks;
private final SemiOrderedShutdownHook shutdownHook;
/** The CHK datastore. Long term storage; data should only be inserted here if
* this node is the closest location on the chain so far, and it is on an
* insert (because inserts will always reach the most specialized node; if we
* allow requests to store here, then we get pollution by inserts for keys not
* close to our specialization). These conclusions derived from Oskar's simulations. */
private CHKStore chkDatastore;
/** The SSK datastore. See description for chkDatastore. */
private SSKStore sskDatastore;
/** The store of DSAPublicKeys (by hash). See description for chkDatastore. */
private PubkeyStore pubKeyDatastore;
/** Client cache store type */
private String clientCacheType;
/** Client cache could not be opened so is a RAMFS until the correct password is entered */
private boolean clientCacheAwaitingPassword;
private boolean databaseAwaitingPassword;
/** Client cache maximum cached keys for each type */
long maxClientCacheKeys;
/** Maximum size of the client cache. Kept to avoid rounding problems. */
private long maxTotalClientCacheSize;
/** The CHK datacache. Short term cache which stores everything that passes
* through this node. */
private CHKStore chkDatacache;
/** The SSK datacache. Short term cache which stores everything that passes
* through this node. */
private SSKStore sskDatacache;
/** The public key datacache (by hash). Short term cache which stores
* everything that passes through this node. */
private PubkeyStore pubKeyDatacache;
/** The CHK client cache. Caches local requests only. */
private CHKStore chkClientcache;
/** The SSK client cache. Caches local requests only. */
private SSKStore sskClientcache;
/** The pubkey client cache. Caches local requests only. */
private PubkeyStore pubKeyClientcache;
// These only cache keys for 30 minutes.
// FIXME make the first two configurable
private long maxSlashdotCacheSize;
private int maxSlashdotCacheKeys;
static final long PURGE_INTERVAL = SECONDS.toMillis(60);
private CHKStore chkSlashdotcache;
private SlashdotStore<CHKBlock> chkSlashdotcacheStore;
private SSKStore sskSlashdotcache;
private SlashdotStore<SSKBlock> sskSlashdotcacheStore;
private PubkeyStore pubKeySlashdotcache;
private SlashdotStore<DSAPublicKey> pubKeySlashdotcacheStore;
/** If false, only ULPRs will use the slashdot cache. If true, everything does. */
private boolean useSlashdotCache;
/** If true, we write stuff to the datastore even though we shouldn't because the HTL is
* too high. However it is flagged as old so it won't be included in the Bloom filter for
* sharing purposes. */
private boolean writeLocalToDatastore;
final NodeGetPubkey getPubKey;
/** FetchContext for ARKs */
public final FetchContext arkFetcherContext;
/** IP detector */
public final NodeIPDetector ipDetector;
/** For debugging/testing, set this to true to stop the
* probabilistic decrement at the edges of the HTLs. */
boolean disableProbabilisticHTLs;
public final RequestTracker tracker;
/** Semi-unique ID for swap requests. Used to identify us so that the
* topology can be reconstructed. */
public long swapIdentifier;
private String myName;
public final LocationManager lm;
/** My peers */
public final PeerManager peers;
/** Node-reference directory (node identity, peers, etc) */
final ProgramDirectory nodeDir;
/** Config directory (l10n overrides, etc) */
final ProgramDirectory cfgDir;
/** User data directory (bookmarks, download lists, etc) */
final ProgramDirectory userDir;
/** Run-time state directory (bootID, PRNG seed, etc) */
final ProgramDirectory runDir;
/** Plugin directory */
final ProgramDirectory pluginDir;
/** File to write crypto master keys into, possibly passworded */
final File masterKeysFile;
/** Directory to put extra peer data into */
final File extraPeerDataDir;
private volatile boolean hasPanicked;
/** Strong RNG */
public final RandomSource random;
/** JCA-compliant strong RNG. WARNING: DO NOT CALL THIS ON THE MAIN NETWORK
* HANDLING THREADS! In some configurations it can block, potentially
* forever, on nextBytes()! */
public final SecureRandom secureRandom;
/** Weak but fast RNG */
public final Random fastWeakRandom;
/** The object which handles incoming messages and allows us to wait for them */
final MessageCore usm;
// Darknet stuff
NodeCrypto darknetCrypto;
// Back compat
private boolean showFriendsVisibilityAlert;
// Opennet stuff
private final NodeCryptoConfig opennetCryptoConfig;
OpennetManager opennet;
private volatile boolean isAllowedToConnectToSeednodes;
private int maxOpennetPeers;
private boolean acceptSeedConnections;
private boolean passOpennetRefsThroughDarknet;
// General stuff
public final Executor executor;
public final PacketSender ps;
public final PrioritizedTicker ticker;
final DNSRequester dnsr;
final NodeDispatcher dispatcher;
public final UptimeEstimator uptime;
public final TokenBucket outputThrottle;
public boolean throttleLocalData;
private int outputBandwidthLimit;
private int inputBandwidthLimit;
private long amountOfDataToCheckCompressionRatio;
private int minimumCompressionPercentage;
private int maxTimeForSingleCompressor;
private boolean connectionSpeedDetection;
boolean inputLimitDefault;
final boolean enableARKs;
final boolean enablePerNodeFailureTables;
final boolean enableULPRDataPropagation;
final boolean enableSwapping;
private volatile boolean publishOurPeersLocation;
private volatile boolean routeAccordingToOurPeersLocation;
boolean enableSwapQueueing;
boolean enablePacketCoalescing;
public static final short DEFAULT_MAX_HTL = (short)18;
private short maxHTL;
private boolean skipWrapperWarning;
private int maxPacketSize;
/** Should inserts ignore low backoff times by default? */
public static final boolean IGNORE_LOW_BACKOFF_DEFAULT = false;
/** Definition of "low backoff times" for above. */
public static final long LOW_BACKOFF = SECONDS.toMillis(30);
/** Should inserts be fairly blatently prioritised on accept by default? */
public static final boolean PREFER_INSERT_DEFAULT = false;
/** Should inserts fork when the HTL reaches cacheability? */
public static final boolean FORK_ON_CACHEABLE_DEFAULT = true;
public final IOStatisticCollector collector;
/** Type identifier for fproxy node to node messages, as sent on DMT.nodeToNodeMessage's */
public static final int N2N_MESSAGE_TYPE_FPROXY = 1;
/** Type identifier for differential node reference messages, as sent on DMT.nodeToNodeMessage's */
public static final int N2N_MESSAGE_TYPE_DIFFNODEREF = 2;
/** Identifier within fproxy messages for simple, short text messages to be displayed on the homepage as useralerts */
public static final int N2N_TEXT_MESSAGE_TYPE_USERALERT = 1;
/** Identifier within fproxy messages for an offer to transfer a file */
public static final int N2N_TEXT_MESSAGE_TYPE_FILE_OFFER = 2;
/** Identifier within fproxy messages for accepting an offer to transfer a file */
public static final int N2N_TEXT_MESSAGE_TYPE_FILE_OFFER_ACCEPTED = 3;
/** Identifier within fproxy messages for rejecting an offer to transfer a file */
public static final int N2N_TEXT_MESSAGE_TYPE_FILE_OFFER_REJECTED = 4;
/** Identified within friend feed for the recommendation of a bookmark */
public static final int N2N_TEXT_MESSAGE_TYPE_BOOKMARK = 5;
/** Identified within friend feed for the recommendation of a file */
public static final int N2N_TEXT_MESSAGE_TYPE_DOWNLOAD = 6;
public static final int EXTRA_PEER_DATA_TYPE_N2NTM = 1;
public static final int EXTRA_PEER_DATA_TYPE_PEER_NOTE = 2;
public static final int EXTRA_PEER_DATA_TYPE_QUEUED_TO_SEND_N2NM = 3;
public static final int EXTRA_PEER_DATA_TYPE_BOOKMARK = 4;
public static final int EXTRA_PEER_DATA_TYPE_DOWNLOAD = 5;
public static final int PEER_NOTE_TYPE_PRIVATE_DARKNET_COMMENT = 1;
/** The bootID of the last time the node booted up. Or -1 if we don't know due to
* permissions problems, or we suspect that the node has been booted and not
* written the file e.g. if we can't write it. So if we want to compare data
* gathered in the last session and only recorded to disk on a clean shutdown
* to data we have now, we just include the lastBootID. */
public final long lastBootID;
public final long bootID;
public final long startupTime;
private SimpleToadletServer toadlets;
public final NodeClientCore clientCore;
// ULPRs, RecentlyFailed, per node failure tables, are all managed by FailureTable.
final FailureTable failureTable;
// The version we were before we restarted.
public int lastVersion;
/** NodeUpdater **/
public final NodeUpdateManager nodeUpdater;
public final SecurityLevels securityLevels;
// Things that's needed to keep track of
public final PluginManager pluginManager;
// Helpers
public final InetAddress localhostAddress;
public final FreenetInetAddress fLocalhostAddress;
// The node starter
private static NodeStarter nodeStarter;
// The watchdog will be silenced until it's true
private boolean hasStarted;
private boolean isStopping = false;
/**
* Minimum uptime for us to consider a node an acceptable place to store a key. We store a key
* to the datastore only if it's from an insert, and we are a sink, but when calculating whether
* we are a sink we ignore nodes which have less uptime (percentage) than this parameter.
*/
static final int MIN_UPTIME_STORE_KEY = 40;
private volatile boolean isPRNGReady = false;
private boolean storePreallocate;
private boolean enableRoutedPing;
private boolean peersOffersDismissed;
/**
* Minimum bandwidth limit in bytes considered usable: 10 KiB. If there is an attempt to set a limit below this -
* excluding the reserved -1 for input bandwidth - the callback will throw. See the callbacks for
* outputBandwidthLimit and inputBandwidthLimit. 10 KiB are equivalent to 50 GiB traffic per month.
*/
private static final int minimumBandwidth = 10 * 1024;
/** Quality of Service mark we will use for all outgoing packets (opennet/darknet) */
private TrafficClass trafficClass;
public TrafficClass getTrafficClass() {
return trafficClass;
}
/*
* Gets minimum bandwidth in bytes considered usable.
*
* @see #minimumBandwidth
*/
public static int getMinimumBandwidth() {
return minimumBandwidth;
}
/**
* Dispatches a probe request with the specified settings
* @see freenet.node.probe.Probe#start(byte, long, Type, Listener)
*/
public void startProbe(final byte htl, final long uid, final Type type, final Listener listener) {
dispatcher.probe.start(htl, uid, type, listener);
}
/**
* Read all storable settings (identity etc) from the node file.
* @param filename The name of the file to read from.
* @throws IOException throw when I/O error occur
*/
private void readNodeFile(String filename) throws IOException {
// REDFLAG: Any way to share this code with NodePeer?
FileInputStream fis = new FileInputStream(filename);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader br = new BufferedReader(isr);
SimpleFieldSet fs = new SimpleFieldSet(br, false, true);
br.close();
// Read contents
String[] udp = fs.getAll("physical.udp");
if((udp != null) && (udp.length > 0)) {
for(String udpAddr : udp) {
// Just keep the first one with the correct port number.
Peer p;
try {
p = new Peer(udpAddr, false, true);
} catch (HostnameSyntaxException e) {
Logger.error(this, "Invalid hostname or IP Address syntax error while parsing our darknet node reference: "+udpAddr);
System.err.println("Invalid hostname or IP Address syntax error while parsing our darknet node reference: "+udpAddr);
continue;
} catch (PeerParseException e) {
throw (IOException)new IOException().initCause(e);
}
if(p.getPort() == getDarknetPortNumber()) {
// DNSRequester doesn't deal with our own node
ipDetector.setOldIPAddress(p.getFreenetAddress());
break;
}
}
}
darknetCrypto.readCrypto(fs);
swapIdentifier = Fields.bytesToLong(darknetCrypto.identityHashHash);
String loc = fs.get("location");
double locD = Location.getLocation(loc);
if (locD == -1.0)
throw new IOException("Invalid location: " + loc);
lm.setLocation(locD);
myName = fs.get("myName");
if(myName == null) {
myName = newName();
}
String verString = fs.get("version");
if(verString == null) {
Logger.error(this, "No version!");
System.err.println("No version!");
} else {
lastVersion = Version.getArbitraryBuildNumber(verString, -1);
}
}
public void makeStore(String val) throws InvalidConfigValueException {
String suffix = getStoreSuffix();
if (val.equals("salt-hash")) {
try {
initSaltHashFS(suffix, true, null);
} catch (NodeInitException e) {
Logger.error(this, "Unable to create new store", e);
System.err.println("Unable to create new store: "+e);
e.printStackTrace();
// FIXME l10n both on the NodeInitException and the wrapper message
throw new InvalidConfigValueException("Unable to create new store: "+e);
}
} else {
initRAMFS();
}
synchronized(Node.this) {
storeType = val;
}
}
private String newName() {
return "Freenet node with no name #"+random.nextLong();
}
private final Object writeNodeFileSync = new Object();
public void writeNodeFile() {
synchronized(writeNodeFileSync) {
writeNodeFile(nodeDir.file("node-"+getDarknetPortNumber()), nodeDir.file("node-"+getDarknetPortNumber()+".bak"));
}
}
public void writeOpennetFile() {
OpennetManager om = opennet;
if(om != null) om.writeFile();
}
private void writeNodeFile(File orig, File backup) {
SimpleFieldSet fs = darknetCrypto.exportPrivateFieldSet();
if(orig.exists()) backup.delete();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(backup);
fs.writeTo(fos);
fos.close();
fos = null;
FileUtil.renameTo(backup, orig);
} catch (IOException ioe) {
Logger.error(this, "IOE :"+ioe.getMessage(), ioe);
return;
} finally {
Closer.close(fos);
}
}
private void initNodeFileSettings() {
Logger.normal(this, "Creating new node file from scratch");
// Don't need to set getDarknetPortNumber()
// FIXME use a real IP!
darknetCrypto.initCrypto();
swapIdentifier = Fields.bytesToLong(darknetCrypto.identityHashHash);
myName = newName();
}
/**
* Read the config file from the arguments.
* Then create a node.
* Anything that needs static init should ideally be in here.
* @param args
*/
public static void main(String[] args) throws IOException {
NodeStarter.main(args);
}
public boolean isUsingWrapper(){
if(nodeStarter!=null && WrapperManager.isControlledByNativeWrapper())
return true;
else
return false;
}
public NodeStarter getNodeStarter(){
return nodeStarter;
}
/**
* Create a Node from a Config object.
* @param config The Config object for this node.
* @param r The random number generator for this node. Passed in because we may want
* to use a non-secure RNG for e.g. one-JVM live-code simulations. Should be a Yarrow in
* a production node. Yarrow will be used if that parameter is null
* @param weakRandom The fast random number generator the node will use. If null a MT
* instance will be used, seeded from the secure PRNG.
* @param lc logging config Handler
* @param ns NodeStarter
* @param executor Executor
* @throws NodeInitException If the node initialization fails.
*/
Node(PersistentConfig config, RandomSource r, RandomSource weakRandom, LoggingConfigHandler lc, NodeStarter ns, Executor executor) throws NodeInitException {
this.shutdownHook = SemiOrderedShutdownHook.get();
// Easy stuff
String tmp = "Initializing Node using Freenet Build #"+Version.buildNumber()+" r"+Version.cvsRevision()+" and freenet-ext Build #"+NodeStarter.extBuildNumber+" r"+NodeStarter.extRevisionNumber+" with "+System.getProperty("java.vendor")+" JVM version "+System.getProperty("java.version")+" running on "+System.getProperty("os.arch")+' '+System.getProperty("os.name")+' '+System.getProperty("os.version");
fixCertsFiles();
Logger.normal(this, tmp);
System.out.println(tmp);
collector = new IOStatisticCollector();
this.executor = executor;
nodeStarter=ns;
if(logConfigHandler != lc)
logConfigHandler=lc;
getPubKey = new NodeGetPubkey(this);
startupTime = System.currentTimeMillis();
SimpleFieldSet oldConfig = config.getSimpleFieldSet();
// Setup node-specific configuration
final SubConfig nodeConfig = config.createSubConfig("node");
final SubConfig installConfig = config.createSubConfig("node.install");
int sortOrder = 0;
// Directory for node-related files other than store
this.userDir = setupProgramDir(installConfig, "userDir", ".",
"Node.userDir", "Node.userDirLong", nodeConfig);
this.cfgDir = setupProgramDir(installConfig, "cfgDir", getUserDir().toString(),
"Node.cfgDir", "Node.cfgDirLong", nodeConfig);
this.nodeDir = setupProgramDir(installConfig, "nodeDir", getUserDir().toString(),
"Node.nodeDir", "Node.nodeDirLong", nodeConfig);
this.runDir = setupProgramDir(installConfig, "runDir", getUserDir().toString(),
"Node.runDir", "Node.runDirLong", nodeConfig);
this.pluginDir = setupProgramDir(installConfig, "pluginDir", userDir().file("plugins").toString(),
"Node.pluginDir", "Node.pluginDirLong", nodeConfig);
// l10n stuffs
nodeConfig.register("l10n", Locale.getDefault().getLanguage().toLowerCase(), sortOrder++, false, true,
"Node.l10nLanguage",
"Node.l10nLanguageLong",
new L10nCallback());
try {
new NodeL10n(BaseL10n.LANGUAGE.mapToLanguage(nodeConfig.getString("l10n")), getCfgDir());
} catch (MissingResourceException e) {
try {
new NodeL10n(BaseL10n.LANGUAGE.mapToLanguage(nodeConfig.getOption("l10n").getDefault()), getCfgDir());
} catch (MissingResourceException e1) {
new NodeL10n(BaseL10n.LANGUAGE.mapToLanguage(BaseL10n.LANGUAGE.getDefault().shortCode), getCfgDir());
}
}
// FProxy config needs to be here too
SubConfig fproxyConfig = config.createSubConfig("fproxy");
try {
toadlets = new SimpleToadletServer(fproxyConfig, new ArrayBucketFactory(), executor, this);
fproxyConfig.finishedInitialization();
toadlets.start();
} catch (IOException e4) {
Logger.error(this, "Could not start web interface: "+e4, e4);
System.err.println("Could not start web interface: "+e4);
e4.printStackTrace();
throw new NodeInitException(NodeInitException.EXIT_COULD_NOT_START_FPROXY, "Could not start FProxy: "+e4);
} catch (InvalidConfigValueException e4) {
System.err.println("Invalid config value, cannot start web interface: "+e4);
e4.printStackTrace();
throw new NodeInitException(NodeInitException.EXIT_COULD_NOT_START_FPROXY, "Could not start FProxy: "+e4);
}
final NativeThread entropyGatheringThread = new NativeThread(new Runnable() {
long tLastAdded = -1;
private void recurse(File f) {
if(isPRNGReady)
return;
extendTimeouts();
File[] subDirs = f.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.exists() && pathname.canRead() && pathname.isDirectory();
}
});
// @see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5086412
if(subDirs != null)
for(File currentDir : subDirs)
recurse(currentDir);
}
@Override
public void run() {
try {
// Delay entropy generation helper hack if enough entropy available
Thread.sleep(100);
} catch (InterruptedException e) {
}
if(isPRNGReady)
return;
System.out.println("Not enough entropy available.");
System.out.println("Trying to gather entropy (randomness) by reading the disk...");
if(File.separatorChar == '/') {
if(new File("/dev/hwrng").exists())
System.out.println("/dev/hwrng exists - have you installed rng-tools?");
else
System.out.println("You should consider installing a better random number generator e.g. haveged.");
}
extendTimeouts();
for(File root : File.listRoots()) {
if(isPRNGReady)
return;
recurse(root);
}
}
/** This is ridiculous, but for some users it can take more than an hour, and timing out sucks
* a few bytes and then times out again. :( */
static final int EXTEND_BY = 60*60*1000;
private void extendTimeouts() {
long now = System.currentTimeMillis();
if(now - tLastAdded < EXTEND_BY/2) return;
long target = tLastAdded + EXTEND_BY;
while(target < now)
target += EXTEND_BY;
long extend = target - now;
assert(extend < Integer.MAX_VALUE);
assert(extend > 0);
WrapperManager.signalStarting((int)extend);
tLastAdded = now;
}
}, "Entropy Gathering Thread", NativeThread.MIN_PRIORITY, true);
// Setup RNG if needed : DO NOT USE IT BEFORE THAT POINT!
if (r == null) {
// Preload required freenet.crypt.Util and freenet.crypt.Rijndael classes (selftest can delay Yarrow startup and trigger false lack-of-enthropy message)
freenet.crypt.Util.mdProviders.size();
freenet.crypt.ciphers.Rijndael.getProviderName();
File seed = userDir.file("prng.seed");
FileUtil.setOwnerRW(seed);
entropyGatheringThread.start();
// Can block.
this.random = new Yarrow(seed);
// http://bugs.sun.com/view_bug.do;jsessionid=ff625daf459fdffffffffcd54f1c775299e0?bug_id=4705093
// This might block on /dev/random while doing new SecureRandom(). Once it's created, it won't block.
ECDH.blockingInit();
} else {
this.random = r;
// if it's not null it's because we are running in the simulator
}
// This can block too.
this.secureRandom = NodeStarter.getGlobalSecureRandom();
isPRNGReady = true;
toadlets.getStartupToadlet().setIsPRNGReady();
if(weakRandom == null) {
byte buffer[] = new byte[16];
random.nextBytes(buffer);
this.fastWeakRandom = new MersenneTwister(buffer);
}else
this.fastWeakRandom = weakRandom;
nodeNameUserAlert = new MeaningfulNodeNameUserAlert(this);
this.config = config;
lm = new LocationManager(random, this);
try {
localhostAddress = InetAddress.getByName("127.0.0.1");
} catch (UnknownHostException e3) {
// Does not do a reverse lookup, so this is impossible
throw new Error(e3);
}
fLocalhostAddress = new FreenetInetAddress(localhostAddress);
this.securityLevels = new SecurityLevels(this, config);
// Location of master key
nodeConfig.register("masterKeyFile", "master.keys", sortOrder++, true, true, "Node.masterKeyFile", "Node.masterKeyFileLong",
new StringCallback() {
@Override
public String get() {
if(masterKeysFile == null) return "none";
else return masterKeysFile.getPath();
}
@Override
public void set(String val) throws InvalidConfigValueException, NodeNeedRestartException {
// FIXME l10n
// FIXME wipe the old one and move
throw new InvalidConfigValueException("Node.masterKeyFile cannot be changed on the fly, you must shutdown, wipe the old file and reconfigure");
}
});
String value = nodeConfig.getString("masterKeyFile");
File f;
if (value.equalsIgnoreCase("none")) {
f = null;
} else {
f = new File(value);
if(f.exists() && !(f.canWrite() && f.canRead()))
throw new NodeInitException(NodeInitException.EXIT_CANT_WRITE_MASTER_KEYS, "Cannot read from and write to master keys file "+f);
}
masterKeysFile = f;
FileUtil.setOwnerRW(masterKeysFile);
nodeConfig.register("showFriendsVisibilityAlert", false, sortOrder++, true, false, "Node.showFriendsVisibilityAlert", "Node.showFriendsVisibilityAlert", new BooleanCallback() {
@Override
public Boolean get() {
synchronized(Node.this) {
return showFriendsVisibilityAlert;
}
}
@Override
public void set(Boolean val) throws InvalidConfigValueException,
NodeNeedRestartException {
synchronized(this) {
if(val == showFriendsVisibilityAlert) return;
if(val) return;
}
unregisterFriendsVisibilityAlert();
}
});
showFriendsVisibilityAlert = nodeConfig.getBoolean("showFriendsVisibilityAlert");
byte[] clientCacheKey = null;
MasterSecret persistentSecret = null;
for(int i=0;i<2; i++) {
try {
if(securityLevels.physicalThreatLevel == PHYSICAL_THREAT_LEVEL.MAXIMUM) {
keys = MasterKeys.createRandom(secureRandom);
} else {
keys = MasterKeys.read(masterKeysFile, secureRandom, "");
}
clientCacheKey = keys.clientCacheMasterKey;
persistentSecret = keys.getPersistentMasterSecret();
databaseKey = keys.createDatabaseKey(secureRandom);
if(securityLevels.getPhysicalThreatLevel() == PHYSICAL_THREAT_LEVEL.HIGH) {
System.err.println("Physical threat level is set to HIGH but no password, resetting to NORMAL - probably timing glitch");
securityLevels.resetPhysicalThreatLevel(PHYSICAL_THREAT_LEVEL.NORMAL);
}
break;
} catch (MasterKeysWrongPasswordException e) {
break;
} catch (MasterKeysFileSizeException e) {
System.err.println("Impossible: master keys file "+masterKeysFile+" too " + e.sizeToString() + "! Deleting to enable startup, but you will lose your client cache.");
masterKeysFile.delete();
} catch (IOException e) {
break;
}
}
// Boot ID
bootID = random.nextLong();
// Fixed length file containing boot ID. Accessed with random access file. So hopefully it will always be
// written. Note that we set lastBootID to -1 if we can't _write_ our ID as well as if we can't read it,
// because if we can't write it then we probably couldn't write it on the last bootup either.
File bootIDFile = runDir.file("bootID");
int BOOT_FILE_LENGTH = 64 / 4; // A long in padded hex bytes
long oldBootID = -1;
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(bootIDFile, "rw");
if(raf.length() < BOOT_FILE_LENGTH) {
oldBootID = -1;
} else {
byte[] buf = new byte[BOOT_FILE_LENGTH];
raf.readFully(buf);
String s = new String(buf, "ISO-8859-1");
try {
oldBootID = Fields.bytesToLong(HexUtil.hexToBytes(s));
} catch (NumberFormatException e) {
oldBootID = -1;
}
raf.seek(0);
}
String s = HexUtil.bytesToHex(Fields.longToBytes(bootID));
byte[] buf = s.getBytes("ISO-8859-1");
if(buf.length != BOOT_FILE_LENGTH)
System.err.println("Not 16 bytes for boot ID "+bootID+" - WTF??");
raf.write(buf);
} catch (IOException e) {
oldBootID = -1;
// If we have an error in reading, *or in writing*, we don't reliably know the last boot ID.
} finally {
Closer.close(raf);
}
lastBootID = oldBootID;
nodeConfig.register("disableProbabilisticHTLs", false, sortOrder++, true, false, "Node.disablePHTLS", "Node.disablePHTLSLong",
new BooleanCallback() {
@Override
public Boolean get() {
return disableProbabilisticHTLs;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
disableProbabilisticHTLs = val;
}
});
disableProbabilisticHTLs = nodeConfig.getBoolean("disableProbabilisticHTLs");
nodeConfig.register("maxHTL", DEFAULT_MAX_HTL, sortOrder++, true, false, "Node.maxHTL", "Node.maxHTLLong", new ShortCallback() {
@Override
public Short get() {
return maxHTL;
}
@Override
public void set(Short val) throws InvalidConfigValueException {
if(val < 0) throw new InvalidConfigValueException("Impossible max HTL");
maxHTL = val;
}
}, false);
maxHTL = nodeConfig.getShort("maxHTL");
class TrafficClassCallback extends StringCallback implements EnumerableOptionCallback {
@Override
public String get() {
return trafficClass.name();
}
@Override
public void set(String tcName) throws InvalidConfigValueException, NodeNeedRestartException {
try {
trafficClass = TrafficClass.fromNameOrValue(tcName);
} catch (IllegalArgumentException e) {
throw new InvalidConfigValueException(e);
}
throw new NodeNeedRestartException("TrafficClass cannot change on the fly");
}
@Override
public String[] getPossibleValues() {
ArrayList<String> array = new ArrayList<String>();
for (TrafficClass tc : TrafficClass.values())
array.add(tc.name());
return array.toArray(new String[0]);
}
}
nodeConfig.register("trafficClass", TrafficClass.getDefault().name(), sortOrder++, true, false,
"Node.trafficClass", "Node.trafficClassLong",
new TrafficClassCallback());
String trafficClassValue = nodeConfig.getString("trafficClass");
try {
trafficClass = TrafficClass.fromNameOrValue(trafficClassValue);
} catch (IllegalArgumentException e) {
Logger.error(this, "Invalid trafficClass:"+trafficClassValue+" resetting the value to default.", e);
trafficClass = TrafficClass.getDefault();
}
// FIXME maybe these should persist? They need to be private.
decrementAtMax = random.nextDouble() <= DECREMENT_AT_MAX_PROB;
decrementAtMin = random.nextDouble() <= DECREMENT_AT_MIN_PROB;
// Determine where to bind to
usm = new MessageCore(executor);
// FIXME maybe these configs should actually be under a node.ip subconfig?
ipDetector = new NodeIPDetector(this);
sortOrder = ipDetector.registerConfigs(nodeConfig, sortOrder);
// ARKs enabled?
nodeConfig.register("enableARKs", true, sortOrder++, true, false, "Node.enableARKs", "Node.enableARKsLong", new BooleanCallback() {
@Override
public Boolean get() {
return enableARKs;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
throw new InvalidConfigValueException("Cannot change on the fly");
}
@Override
public boolean isReadOnly() {
return true;
}
});
enableARKs = nodeConfig.getBoolean("enableARKs");
nodeConfig.register("enablePerNodeFailureTables", true, sortOrder++, true, false, "Node.enablePerNodeFailureTables", "Node.enablePerNodeFailureTablesLong", new BooleanCallback() {
@Override
public Boolean get() {
return enablePerNodeFailureTables;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
throw new InvalidConfigValueException("Cannot change on the fly");
}
@Override
public boolean isReadOnly() {
return true;
}
});
enablePerNodeFailureTables = nodeConfig.getBoolean("enablePerNodeFailureTables");
nodeConfig.register("enableULPRDataPropagation", true, sortOrder++, true, false, "Node.enableULPRDataPropagation", "Node.enableULPRDataPropagationLong", new BooleanCallback() {
@Override
public Boolean get() {
return enableULPRDataPropagation;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
throw new InvalidConfigValueException("Cannot change on the fly");
}
@Override
public boolean isReadOnly() {
return true;
}
});
enableULPRDataPropagation = nodeConfig.getBoolean("enableULPRDataPropagation");
nodeConfig.register("enableSwapping", true, sortOrder++, true, false, "Node.enableSwapping", "Node.enableSwappingLong", new BooleanCallback() {
@Override
public Boolean get() {
return enableSwapping;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
throw new InvalidConfigValueException("Cannot change on the fly");
}
@Override
public boolean isReadOnly() {
return true;
}
});
enableSwapping = nodeConfig.getBoolean("enableSwapping");
/*
* Publish our peers' locations is enabled, even in MAXIMUM network security and/or HIGH friends security,
* because a node which doesn't publish its peers' locations will get dramatically less traffic.
*
* Publishing our peers' locations does make us slightly more vulnerable to some attacks, but I don't think
* it's a big difference: swapping reveals the same information, it just doesn't update as quickly. This
* may help slightly, but probably not dramatically against a clever attacker.
*
* FIXME review this decision.
*/
nodeConfig.register("publishOurPeersLocation", true, sortOrder++, true, false, "Node.publishOurPeersLocation", "Node.publishOurPeersLocationLong", new BooleanCallback() {
@Override
public Boolean get() {
return publishOurPeersLocation;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
publishOurPeersLocation = val;
}
});
publishOurPeersLocation = nodeConfig.getBoolean("publishOurPeersLocation");
nodeConfig.register("routeAccordingToOurPeersLocation", true, sortOrder++, true, false, "Node.routeAccordingToOurPeersLocation", "Node.routeAccordingToOurPeersLocation", new BooleanCallback() {
@Override
public Boolean get() {
return routeAccordingToOurPeersLocation;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
routeAccordingToOurPeersLocation = val;
}
});
routeAccordingToOurPeersLocation = nodeConfig.getBoolean("routeAccordingToOurPeersLocation");
nodeConfig.register("enableSwapQueueing", true, sortOrder++, true, false, "Node.enableSwapQueueing", "Node.enableSwapQueueingLong", new BooleanCallback() {
@Override
public Boolean get() {
return enableSwapQueueing;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
enableSwapQueueing = val;
}
});
enableSwapQueueing = nodeConfig.getBoolean("enableSwapQueueing");
nodeConfig.register("enablePacketCoalescing", true, sortOrder++, true, false, "Node.enablePacketCoalescing", "Node.enablePacketCoalescingLong", new BooleanCallback() {
@Override
public Boolean get() {
return enablePacketCoalescing;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
enablePacketCoalescing = val;
}
});
enablePacketCoalescing = nodeConfig.getBoolean("enablePacketCoalescing");
// Determine the port number
// @see #191
if(oldConfig != null && "-1".equals(oldConfig.get("node.listenPort")))
throw new NodeInitException(NodeInitException.EXIT_COULD_NOT_BIND_USM, "Your freenet.ini file is corrupted! 'listenPort=-1'");
NodeCryptoConfig darknetConfig = new NodeCryptoConfig(nodeConfig, sortOrder++, false, securityLevels);
sortOrder += NodeCryptoConfig.OPTION_COUNT;
darknetCrypto = new NodeCrypto(this, false, darknetConfig, startupTime, enableARKs);
// Must be created after darknetCrypto
dnsr = new DNSRequester(this);
ps = new PacketSender(this);
ticker = new PrioritizedTicker(executor, getDarknetPortNumber());
if(executor instanceof PooledExecutor)
((PooledExecutor)executor).setTicker(ticker);
Logger.normal(Node.class, "Creating node...");
shutdownHook.addEarlyJob(new Thread() {
@Override
public void run() {
if (opennet != null)
opennet.stop(false);
}
});
shutdownHook.addEarlyJob(new Thread() {
@Override
public void run() {
darknetCrypto.stop();
}
});
// Bandwidth limit
nodeConfig.register("outputBandwidthLimit", "15K", sortOrder++, false, true, "Node.outBWLimit", "Node.outBWLimitLong", new IntCallback() {
@Override
public Integer get() {
//return BlockTransmitter.getHardBandwidthLimit();
return outputBandwidthLimit;
}
@Override
public void set(Integer obwLimit) throws InvalidConfigValueException {
BandwidthManager.checkOutputBandwidthLimit(obwLimit);
try {
outputThrottle.changeNanosAndBucketSize(SECONDS.toNanos(1) / obwLimit, obwLimit/2);
} catch (IllegalArgumentException e) {
throw new InvalidConfigValueException(e);
}
synchronized(Node.this) {
outputBandwidthLimit = obwLimit;
}
}
});
int obwLimit = nodeConfig.getInt("outputBandwidthLimit");
if (obwLimit < minimumBandwidth) {
obwLimit = minimumBandwidth; // upgrade slow nodes automatically
Logger.normal(Node.class, "Output bandwidth was lower than minimum bandwidth. Increased to minimum bandwidth.");
}
outputBandwidthLimit = obwLimit;
try {
BandwidthManager.checkOutputBandwidthLimit(outputBandwidthLimit);
} catch (InvalidConfigValueException e) {
throw new NodeInitException(NodeInitException.EXIT_BAD_BWLIMIT, e.getMessage());
}
// Bucket size of 0.5 seconds' worth of bytes.
// Add them at a rate determined by the obwLimit.
// Maximum forced bytes 80%, in other words, 20% of the bandwidth is reserved for
// block transfers, so we will use that 20% for block transfers even if more than 80% of the limit is used for non-limited data (resends etc).
int bucketSize = obwLimit/2;
// Must have at least space for ONE PACKET.
// FIXME: make compatible with alternate transports.
bucketSize = Math.max(bucketSize, 2048);
try {
outputThrottle = new TokenBucket(bucketSize, SECONDS.toNanos(1) / obwLimit, obwLimit/2);
} catch (IllegalArgumentException e) {
throw new NodeInitException(NodeInitException.EXIT_BAD_BWLIMIT, e.getMessage());
}
nodeConfig.register("inputBandwidthLimit", "-1", sortOrder++, false, true, "Node.inBWLimit", "Node.inBWLimitLong", new IntCallback() {
@Override
public Integer get() {
if(inputLimitDefault) return -1;
return inputBandwidthLimit;
}
@Override
public void set(Integer ibwLimit) throws InvalidConfigValueException {
synchronized(Node.this) {
BandwidthManager.checkInputBandwidthLimit(ibwLimit);
if(ibwLimit == -1) {
inputLimitDefault = true;
ibwLimit = outputBandwidthLimit * 4;
} else {
inputLimitDefault = false;
}
inputBandwidthLimit = ibwLimit;
}
}
});
int ibwLimit = nodeConfig.getInt("inputBandwidthLimit");
if(ibwLimit == -1) {
inputLimitDefault = true;
ibwLimit = obwLimit * 4;
}
else if (ibwLimit < minimumBandwidth) {
ibwLimit = minimumBandwidth; // upgrade slow nodes automatically
Logger.normal(Node.class, "Input bandwidth was lower than minimum bandwidth. Increased to minimum bandwidth.");
}
inputBandwidthLimit = ibwLimit;
try {
BandwidthManager.checkInputBandwidthLimit(inputBandwidthLimit);
} catch (InvalidConfigValueException e) {
throw new NodeInitException(NodeInitException.EXIT_BAD_BWLIMIT, e.getMessage());
}
nodeConfig.register("amountOfDataToCheckCompressionRatio", "8MiB", sortOrder++,
true, true, "Node.amountOfDataToCheckCompressionRatio",
"Node.amountOfDataToCheckCompressionRatioLong", new LongCallback() {
@Override
public Long get() {
return amountOfDataToCheckCompressionRatio;
}
@Override
public void set(Long amountOfDataToCheckCompressionRatio) {
synchronized(Node.this) {
Node.this.amountOfDataToCheckCompressionRatio = amountOfDataToCheckCompressionRatio;
}
}
}, true);
amountOfDataToCheckCompressionRatio = nodeConfig.getLong("amountOfDataToCheckCompressionRatio");
nodeConfig.register("minimumCompressionPercentage", "10", sortOrder++,
true, true, "Node.minimumCompressionPercentage",
"Node.minimumCompressionPercentageLong", new IntCallback() {
@Override
public Integer get() {
return minimumCompressionPercentage;
}
@Override
public void set(Integer minimumCompressionPercentage) {
synchronized(Node.this) {
if (minimumCompressionPercentage < 0 || minimumCompressionPercentage > 100) {
Logger.normal(Node.class, "Wrong minimum compression percentage" + minimumCompressionPercentage);
return;
}
Node.this.minimumCompressionPercentage = minimumCompressionPercentage;
}
}
}, Dimension.NOT);
minimumCompressionPercentage = nodeConfig.getInt("minimumCompressionPercentage");
nodeConfig.register("maxTimeForSingleCompressor", "20m", sortOrder++,
true, true, "Node.maxTimeForSingleCompressor",
"Node.maxTimeForSingleCompressorLong", new IntCallback() {
@Override
public Integer get() {
return maxTimeForSingleCompressor;
}
@Override
public void set(Integer maxTimeForSingleCompressor) {
synchronized(Node.this) {
Node.this.maxTimeForSingleCompressor = maxTimeForSingleCompressor;
}
}
}, Dimension.DURATION);
maxTimeForSingleCompressor = nodeConfig.getInt("maxTimeForSingleCompressor");
nodeConfig.register("connectionSpeedDetection", true, sortOrder++,
true, true, "Node.connectionSpeedDetection",
"Node.connectionSpeedDetectionLong", new BooleanCallback() {
@Override
public Boolean get() {
return connectionSpeedDetection;
}
@Override
public void set(Boolean connectionSpeedDetection) {
synchronized(Node.this) {
Node.this.connectionSpeedDetection = connectionSpeedDetection;
}
}
});
connectionSpeedDetection = nodeConfig.getBoolean("connectionSpeedDetection");
nodeConfig.register("throttleLocalTraffic", false, sortOrder++, true, false, "Node.throttleLocalTraffic", "Node.throttleLocalTrafficLong", new BooleanCallback() {
@Override
public Boolean get() {
return throttleLocalData;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
throttleLocalData = val;
}
});
throttleLocalData = nodeConfig.getBoolean("throttleLocalTraffic");
String s = "Testnet mode DISABLED. You may have some level of anonymity. :)\n"+
"Note that this version of Freenet is still a very early alpha, and may well have numerous bugs and design flaws.\n"+
"In particular: YOU ARE WIDE OPEN TO YOUR IMMEDIATE PEERS! They can eavesdrop on your requests with relatively little difficulty at present (correlation attacks etc).";
Logger.normal(this, s);
System.err.println(s);
File nodeFile = nodeDir.file("node-"+getDarknetPortNumber());
File nodeFileBackup = nodeDir.file("node-"+getDarknetPortNumber()+".bak");
// After we have set up testnet and IP address, load the node file
try {
// FIXME should take file directly?
readNodeFile(nodeFile.getPath());
} catch (IOException e) {
try {
System.err.println("Trying to read node file backup ...");
readNodeFile(nodeFileBackup.getPath());
} catch (IOException e1) {
if(nodeFile.exists() || nodeFileBackup.exists()) {
System.err.println("No node file or cannot read, (re)initialising crypto etc");
System.err.println(e1.toString());
e1.printStackTrace();
System.err.println("After:");
System.err.println(e.toString());
e.printStackTrace();
} else {
System.err.println("Creating new cryptographic keys...");
}
initNodeFileSettings();
}
}
// Then read the peers
peers = new PeerManager(this, shutdownHook);
tracker = new RequestTracker(peers, ticker);
usm.setDispatcher(dispatcher=new NodeDispatcher(this));
uptime = new UptimeEstimator(runDir, ticker, darknetCrypto.identityHash);
// ULPRs
failureTable = new FailureTable(this);
nodeStats = new NodeStats(this, sortOrder, config.createSubConfig("node.load"), obwLimit, ibwLimit, lastVersion);
// clientCore needs new load management and other settings from stats.
clientCore = new NodeClientCore(this, config, nodeConfig, installConfig, getDarknetPortNumber(), sortOrder, oldConfig, fproxyConfig, toadlets, databaseKey, persistentSecret);
toadlets.setCore(clientCore);
if (JVMVersion.isEOL()) {
clientCore.alerts.register(new JVMVersionAlert());
}
if(showFriendsVisibilityAlert)
registerFriendsVisibilityAlert();
// Node updater support
System.out.println("Initializing Node Updater");
try {
nodeUpdater = NodeUpdateManager.maybeCreate(this, config);
} catch (InvalidConfigValueException e) {
e.printStackTrace();
throw new NodeInitException(NodeInitException.EXIT_COULD_NOT_START_UPDATER, "Could not create Updater: "+e);
}
// Opennet
final SubConfig opennetConfig = config.createSubConfig("node.opennet");
opennetConfig.register("connectToSeednodes", true, 0, true, false, "Node.withAnnouncement", "Node.withAnnouncementLong", new BooleanCallback() {
@Override
public Boolean get() {
return isAllowedToConnectToSeednodes;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException {
if (get().equals(val))
return;
synchronized(Node.this) {
isAllowedToConnectToSeednodes = val;
if(opennet != null)
throw new NodeNeedRestartException(l10n("connectToSeednodesCannotBeChangedMustDisableOpennetOrReboot"));
}
}
});
isAllowedToConnectToSeednodes = opennetConfig.getBoolean("connectToSeednodes");
// Can be enabled on the fly
opennetConfig.register("enabled", false, 0, true, true, "Node.opennetEnabled", "Node.opennetEnabledLong", new BooleanCallback() {
@Override
public Boolean get() {
synchronized(Node.this) {
return opennet != null;
}
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
OpennetManager o;
synchronized(Node.this) {
if(val == (opennet != null)) return;
if(val) {
try {
o = opennet = new OpennetManager(Node.this, opennetCryptoConfig, System.currentTimeMillis(), isAllowedToConnectToSeednodes);
} catch (NodeInitException e) {
opennet = null;
throw new InvalidConfigValueException(e.getMessage());
}
} else {
o = opennet;
opennet = null;
}
}
if(val) o.start();
else o.stop(true);
ipDetector.ipDetectorManager.notifyPortChange(getPublicInterfacePorts());
}
});
boolean opennetEnabled = opennetConfig.getBoolean("enabled");
opennetConfig.register("maxOpennetPeers", OpennetManager.MAX_PEERS_FOR_SCALING, 1, true, false, "Node.maxOpennetPeers",
"Node.maxOpennetPeersLong", new IntCallback() {
@Override
public Integer get() {
return maxOpennetPeers;
}
@Override
public void set(Integer inputMaxOpennetPeers) throws InvalidConfigValueException {
if(inputMaxOpennetPeers < 0) throw new InvalidConfigValueException(l10n("mustBePositive"));
if(inputMaxOpennetPeers > OpennetManager.MAX_PEERS_FOR_SCALING) throw new InvalidConfigValueException(l10n("maxOpennetPeersMustBeTwentyOrLess", "maxpeers", Integer.toString(OpennetManager.MAX_PEERS_FOR_SCALING)));
maxOpennetPeers = inputMaxOpennetPeers;
}
}
, false);
maxOpennetPeers = opennetConfig.getInt("maxOpennetPeers");
if(maxOpennetPeers > OpennetManager.MAX_PEERS_FOR_SCALING) {
Logger.error(this, "maxOpennetPeers may not be over "+OpennetManager.MAX_PEERS_FOR_SCALING);
maxOpennetPeers = OpennetManager.MAX_PEERS_FOR_SCALING;
}
opennetCryptoConfig = new NodeCryptoConfig(opennetConfig, 2 /* 0 = enabled */, true, securityLevels);
if(opennetEnabled) {
opennet = new OpennetManager(this, opennetCryptoConfig, System.currentTimeMillis(), isAllowedToConnectToSeednodes);
// Will be started later
} else {
opennet = null;
}
securityLevels.addNetworkThreatLevelListener(new SecurityLevelListener<NETWORK_THREAT_LEVEL>() {
@Override
public void onChange(NETWORK_THREAT_LEVEL oldLevel, NETWORK_THREAT_LEVEL newLevel) {
if(newLevel == NETWORK_THREAT_LEVEL.HIGH
|| newLevel == NETWORK_THREAT_LEVEL.MAXIMUM) {
OpennetManager om;
synchronized(Node.this) {
om = opennet;
if(om != null)
opennet = null;
}
if(om != null) {
om.stop(true);
ipDetector.ipDetectorManager.notifyPortChange(getPublicInterfacePorts());
}
} else if(newLevel == NETWORK_THREAT_LEVEL.NORMAL
|| newLevel == NETWORK_THREAT_LEVEL.LOW) {
OpennetManager o = null;
synchronized(Node.this) {
if(opennet == null) {
try {
o = opennet = new OpennetManager(Node.this, opennetCryptoConfig, System.currentTimeMillis(), isAllowedToConnectToSeednodes);
} catch (NodeInitException e) {
opennet = null;
Logger.error(this, "UNABLE TO ENABLE OPENNET: "+e, e);
clientCore.alerts.register(new SimpleUserAlert(false, l10n("enableOpennetFailedTitle"), l10n("enableOpennetFailed", "message", e.getLocalizedMessage()), l10n("enableOpennetFailed", "message", e.getLocalizedMessage()), UserAlert.ERROR));
}
}
}
if(o != null) {
o.start();
ipDetector.ipDetectorManager.notifyPortChange(getPublicInterfacePorts());
}
}
Node.this.config.store();
}
});
opennetConfig.register("acceptSeedConnections", false, 2, true, true, "Node.acceptSeedConnectionsShort", "Node.acceptSeedConnections", new BooleanCallback() {
@Override
public Boolean get() {
return acceptSeedConnections;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
acceptSeedConnections = val;
}
});
acceptSeedConnections = opennetConfig.getBoolean("acceptSeedConnections");
if(acceptSeedConnections && opennet != null)
opennet.crypto.socket.getAddressTracker().setHugeTracker();
opennetConfig.finishedInitialization();
nodeConfig.register("passOpennetPeersThroughDarknet", true, sortOrder++, true, false, "Node.passOpennetPeersThroughDarknet", "Node.passOpennetPeersThroughDarknetLong",
new BooleanCallback() {
@Override
public Boolean get() {
synchronized(Node.this) {
return passOpennetRefsThroughDarknet;
}
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
synchronized(Node.this) {
passOpennetRefsThroughDarknet = val;
}
}
});
passOpennetRefsThroughDarknet = nodeConfig.getBoolean("passOpennetPeersThroughDarknet");
this.extraPeerDataDir = userDir.file("extra-peer-data-"+getDarknetPortNumber());
if (!((extraPeerDataDir.exists() && extraPeerDataDir.isDirectory()) || (extraPeerDataDir.mkdir()))) {
String msg = "Could not find or create extra peer data directory";
throw new NodeInitException(NodeInitException.EXIT_BAD_DIR, msg);
}
// Name
nodeConfig.register("name", myName, sortOrder++, false, true, "Node.nodeName", "Node.nodeNameLong",
new NodeNameCallback());
myName = nodeConfig.getString("name");
// Datastore
nodeConfig.register("storeForceBigShrinks", false, sortOrder++, true, false, "Node.forceBigShrink", "Node.forceBigShrinkLong",
new BooleanCallback() {
@Override
public Boolean get() {
synchronized(Node.this) {
return storeForceBigShrinks;
}
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
synchronized(Node.this) {
storeForceBigShrinks = val;
}
}
});
// Datastore
nodeConfig.register("storeType", "ram", sortOrder++, true, true, "Node.storeType", "Node.storeTypeLong", new StoreTypeCallback());
storeType = nodeConfig.getString("storeType");
/*
* Very small initial store size, since the node will preallocate it when starting up for the first time,
* BLOCKING STARTUP, and since everyone goes through the wizard anyway...
*/
nodeConfig.register("storeSize", DEFAULT_STORE_SIZE, sortOrder++, false, true, "Node.storeSize", "Node.storeSizeLong",
new LongCallback() {
@Override
public Long get() {
return maxTotalDatastoreSize;
}
@Override
public void set(Long storeSize) throws InvalidConfigValueException {
if(storeSize < MIN_STORE_SIZE)
throw new InvalidConfigValueException(l10n("invalidStoreSize"));
long newMaxStoreKeys = storeSize / sizePerKey;
if(newMaxStoreKeys == maxTotalKeys) return;
// Update each datastore
synchronized(Node.this) {
maxTotalDatastoreSize = storeSize;
maxTotalKeys = newMaxStoreKeys;
maxStoreKeys = maxTotalKeys / 2;
maxCacheKeys = maxTotalKeys - maxStoreKeys;
}
try {
chkDatastore.setMaxKeys(maxStoreKeys, storeForceBigShrinks);
chkDatacache.setMaxKeys(maxCacheKeys, storeForceBigShrinks);
pubKeyDatastore.setMaxKeys(maxStoreKeys, storeForceBigShrinks);
pubKeyDatacache.setMaxKeys(maxCacheKeys, storeForceBigShrinks);
sskDatastore.setMaxKeys(maxStoreKeys, storeForceBigShrinks);
sskDatacache.setMaxKeys(maxCacheKeys, storeForceBigShrinks);
} catch (IOException e) {
// FIXME we need to be able to tell the user.
Logger.error(this, "Caught "+e+" resizing the datastore", e);
System.err.println("Caught "+e+" resizing the datastore");
e.printStackTrace();
}
//Perhaps a bit hackish...? Seems like this should be near it's definition in NodeStats.
nodeStats.avgStoreCHKLocation.changeMaxReports((int)maxStoreKeys);
nodeStats.avgCacheCHKLocation.changeMaxReports((int)maxCacheKeys);
nodeStats.avgSlashdotCacheCHKLocation.changeMaxReports((int)maxCacheKeys);
nodeStats.avgClientCacheCHKLocation.changeMaxReports((int)maxCacheKeys);
nodeStats.avgStoreSSKLocation.changeMaxReports((int)maxStoreKeys);
nodeStats.avgCacheSSKLocation.changeMaxReports((int)maxCacheKeys);
nodeStats.avgSlashdotCacheSSKLocation.changeMaxReports((int)maxCacheKeys);
nodeStats.avgClientCacheSSKLocation.changeMaxReports((int)maxCacheKeys);
}
}, true);
maxTotalDatastoreSize = nodeConfig.getLong("storeSize");
if(maxTotalDatastoreSize < MIN_STORE_SIZE && !storeType.equals("ram")) { // totally arbitrary minimum!
throw new NodeInitException(NodeInitException.EXIT_INVALID_STORE_SIZE, "Store size too small");
}
maxTotalKeys = maxTotalDatastoreSize / sizePerKey;
nodeConfig.register("storeUseSlotFilters", true, sortOrder++, true, false, "Node.storeUseSlotFilters", "Node.storeUseSlotFiltersLong", new BooleanCallback() {
public Boolean get() {
synchronized(Node.this) {
return storeUseSlotFilters;
}
}
public void set(Boolean val) throws InvalidConfigValueException,
NodeNeedRestartException {
synchronized(Node.this) {
storeUseSlotFilters = val;
}
// FIXME l10n
throw new NodeNeedRestartException("Need to restart to change storeUseSlotFilters");
}
});
storeUseSlotFilters = nodeConfig.getBoolean("storeUseSlotFilters");
nodeConfig.register("storeSaltHashSlotFilterPersistenceTime", ResizablePersistentIntBuffer.DEFAULT_PERSISTENCE_TIME, sortOrder++, true, false,
"Node.storeSaltHashSlotFilterPersistenceTime", "Node.storeSaltHashSlotFilterPersistenceTimeLong", new IntCallback() {
@Override
public Integer get() {
return ResizablePersistentIntBuffer.getPersistenceTime();
}
@Override
public void set(Integer val)
throws InvalidConfigValueException,
NodeNeedRestartException {
if(val >= -1)
ResizablePersistentIntBuffer.setPersistenceTime(val);
else
throw new InvalidConfigValueException(l10n("slotFilterPersistenceTimeError"));
}
}, false);
nodeConfig.register("storeSaltHashResizeOnStart", false, sortOrder++, true, false,<|fim▁hole|> @Override
public Boolean get() {
return storeSaltHashResizeOnStart;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException {
storeSaltHashResizeOnStart = val;
}
});
storeSaltHashResizeOnStart = nodeConfig.getBoolean("storeSaltHashResizeOnStart");
this.storeDir = setupProgramDir(installConfig, "storeDir", userDir().file("datastore").getPath(), "Node.storeDirectory", "Node.storeDirectoryLong", nodeConfig);
installConfig.finishedInitialization();
final String suffix = getStoreSuffix();
maxStoreKeys = maxTotalKeys / 2;
maxCacheKeys = maxTotalKeys - maxStoreKeys;
/*
* On Windows, setting the file length normally involves writing lots of zeros.
* So it's an uninterruptible system call that takes a loooong time. On OS/X,
* presumably the same is true. If the RNG is fast enough, this means that
* setting the length and writing random data take exactly the same amount
* of time. On most versions of Unix, holes can be created. However on all
* systems, predictable disk usage is a good thing. So lets turn it on by
* default for now, on all systems. The datastore can be read but mostly not
* written while the random data is being written.
*/
nodeConfig.register("storePreallocate", true, sortOrder++, true, true, "Node.storePreallocate", "Node.storePreallocateLong",
new BooleanCallback() {
@Override
public Boolean get() {
return storePreallocate;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException {
storePreallocate = val;
if (storeType.equals("salt-hash")) {
setPreallocate(chkDatastore, val);
setPreallocate(chkDatacache, val);
setPreallocate(pubKeyDatastore, val);
setPreallocate(pubKeyDatacache, val);
setPreallocate(sskDatastore, val);
setPreallocate(sskDatacache, val);
}
}
private void setPreallocate(StoreCallback<?> datastore,
boolean val) {
// Avoid race conditions by checking first.
FreenetStore<?> store = datastore.getStore();
if(store instanceof SaltedHashFreenetStore)
((SaltedHashFreenetStore<?>)store).setPreallocate(val);
}}
);
storePreallocate = nodeConfig.getBoolean("storePreallocate");
if(File.separatorChar == '/' && System.getProperty("os.name").toLowerCase().indexOf("mac os") < 0) {
securityLevels.addPhysicalThreatLevelListener(new SecurityLevelListener<SecurityLevels.PHYSICAL_THREAT_LEVEL>() {
@Override
public void onChange(PHYSICAL_THREAT_LEVEL oldLevel, PHYSICAL_THREAT_LEVEL newLevel) {
try {
if(newLevel == PHYSICAL_THREAT_LEVEL.LOW)
nodeConfig.set("storePreallocate", false);
else
nodeConfig.set("storePreallocate", true);
} catch (NodeNeedRestartException e) {
// Ignore
} catch (InvalidConfigValueException e) {
// Ignore
}
}
});
}
securityLevels.addPhysicalThreatLevelListener(new SecurityLevelListener<SecurityLevels.PHYSICAL_THREAT_LEVEL>() {
@Override
public void onChange(PHYSICAL_THREAT_LEVEL oldLevel, PHYSICAL_THREAT_LEVEL newLevel) {
if(newLevel == PHYSICAL_THREAT_LEVEL.MAXIMUM) {
synchronized(this) {
clientCacheAwaitingPassword = false;
databaseAwaitingPassword = false;
}
try {
killMasterKeysFile();
clientCore.clientLayerPersister.disableWrite();
clientCore.clientLayerPersister.waitForNotWriting();
clientCore.clientLayerPersister.deleteAllFiles();
} catch (IOException e) {
masterKeysFile.delete();
Logger.error(this, "Unable to securely delete "+masterKeysFile);
System.err.println(NodeL10n.getBase().getString("SecurityLevels.cantDeletePasswordFile", "filename", masterKeysFile.getAbsolutePath()));
clientCore.alerts.register(new SimpleUserAlert(true, NodeL10n.getBase().getString("SecurityLevels.cantDeletePasswordFileTitle"), NodeL10n.getBase().getString("SecurityLevels.cantDeletePasswordFile"), NodeL10n.getBase().getString("SecurityLevels.cantDeletePasswordFileTitle"), UserAlert.CRITICAL_ERROR));
}
}
if(oldLevel == PHYSICAL_THREAT_LEVEL.MAXIMUM && newLevel != PHYSICAL_THREAT_LEVEL.HIGH) {
// Not passworded.
// Create the master.keys.
// Keys must exist.
try {
MasterKeys keys;
synchronized(this) {
keys = Node.this.keys;
}
keys.changePassword(masterKeysFile, "", secureRandom);
} catch (IOException e) {
Logger.error(this, "Unable to create encryption keys file: "+masterKeysFile+" : "+e, e);
System.err.println("Unable to create encryption keys file: "+masterKeysFile+" : "+e);
e.printStackTrace();
}
}
}
});
if(securityLevels.physicalThreatLevel == PHYSICAL_THREAT_LEVEL.MAXIMUM) {
try {
killMasterKeysFile();
} catch (IOException e) {
String msg = "Unable to securely delete old master.keys file when switching to MAXIMUM seclevel!!";
System.err.println(msg);
throw new NodeInitException(NodeInitException.EXIT_CANT_WRITE_MASTER_KEYS, msg);
}
}
long defaultCacheSize;
long memoryLimit = NodeStarter.getMemoryLimitBytes();
// This is tricky because systems with low memory probably also have slow disks, but using
// up too much memory can be catastrophic...
// Total alchemy, FIXME!
if(memoryLimit == Long.MAX_VALUE || memoryLimit < 0)
defaultCacheSize = 1024*1024;
else if(memoryLimit <= 128*1024*1024)
defaultCacheSize = 0; // Turn off completely for very small memory.
else {
// 9 stores, total should be 5% of memory, up to maximum of 1MB per store at 308MB+
defaultCacheSize = Math.min(1024*1024, (memoryLimit - 128*1024*1024) / (20*9));
}
nodeConfig.register("cachingFreenetStoreMaxSize", defaultCacheSize, sortOrder++, true, false, "Node.cachingFreenetStoreMaxSize", "Node.cachingFreenetStoreMaxSizeLong",
new LongCallback() {
@Override
public Long get() {
synchronized(Node.this) {
return cachingFreenetStoreMaxSize;
}
}
@Override
public void set(Long val) throws InvalidConfigValueException, NodeNeedRestartException {
if(val < 0) throw new InvalidConfigValueException(l10n("invalidMemoryCacheSize"));
// Any positive value is legal. In particular, e.g. 1200 bytes would cause us to cache SSKs but not CHKs.
synchronized(Node.this) {
cachingFreenetStoreMaxSize = val;
}
throw new NodeNeedRestartException("Caching Maximum Size cannot be changed on the fly");
}
}, true);
cachingFreenetStoreMaxSize = nodeConfig.getLong("cachingFreenetStoreMaxSize");
if(cachingFreenetStoreMaxSize < 0)
throw new NodeInitException(NodeInitException.EXIT_BAD_CONFIG, l10n("invalidMemoryCacheSize"));
nodeConfig.register("cachingFreenetStorePeriod", "300k", sortOrder++, true, false, "Node.cachingFreenetStorePeriod", "Node.cachingFreenetStorePeriod",
new LongCallback() {
@Override
public Long get() {
synchronized(Node.this) {
return cachingFreenetStorePeriod;
}
}
@Override
public void set(Long val) throws InvalidConfigValueException, NodeNeedRestartException {
synchronized(Node.this) {
cachingFreenetStorePeriod = val;
}
throw new NodeNeedRestartException("Caching Period cannot be changed on the fly");
}
}, true);
cachingFreenetStorePeriod = nodeConfig.getLong("cachingFreenetStorePeriod");
if(cachingFreenetStoreMaxSize > 0 && cachingFreenetStorePeriod > 0) {
cachingFreenetStoreTracker = new CachingFreenetStoreTracker(cachingFreenetStoreMaxSize, cachingFreenetStorePeriod, ticker);
}
boolean shouldWriteConfig = false;
if(storeType.equals("bdb-index")) {
System.err.println("Old format Berkeley DB datastore detected.");
System.err.println("This datastore format is no longer supported.");
System.err.println("The old datastore will be securely deleted.");
storeType = "salt-hash";
shouldWriteConfig = true;
deleteOldBDBIndexStoreFiles();
}
if (storeType.equals("salt-hash")) {
initRAMFS();
initSaltHashFS(suffix, false, null);
} else {
initRAMFS();
}
if(databaseAwaitingPassword) createPasswordUserAlert();
// Client cache
// Default is 10MB, in memory only. The wizard will change this.
nodeConfig.register("clientCacheType", "ram", sortOrder++, true, true, "Node.clientCacheType", "Node.clientCacheTypeLong", new ClientCacheTypeCallback());
clientCacheType = nodeConfig.getString("clientCacheType");
nodeConfig.register("clientCacheSize", DEFAULT_CLIENT_CACHE_SIZE, sortOrder++, false, true, "Node.clientCacheSize", "Node.clientCacheSizeLong",
new LongCallback() {
@Override
public Long get() {
return maxTotalClientCacheSize;
}
@Override
public void set(Long storeSize) throws InvalidConfigValueException {
if(storeSize < MIN_CLIENT_CACHE_SIZE)
throw new InvalidConfigValueException(l10n("invalidStoreSize"));
long newMaxStoreKeys = storeSize / sizePerKey;
if(newMaxStoreKeys == maxClientCacheKeys) return;
// Update each datastore
synchronized(Node.this) {
maxTotalClientCacheSize = storeSize;
maxClientCacheKeys = newMaxStoreKeys;
}
try {
chkClientcache.setMaxKeys(maxClientCacheKeys, storeForceBigShrinks);
pubKeyClientcache.setMaxKeys(maxClientCacheKeys, storeForceBigShrinks);
sskClientcache.setMaxKeys(maxClientCacheKeys, storeForceBigShrinks);
} catch (IOException e) {
// FIXME we need to be able to tell the user.
Logger.error(this, "Caught "+e+" resizing the clientcache", e);
System.err.println("Caught "+e+" resizing the clientcache");
e.printStackTrace();
}
}
}, true);
maxTotalClientCacheSize = nodeConfig.getLong("clientCacheSize");
if(maxTotalClientCacheSize < MIN_CLIENT_CACHE_SIZE) {
throw new NodeInitException(NodeInitException.EXIT_INVALID_STORE_SIZE, "Client cache size too small");
}
maxClientCacheKeys = maxTotalClientCacheSize / sizePerKey;
boolean startedClientCache = false;
if (clientCacheType.equals("salt-hash")) {
if(clientCacheKey == null) {
System.err.println("Cannot open client-cache, it is passworded");
setClientCacheAwaitingPassword();
} else {
initSaltHashClientCacheFS(suffix, false, clientCacheKey);
startedClientCache = true;
}
} else if(clientCacheType.equals("none")) {
initNoClientCacheFS();
startedClientCache = true;
} else { // ram
initRAMClientCacheFS();
startedClientCache = true;
}
if(!startedClientCache)
initRAMClientCacheFS();
if(!clientCore.loadedDatabase() && databaseKey != null) {
try {
lateSetupDatabase(databaseKey);
} catch (MasterKeysWrongPasswordException e2) {
System.err.println("Impossible: "+e2);
e2.printStackTrace();
} catch (MasterKeysFileSizeException e2) {
System.err.println("Impossible: "+e2);
e2.printStackTrace();
} catch (IOException e2) {
System.err.println("Unable to load database: "+e2);
e2.printStackTrace();
}
}
nodeConfig.register("useSlashdotCache", true, sortOrder++, true, false, "Node.useSlashdotCache", "Node.useSlashdotCacheLong", new BooleanCallback() {
@Override
public Boolean get() {
return useSlashdotCache;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException {
useSlashdotCache = val;
}
});
useSlashdotCache = nodeConfig.getBoolean("useSlashdotCache");
nodeConfig.register("writeLocalToDatastore", false, sortOrder++, true, false, "Node.writeLocalToDatastore", "Node.writeLocalToDatastoreLong", new BooleanCallback() {
@Override
public Boolean get() {
return writeLocalToDatastore;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException {
writeLocalToDatastore = val;
}
});
writeLocalToDatastore = nodeConfig.getBoolean("writeLocalToDatastore");
// LOW network *and* physical seclevel = writeLocalToDatastore
securityLevels.addNetworkThreatLevelListener(new SecurityLevelListener<NETWORK_THREAT_LEVEL>() {
@Override
public void onChange(NETWORK_THREAT_LEVEL oldLevel, NETWORK_THREAT_LEVEL newLevel) {
if(newLevel == NETWORK_THREAT_LEVEL.LOW && securityLevels.getPhysicalThreatLevel() == PHYSICAL_THREAT_LEVEL.LOW)
writeLocalToDatastore = true;
else
writeLocalToDatastore = false;
}
});
securityLevels.addPhysicalThreatLevelListener(new SecurityLevelListener<PHYSICAL_THREAT_LEVEL>() {
@Override
public void onChange(PHYSICAL_THREAT_LEVEL oldLevel, PHYSICAL_THREAT_LEVEL newLevel) {
if(newLevel == PHYSICAL_THREAT_LEVEL.LOW && securityLevels.getNetworkThreatLevel() == NETWORK_THREAT_LEVEL.LOW)
writeLocalToDatastore = true;
else
writeLocalToDatastore = false;
}
});
nodeConfig.register("slashdotCacheLifetime", MINUTES.toMillis(30), sortOrder++, true, false, "Node.slashdotCacheLifetime", "Node.slashdotCacheLifetimeLong", new LongCallback() {
@Override
public Long get() {
return chkSlashdotcacheStore.getLifetime();
}
@Override
public void set(Long val) throws InvalidConfigValueException, NodeNeedRestartException {
if(val < 0) throw new InvalidConfigValueException("Must be positive!");
chkSlashdotcacheStore.setLifetime(val);
pubKeySlashdotcacheStore.setLifetime(val);
sskSlashdotcacheStore.setLifetime(val);
}
}, false);
long slashdotCacheLifetime = nodeConfig.getLong("slashdotCacheLifetime");
nodeConfig.register("slashdotCacheSize", DEFAULT_SLASHDOT_CACHE_SIZE, sortOrder++, false, true, "Node.slashdotCacheSize", "Node.slashdotCacheSizeLong",
new LongCallback() {
@Override
public Long get() {
return maxSlashdotCacheSize;
}
@Override
public void set(Long storeSize) throws InvalidConfigValueException {
if(storeSize < MIN_SLASHDOT_CACHE_SIZE)
throw new InvalidConfigValueException(l10n("invalidStoreSize"));
int newMaxStoreKeys = (int) Math.min(storeSize / sizePerKey, Integer.MAX_VALUE);
if(newMaxStoreKeys == maxSlashdotCacheKeys) return;
// Update each datastore
synchronized(Node.this) {
maxSlashdotCacheSize = storeSize;
maxSlashdotCacheKeys = newMaxStoreKeys;
}
try {
chkSlashdotcache.setMaxKeys(maxSlashdotCacheKeys, storeForceBigShrinks);
pubKeySlashdotcache.setMaxKeys(maxSlashdotCacheKeys, storeForceBigShrinks);
sskSlashdotcache.setMaxKeys(maxSlashdotCacheKeys, storeForceBigShrinks);
} catch (IOException e) {
// FIXME we need to be able to tell the user.
Logger.error(this, "Caught "+e+" resizing the slashdotcache", e);
System.err.println("Caught "+e+" resizing the slashdotcache");
e.printStackTrace();
}
}
}, true);
maxSlashdotCacheSize = nodeConfig.getLong("slashdotCacheSize");
if(maxSlashdotCacheSize < MIN_SLASHDOT_CACHE_SIZE) {
throw new NodeInitException(NodeInitException.EXIT_INVALID_STORE_SIZE, "Slashdot cache size too small");
}
maxSlashdotCacheKeys = (int) Math.min(maxSlashdotCacheSize / sizePerKey, Integer.MAX_VALUE);
chkSlashdotcache = new CHKStore();
chkSlashdotcacheStore = new SlashdotStore<CHKBlock>(chkSlashdotcache, maxSlashdotCacheKeys, slashdotCacheLifetime, PURGE_INTERVAL, ticker, this.clientCore.tempBucketFactory);
pubKeySlashdotcache = new PubkeyStore();
pubKeySlashdotcacheStore = new SlashdotStore<DSAPublicKey>(pubKeySlashdotcache, maxSlashdotCacheKeys, slashdotCacheLifetime, PURGE_INTERVAL, ticker, this.clientCore.tempBucketFactory);
getPubKey.setLocalSlashdotcache(pubKeySlashdotcache);
sskSlashdotcache = new SSKStore(getPubKey);
sskSlashdotcacheStore = new SlashdotStore<SSKBlock>(sskSlashdotcache, maxSlashdotCacheKeys, slashdotCacheLifetime, PURGE_INTERVAL, ticker, this.clientCore.tempBucketFactory);
// MAXIMUM seclevel = no slashdot cache.
securityLevels.addNetworkThreatLevelListener(new SecurityLevelListener<NETWORK_THREAT_LEVEL>() {
@Override
public void onChange(NETWORK_THREAT_LEVEL oldLevel, NETWORK_THREAT_LEVEL newLevel) {
if(newLevel == NETWORK_THREAT_LEVEL.MAXIMUM)
useSlashdotCache = false;
else if(oldLevel == NETWORK_THREAT_LEVEL.MAXIMUM)
useSlashdotCache = true;
}
});
nodeConfig.register("skipWrapperWarning", false, sortOrder++, true, false, "Node.skipWrapperWarning", "Node.skipWrapperWarningLong", new BooleanCallback() {
@Override
public void set(Boolean value) throws InvalidConfigValueException, NodeNeedRestartException {
skipWrapperWarning = value;
}
@Override
public Boolean get() {
return skipWrapperWarning;
}
});
skipWrapperWarning = nodeConfig.getBoolean("skipWrapperWarning");
nodeConfig.register("maxPacketSize", 1280, sortOrder++, true, true, "Node.maxPacketSize", "Node.maxPacketSizeLong", new IntCallback() {
@Override
public Integer get() {
synchronized(Node.this) {
return maxPacketSize;
}
}
@Override
public void set(Integer val) throws InvalidConfigValueException,
NodeNeedRestartException {
synchronized(Node.this) {
if(val == maxPacketSize) return;
if(val < UdpSocketHandler.MIN_MTU) throw new InvalidConfigValueException("Must be over 576");
if(val > 1492) throw new InvalidConfigValueException("Larger than ethernet frame size unlikely to work!");
maxPacketSize = val;
}
updateMTU();
}
}, true);
maxPacketSize = nodeConfig.getInt("maxPacketSize");
nodeConfig.register("enableRoutedPing", false, sortOrder++, true, false, "Node.enableRoutedPing", "Node.enableRoutedPingLong", new BooleanCallback() {
@Override
public Boolean get() {
synchronized(Node.this) {
return enableRoutedPing;
}
}
@Override
public void set(Boolean val) throws InvalidConfigValueException,
NodeNeedRestartException {
synchronized(Node.this) {
enableRoutedPing = val;
}
}
});
enableRoutedPing = nodeConfig.getBoolean("enableRoutedPing");
updateMTU();
// peers-offers/*.fref files
peersOffersFrefFilesConfiguration(nodeConfig, sortOrder++);
if (!peersOffersDismissed && checkPeersOffersFrefFiles())
PeersOffersUserAlert.createAlert(this);
/* Take care that no configuration options are registered after this point; they will not persist
* between restarts.
*/
nodeConfig.finishedInitialization();
if(shouldWriteConfig) config.store();
writeNodeFile();
// Initialize the plugin manager
Logger.normal(this, "Initializing Plugin Manager");
System.out.println("Initializing Plugin Manager");
pluginManager = new PluginManager(this, lastVersion);
shutdownHook.addEarlyJob(new NativeThread("Shutdown plugins", NativeThread.HIGH_PRIORITY, true) {
@Override
public void realRun() {
pluginManager.stop(SECONDS.toMillis(30)); // FIXME make it configurable??
}
});
// FIXME
// Short timeouts and JVM timeouts with nothing more said than the above have been seen...
// I don't know why... need a stack dump...
// For now just give it an extra 2 minutes. If it doesn't start in that time,
// it's likely (on reports so far) that a restart will fix it.
// And we have to get a build out because ALL plugins are now failing to load,
// including the absolutely essential (for most nodes) JSTUN and UPnP.
WrapperManager.signalStarting((int) MINUTES.toMillis(2));
FetchContext ctx = clientCore.makeClient((short)0, true, false).getFetchContext();
ctx.allowSplitfiles = false;
ctx.dontEnterImplicitArchives = true;
ctx.maxArchiveRestarts = 0;
ctx.maxMetadataSize = 256;
ctx.maxNonSplitfileRetries = 10;
ctx.maxOutputLength = 4096;
ctx.maxRecursionLevel = 2;
ctx.maxTempLength = 4096;
this.arkFetcherContext = ctx;
registerNodeToNodeMessageListener(N2N_MESSAGE_TYPE_FPROXY, fproxyN2NMListener);
registerNodeToNodeMessageListener(Node.N2N_MESSAGE_TYPE_DIFFNODEREF, diffNoderefListener);
// FIXME this is a hack
// toadlet server should start after all initialized
// see NodeClientCore line 437
if (toadlets.isEnabled()) {
toadlets.finishStart();
toadlets.createFproxy();
toadlets.removeStartupToadlet();
}
Logger.normal(this, "Node constructor completed");
System.out.println("Node constructor completed");
new BandwidthManager(this).start();
}
private void peersOffersFrefFilesConfiguration(SubConfig nodeConfig, int configOptionSortOrder) {
final Node node = this;
nodeConfig.register("peersOffersDismissed", false, configOptionSortOrder, true, true,
"Node.peersOffersDismissed", "Node.peersOffersDismissedLong", new BooleanCallback() {
@Override
public Boolean get() {
return peersOffersDismissed;
}
@Override
public void set(Boolean val) {
if (val) {
for (UserAlert alert : clientCore.alerts.getAlerts())
if (alert instanceof PeersOffersUserAlert)
clientCore.alerts.unregister(alert);
} else
PeersOffersUserAlert.createAlert(node);
peersOffersDismissed = val;
}
});
peersOffersDismissed = nodeConfig.getBoolean("peersOffersDismissed");
}
private boolean checkPeersOffersFrefFiles() {
File[] files = runDir.file("peers-offers").listFiles();
if (files != null && files.length > 0) {
for (File file : files) {
if (file.isFile()) {
String filename = file.getName();
if (filename.endsWith(".fref"))
return true;
}
}
}
return false;
}
/** Delete files from old BDB-index datastore. */
private void deleteOldBDBIndexStoreFiles() {
File dbDir = storeDir.file("database-"+getDarknetPortNumber());
FileUtil.removeAll(dbDir);
File dir = storeDir.dir();
File[] list = dir.listFiles();
for(File f : list) {
String name = f.getName();
if(f.isFile() &&
name.toLowerCase().matches("((chk)|(ssk)|(pubkey))-[0-9]*\\.((store)|(cache))(\\.((keys)|(lru)))?")) {
System.out.println("Deleting old datastore file \""+f+"\"");
try {
FileUtil.secureDelete(f);
} catch (IOException e) {
System.err.println("Failed to delete old datastore file \""+f+"\": "+e);
e.printStackTrace();
}
}
}
}
private void fixCertsFiles() {
// Hack to update certificates file to fix update.cmd
// startssl.pem: Might be useful for old versions of update.sh too?
File certs = new File(PluginDownLoaderOfficialHTTPS.certfileOld);
fixCertsFile(certs);
if(FileUtil.detectedOS.isWindows) {
// updater\startssl.pem: Needed for Windows update.cmd.
certs = new File("updater", PluginDownLoaderOfficialHTTPS.certfileOld);
fixCertsFile(certs);
}
}
private void fixCertsFile(File certs) {
long oldLength = certs.exists() ? certs.length() : -1;
try {
File tmpFile = File.createTempFile(PluginDownLoaderOfficialHTTPS.certfileOld, ".tmp", new File("."));
PluginDownLoaderOfficialHTTPS.writeCertsTo(tmpFile);
if(FileUtil.renameTo(tmpFile, certs)) {
long newLength = certs.length();
if(newLength != oldLength)
System.err.println("Updated "+certs+" so that update scripts will work");
} else {
if(certs.length() != tmpFile.length()) {
System.err.println("Cannot update "+certs+" : last-resort update scripts (in particular update.cmd on Windows) may not work");
File manual = new File(PluginDownLoaderOfficialHTTPS.certfileOld+".new");
manual.delete();
if(tmpFile.renameTo(manual))
System.err.println("Please delete "+certs+" and rename "+manual+" over it");
else
tmpFile.delete();
}
}
} catch (IOException e) {
}
}
/**
** Sets up a program directory using the config value defined by the given
** parameters.
*/
public ProgramDirectory setupProgramDir(SubConfig installConfig,
String cfgKey, String defaultValue, String shortdesc, String longdesc, String moveErrMsg,
SubConfig oldConfig) throws NodeInitException {
ProgramDirectory dir = new ProgramDirectory(moveErrMsg);
int sortOrder = ProgramDirectory.nextOrder();
// forceWrite=true because currently it can't be changed on the fly, also for packages
installConfig.register(cfgKey, defaultValue, sortOrder, true, true, shortdesc, longdesc, dir.getStringCallback());
String dirName = installConfig.getString(cfgKey);
try {
dir.move(dirName);
} catch (IOException e) {
throw new NodeInitException(NodeInitException.EXIT_BAD_DIR, "could not set up directory: " + longdesc);
}
return dir;
}
protected ProgramDirectory setupProgramDir(SubConfig installConfig,
String cfgKey, String defaultValue, String shortdesc, String longdesc,
SubConfig oldConfig) throws NodeInitException {
return setupProgramDir(installConfig, cfgKey, defaultValue, shortdesc, longdesc, null, oldConfig);
}
public void lateSetupDatabase(DatabaseKey databaseKey) throws MasterKeysWrongPasswordException, MasterKeysFileSizeException, IOException {
if(clientCore.loadedDatabase()) return;
System.out.println("Starting late database initialisation");
try {
if(!clientCore.lateInitDatabase(databaseKey))
failLateInitDatabase();
} catch (NodeInitException e) {
failLateInitDatabase();
}
}
private void failLateInitDatabase() {
System.err.println("Failed late initialisation of database, closing...");
}
public void killMasterKeysFile() throws IOException {
MasterKeys.killMasterKeys(masterKeysFile);
}
private void setClientCacheAwaitingPassword() {
createPasswordUserAlert();
synchronized(this) {
clientCacheAwaitingPassword = true;
}
}
/** Called when the client layer needs the decryption password. */
void setDatabaseAwaitingPassword() {
synchronized(this) {
databaseAwaitingPassword = true;
}
}
private final UserAlert masterPasswordUserAlert = new UserAlert() {
final long creationTime = System.currentTimeMillis();
@Override
public String anchor() {
return "password";
}
@Override
public String dismissButtonText() {
return null;
}
@Override
public long getUpdatedTime() {
return creationTime;
}
@Override
public FCPMessage getFCPMessage() {
return new FeedMessage(getTitle(), getShortText(), getText(), getPriorityClass(), getUpdatedTime());
}
@Override
public HTMLNode getHTMLText() {
HTMLNode content = new HTMLNode("div");
SecurityLevelsToadlet.generatePasswordFormPage(false, clientCore.getToadletContainer(), content, false, false, false, null, null);
return content;
}
@Override
public short getPriorityClass() {
return UserAlert.ERROR;
}
@Override
public String getShortText() {
return NodeL10n.getBase().getString("SecurityLevels.enterPassword");
}
@Override
public String getText() {
return NodeL10n.getBase().getString("SecurityLevels.enterPassword");
}
@Override
public String getTitle() {
return NodeL10n.getBase().getString("SecurityLevels.enterPassword");
}
@Override
public boolean isEventNotification() {
return false;
}
@Override
public boolean isValid() {
synchronized(Node.this) {
return clientCacheAwaitingPassword || databaseAwaitingPassword;
}
}
@Override
public void isValid(boolean validity) {
// Ignore
}
@Override
public void onDismiss() {
// Ignore
}
@Override
public boolean shouldUnregisterOnDismiss() {
return false;
}
@Override
public boolean userCanDismiss() {
return false;
}
};
private void createPasswordUserAlert() {
this.clientCore.alerts.register(masterPasswordUserAlert);
}
private void initRAMClientCacheFS() {
chkClientcache = new CHKStore();
new RAMFreenetStore<CHKBlock>(chkClientcache, (int) Math.min(Integer.MAX_VALUE, maxClientCacheKeys));
pubKeyClientcache = new PubkeyStore();
new RAMFreenetStore<DSAPublicKey>(pubKeyClientcache, (int) Math.min(Integer.MAX_VALUE, maxClientCacheKeys));
sskClientcache = new SSKStore(getPubKey);
new RAMFreenetStore<SSKBlock>(sskClientcache, (int) Math.min(Integer.MAX_VALUE, maxClientCacheKeys));
}
private void initNoClientCacheFS() {
chkClientcache = new CHKStore();
new NullFreenetStore<CHKBlock>(chkClientcache);
pubKeyClientcache = new PubkeyStore();
new NullFreenetStore<DSAPublicKey>(pubKeyClientcache);
sskClientcache = new SSKStore(getPubKey);
new NullFreenetStore<SSKBlock>(sskClientcache);
}
private String getStoreSuffix() {
return "-" + getDarknetPortNumber();
}
private void finishInitSaltHashFS(final String suffix, NodeClientCore clientCore) {
if(clientCore.alerts == null) throw new NullPointerException();
chkDatastore.getStore().setUserAlertManager(clientCore.alerts);
chkDatacache.getStore().setUserAlertManager(clientCore.alerts);
pubKeyDatastore.getStore().setUserAlertManager(clientCore.alerts);
pubKeyDatacache.getStore().setUserAlertManager(clientCore.alerts);
sskDatastore.getStore().setUserAlertManager(clientCore.alerts);
sskDatacache.getStore().setUserAlertManager(clientCore.alerts);
}
private void initRAMFS() {
chkDatastore = new CHKStore();
new RAMFreenetStore<CHKBlock>(chkDatastore, (int) Math.min(Integer.MAX_VALUE, maxStoreKeys));
chkDatacache = new CHKStore();
new RAMFreenetStore<CHKBlock>(chkDatacache, (int) Math.min(Integer.MAX_VALUE, maxCacheKeys));
pubKeyDatastore = new PubkeyStore();
new RAMFreenetStore<DSAPublicKey>(pubKeyDatastore, (int) Math.min(Integer.MAX_VALUE, maxStoreKeys));
pubKeyDatacache = new PubkeyStore();
getPubKey.setDataStore(pubKeyDatastore, pubKeyDatacache);
new RAMFreenetStore<DSAPublicKey>(pubKeyDatacache, (int) Math.min(Integer.MAX_VALUE, maxCacheKeys));
sskDatastore = new SSKStore(getPubKey);
new RAMFreenetStore<SSKBlock>(sskDatastore, (int) Math.min(Integer.MAX_VALUE, maxStoreKeys));
sskDatacache = new SSKStore(getPubKey);
new RAMFreenetStore<SSKBlock>(sskDatacache, (int) Math.min(Integer.MAX_VALUE, maxCacheKeys));
}
private long cachingFreenetStoreMaxSize;
private long cachingFreenetStorePeriod;
private CachingFreenetStoreTracker cachingFreenetStoreTracker;
private void initSaltHashFS(final String suffix, boolean dontResizeOnStart, byte[] masterKey) throws NodeInitException {
try {
final CHKStore chkDatastore = new CHKStore();
final FreenetStore<CHKBlock> chkDataFS = makeStore("CHK", true, chkDatastore, dontResizeOnStart, masterKey);
final CHKStore chkDatacache = new CHKStore();
final FreenetStore<CHKBlock> chkCacheFS = makeStore("CHK", false, chkDatacache, dontResizeOnStart, masterKey);
((SaltedHashFreenetStore<CHKBlock>) chkCacheFS.getUnderlyingStore()).setAltStore(((SaltedHashFreenetStore<CHKBlock>) chkDataFS.getUnderlyingStore()));
final PubkeyStore pubKeyDatastore = new PubkeyStore();
final FreenetStore<DSAPublicKey> pubkeyDataFS = makeStore("PUBKEY", true, pubKeyDatastore, dontResizeOnStart, masterKey);
final PubkeyStore pubKeyDatacache = new PubkeyStore();
final FreenetStore<DSAPublicKey> pubkeyCacheFS = makeStore("PUBKEY", false, pubKeyDatacache, dontResizeOnStart, masterKey);
((SaltedHashFreenetStore<DSAPublicKey>) pubkeyCacheFS.getUnderlyingStore()).setAltStore(((SaltedHashFreenetStore<DSAPublicKey>) pubkeyDataFS.getUnderlyingStore()));
final SSKStore sskDatastore = new SSKStore(getPubKey);
final FreenetStore<SSKBlock> sskDataFS = makeStore("SSK", true, sskDatastore, dontResizeOnStart, masterKey);
final SSKStore sskDatacache = new SSKStore(getPubKey);
final FreenetStore<SSKBlock> sskCacheFS = makeStore("SSK", false, sskDatacache, dontResizeOnStart, masterKey);
((SaltedHashFreenetStore<SSKBlock>) sskCacheFS.getUnderlyingStore()).setAltStore(((SaltedHashFreenetStore<SSKBlock>) sskDataFS.getUnderlyingStore()));
boolean delay =
chkDataFS.start(ticker, false) |
chkCacheFS.start(ticker, false) |
pubkeyDataFS.start(ticker, false) |
pubkeyCacheFS.start(ticker, false) |
sskDataFS.start(ticker, false) |
sskCacheFS.start(ticker, false);
if(delay) {
System.err.println("Delayed init of datastore");
initRAMFS();
final Runnable migrate = new MigrateOldStoreData(false);
this.getTicker().queueTimedJob(new Runnable() {
@Override
public void run() {
System.err.println("Starting delayed init of datastore");
try {
chkDataFS.start(ticker, true);
chkCacheFS.start(ticker, true);
pubkeyDataFS.start(ticker, true);
pubkeyCacheFS.start(ticker, true);
sskDataFS.start(ticker, true);
sskCacheFS.start(ticker, true);
} catch (IOException e) {
Logger.error(this, "Failed to start datastore: "+e, e);
System.err.println("Failed to start datastore: "+e);
e.printStackTrace();
return;
}
Node.this.chkDatastore = chkDatastore;
Node.this.chkDatacache = chkDatacache;
Node.this.pubKeyDatastore = pubKeyDatastore;
Node.this.pubKeyDatacache = pubKeyDatacache;
getPubKey.setDataStore(pubKeyDatastore, pubKeyDatacache);
Node.this.sskDatastore = sskDatastore;
Node.this.sskDatacache = sskDatacache;
finishInitSaltHashFS(suffix, clientCore);
System.err.println("Finishing delayed init of datastore");
migrate.run();
}
}, "Start store", 0, true, false); // Use Ticker to guarantee that this runs *after* constructors have completed.
} else {
Node.this.chkDatastore = chkDatastore;
Node.this.chkDatacache = chkDatacache;
Node.this.pubKeyDatastore = pubKeyDatastore;
Node.this.pubKeyDatacache = pubKeyDatacache;
getPubKey.setDataStore(pubKeyDatastore, pubKeyDatacache);
Node.this.sskDatastore = sskDatastore;
Node.this.sskDatacache = sskDatacache;
this.getTicker().queueTimedJob(new Runnable() {
@Override
public void run() {
Node.this.chkDatastore = chkDatastore;
Node.this.chkDatacache = chkDatacache;
Node.this.pubKeyDatastore = pubKeyDatastore;
Node.this.pubKeyDatacache = pubKeyDatacache;
getPubKey.setDataStore(pubKeyDatastore, pubKeyDatacache);
Node.this.sskDatastore = sskDatastore;
Node.this.sskDatacache = sskDatacache;
finishInitSaltHashFS(suffix, clientCore);
}
}, "Start store", 0, true, false);
}
} catch (IOException e) {
System.err.println("Could not open store: " + e);
e.printStackTrace();
throw new NodeInitException(NodeInitException.EXIT_STORE_OTHER, e.getMessage());
}
}
private void initSaltHashClientCacheFS(final String suffix, boolean dontResizeOnStart, byte[] clientCacheMasterKey) throws NodeInitException {
try {
final CHKStore chkClientcache = new CHKStore();
final FreenetStore<CHKBlock> chkDataFS = makeClientcache("CHK", true, chkClientcache, dontResizeOnStart, clientCacheMasterKey);
final PubkeyStore pubKeyClientcache = new PubkeyStore();
final FreenetStore<DSAPublicKey> pubkeyDataFS = makeClientcache("PUBKEY", true, pubKeyClientcache, dontResizeOnStart, clientCacheMasterKey);
final SSKStore sskClientcache = new SSKStore(getPubKey);
final FreenetStore<SSKBlock> sskDataFS = makeClientcache("SSK", true, sskClientcache, dontResizeOnStart, clientCacheMasterKey);
boolean delay =
chkDataFS.start(ticker, false) |
pubkeyDataFS.start(ticker, false) |
sskDataFS.start(ticker, false);
if(delay) {
System.err.println("Delayed init of client-cache");
initRAMClientCacheFS();
final Runnable migrate = new MigrateOldStoreData(true);
getTicker().queueTimedJob(new Runnable() {
@Override
public void run() {
System.err.println("Starting delayed init of client-cache");
try {
chkDataFS.start(ticker, true);
pubkeyDataFS.start(ticker, true);
sskDataFS.start(ticker, true);
} catch (IOException e) {
Logger.error(this, "Failed to start client-cache: "+e, e);
System.err.println("Failed to start client-cache: "+e);
e.printStackTrace();
return;
}
Node.this.chkClientcache = chkClientcache;
Node.this.pubKeyClientcache = pubKeyClientcache;
getPubKey.setLocalDataStore(pubKeyClientcache);
Node.this.sskClientcache = sskClientcache;
System.err.println("Finishing delayed init of client-cache");
migrate.run();
}
}, "Migrate store", 0, true, false);
} else {
Node.this.chkClientcache = chkClientcache;
Node.this.pubKeyClientcache = pubKeyClientcache;
getPubKey.setLocalDataStore(pubKeyClientcache);
Node.this.sskClientcache = sskClientcache;
}
} catch (IOException e) {
System.err.println("Could not open store: " + e);
e.printStackTrace();
throw new NodeInitException(NodeInitException.EXIT_STORE_OTHER, e.getMessage());
}
}
private <T extends StorableBlock> FreenetStore<T> makeClientcache(String type, boolean isStore, StoreCallback<T> cb, boolean dontResizeOnStart, byte[] clientCacheMasterKey) throws IOException {
FreenetStore<T> store = makeStore(type, "clientcache", maxClientCacheKeys, cb, dontResizeOnStart, clientCacheMasterKey);
return store;
}
private <T extends StorableBlock> FreenetStore<T> makeStore(String type, boolean isStore, StoreCallback<T> cb, boolean dontResizeOnStart, byte[] clientCacheMasterKey) throws IOException {
String store = isStore ? "store" : "cache";
long maxKeys = isStore ? maxStoreKeys : maxCacheKeys;
return makeStore(type, store, maxKeys, cb, dontResizeOnStart, clientCacheMasterKey);
}
private <T extends StorableBlock> FreenetStore<T> makeStore(String type, String store, long maxKeys, StoreCallback<T> cb, boolean lateStart, byte[] clientCacheMasterKey) throws IOException {
Logger.normal(this, "Initializing "+type+" Data"+store);
System.out.println("Initializing "+type+" Data"+store+" (" + maxStoreKeys + " keys)");
SaltedHashFreenetStore<T> fs = SaltedHashFreenetStore.<T>construct(getStoreDir(), type+"-"+store, cb,
random, maxKeys, storeUseSlotFilters, shutdownHook, storePreallocate, storeSaltHashResizeOnStart && !lateStart, lateStart ? ticker : null, clientCacheMasterKey);
cb.setStore(fs);
if(cachingFreenetStoreMaxSize > 0)
return new CachingFreenetStore<T>(cb, fs, cachingFreenetStoreTracker);
else
return fs;
}
public void start(boolean noSwaps) throws NodeInitException {
// IMPORTANT: Read the peers only after we have finished initializing Node.
// Peer constructors are complex and can call methods on Node.
peers.tryReadPeers(nodeDir.file("peers-"+getDarknetPortNumber()).getPath(), darknetCrypto, null, false, false);
peers.updatePMUserAlert();
dispatcher.start(nodeStats); // must be before usm
dnsr.start();
peers.start(); // must be before usm
nodeStats.start();
uptime.start();
failureTable.start();
darknetCrypto.start();
if(opennet != null)
opennet.start();
ps.start(nodeStats);
ticker.start();
scheduleVersionTransition();
usm.start(ticker);
if(isUsingWrapper()) {
Logger.normal(this, "Using wrapper correctly: "+nodeStarter);
System.out.println("Using wrapper correctly: "+nodeStarter);
} else {
Logger.error(this, "NOT using wrapper (at least not correctly). Your freenet-ext.jar <http://downloads.freenetproject.org/alpha/freenet-ext.jar> and/or wrapper.conf <https://emu.freenetproject.org/svn/trunk/apps/installer/installclasspath/config/wrapper.conf> need to be updated.");
System.out.println("NOT using wrapper (at least not correctly). Your freenet-ext.jar <http://downloads.freenetproject.org/alpha/freenet-ext.jar> and/or wrapper.conf <https://emu.freenetproject.org/svn/trunk/apps/installer/installclasspath/config/wrapper.conf> need to be updated.");
}
Logger.normal(this, "Freenet 0.7.5 Build #"+Version.buildNumber()+" r"+Version.cvsRevision());
System.out.println("Freenet 0.7.5 Build #"+Version.buildNumber()+" r"+Version.cvsRevision());
Logger.normal(this, "FNP port is on "+darknetCrypto.getBindTo()+ ':' +getDarknetPortNumber());
System.out.println("FNP port is on "+darknetCrypto.getBindTo()+ ':' +getDarknetPortNumber());
// Start services
// SubConfig pluginManagerConfig = new SubConfig("pluginmanager3", config);
// pluginManager3 = new freenet.plugin_new.PluginManager(pluginManagerConfig);
ipDetector.start();
// Start sending swaps
lm.start();
// Node Updater
try{
Logger.normal(this, "Starting the node updater");
nodeUpdater.start();
}catch (Exception e) {
e.printStackTrace();
throw new NodeInitException(NodeInitException.EXIT_COULD_NOT_START_UPDATER, "Could not start Updater: "+e);
}
/* TODO: Make sure that this is called BEFORE any instances of HTTPFilter are created.
* HTTPFilter uses checkForGCJCharConversionBug() which returns the value of the static
* variable jvmHasGCJCharConversionBug - and this is initialized in the following function.
* If this is not possible then create a separate function to check for the GCJ bug and
* call this function earlier.
*/
checkForEvilJVMBugs();
if(!NativeThread.HAS_ENOUGH_NICE_LEVELS)
clientCore.alerts.register(new NotEnoughNiceLevelsUserAlert());
this.clientCore.start(config);
tracker.startDeadUIDChecker();
// After everything has been created, write the config file back to disk.
if(config instanceof FreenetFilePersistentConfig) {
FreenetFilePersistentConfig cfg = (FreenetFilePersistentConfig) config;
cfg.finishedInit(this.ticker);
cfg.setHasNodeStarted();
}
config.store();
// Process any data in the extra peer data directory
peers.readExtraPeerData();
Logger.normal(this, "Started node");
hasStarted = true;
}
private void scheduleVersionTransition() {
long now = System.currentTimeMillis();
long transition = Version.transitionTime();
if(now < transition)
ticker.queueTimedJob(new Runnable() {
@Override
public void run() {
freenet.support.Logger.OSThread.logPID(this);
for(PeerNode pn: peers.myPeers()) {
pn.updateVersionRoutablity();
}
}
}, transition - now);
}
private static boolean jvmHasGCJCharConversionBug=false;
private void checkForEvilJVMBugs() {
// Now check whether we are likely to get the EvilJVMBug.
// If we are running a Sun/Oracle or Blackdown JVM, on Linux, and LD_ASSUME_KERNEL is not set, then we are.
String jvmVendor = System.getProperty("java.vm.vendor");
String jvmSpecVendor = System.getProperty("java.specification.vendor","");
String javaVersion = System.getProperty("java.version");
String jvmName = System.getProperty("java.vm.name");
String osName = System.getProperty("os.name");
String osVersion = System.getProperty("os.version");
boolean isOpenJDK = false;
//boolean isOracle = false;
if(logMINOR) Logger.minor(this, "JVM vendor: "+jvmVendor+", JVM name: "+jvmName+", JVM version: "+javaVersion+", OS name: "+osName+", OS version: "+osVersion);
if(jvmName.startsWith("OpenJDK ")) {
isOpenJDK = true;
}
//Add some checks for "Oracle" to futureproof against them renaming from "Sun".
//Should have no effect because if a user has downloaded a new enough file for Oracle to have changed the name these bugs shouldn't apply.
//Still, one never knows and this code might be extended to cover future bugs.
if((!isOpenJDK) && (jvmVendor.startsWith("Sun ") || jvmVendor.startsWith("Oracle ")) || (jvmVendor.startsWith("The FreeBSD Foundation") && (jvmSpecVendor.startsWith("Sun ") || jvmSpecVendor.startsWith("Oracle "))) || (jvmVendor.startsWith("Apple "))) {
//isOracle = true;
// Sun/Oracle bugs
// Spurious OOMs
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4855795
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=2138757
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=2138759
// Fixed in 1.5.0_10 and 1.4.2_13
boolean is150 = javaVersion.startsWith("1.5.0_");
boolean is160 = javaVersion.startsWith("1.6.0_");
if(is150 || is160) {
String[] split = javaVersion.split("_");
String secondPart = split[1];
if(secondPart.indexOf("-") != -1) {
split = secondPart.split("-");
secondPart = split[0];
}
int subver = Integer.parseInt(secondPart);
Logger.minor(this, "JVM version: "+javaVersion+" subver: "+subver+" from "+secondPart);
}
} else if (jvmVendor.startsWith("Apple ") || jvmVendor.startsWith("\"Apple ")) {
//Note that Sun/Oracle does not produce VMs for the Macintosh operating system, dont ask the user to find one...
} else if(!isOpenJDK) {
if(jvmVendor.startsWith("Free Software Foundation")) {
// GCJ/GIJ.
try {
javaVersion = System.getProperty("java.version").split(" ")[0].replaceAll("[.]","");
int jvmVersionInt = Integer.parseInt(javaVersion);
if(jvmVersionInt <= 422 && jvmVersionInt >= 100) // make sure that no bogus values cause true
jvmHasGCJCharConversionBug=true;
}
catch(Throwable t) {
Logger.error(this, "GCJ version check is broken!", t);
}
clientCore.alerts.register(new SimpleUserAlert(true, l10n("usingGCJTitle"), l10n("usingGCJ"), l10n("usingGCJTitle"), UserAlert.WARNING));
}
}
if(!isUsingWrapper() && !skipWrapperWarning) {
clientCore.alerts.register(new SimpleUserAlert(true, l10n("notUsingWrapperTitle"), l10n("notUsingWrapper"), l10n("notUsingWrapperShort"), UserAlert.WARNING));
}
// Unfortunately debian's version of OpenJDK appears to have segfaulting issues.
// Which presumably are exploitable.
// So we can't recommend people switch just yet. :(
// if(isOracle && Rijndael.AesCtrProvider == null) {
// if(!(FileUtil.detectedOS == FileUtil.OperatingSystem.Windows || FileUtil.detectedOS == FileUtil.OperatingSystem.MacOS))
// clientCore.alerts.register(new SimpleUserAlert(true, l10n("usingOracleTitle"), l10n("usingOracle"), l10n("usingOracleTitle"), UserAlert.WARNING));
// }
}
public static boolean checkForGCJCharConversionBug() {
return jvmHasGCJCharConversionBug; // should be initialized on early startup
}
private String l10n(String key) {
return NodeL10n.getBase().getString("Node."+key);
}
private String l10n(String key, String pattern, String value) {
return NodeL10n.getBase().getString("Node."+key, pattern, value);
}
private String l10n(String key, String[] pattern, String[] value) {
return NodeL10n.getBase().getString("Node."+key, pattern, value);
}
/**
* Export volatile data about the node as a SimpleFieldSet
*/
public SimpleFieldSet exportVolatileFieldSet() {
return nodeStats.exportVolatileFieldSet();
}
/**
* Do a routed ping of another node on the network by its location.
* @param loc2 The location of the other node to ping. It must match
* exactly.
* @param pubKeyHash The hash of the pubkey of the target node. We match
* by location; this is just a shortcut if we get close.
* @return The number of hops it took to find the node, if it was found.
* Otherwise -1.
*/
public int routedPing(double loc2, byte[] pubKeyHash) {
long uid = random.nextLong();
int initialX = random.nextInt();
Message m = DMT.createFNPRoutedPing(uid, loc2, maxHTL, initialX, pubKeyHash);
Logger.normal(this, "Message: "+m);
dispatcher.handleRouted(m, null);
// FIXME: might be rejected
MessageFilter mf1 = MessageFilter.create().setField(DMT.UID, uid).setType(DMT.FNPRoutedPong).setTimeout(5000);
try {
//MessageFilter mf2 = MessageFilter.create().setField(DMT.UID, uid).setType(DMT.FNPRoutedRejected).setTimeout(5000);
// Ignore Rejected - let it be retried on other peers
m = usm.waitFor(mf1/*.or(mf2)*/, null);
} catch (DisconnectedException e) {
Logger.normal(this, "Disconnected in waiting for pong");
return -1;
}
if(m == null) return -1;
if(m.getSpec() == DMT.FNPRoutedRejected) return -1;
return m.getInt(DMT.COUNTER) - initialX;
}
/**
* Look for a block in the datastore, as part of a request.
* @param key The key to fetch.
* @param uid The UID of the request (for logging only).
* @param promoteCache Whether to promote the key if found.
* @param canReadClientCache If the request is local, we can read the client cache.
* @param canWriteClientCache If the request is local, and the client hasn't turned off
* writing to the client cache, we can write to the client cache.
* @param canWriteDatastore If the request HTL is too high, including if it is local, we
* cannot write to the datastore.
* @return A KeyBlock for the key requested or null.
*/
private KeyBlock makeRequestLocal(Key key, long uid, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore, boolean offersOnly) {
KeyBlock kb = null;
if (key instanceof NodeCHK) {
kb = fetch(key, false, canReadClientCache, canWriteClientCache, canWriteDatastore, null);
} else if (key instanceof NodeSSK) {
NodeSSK sskKey = (NodeSSK) key;
DSAPublicKey pubKey = sskKey.getPubKey();
if (pubKey == null) {
pubKey = getPubKey.getKey(sskKey.getPubKeyHash(), canReadClientCache, offersOnly, null);
if (logMINOR)
Logger.minor(this, "Fetched pubkey: " + pubKey);
try {
sskKey.setPubKey(pubKey);
} catch (SSKVerifyException e) {
Logger.error(this, "Error setting pubkey: " + e, e);
}
}
if (pubKey != null) {
if (logMINOR)
Logger.minor(this, "Got pubkey: " + pubKey);
kb = fetch(sskKey, canReadClientCache, canWriteClientCache, canWriteDatastore, false, null);
} else {
if (logMINOR)
Logger.minor(this, "Not found because no pubkey: " + uid);
}
} else
throw new IllegalStateException("Unknown key type: " + key.getClass());
if (kb != null) {
// Probably somebody waiting for it. Trip it.
if (clientCore != null && clientCore.requestStarters != null) {
if (kb instanceof CHKBlock) {
clientCore.requestStarters.chkFetchSchedulerBulk.tripPendingKey(kb);
clientCore.requestStarters.chkFetchSchedulerRT.tripPendingKey(kb);
} else {
clientCore.requestStarters.sskFetchSchedulerBulk.tripPendingKey(kb);
clientCore.requestStarters.sskFetchSchedulerRT.tripPendingKey(kb);
}
}
failureTable.onFound(kb);
return kb;
}
return null;
}
/**
* Check the datastore, then if the key is not in the store,
* check whether another node is requesting the same key at
* the same HTL, and if all else fails, create a new
* RequestSender for the key/htl.
* @param closestLocation The closest location to the key so far.
* @param localOnly If true, only check the datastore.
* @return A KeyBlock if the data is in the store, otherwise
* a RequestSender, unless the HTL is 0, in which case NULL.
* RequestSender.
*/
public Object makeRequestSender(Key key, short htl, long uid, RequestTag tag, PeerNode source, boolean localOnly, boolean ignoreStore, boolean offersOnly, boolean canReadClientCache, boolean canWriteClientCache, boolean realTimeFlag) {
boolean canWriteDatastore = canWriteDatastoreRequest(htl);
if(logMINOR) Logger.minor(this, "makeRequestSender("+key+ ',' +htl+ ',' +uid+ ',' +source+") on "+getDarknetPortNumber());
// In store?
if(!ignoreStore) {
KeyBlock kb = makeRequestLocal(key, uid, canReadClientCache, canWriteClientCache, canWriteDatastore, offersOnly);
if (kb != null)
return kb;
}
if(localOnly) return null;
if(logMINOR) Logger.minor(this, "Not in store locally");
// Transfer coalescing - match key only as HTL irrelevant
RequestSender sender = key instanceof NodeCHK ?
tracker.getTransferringRequestSenderByKey((NodeCHK)key, realTimeFlag) : null;
if(sender != null) {
if(logMINOR) Logger.minor(this, "Data already being transferred: "+sender);
sender.setTransferCoalesced();
tag.setSender(sender, true);
return sender;
}
// HTL == 0 => Don't search further
if(htl == 0) {
if(logMINOR) Logger.minor(this, "No HTL");
return null;
}
sender = new RequestSender(key, null, htl, uid, tag, this, source, offersOnly, canWriteClientCache, canWriteDatastore, realTimeFlag);
tag.setSender(sender, false);
sender.start();
if(logMINOR) Logger.minor(this, "Created new sender: "+sender);
return sender;
}
/** Can we write to the datastore for a given request?
* We do not write to the datastore until 2 hops below maximum. This is an average of 4
* hops from the originator. Thus, data returned from local requests is never cached,
* finally solving The Register's attack, Bloom filter sharing doesn't give away your local
* requests and inserts, and *anything starting at high HTL* is not cached, including stuff
* from other nodes which hasn't been decremented far enough yet, so it's not ONLY local
* requests that don't get cached. */
boolean canWriteDatastoreRequest(short htl) {
return htl <= (maxHTL - 2);
}
/** Can we write to the datastore for a given insert?
* We do not write to the datastore until 3 hops below maximum. This is an average of 5
* hops from the originator. Thus, data sent by local inserts is never cached,
* finally solving The Register's attack, Bloom filter sharing doesn't give away your local
* requests and inserts, and *anything starting at high HTL* is not cached, including stuff
* from other nodes which hasn't been decremented far enough yet, so it's not ONLY local
* inserts that don't get cached. */
boolean canWriteDatastoreInsert(short htl) {
return htl <= (maxHTL - 3);
}
/**
* Fetch a block from the datastore.
* @param key
* @param canReadClientCache
* @param canWriteClientCache
* @param canWriteDatastore
* @param forULPR
* @param mustBeMarkedAsPostCachingChanges If true, the key must have the
* ENTRY_NEW_BLOCK flag (if saltedhash), indicating that it a) has been added
* since the caching changes in 1224 (since we didn't delete the stores), and b)
* that it wasn't added due to low network security caching everything, unless we
* are currently in low network security mode. Only applies to main store.
*/
public KeyBlock fetch(Key key, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR, BlockMetadata meta) {
if(key instanceof NodeSSK)
return fetch((NodeSSK)key, false, canReadClientCache, canWriteClientCache, canWriteDatastore, forULPR, meta);
else if(key instanceof NodeCHK)
return fetch((NodeCHK)key, false, canReadClientCache, canWriteClientCache, canWriteDatastore, forULPR, meta);
else throw new IllegalArgumentException();
}
public SSKBlock fetch(NodeSSK key, boolean dontPromote, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR, BlockMetadata meta) {
double loc=key.toNormalizedDouble();
double dist=Location.distance(lm.getLocation(), loc);
if(canReadClientCache) {
try {
SSKBlock block = sskClientcache.fetch(key, dontPromote || !canWriteClientCache, canReadClientCache, forULPR, false, meta);
if(block != null) {
nodeStats.avgClientCacheSSKSuccess.report(loc);
if (dist > nodeStats.furthestClientCacheSSKSuccess)
nodeStats.furthestClientCacheSSKSuccess=dist;
if(logDEBUG) Logger.debug(this, "Found key "+key+" in client-cache");
return block;
}
} catch (IOException e) {
Logger.error(this, "Could not read from client cache: "+e, e);
}
}
if(forULPR || useSlashdotCache || canReadClientCache) {
try {
SSKBlock block = sskSlashdotcache.fetch(key, dontPromote, canReadClientCache, forULPR, false, meta);
if(block != null) {
nodeStats.avgSlashdotCacheSSKSuccess.report(loc);
if (dist > nodeStats.furthestSlashdotCacheSSKSuccess)
nodeStats.furthestSlashdotCacheSSKSuccess=dist;
if(logDEBUG) Logger.debug(this, "Found key "+key+" in slashdot-cache");
return block;
}
} catch (IOException e) {
Logger.error(this, "Could not read from slashdot/ULPR cache: "+e, e);
}
}
boolean ignoreOldBlocks = !writeLocalToDatastore;
if(canReadClientCache) ignoreOldBlocks = false;
if(logMINOR) dumpStoreHits();
try {
nodeStats.avgRequestLocation.report(loc);
SSKBlock block = sskDatastore.fetch(key, dontPromote || !canWriteDatastore, canReadClientCache, forULPR, ignoreOldBlocks, meta);
if(block == null) {
SSKStore store = oldSSK;
if(store != null)
block = store.fetch(key, dontPromote || !canWriteDatastore, canReadClientCache, forULPR, ignoreOldBlocks, meta);
}
if(block != null) {
nodeStats.avgStoreSSKSuccess.report(loc);
if (dist > nodeStats.furthestStoreSSKSuccess)
nodeStats.furthestStoreSSKSuccess=dist;
if(logDEBUG) Logger.debug(this, "Found key "+key+" in store");
return block;
}
block=sskDatacache.fetch(key, dontPromote || !canWriteDatastore, canReadClientCache, forULPR, ignoreOldBlocks, meta);
if(block == null) {
SSKStore store = oldSSKCache;
if(store != null)
block = store.fetch(key, dontPromote || !canWriteDatastore, canReadClientCache, forULPR, ignoreOldBlocks, meta);
}
if (block != null) {
nodeStats.avgCacheSSKSuccess.report(loc);
if (dist > nodeStats.furthestCacheSSKSuccess)
nodeStats.furthestCacheSSKSuccess=dist;
if(logDEBUG) Logger.debug(this, "Found key "+key+" in cache");
}
return block;
} catch (IOException e) {
Logger.error(this, "Cannot fetch data: "+e, e);
return null;
}
}
public CHKBlock fetch(NodeCHK key, boolean dontPromote, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR, BlockMetadata meta) {
double loc=key.toNormalizedDouble();
double dist=Location.distance(lm.getLocation(), loc);
if(canReadClientCache) {
try {
CHKBlock block = chkClientcache.fetch(key, dontPromote || !canWriteClientCache, false, meta);
if(block != null) {
nodeStats.avgClientCacheCHKSuccess.report(loc);
if (dist > nodeStats.furthestClientCacheCHKSuccess)
nodeStats.furthestClientCacheCHKSuccess=dist;
return block;
}
} catch (IOException e) {
Logger.error(this, "Could not read from client cache: "+e, e);
}
}
if(forULPR || useSlashdotCache || canReadClientCache) {
try {
CHKBlock block = chkSlashdotcache.fetch(key, dontPromote, false, meta);
if(block != null) {
nodeStats.avgSlashdotCacheCHKSucess.report(loc);
if (dist > nodeStats.furthestSlashdotCacheCHKSuccess)
nodeStats.furthestSlashdotCacheCHKSuccess=dist;
return block;
}
} catch (IOException e) {
Logger.error(this, "Could not read from slashdot/ULPR cache: "+e, e);
}
}
boolean ignoreOldBlocks = !writeLocalToDatastore;
if(canReadClientCache) ignoreOldBlocks = false;
if(logMINOR) dumpStoreHits();
try {
nodeStats.avgRequestLocation.report(loc);
CHKBlock block = chkDatastore.fetch(key, dontPromote || !canWriteDatastore, ignoreOldBlocks, meta);
if(block == null) {
CHKStore store = oldCHK;
if(store != null)
block = store.fetch(key, dontPromote || !canWriteDatastore, ignoreOldBlocks, meta);
}
if (block != null) {
nodeStats.avgStoreCHKSuccess.report(loc);
if (dist > nodeStats.furthestStoreCHKSuccess)
nodeStats.furthestStoreCHKSuccess=dist;
return block;
}
block=chkDatacache.fetch(key, dontPromote || !canWriteDatastore, ignoreOldBlocks, meta);
if(block == null) {
CHKStore store = oldCHKCache;
if(store != null)
block = store.fetch(key, dontPromote || !canWriteDatastore, ignoreOldBlocks, meta);
}
if (block != null) {
nodeStats.avgCacheCHKSuccess.report(loc);
if (dist > nodeStats.furthestCacheCHKSuccess)
nodeStats.furthestCacheCHKSuccess=dist;
}
return block;
} catch (IOException e) {
Logger.error(this, "Cannot fetch data: "+e, e);
return null;
}
}
CHKStore getChkDatacache() {
return chkDatacache;
}
CHKStore getChkDatastore() {
return chkDatastore;
}
SSKStore getSskDatacache() {
return sskDatacache;
}
SSKStore getSskDatastore() {
return sskDatastore;
}
CHKStore getChkSlashdotCache() {
return chkSlashdotcache;
}
CHKStore getChkClientCache() {
return chkClientcache;
}
SSKStore getSskSlashdotCache() {
return sskSlashdotcache;
}
SSKStore getSskClientCache() {
return sskClientcache;
}
/**
* This method returns all statistics info for our data store stats table
*
* @return map that has an entry for each data store instance type and corresponding stats
*/
public Map<DataStoreInstanceType, DataStoreStats> getDataStoreStats() {
Map<DataStoreInstanceType, DataStoreStats> map = new LinkedHashMap<DataStoreInstanceType, DataStoreStats>();
map.put(new DataStoreInstanceType(CHK, STORE), new StoreCallbackStats(chkDatastore, nodeStats.chkStoreStats()));
map.put(new DataStoreInstanceType(CHK, CACHE), new StoreCallbackStats(chkDatacache, nodeStats.chkCacheStats()));
map.put(new DataStoreInstanceType(CHK, SLASHDOT), new StoreCallbackStats(chkSlashdotcache,nodeStats.chkSlashDotCacheStats()));
map.put(new DataStoreInstanceType(CHK, CLIENT), new StoreCallbackStats(chkClientcache, nodeStats.chkClientCacheStats()));
map.put(new DataStoreInstanceType(SSK, STORE), new StoreCallbackStats(sskDatastore, nodeStats.sskStoreStats()));
map.put(new DataStoreInstanceType(SSK, CACHE), new StoreCallbackStats(sskDatacache, nodeStats.sskCacheStats()));
map.put(new DataStoreInstanceType(SSK, SLASHDOT), new StoreCallbackStats(sskSlashdotcache, nodeStats.sskSlashDotCacheStats()));
map.put(new DataStoreInstanceType(SSK, CLIENT), new StoreCallbackStats(sskClientcache, nodeStats.sskClientCacheStats()));
map.put(new DataStoreInstanceType(PUB_KEY, STORE), new StoreCallbackStats(pubKeyDatastore, new NotAvailNodeStoreStats()));
map.put(new DataStoreInstanceType(PUB_KEY, CACHE), new StoreCallbackStats(pubKeyDatacache, new NotAvailNodeStoreStats()));
map.put(new DataStoreInstanceType(PUB_KEY, SLASHDOT), new StoreCallbackStats(pubKeySlashdotcache, new NotAvailNodeStoreStats()));
map.put(new DataStoreInstanceType(PUB_KEY, CLIENT), new StoreCallbackStats(pubKeyClientcache, new NotAvailNodeStoreStats()));
return map;
}
public long getMaxTotalKeys() {
return maxTotalKeys;
}
long timeLastDumpedHits;
public void dumpStoreHits() {
long now = System.currentTimeMillis();
if(now - timeLastDumpedHits > 5000) {
timeLastDumpedHits = now;
} else return;
Logger.minor(this, "Distribution of hits and misses over stores:\n"+
"CHK Datastore: "+chkDatastore.hits()+ '/' +(chkDatastore.hits()+chkDatastore.misses())+ '/' +chkDatastore.keyCount()+
"\nCHK Datacache: "+chkDatacache.hits()+ '/' +(chkDatacache.hits()+chkDatacache.misses())+ '/' +chkDatacache.keyCount()+
"\nSSK Datastore: "+sskDatastore.hits()+ '/' +(sskDatastore.hits()+sskDatastore.misses())+ '/' +sskDatastore.keyCount()+
"\nSSK Datacache: "+sskDatacache.hits()+ '/' +(sskDatacache.hits()+sskDatacache.misses())+ '/' +sskDatacache.keyCount());
}
public void storeShallow(CHKBlock block, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR) {
store(block, false, canWriteClientCache, canWriteDatastore, forULPR);
}
/**
* Store a datum.
* @param block
* a KeyBlock
* @param deep If true, insert to the store as well as the cache. Do not set
* this to true unless the store results from an insert, and this node is the
* closest node to the target; see the description of chkDatastore.
*/
public void store(KeyBlock block, boolean deep, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR) throws KeyCollisionException {
if(block instanceof CHKBlock)
store((CHKBlock)block, deep, canWriteClientCache, canWriteDatastore, forULPR);
else if(block instanceof SSKBlock)
store((SSKBlock)block, deep, false, canWriteClientCache, canWriteDatastore, forULPR);
else throw new IllegalArgumentException("Unknown keytype ");
}
private void store(CHKBlock block, boolean deep, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR) {
try {
double loc = block.getKey().toNormalizedDouble();
if (canWriteClientCache) {
chkClientcache.put(block, false);
nodeStats.avgClientCacheCHKLocation.report(loc);
}
if ((forULPR || useSlashdotCache) && !(canWriteDatastore || writeLocalToDatastore)) {
chkSlashdotcache.put(block, false);
nodeStats.avgSlashdotCacheCHKLocation.report(loc);
}
if (canWriteDatastore || writeLocalToDatastore) {
if (deep) {
chkDatastore.put(block, !canWriteDatastore);
nodeStats.avgStoreCHKLocation.report(loc);
}
chkDatacache.put(block, !canWriteDatastore);
nodeStats.avgCacheCHKLocation.report(loc);
}
if (canWriteDatastore || forULPR || useSlashdotCache)
failureTable.onFound(block);
} catch (IOException e) {
Logger.error(this, "Cannot store data: "+e, e);
} catch (Throwable t) {
System.err.println(t);
t.printStackTrace();
Logger.error(this, "Caught "+t+" storing data", t);
}
if(clientCore != null && clientCore.requestStarters != null) {
clientCore.requestStarters.chkFetchSchedulerBulk.tripPendingKey(block);
clientCore.requestStarters.chkFetchSchedulerRT.tripPendingKey(block);
}
}
/** Store the block if this is a sink. Call for inserts. */
public void storeInsert(SSKBlock block, boolean deep, boolean overwrite, boolean canWriteClientCache, boolean canWriteDatastore) throws KeyCollisionException {
store(block, deep, overwrite, canWriteClientCache, canWriteDatastore, false);
}
/** Store only to the cache, and not the store. Called by requests,
* as only inserts cause data to be added to the store. */
public void storeShallow(SSKBlock block, boolean canWriteClientCache, boolean canWriteDatastore, boolean fromULPR) throws KeyCollisionException {
store(block, false, canWriteClientCache, canWriteDatastore, fromULPR);
}
public void store(SSKBlock block, boolean deep, boolean overwrite, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR) throws KeyCollisionException {
try {
// Store the pubkey before storing the data, otherwise we can get a race condition and
// end up deleting the SSK data.
double loc = block.getKey().toNormalizedDouble();
getPubKey.cacheKey((block.getKey()).getPubKeyHash(), (block.getKey()).getPubKey(), deep, canWriteClientCache, canWriteDatastore, forULPR || useSlashdotCache, writeLocalToDatastore);
if(canWriteClientCache) {
sskClientcache.put(block, overwrite, false);
nodeStats.avgClientCacheSSKLocation.report(loc);
}
if((forULPR || useSlashdotCache) && !(canWriteDatastore || writeLocalToDatastore)) {
sskSlashdotcache.put(block, overwrite, false);
nodeStats.avgSlashdotCacheSSKLocation.report(loc);
}
if(canWriteDatastore || writeLocalToDatastore) {
if(deep) {
sskDatastore.put(block, overwrite, !canWriteDatastore);
nodeStats.avgStoreSSKLocation.report(loc);
}
sskDatacache.put(block, overwrite, !canWriteDatastore);
nodeStats.avgCacheSSKLocation.report(loc);
}
if(canWriteDatastore || forULPR || useSlashdotCache)
failureTable.onFound(block);
} catch (IOException e) {
Logger.error(this, "Cannot store data: "+e, e);
} catch (KeyCollisionException e) {
throw e;
} catch (Throwable t) {
System.err.println(t);
t.printStackTrace();
Logger.error(this, "Caught "+t+" storing data", t);
}
if(clientCore != null && clientCore.requestStarters != null) {
clientCore.requestStarters.sskFetchSchedulerBulk.tripPendingKey(block);
clientCore.requestStarters.sskFetchSchedulerRT.tripPendingKey(block);
}
}
final boolean decrementAtMax;
final boolean decrementAtMin;
/**
* Decrement the HTL according to the policy of the given
* NodePeer if it is non-null, or do something else if it is
* null.
*/
public short decrementHTL(PeerNode source, short htl) {
if(source != null)
return source.decrementHTL(htl);
// Otherwise...
if(htl >= maxHTL) htl = maxHTL;
if(htl <= 0) {
return 0;
}
if(htl == maxHTL) {
if(decrementAtMax || disableProbabilisticHTLs) htl--;
return htl;
}
if(htl == 1) {
if(decrementAtMin || disableProbabilisticHTLs) htl--;
return htl;
}
return --htl;
}
/**
* Fetch or create an CHKInsertSender for a given key/htl.
* @param key The key to be inserted.
* @param htl The current HTL. We can't coalesce inserts across
* HTL's.
* @param uid The UID of the caller's request chain, or a new
* one. This is obviously not used if there is already an
* CHKInsertSender running.
* @param source The node that sent the InsertRequest, or null
* if it originated locally.
* @param ignoreLowBackoff
* @param preferInsert
*/
public CHKInsertSender makeInsertSender(NodeCHK key, short htl, long uid, InsertTag tag, PeerNode source,
byte[] headers, PartiallyReceivedBlock prb, boolean fromStore, boolean canWriteClientCache, boolean forkOnCacheable, boolean preferInsert, boolean ignoreLowBackoff, boolean realTimeFlag) {
if(logMINOR) Logger.minor(this, "makeInsertSender("+key+ ',' +htl+ ',' +uid+ ',' +source+",...,"+fromStore);
CHKInsertSender is = null;
is = new CHKInsertSender(key, uid, tag, headers, htl, source, this, prb, fromStore, canWriteClientCache, forkOnCacheable, preferInsert, ignoreLowBackoff,realTimeFlag);
is.start();
// CHKInsertSender adds itself to insertSenders
return is;
}
/**
* Fetch or create an SSKInsertSender for a given key/htl.
* @param key The key to be inserted.
* @param htl The current HTL. We can't coalesce inserts across
* HTL's.
* @param uid The UID of the caller's request chain, or a new
* one. This is obviously not used if there is already an
* SSKInsertSender running.
* @param source The node that sent the InsertRequest, or null
* if it originated locally.
* @param ignoreLowBackoff
* @param preferInsert
*/
public SSKInsertSender makeInsertSender(SSKBlock block, short htl, long uid, InsertTag tag, PeerNode source,
boolean fromStore, boolean canWriteClientCache, boolean canWriteDatastore, boolean forkOnCacheable, boolean preferInsert, boolean ignoreLowBackoff, boolean realTimeFlag) {
NodeSSK key = block.getKey();
if(key.getPubKey() == null) {
throw new IllegalArgumentException("No pub key when inserting");
}
getPubKey.cacheKey(key.getPubKeyHash(), key.getPubKey(), false, canWriteClientCache, canWriteDatastore, false, writeLocalToDatastore);
Logger.minor(this, "makeInsertSender("+key+ ',' +htl+ ',' +uid+ ',' +source+",...,"+fromStore);
SSKInsertSender is = null;
is = new SSKInsertSender(block, uid, tag, htl, source, this, fromStore, canWriteClientCache, forkOnCacheable, preferInsert, ignoreLowBackoff, realTimeFlag);
is.start();
return is;
}
/**
* @return Some status information.
*/
public String getStatus() {
StringBuilder sb = new StringBuilder();
if (peers != null)
sb.append(peers.getStatus());
else
sb.append("No peers yet");
sb.append(tracker.getNumTransferringRequestSenders());
sb.append('\n');
return sb.toString();
}
/**
* @return TMCI peer list
*/
public String getTMCIPeerList() {
StringBuilder sb = new StringBuilder();
if (peers != null)
sb.append(peers.getTMCIPeerList());
else
sb.append("No peers yet");
return sb.toString();
}
/** Length of signature parameters R and S */
static final int SIGNATURE_PARAMETER_LENGTH = 32;
public ClientKeyBlock fetchKey(ClientKey key, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore) throws KeyVerifyException {
if(key instanceof ClientCHK)
return fetch((ClientCHK)key, canReadClientCache, canWriteClientCache, canWriteDatastore);
else if(key instanceof ClientSSK)
return fetch((ClientSSK)key, canReadClientCache, canWriteClientCache, canWriteDatastore);
else
throw new IllegalStateException("Don't know what to do with "+key);
}
public ClientKeyBlock fetch(ClientSSK clientSSK, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore) throws SSKVerifyException {
DSAPublicKey key = clientSSK.getPubKey();
if(key == null) {
key = getPubKey.getKey(clientSSK.pubKeyHash, canReadClientCache, false, null);
}
if(key == null) return null;
clientSSK.setPublicKey(key);
SSKBlock block = fetch((NodeSSK)clientSSK.getNodeKey(true), false, canReadClientCache, canWriteClientCache, canWriteDatastore, false, null);
if(block == null) {
if(logMINOR)
Logger.minor(this, "Could not find key for "+clientSSK);
return null;
}
// Move the pubkey to the top of the LRU, and fix it if it
// was corrupt.
getPubKey.cacheKey(clientSSK.pubKeyHash, key, false, canWriteClientCache, canWriteDatastore, false, writeLocalToDatastore);
return ClientSSKBlock.construct(block, clientSSK);
}
private ClientKeyBlock fetch(ClientCHK clientCHK, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore) throws CHKVerifyException {
CHKBlock block = fetch(clientCHK.getNodeCHK(), false, canReadClientCache, canWriteClientCache, canWriteDatastore, false, null);
if(block == null) return null;
return new ClientCHKBlock(block, clientCHK);
}
public void exit(int reason) {
try {
this.park();
System.out.println("Goodbye.");
System.out.println(reason);
} finally {
System.exit(reason);
}
}
public void exit(String reason){
try {
this.park();
System.out.println("Goodbye. from "+this+" ("+reason+ ')');
} finally {
System.exit(0);
}
}
/**
* Returns true if the node is shutting down.
* The packet receiver calls this for every packet, and boolean is atomic, so this method is not synchronized.
*/
public boolean isStopping() {
return isStopping;
}
/**
* Get the node into a state where it can be stopped safely
* May be called twice - once in exit (above) and then again
* from the wrapper triggered by calling System.exit(). Beware!
*/
public void park() {
synchronized(this) {
if(isStopping) return;
isStopping = true;
}
try {
Message msg = DMT.createFNPDisconnect(false, false, -1, new ShortBuffer(new byte[0]));
peers.localBroadcast(msg, true, false, peers.ctrDisconn);
} catch (Throwable t) {
try {
// E.g. if we haven't finished startup
Logger.error(this, "Failed to tell peers we are going down: "+t, t);
} catch (Throwable t1) {
// Ignore. We don't want to mess up the exit process!
}
}
config.store();
if(random instanceof PersistentRandomSource) {
((PersistentRandomSource) random).write_seed(true);
}
}
public NodeUpdateManager getNodeUpdater(){
return nodeUpdater;
}
public DarknetPeerNode[] getDarknetConnections() {
return peers.getDarknetPeers();
}
public boolean addPeerConnection(PeerNode pn) {
boolean retval = peers.addPeer(pn);
peers.writePeersUrgent(pn.isOpennet());
return retval;
}
public void removePeerConnection(PeerNode pn) {
peers.disconnectAndRemove(pn, true, false, false);
}
public void onConnectedPeer() {
if(logMINOR) Logger.minor(this, "onConnectedPeer()");
ipDetector.onConnectedPeer();
}
public int getFNPPort(){
return this.getDarknetPortNumber();
}
public boolean isOudated() {
return peers.isOutdated();
}
private Map<Integer, NodeToNodeMessageListener> n2nmListeners = new HashMap<Integer, NodeToNodeMessageListener>();
public synchronized void registerNodeToNodeMessageListener(int type, NodeToNodeMessageListener listener) {
n2nmListeners.put(type, listener);
}
/**
* Handle a received node to node message
*/
public void receivedNodeToNodeMessage(Message m, PeerNode src) {
int type = ((Integer) m.getObject(DMT.NODE_TO_NODE_MESSAGE_TYPE)).intValue();
ShortBuffer messageData = (ShortBuffer) m.getObject(DMT.NODE_TO_NODE_MESSAGE_DATA);
receivedNodeToNodeMessage(src, type, messageData, false);
}
public void receivedNodeToNodeMessage(PeerNode src, int type, ShortBuffer messageData, boolean partingMessage) {
boolean fromDarknet = src instanceof DarknetPeerNode;
NodeToNodeMessageListener listener = null;
synchronized(this) {
listener = n2nmListeners.get(type);
}
if(listener == null) {
Logger.error(this, "Unknown n2nm ID: "+type+" - discarding packet length "+messageData.getLength());
return;
}
listener.handleMessage(messageData.getData(), fromDarknet, src, type);
}
private NodeToNodeMessageListener diffNoderefListener = new NodeToNodeMessageListener() {
@Override
public void handleMessage(byte[] data, boolean fromDarknet, PeerNode src, int type) {
Logger.normal(this, "Received differential node reference node to node message from "+src.getPeer());
SimpleFieldSet fs = null;
try {
fs = new SimpleFieldSet(new String(data, "UTF-8"), false, true, false);
} catch (IOException e) {
Logger.error(this, "IOException while parsing node to node message data", e);
return;
}
if(fs.get("n2nType") != null) {
fs.removeValue("n2nType");
}
try {
src.processDiffNoderef(fs);
} catch (FSParseException e) {
Logger.error(this, "FSParseException while parsing node to node message data", e);
return;
}
}
};
private NodeToNodeMessageListener fproxyN2NMListener = new NodeToNodeMessageListener() {
@Override
public void handleMessage(byte[] data, boolean fromDarknet, PeerNode src, int type) {
if(!fromDarknet) {
Logger.error(this, "Got N2NTM from non-darknet node ?!?!?!: from "+src);
return;
}
DarknetPeerNode darkSource = (DarknetPeerNode) src;
Logger.normal(this, "Received N2NTM from '"+darkSource.getPeer()+"'");
SimpleFieldSet fs = null;
try {
fs = new SimpleFieldSet(new String(data, "UTF-8"), false, true, false);
} catch (UnsupportedEncodingException e) {
throw new Error("Impossible: JVM doesn't support UTF-8: " + e, e);
} catch (IOException e) {
Logger.error(this, "IOException while parsing node to node message data", e);
return;
}
fs.putOverwrite("n2nType", Integer.toString(type));
fs.putOverwrite("receivedTime", Long.toString(System.currentTimeMillis()));
fs.putOverwrite("receivedAs", "nodeToNodeMessage");
int fileNumber = darkSource.writeNewExtraPeerDataFile( fs, EXTRA_PEER_DATA_TYPE_N2NTM);
if( fileNumber == -1 ) {
Logger.error( this, "Failed to write N2NTM to extra peer data file for peer "+darkSource.getPeer());
}
// Keep track of the fileNumber so we can potentially delete the extra peer data file later, the file is authoritative
try {
handleNodeToNodeTextMessageSimpleFieldSet(fs, darkSource, fileNumber);
} catch (FSParseException e) {
// Shouldn't happen
throw new Error(e);
}
}
};
/**
* Handle a node to node text message SimpleFieldSet
* @throws FSParseException
*/
public void handleNodeToNodeTextMessageSimpleFieldSet(SimpleFieldSet fs, DarknetPeerNode source, int fileNumber) throws FSParseException {
if(logMINOR)
Logger.minor(this, "Got node to node message: \n"+fs);
int overallType = fs.getInt("n2nType");
fs.removeValue("n2nType");
if(overallType == Node.N2N_MESSAGE_TYPE_FPROXY) {
handleFproxyNodeToNodeTextMessageSimpleFieldSet(fs, source, fileNumber);
} else {
Logger.error(this, "Received unknown node to node message type '"+overallType+"' from "+source.getPeer());
}
}
private void handleFproxyNodeToNodeTextMessageSimpleFieldSet(SimpleFieldSet fs, DarknetPeerNode source, int fileNumber) throws FSParseException {
int type = fs.getInt("type");
if(type == Node.N2N_TEXT_MESSAGE_TYPE_USERALERT) {
source.handleFproxyN2NTM(fs, fileNumber);
} else if(type == Node.N2N_TEXT_MESSAGE_TYPE_FILE_OFFER) {
source.handleFproxyFileOffer(fs, fileNumber);
} else if(type == Node.N2N_TEXT_MESSAGE_TYPE_FILE_OFFER_ACCEPTED) {
source.handleFproxyFileOfferAccepted(fs, fileNumber);
} else if(type == Node.N2N_TEXT_MESSAGE_TYPE_FILE_OFFER_REJECTED) {
source.handleFproxyFileOfferRejected(fs, fileNumber);
} else if(type == Node.N2N_TEXT_MESSAGE_TYPE_BOOKMARK) {
source.handleFproxyBookmarkFeed(fs, fileNumber);
} else if(type == Node.N2N_TEXT_MESSAGE_TYPE_DOWNLOAD) {
source.handleFproxyDownloadFeed(fs, fileNumber);
} else {
Logger.error(this, "Received unknown fproxy node to node message sub-type '"+type+"' from "+source.getPeer());
}
}
public String getMyName() {
return myName;
}
public MessageCore getUSM() {
return usm;
}
public LocationManager getLocationManager() {
return lm;
}
public int getSwaps() {
return LocationManager.swaps;
}
public int getNoSwaps() {
return LocationManager.noSwaps;
}
public int getStartedSwaps() {
return LocationManager.startedSwaps;
}
public int getSwapsRejectedAlreadyLocked() {
return LocationManager.swapsRejectedAlreadyLocked;
}
public int getSwapsRejectedNowhereToGo() {
return LocationManager.swapsRejectedNowhereToGo;
}
public int getSwapsRejectedRateLimit() {
return LocationManager.swapsRejectedRateLimit;
}
public int getSwapsRejectedRecognizedID() {
return LocationManager.swapsRejectedRecognizedID;
}
public PeerNode[] getPeerNodes() {
return peers.myPeers();
}
public PeerNode[] getConnectedPeers() {
return peers.connectedPeers();
}
/**
* Return a peer of the node given its ip and port, name or identity, as a String
*/
public PeerNode getPeerNode(String nodeIdentifier) {
for(PeerNode pn: peers.myPeers()) {
Peer peer = pn.getPeer();
String nodeIpAndPort = "";
if(peer != null) {
nodeIpAndPort = peer.toString();
}
String identity = pn.getIdentityString();
if(pn instanceof DarknetPeerNode) {
DarknetPeerNode dpn = (DarknetPeerNode) pn;
String name = dpn.myName;
if(identity.equals(nodeIdentifier) || nodeIpAndPort.equals(nodeIdentifier) || name.equals(nodeIdentifier)) {
return pn;
}
} else {
if(identity.equals(nodeIdentifier) || nodeIpAndPort.equals(nodeIdentifier)) {
return pn;
}
}
}
return null;
}
public boolean isHasStarted() {
return hasStarted;
}
public void queueRandomReinsert(KeyBlock block) {
clientCore.queueRandomReinsert(block);
}
public String getExtraPeerDataDir() {
return extraPeerDataDir.getPath();
}
public boolean noConnectedPeers() {
return !peers.anyConnectedPeers();
}
public double getLocation() {
return lm.getLocation();
}
public double getLocationChangeSession() {
return lm.getLocChangeSession();
}
public int getAverageOutgoingSwapTime() {
return lm.getAverageSwapTime();
}
public long getSendSwapInterval() {
return lm.getSendSwapInterval();
}
public int getNumberOfRemotePeerLocationsSeenInSwaps() {
return lm.numberOfRemotePeerLocationsSeenInSwaps;
}
public boolean isAdvancedModeEnabled() {
if(clientCore == null) return false;
return clientCore.isAdvancedModeEnabled();
}
public boolean isFProxyJavascriptEnabled() {
return clientCore.isFProxyJavascriptEnabled();
}
// FIXME convert these kind of threads to Checkpointed's and implement a handler
// using the PacketSender/Ticker. Would save a few threads.
public int getNumARKFetchers() {
int x = 0;
for(PeerNode p: peers.myPeers()) {
if(p.isFetchingARK()) x++;
}
return x;
}
// FIXME put this somewhere else
private volatile Object statsSync = new Object();
/** The total number of bytes of real data i.e. payload sent by the node */
private long totalPayloadSent;
public void sentPayload(int len) {
synchronized(statsSync) {
totalPayloadSent += len;
}
}
/**
* Get the total number of bytes of payload (real data) sent by the node
*
* @return Total payload sent in bytes
*/
public long getTotalPayloadSent() {
synchronized(statsSync) {
return totalPayloadSent;
}
}
public void setName(String key) throws InvalidConfigValueException, NodeNeedRestartException {
config.get("node").getOption("name").setValue(key);
}
public Ticker getTicker() {
return ticker;
}
public int getUnclaimedFIFOSize() {
return usm.getUnclaimedFIFOSize();
}
/**
* Connect this node to another node (for purposes of testing)
*/
public void connectToSeednode(SeedServerTestPeerNode node) throws OpennetDisabledException, FSParseException, PeerParseException, ReferenceSignatureVerificationException {
peers.addPeer(node,false,false);
}
public void connect(Node node, FRIEND_TRUST trust, FRIEND_VISIBILITY visibility) throws FSParseException, PeerParseException, ReferenceSignatureVerificationException, PeerTooOldException {
peers.connect(node.darknetCrypto.exportPublicFieldSet(), darknetCrypto.packetMangler, trust, visibility);
}
public short maxHTL() {
return maxHTL;
}
public int getDarknetPortNumber() {
return darknetCrypto.portNumber;
}
public synchronized int getOutputBandwidthLimit() {
return outputBandwidthLimit;
}
public synchronized int getInputBandwidthLimit() {
if(inputLimitDefault)
return outputBandwidthLimit * 4;
return inputBandwidthLimit;
}
/**
* @return total datastore size in bytes.
*/
public synchronized long getStoreSize() {
return maxTotalDatastoreSize;
}
@Override
public synchronized void setTimeSkewDetectedUserAlert() {
if(timeSkewDetectedUserAlert == null) {
timeSkewDetectedUserAlert = new TimeSkewDetectedUserAlert();
clientCore.alerts.register(timeSkewDetectedUserAlert);
}
}
public File getNodeDir() { return nodeDir.dir(); }
public File getCfgDir() { return cfgDir.dir(); }
public File getUserDir() { return userDir.dir(); }
public File getRunDir() { return runDir.dir(); }
public File getStoreDir() { return storeDir.dir(); }
public File getPluginDir() { return pluginDir.dir(); }
public ProgramDirectory nodeDir() { return nodeDir; }
public ProgramDirectory cfgDir() { return cfgDir; }
public ProgramDirectory userDir() { return userDir; }
public ProgramDirectory runDir() { return runDir; }
public ProgramDirectory storeDir() { return storeDir; }
public ProgramDirectory pluginDir() { return pluginDir; }
public DarknetPeerNode createNewDarknetNode(SimpleFieldSet fs, FRIEND_TRUST trust, FRIEND_VISIBILITY visibility) throws FSParseException, PeerParseException, ReferenceSignatureVerificationException, PeerTooOldException {
return new DarknetPeerNode(fs, this, darknetCrypto, false, trust, visibility);
}
public OpennetPeerNode createNewOpennetNode(SimpleFieldSet fs) throws FSParseException, OpennetDisabledException, PeerParseException, ReferenceSignatureVerificationException, PeerTooOldException {
if(opennet == null) throw new OpennetDisabledException("Opennet is not currently enabled");
return new OpennetPeerNode(fs, this, opennet.crypto, opennet, false);
}
public SeedServerTestPeerNode createNewSeedServerTestPeerNode(SimpleFieldSet fs) throws FSParseException, OpennetDisabledException, PeerParseException, ReferenceSignatureVerificationException, PeerTooOldException {
if(opennet == null) throw new OpennetDisabledException("Opennet is not currently enabled");
return new SeedServerTestPeerNode(fs, this, opennet.crypto, true);
}
public OpennetPeerNode addNewOpennetNode(SimpleFieldSet fs, ConnectionType connectionType) throws FSParseException, PeerParseException, ReferenceSignatureVerificationException {
// FIXME: perhaps this should throw OpennetDisabledExcemption rather than returing false?
if(opennet == null) return null;
return opennet.addNewOpennetNode(fs, connectionType, false);
}
public byte[] getOpennetPubKeyHash() {
return opennet.crypto.ecdsaPubKeyHash;
}
public byte[] getDarknetPubKeyHash() {
return darknetCrypto.ecdsaPubKeyHash;
}
public synchronized boolean isOpennetEnabled() {
return opennet != null;
}
public SimpleFieldSet exportDarknetPublicFieldSet() {
return darknetCrypto.exportPublicFieldSet();
}
public SimpleFieldSet exportOpennetPublicFieldSet() {
return opennet.crypto.exportPublicFieldSet();
}
public SimpleFieldSet exportDarknetPrivateFieldSet() {
return darknetCrypto.exportPrivateFieldSet();
}
public SimpleFieldSet exportOpennetPrivateFieldSet() {
return opennet.crypto.exportPrivateFieldSet();
}
/**
* Should the IP detection code only use the IP address override and the bindTo information,
* rather than doing a full detection?
*/
public synchronized boolean dontDetect() {
// Only return true if bindTo is set on all ports which are in use
if(!darknetCrypto.getBindTo().isRealInternetAddress(false, true, false)) return false;
if(opennet != null) {
if(opennet.crypto.getBindTo().isRealInternetAddress(false, true, false)) return false;
}
return true;
}
public int getOpennetFNPPort() {
if(opennet == null) return -1;
return opennet.crypto.portNumber;
}
public OpennetManager getOpennet() {
return opennet;
}
public synchronized boolean passOpennetRefsThroughDarknet() {
return passOpennetRefsThroughDarknet;
}
/**
* Get the set of public ports that need to be forwarded. These are internal
* ports, not necessarily external - they may be rewritten by the NAT.
* @return A Set of ForwardPort's to be fed to port forward plugins.
*/
public Set<ForwardPort> getPublicInterfacePorts() {
HashSet<ForwardPort> set = new HashSet<ForwardPort>();
// FIXME IPv6 support
set.add(new ForwardPort("darknet", false, ForwardPort.PROTOCOL_UDP_IPV4, darknetCrypto.portNumber));
if(opennet != null) {
NodeCrypto crypto = opennet.crypto;
if(crypto != null) {
set.add(new ForwardPort("opennet", false, ForwardPort.PROTOCOL_UDP_IPV4, crypto.portNumber));
}
}
return set;
}
/**
* Get the time since the node was started in milliseconds.
*
* @return Uptime in milliseconds
*/
public long getUptime() {
return System.currentTimeMillis() - usm.getStartedTime();
}
public synchronized UdpSocketHandler[] getPacketSocketHandlers() {
// FIXME better way to get these!
if(opennet != null) {
return new UdpSocketHandler[] { darknetCrypto.socket, opennet.crypto.socket };
// TODO Auto-generated method stub
} else {
return new UdpSocketHandler[] { darknetCrypto.socket };
}
}
public int getMaxOpennetPeers() {
return maxOpennetPeers;
}
public void onAddedValidIP() {
OpennetManager om;
synchronized(this) {
om = opennet;
}
if(om != null) {
Announcer announcer = om.announcer;
if(announcer != null) {
announcer.maybeSendAnnouncement();
}
}
}
public boolean isSeednode() {
return acceptSeedConnections;
}
/**
* Returns true if the packet receiver should try to decode/process packets that are not from a peer (i.e. from a seed connection)
* The packet receiver calls this upon receiving an unrecognized packet.
*/
public boolean wantAnonAuth(boolean isOpennet) {
if(isOpennet)
return opennet != null && acceptSeedConnections;
else
return false;
}
// FIXME make this configurable
// Probably should wait until we have non-opennet anon auth so we can add it to NodeCrypto.
public boolean wantAnonAuthChangeIP(boolean isOpennet) {
return !isOpennet;
}
public boolean opennetDefinitelyPortForwarded() {
OpennetManager om;
synchronized(this) {
om = this.opennet;
}
if(om == null) return false;
NodeCrypto crypto = om.crypto;
if(crypto == null) return false;
return crypto.definitelyPortForwarded();
}
public boolean darknetDefinitelyPortForwarded() {
if(darknetCrypto == null) return false;
return darknetCrypto.definitelyPortForwarded();
}
public boolean hasKey(Key key, boolean canReadClientCache, boolean forULPR) {
// FIXME optimise!
if(key instanceof NodeCHK)
return fetch((NodeCHK)key, true, canReadClientCache, false, false, forULPR, null) != null;
else
return fetch((NodeSSK)key, true, canReadClientCache, false, false, forULPR, null) != null;
}
/**
* Warning: does not announce change in location!
*/
public void setLocation(double loc) {
lm.setLocation(loc);
}
public boolean peersWantKey(Key key) {
return failureTable.peersWantKey(key, null);
}
private SimpleUserAlert alertMTUTooSmall;
public final RequestClient nonPersistentClientBulk = new RequestClientBuilder().build();
public final RequestClient nonPersistentClientRT = new RequestClientBuilder().realTime().build();
public void setDispatcherHook(NodeDispatcherCallback cb) {
this.dispatcher.setHook(cb);
}
public boolean shallWePublishOurPeersLocation() {
return publishOurPeersLocation;
}
public boolean shallWeRouteAccordingToOurPeersLocation(int htl) {
return routeAccordingToOurPeersLocation && htl > 1;
}
/** Can be called to decrypt client.dat* etc, or can be called when switching from another
* security level to HIGH. */
public void setMasterPassword(String password, boolean inFirstTimeWizard) throws AlreadySetPasswordException, MasterKeysWrongPasswordException, MasterKeysFileSizeException, IOException {
MasterKeys k;
synchronized(this) {
if(keys == null) {
// Decrypting.
keys = MasterKeys.read(masterKeysFile, secureRandom, password);
databaseKey = keys.createDatabaseKey(secureRandom);
} else {
// Setting password when changing to HIGH from another mode.
keys.changePassword(masterKeysFile, password, secureRandom);
return;
}
k = keys;
}
setPasswordInner(k, inFirstTimeWizard);
}
private void setPasswordInner(MasterKeys keys, boolean inFirstTimeWizard) throws MasterKeysWrongPasswordException, MasterKeysFileSizeException, IOException {
MasterSecret secret = keys.getPersistentMasterSecret();
clientCore.setupMasterSecret(secret);
boolean wantClientCache = false;
boolean wantDatabase = false;
synchronized(this) {
wantClientCache = clientCacheAwaitingPassword;
wantDatabase = databaseAwaitingPassword;
databaseAwaitingPassword = false;
}
if(wantClientCache)
activatePasswordedClientCache(keys);
if(wantDatabase)
lateSetupDatabase(keys.createDatabaseKey(secureRandom));
}
private void activatePasswordedClientCache(MasterKeys keys) {
synchronized(this) {
if(clientCacheType.equals("ram")) {
System.err.println("RAM client cache cannot be passworded!");
return;
}
if(!clientCacheType.equals("salt-hash")) {
System.err.println("Unknown client cache type, cannot activate passworded store: "+clientCacheType);
return;
}
}
Runnable migrate = new MigrateOldStoreData(true);
String suffix = getStoreSuffix();
try {
initSaltHashClientCacheFS(suffix, true, keys.clientCacheMasterKey);
} catch (NodeInitException e) {
Logger.error(this, "Unable to activate passworded client cache", e);
System.err.println("Unable to activate passworded client cache: "+e);
e.printStackTrace();
return;
}
synchronized(this) {
clientCacheAwaitingPassword = false;
}
executor.execute(migrate, "Migrate data from previous store");
}
public void changeMasterPassword(String oldPassword, String newPassword, boolean inFirstTimeWizard) throws MasterKeysWrongPasswordException, MasterKeysFileSizeException, IOException, AlreadySetPasswordException {
if(securityLevels.getPhysicalThreatLevel() == PHYSICAL_THREAT_LEVEL.MAXIMUM)
Logger.error(this, "Changing password while physical threat level is at MAXIMUM???");
if(masterKeysFile.exists()) {
keys.changePassword(masterKeysFile, newPassword, secureRandom);
setPasswordInner(keys, inFirstTimeWizard);
} else {
setMasterPassword(newPassword, inFirstTimeWizard);
}
}
public static class AlreadySetPasswordException extends Exception {
final private static long serialVersionUID = -7328456475029374032L;
}
public synchronized File getMasterPasswordFile() {
return masterKeysFile;
}
boolean hasPanicked() {
return hasPanicked;
}
public void panic() {
hasPanicked = true;
clientCore.clientLayerPersister.panic();
clientCore.clientLayerPersister.killAndWaitForNotRunning();
try {
MasterKeys.killMasterKeys(getMasterPasswordFile());
} catch (IOException e) {
System.err.println("Unable to wipe master passwords key file!");
System.err.println("Please delete " + getMasterPasswordFile()
+ " to ensure that nobody can recover your old downloads.");
}
// persistent-temp will be cleaned on restart.
}
public void finishPanic() {
WrapperManager.restart();
System.exit(0);
}
public boolean awaitingPassword() {
if(clientCacheAwaitingPassword) return true;
if(databaseAwaitingPassword) return true;
return false;
}
public boolean wantEncryptedDatabase() {
return this.securityLevels.getPhysicalThreatLevel() != PHYSICAL_THREAT_LEVEL.LOW;
}
public boolean wantNoPersistentDatabase() {
return this.securityLevels.getPhysicalThreatLevel() == PHYSICAL_THREAT_LEVEL.MAXIMUM;
}
public boolean hasDatabase() {
return !clientCore.clientLayerPersister.isKilledOrNotLoaded();
}
/**
* @return canonical path of the database file in use.
*/
public String getDatabasePath() throws IOException {
return clientCore.clientLayerPersister.getWriteFilename().toString();
}
/** Should we commit the block to the store rather than the cache?
*
* <p>We used to check whether we are a sink by checking whether any peer has
* a closer location than we do. Then we made low-uptime nodes exempt from
* this calculation: if we route to a low uptime node with a closer location,
* we want to store it anyway since he may go offline. The problem was that
* if we routed to a low-uptime node, and there was another option that wasn't
* low-uptime but was closer to the target than we were, then we would not
* store in the store. Also, routing isn't always by the closest peer location:
* FOAF and per-node failure tables change it. So now, we consider the nodes
* we have actually routed to:</p>
*
* <p>Store in datastore if our location is closer to the target than:</p><ol>
* <li>the source location (if any, and ignoring if low-uptime)</li>
* <li>the locations of the nodes we just routed to (ditto)</li>
* </ol>
*
* @param key
* @param source
* @param routedTo
* @return
*/
public boolean shouldStoreDeep(Key key, PeerNode source, PeerNode[] routedTo) {
double myLoc = getLocation();
double target = key.toNormalizedDouble();
double myDist = Location.distance(myLoc, target);
// First, calculate whether we would have stored it using the old formula.
if(logMINOR) Logger.minor(this, "Should store for "+key+" ?");
// Don't sink store if any of the nodes we routed to, or our predecessor, is both high-uptime and closer to the target than we are.
if(source != null && !source.isLowUptime()) {
if(Location.distance(source, target) < myDist) {
if(logMINOR) Logger.minor(this, "Not storing because source is closer to target for "+key+" : "+source);
return false;
}
}
for(PeerNode pn : routedTo) {
if(Location.distance(pn, target) < myDist && !pn.isLowUptime()) {
if(logMINOR) Logger.minor(this, "Not storing because peer "+pn+" is closer to target for "+key+" his loc "+pn.getLocation()+" my loc "+myLoc+" target is "+target);
return false;
} else {
if(logMINOR) Logger.minor(this, "Should store maybe, peer "+pn+" loc = "+pn.getLocation()+" my loc is "+myLoc+" target is "+target+" low uptime is "+pn.isLowUptime());
}
}
if(logMINOR) Logger.minor(this, "Should store returning true for "+key+" target="+target+" myLoc="+myLoc+" peers: "+routedTo.length);
return true;
}
public boolean getWriteLocalToDatastore() {
return writeLocalToDatastore;
}
public boolean getUseSlashdotCache() {
return useSlashdotCache;
}
// FIXME remove the visibility alert after a few builds.
public void createVisibilityAlert() {
synchronized(this) {
if(showFriendsVisibilityAlert) return;
showFriendsVisibilityAlert = true;
}
// Wait until startup completed.
this.getTicker().queueTimedJob(new Runnable() {
@Override
public void run() {
config.store();
}
}, 0);
registerFriendsVisibilityAlert();
}
private UserAlert visibilityAlert = new SimpleUserAlert(true, l10n("pleaseSetPeersVisibilityAlertTitle"), l10n("pleaseSetPeersVisibilityAlert"), l10n("pleaseSetPeersVisibilityAlert"), UserAlert.ERROR) {
@Override
public void onDismiss() {
synchronized(Node.this) {
showFriendsVisibilityAlert = false;
}
config.store();
unregisterFriendsVisibilityAlert();
}
};
private void registerFriendsVisibilityAlert() {
if(clientCore == null || clientCore.alerts == null) {
// Wait until startup completed.
this.getTicker().queueTimedJob(new Runnable() {
@Override
public void run() {
registerFriendsVisibilityAlert();
}
}, 0);
return;
}
clientCore.alerts.register(visibilityAlert);
}
private void unregisterFriendsVisibilityAlert() {
clientCore.alerts.unregister(visibilityAlert);
}
public int getMinimumMTU() {
int mtu;
synchronized(this) {
mtu = maxPacketSize;
}
if(ipDetector != null) {
int detected = ipDetector.getMinimumDetectedMTU();
if(detected < mtu) return detected;
}
return mtu;
}
public void updateMTU() {
this.darknetCrypto.socket.calculateMaxPacketSize();
OpennetManager om = opennet;
if(om != null) {
om.crypto.socket.calculateMaxPacketSize();
}
}
public static boolean isTestnetEnabled() {
return false;
}
public MersenneTwister createRandom() {
byte[] buf = new byte[16];
random.nextBytes(buf);
return new MersenneTwister(buf);
}
public boolean enableNewLoadManagement(boolean realTimeFlag) {
NodeStats stats = this.nodeStats;
if(stats == null) {
Logger.error(this, "Calling enableNewLoadManagement before Node constructor completes! FIX THIS!", new Exception("error"));
return false;
}
return stats.enableNewLoadManagement(realTimeFlag);
}
/** FIXME move to Probe.java? */
public boolean enableRoutedPing() {
return enableRoutedPing;
}
public boolean updateIsUrgent() {
OpennetManager om = getOpennet();
if(om != null) {
if(om.announcer != null && om.announcer.isWaitingForUpdater())
return true;
}
if(peers.getPeerNodeStatusSize(PeerManager.PEER_NODE_STATUS_TOO_NEW, true) > PeerManager.OUTDATED_MIN_TOO_NEW_DARKNET)
return true;
return false;
}
public byte[] getPluginStoreKey(String storeIdentifier) {
DatabaseKey key;
synchronized(this) {
key = databaseKey;
}
if(key != null)
return key.getPluginStoreKey(storeIdentifier);
else
return null;
}
public PluginManager getPluginManager() {
return pluginManager;
}
DatabaseKey getDatabaseKey() {
return databaseKey;
}
}<|fim▁end|> | "Node.storeSaltHashResizeOnStart", "Node.storeSaltHashResizeOnStartLong", new BooleanCallback() { |
<|file_name|>server.go<|end_file_name|><|fim▁begin|>package main
import (
"fmt"
"log"
"net"
"os"
"github.com/kennylevinsen/g9p"
"github.com/kennylevinsen/g9ptools/fileserver"
"github.com/kennylevinsen/g9ptools/ramfs/ramtree"
)
func main() {
if len(os.Args) < 5 {
fmt.Printf("Too few arguments\n")
fmt.Printf("%s service UID GID address\n", os.Args[0])
fmt.Printf("UID and GID are the user/group that owns /\n")
return
}
service := os.Args[1]
user := os.Args[2]
group := os.Args[3]
addr := os.Args[4]
root := ramtree.NewRAMTree("/", 0777, user, group)
l, err := net.Listen("tcp", addr)
if err != nil {
log.Fatalf("Unable to listen: %v", err)<|fim▁hole|>
h := func() g9p.Handler {
m := make(map[string]fileserver.Dir)
m[service] = root
return fileserver.NewFileServer(nil, m, 10*1024*1024, fileserver.Debug)
}
log.Printf("Starting ramfs at %s", addr)
g9p.ServeListener(l, h)
}<|fim▁end|> | } |
<|file_name|>org.py<|end_file_name|><|fim▁begin|># Copyright (c) 2014-present PlatformIO <[email protected]>
#
# 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.
# pylint: disable=unused-argument
import json
import click
from tabulate import tabulate
from platformio.clients.account import AccountClient
from platformio.commands.account import validate_email, validate_username
@click.group("org", short_help="Manage Organizations")
def cli():
pass
def validate_orgname(value):
return validate_username(value, "Organization name")
@cli.command("create", short_help="Create a new organization")
@click.argument(
"orgname", callback=lambda _, __, value: validate_orgname(value),
)
@click.option(
"--email", callback=lambda _, __, value: validate_email(value) if value else value<|fim▁hole|>)
@click.option("--displayname",)
def org_create(orgname, email, displayname):
client = AccountClient()
client.create_org(orgname, email, displayname)
return click.secho(
"The organization %s has been successfully created." % orgname, fg="green",
)
@cli.command("list", short_help="List organizations")
@click.option("--json-output", is_flag=True)
def org_list(json_output):
client = AccountClient()
orgs = client.list_orgs()
if json_output:
return click.echo(json.dumps(orgs))
if not orgs:
return click.echo("You do not have any organizations")
for org in orgs:
click.echo()
click.secho(org.get("orgname"), fg="cyan")
click.echo("-" * len(org.get("orgname")))
data = []
if org.get("displayname"):
data.append(("Display Name:", org.get("displayname")))
if org.get("email"):
data.append(("Email:", org.get("email")))
data.append(
(
"Owners:",
", ".join((owner.get("username") for owner in org.get("owners"))),
)
)
click.echo(tabulate(data, tablefmt="plain"))
return click.echo()
@cli.command("update", short_help="Update organization")
@click.argument("orgname")
@click.option(
"--new-orgname", callback=lambda _, __, value: validate_orgname(value),
)
@click.option("--email")
@click.option("--displayname",)
def org_update(orgname, **kwargs):
client = AccountClient()
org = client.get_org(orgname)
del org["owners"]
new_org = org.copy()
if not any(kwargs.values()):
for field in org:
new_org[field] = click.prompt(
field.replace("_", " ").capitalize(), default=org[field]
)
if field == "email":
validate_email(new_org[field])
if field == "orgname":
validate_orgname(new_org[field])
else:
new_org.update(
{key.replace("new_", ""): value for key, value in kwargs.items() if value}
)
client.update_org(orgname, new_org)
return click.secho(
"The organization %s has been successfully updated." % orgname, fg="green",
)
@cli.command("destroy", short_help="Destroy organization")
@click.argument("orgname")
def account_destroy(orgname):
client = AccountClient()
click.confirm(
"Are you sure you want to delete the %s organization account?\n"
"Warning! All linked data will be permanently removed and can not be restored."
% orgname,
abort=True,
)
client.destroy_org(orgname)
return click.secho("Organization %s has been destroyed." % orgname, fg="green",)
@cli.command("add", short_help="Add a new owner to organization")
@click.argument("orgname",)
@click.argument("username",)
def org_add_owner(orgname, username):
client = AccountClient()
client.add_org_owner(orgname, username)
return click.secho(
"The new owner %s has been successfully added to the %s organization."
% (username, orgname),
fg="green",
)
@cli.command("remove", short_help="Remove an owner from organization")
@click.argument("orgname",)
@click.argument("username",)
def org_remove_owner(orgname, username):
client = AccountClient()
client.remove_org_owner(orgname, username)
return click.secho(
"The %s owner has been successfully removed from the %s organization."
% (username, orgname),
fg="green",
)<|fim▁end|> | |
<|file_name|>qunit.js<|end_file_name|><|fim▁begin|>/**
* QUnit v1.3.0pre - A JavaScript Unit Testing Framework
*
* http://docs.jquery.com/QUnit
*
* Copyright (c) 2011 John Resig, Jörn Zaefferer
* Dual licensed under the MIT (MIT-LICENSE.txt)
* or GPL (GPL-LICENSE.txt) licenses.
* Pulled Live from Git Sat Jan 14 01:10:01 UTC 2012
* Last Commit: 0712230bb203c262211649b32bd712ec7df5f857
*/
(function(window) {
var defined = {
setTimeout: typeof window.setTimeout !== "undefined",
sessionStorage: (function() {
try {
return !!sessionStorage.getItem;
} catch(e) {
return false;
}
})()
};
var testId = 0,
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty;
var Test = function(name, testName, expected, testEnvironmentArg, async, callback) {
this.name = name;
this.testName = testName;
this.expected = expected;
this.testEnvironmentArg = testEnvironmentArg;
this.async = async;
this.callback = callback;
this.assertions = [];
};
Test.prototype = {
init: function() {
var tests = id("qunit-tests");
if (tests) {
var b = document.createElement("strong");
b.innerHTML = "Running " + this.name;
var li = document.createElement("li");
li.appendChild( b );
li.className = "running";
li.id = this.id = "test-output" + testId++;
tests.appendChild( li );
}
},
setup: function() {
if (this.module != config.previousModule) {
if ( config.previousModule ) {
runLoggingCallbacks('moduleDone', QUnit, {
name: config.previousModule,
failed: config.moduleStats.bad,
passed: config.moduleStats.all - config.moduleStats.bad,
total: config.moduleStats.all
} );
}
config.previousModule = this.module;
config.moduleStats = { all: 0, bad: 0 };
runLoggingCallbacks( 'moduleStart', QUnit, {
name: this.module
} );
}
config.current = this;
this.testEnvironment = extend({
setup: function() {},
teardown: function() {}
}, this.moduleTestEnvironment);
if (this.testEnvironmentArg) {
extend(this.testEnvironment, this.testEnvironmentArg);
}
runLoggingCallbacks( 'testStart', QUnit, {
name: this.testName,
module: this.module
});
// allow utility functions to access the current test environment
// TODO why??
QUnit.current_testEnvironment = this.testEnvironment;
try {
if ( !config.pollution ) {
saveGlobal();
}
this.testEnvironment.setup.call(this.testEnvironment);
} catch(e) {
QUnit.ok( false, "Setup failed on " + this.testName + ": " + e.message );
}
},
run: function() {
config.current = this;
if ( this.async ) {
QUnit.stop();
}
if ( config.notrycatch ) {
this.callback.call(this.testEnvironment);
return;
}
try {
this.callback.call(this.testEnvironment);
} catch(e) {
fail("Test " + this.testName + " died, exception and test follows", e, this.callback);
QUnit.ok( false, "Died on test #" + (this.assertions.length + 1) + ": " + e.message + " - " + QUnit.jsDump.parse(e) );
// else next test will carry the responsibility
saveGlobal();
// Restart the tests if they're blocking
if ( config.blocking ) {
QUnit.start();
}
}
},
teardown: function() {
config.current = this;
try {
this.testEnvironment.teardown.call(this.testEnvironment);
checkPollution();
} catch(e) {
QUnit.ok( false, "Teardown failed on " + this.testName + ": " + e.message );
}
},
finish: function() {
config.current = this;
if ( this.expected != null && this.expected != this.assertions.length ) {
QUnit.ok( false, "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run" );
}
var good = 0, bad = 0,
tests = id("qunit-tests");
config.stats.all += this.assertions.length;
config.moduleStats.all += this.assertions.length;
if ( tests ) {
var ol = document.createElement("ol");
for ( var i = 0; i < this.assertions.length; i++ ) {
var assertion = this.assertions[i];
var li = document.createElement("li");
li.className = assertion.result ? "pass" : "fail";
li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed");
ol.appendChild( li );
if ( assertion.result ) {
good++;
} else {
bad++;
config.stats.bad++;
config.moduleStats.bad++;
}
}
// store result when possible
if ( QUnit.config.reorder && defined.sessionStorage ) {
if (bad) {
sessionStorage.setItem("qunit-" + this.module + "-" + this.testName, bad);
} else {
sessionStorage.removeItem("qunit-" + this.module + "-" + this.testName);
}
}
if (bad == 0) {
ol.style.display = "none";
}
var b = document.createElement("strong");
b.innerHTML = this.name + " <b class='counts'>(<b class='failed'>" + bad + "</b>, <b class='passed'>" + good + "</b>, " + this.assertions.length + ")</b>";
var a = document.createElement("a");
a.innerHTML = "Rerun";
a.href = QUnit.url({ filter: getText([b]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") });
addEvent(b, "click", function() {
var next = b.nextSibling.nextSibling,
display = next.style.display;
next.style.display = display === "none" ? "block" : "none";
});
addEvent(b, "dblclick", function(e) {
var target = e && e.target ? e.target : window.event.srcElement;
if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) {
target = target.parentNode;
}
if ( window.location && target.nodeName.toLowerCase() === "strong" ) {
window.location = QUnit.url({ filter: getText([target]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") });
}
});
var li = id(this.id);
li.className = bad ? "fail" : "pass";
li.removeChild( li.firstChild );
li.appendChild( b );
li.appendChild( a );
li.appendChild( ol );
} else {
for ( var i = 0; i < this.assertions.length; i++ ) {
if ( !this.assertions[i].result ) {
bad++;
config.stats.bad++;
config.moduleStats.bad++;
}
}
}
try {
QUnit.reset();
} catch(e) {
fail("reset() failed, following Test " + this.testName + ", exception and reset fn follows", e, QUnit.reset);
}
runLoggingCallbacks( 'testDone', QUnit, {
name: this.testName,
module: this.module,
failed: bad,
passed: this.assertions.length - bad,
total: this.assertions.length
} );
},
queue: function() {
var test = this;
synchronize(function() {
test.init();
});
function run() {
// each of these can by async
synchronize(function() {
test.setup();
});
synchronize(function() {
test.run();
});
synchronize(function() {
test.teardown();
});
synchronize(function() {
test.finish();
});
}
// defer when previous test run passed, if storage is available
var bad = QUnit.config.reorder && defined.sessionStorage && +sessionStorage.getItem("qunit-" + this.module + "-" + this.testName);
if (bad) {
run();
} else {
synchronize(run, true);
};
}
};
var QUnit = {
// call on start of module test to prepend name to all tests
module: function(name, testEnvironment) {
config.currentModule = name;
config.currentModuleTestEnviroment = testEnvironment;
},
asyncTest: function(testName, expected, callback) {
if ( arguments.length === 2 ) {
callback = expected;
expected = null;
}
QUnit.test(testName, expected, callback, true);
},
test: function(testName, expected, callback, async) {
var name = '<span class="test-name">' + escapeInnerText(testName) + '</span>', testEnvironmentArg;
if ( arguments.length === 2 ) {
callback = expected;
expected = null;
}
// is 2nd argument a testEnvironment?
if ( expected && typeof expected === 'object') {
testEnvironmentArg = expected;
expected = null;
}
if ( config.currentModule ) {
name = '<span class="module-name">' + config.currentModule + "</span>: " + name;
}
if ( !validTest(config.currentModule + ": " + testName) ) {
return;
}
var test = new Test(name, testName, expected, testEnvironmentArg, async, callback);
test.module = config.currentModule;
test.moduleTestEnvironment = config.currentModuleTestEnviroment;
test.queue();
},
/**
* Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
*/
expect: function(asserts) {
config.current.expected = asserts;
},
/**
* Asserts true.
* @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
*/
ok: function(a, msg) {
a = !!a;
var details = {
result: a,
message: msg
};
msg = escapeInnerText(msg);
runLoggingCallbacks( 'log', QUnit, details );
config.current.assertions.push({
result: a,
message: msg
});
},
/**
* Checks that the first two arguments are equal, with an optional message.
* Prints out both actual and expected values.
*
* Prefered to ok( actual == expected, message )
*
* @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." );
*
* @param Object actual
* @param Object expected
* @param String message (optional)
*/
equal: function(actual, expected, message) {
QUnit.push(expected == actual, actual, expected, message);
},
notEqual: function(actual, expected, message) {
QUnit.push(expected != actual, actual, expected, message);
},
deepEqual: function(actual, expected, message) {
QUnit.push(QUnit.equiv(actual, expected), actual, expected, message);
},
notDeepEqual: function(actual, expected, message) {
QUnit.push(!QUnit.equiv(actual, expected), actual, expected, message);
},
strictEqual: function(actual, expected, message) {
QUnit.push(expected === actual, actual, expected, message);
},
notStrictEqual: function(actual, expected, message) {
QUnit.push(expected !== actual, actual, expected, message);
},
raises: function(block, expected, message) {
var actual, ok = false;
if (typeof expected === 'string') {
message = expected;
expected = null;
}
try {
block();
} catch (e) {
actual = e;
}
if (actual) {
// we don't want to validate thrown error
if (!expected) {
ok = true;
// expected is a regexp
} else if (QUnit.objectType(expected) === "regexp") {
ok = expected.test(actual);
// expected is a constructor
} else if (actual instanceof expected) {
ok = true;
// expected is a validation function which returns true is validation passed
} else if (expected.call({}, actual) === true) {
ok = true;
}
}
QUnit.ok(ok, message);
},
start: function(count) {
config.semaphore -= count || 1;
if (config.semaphore > 0) {
// don't start until equal number of stop-calls
return;
}
if (config.semaphore < 0) {
// ignore if start is called more often then stop
config.semaphore = 0;
}
// A slight delay, to avoid any current callbacks
if ( defined.setTimeout ) {
window.setTimeout(function() {
if (config.semaphore > 0) {
return;
}
if ( config.timeout ) {
clearTimeout(config.timeout);
}
config.blocking = false;
process(true);
}, 13);
} else {
config.blocking = false;
process(true);
}
},
stop: function(count) {
config.semaphore += count || 1;
config.blocking = true;
if ( config.testTimeout && defined.setTimeout ) {
clearTimeout(config.timeout);
config.timeout = window.setTimeout(function() {
QUnit.ok( false, "Test timed out" );
config.semaphore = 1;
QUnit.start();
}, config.testTimeout);
}
}
};
//We want access to the constructor's prototype
(function() {
function F(){};
F.prototype = QUnit;
QUnit = new F();
//Make F QUnit's constructor so that we can add to the prototype later
QUnit.constructor = F;
})();
// Backwards compatibility, deprecated
QUnit.equals = QUnit.equal;
QUnit.same = QUnit.deepEqual;
// Maintain internal state
var config = {
// The queue of tests to run
queue: [],
// block until document ready
blocking: true,
// when enabled, show only failing tests
// gets persisted through sessionStorage and can be changed in UI via checkbox
hidepassed: false,
// by default, run previously failed tests first
// very useful in combination with "Hide passed tests" checked
reorder: true,
// by default, modify document.title when suite is done
altertitle: true,
urlConfig: ['noglobals', 'notrycatch'],
//logging callback queues
begin: [],
done: [],
log: [],
testStart: [],
testDone: [],
moduleStart: [],
moduleDone: []
};
// Load paramaters
(function() {
var location = window.location || { search: "", protocol: "file:" },
params = location.search.slice( 1 ).split( "&" ),
length = params.length,
urlParams = {},
current;
if ( params[ 0 ] ) {
for ( var i = 0; i < length; i++ ) {
current = params[ i ].split( "=" );
current[ 0 ] = decodeURIComponent( current[ 0 ] );
// allow just a key to turn on a flag, e.g., test.html?noglobals
current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true;
urlParams[ current[ 0 ] ] = current[ 1 ];
}
}
QUnit.urlParams = urlParams;
config.filter = urlParams.filter;
// Figure out if we're running the tests from a server or not
QUnit.isLocal = !!(location.protocol === 'file:');
})();
// Expose the API as global variables, unless an 'exports'
// object exists, in that case we assume we're in CommonJS
if ( typeof exports === "undefined" || typeof require === "undefined" ) {
extend(window, QUnit);
window.QUnit = QUnit;
} else {
extend(exports, QUnit);
exports.QUnit = QUnit;
}
// define these after exposing globals to keep them in these QUnit namespace only
extend(QUnit, {
config: config,
// Initialize the configuration options
init: function() {
extend(config, {
stats: { all: 0, bad: 0 },
moduleStats: { all: 0, bad: 0 },
started: +new Date,
updateRate: 1000,
blocking: false,
autostart: true,
autorun: false,
filter: "",
queue: [],
semaphore: 0
});
var tests = id( "qunit-tests" ),
banner = id( "qunit-banner" ),
result = id( "qunit-testresult" );
if ( tests ) {
tests.innerHTML = "";
}
if ( banner ) {
banner.className = "";
}
if ( result ) {
result.parentNode.removeChild( result );
}
if ( tests ) {
result = document.createElement( "p" );
result.id = "qunit-testresult";
result.className = "result";
tests.parentNode.insertBefore( result, tests );
result.innerHTML = 'Running...<br/> ';
}
},
/**
* Resets the test setup. Useful for tests that modify the DOM.
*
* If jQuery is available, uses jQuery's html(), otherwise just innerHTML.
*/
reset: function() {
if ( window.jQuery ) {
jQuery( "#qunit-fixture" ).html( config.fixture );
} else {
var main = id( 'qunit-fixture' );
if ( main ) {
main.innerHTML = config.fixture;
}
}
},
/**
* Trigger an event on an element.
*
* @example triggerEvent( document.body, "click" );
*
* @param DOMElement elem
* @param String type
*/
triggerEvent: function( elem, type, event ) {
if ( document.createEvent ) {
event = document.createEvent("MouseEvents");
event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
elem.dispatchEvent( event );
} else if ( elem.fireEvent ) {
elem.fireEvent("on"+type);
}
},
// Safe object type checking
is: function( type, obj ) {
return QUnit.objectType( obj ) == type;
},
objectType: function( obj ) {
if (typeof obj === "undefined") {
return "undefined";
// consider: typeof null === object
}
if (obj === null) {
return "null";
}
var type = toString.call( obj ).match(/^\[object\s(.*)\]$/)[1] || '';
switch (type) {
case 'Number':
if (isNaN(obj)) {
return "nan";
} else {
return "number";
}
case 'String':
case 'Boolean':
case 'Array':
case 'Date':
case 'RegExp':
case 'Function':
return type.toLowerCase();
}
if (typeof obj === "object") {
return "object";
}
return undefined;
},
push: function(result, actual, expected, message) {
var details = {
result: result,
message: message,
actual: actual,
expected: expected
};
message = escapeInnerText(message) || (result ? "okay" : "failed");
message = '<span class="test-message">' + message + "</span>";
expected = escapeInnerText(QUnit.jsDump.parse(expected));
actual = escapeInnerText(QUnit.jsDump.parse(actual));
var output = message + '<table><tr class="test-expected"><th>Expected: </th><td><pre>' + expected + '</pre></td></tr>';
if (actual != expected) {
output += '<tr class="test-actual"><th>Result: </th><td><pre>' + actual + '</pre></td></tr>';
output += '<tr class="test-diff"><th>Diff: </th><td><pre>' + QUnit.diff(expected, actual) +'</pre></td></tr>';
}
if (!result) {
var source = sourceFromStacktrace();
if (source) {
details.source = source;
output += '<tr class="test-source"><th>Source: </th><td><pre>' + escapeInnerText(source) + '</pre></td></tr>';
}
}
output += "</table>";
runLoggingCallbacks( 'log', QUnit, details );
config.current.assertions.push({
result: !!result,
message: output
});
},
url: function( params ) {
params = extend( extend( {}, QUnit.urlParams ), params );
var querystring = "?",
key;
for ( key in params ) {
if ( !hasOwn.call( params, key ) ) {
continue;
}
querystring += encodeURIComponent( key ) + "=" +
encodeURIComponent( params[ key ] ) + "&";
}
return window.location.pathname + querystring.slice( 0, -1 );
},
extend: extend,
id: id,
addEvent: addEvent
});
//QUnit.constructor is set to the empty F() above so that we can add to it's prototype later
//Doing this allows us to tell if the following methods have been overwritten on the actual
//QUnit object, which is a deprecated way of using the callbacks.
extend(QUnit.constructor.prototype, {
// Logging callbacks; all receive a single argument with the listed properties
// run test/logs.html for any related changes
begin: registerLoggingCallback('begin'),
// done: { failed, passed, total, runtime }
done: registerLoggingCallback('done'),
// log: { result, actual, expected, message }
log: registerLoggingCallback('log'),
// testStart: { name }
testStart: registerLoggingCallback('testStart'),
// testDone: { name, failed, passed, total }
testDone: registerLoggingCallback('testDone'),
// moduleStart: { name }
moduleStart: registerLoggingCallback('moduleStart'),
// moduleDone: { name, failed, passed, total }
moduleDone: registerLoggingCallback('moduleDone')
});
if ( typeof document === "undefined" || document.readyState === "complete" ) {
config.autorun = true;
}
QUnit.load = function() {
runLoggingCallbacks( 'begin', QUnit, {} );
// Initialize the config, saving the execution queue
var oldconfig = extend({}, config);
QUnit.init();
extend(config, oldconfig);
config.blocking = false;
var urlConfigHtml = '', len = config.urlConfig.length;
for ( var i = 0, val; i < len, val = config.urlConfig[i]; i++ ) {
config[val] = QUnit.urlParams[val];
urlConfigHtml += '<label><input name="' + val + '" type="checkbox"' + ( config[val] ? ' checked="checked"' : '' ) + '>' + val + '</label>';
}
var userAgent = id("qunit-userAgent");
if ( userAgent ) {
userAgent.innerHTML = navigator.userAgent;
}
var banner = id("qunit-header");
if ( banner ) {
banner.innerHTML = '<a href="' + QUnit.url({ filter: undefined }) + '"> ' + banner.innerHTML + '</a> ' + urlConfigHtml;
addEvent( banner, "change", function( event ) {
var params = {};
params[ event.target.name ] = event.target.checked ? true : undefined;
window.location = QUnit.url( params );
});
}
var toolbar = id("qunit-testrunner-toolbar");
if ( toolbar ) {
var filter = document.createElement("input");
filter.type = "checkbox";
filter.id = "qunit-filter-pass";
addEvent( filter, "click", function() {
var ol = document.getElementById("qunit-tests");
if ( filter.checked ) {
ol.className = ol.className + " hidepass";
} else {
var tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " ";
ol.className = tmp.replace(/ hidepass /, " ");
}
if ( defined.sessionStorage ) {
if (filter.checked) {
sessionStorage.setItem("qunit-filter-passed-tests", "true");
} else {
sessionStorage.removeItem("qunit-filter-passed-tests");
}
}
});
if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem("qunit-filter-passed-tests") ) {
filter.checked = true;
var ol = document.getElementById("qunit-tests");
ol.className = ol.className + " hidepass";
}
toolbar.appendChild( filter );
var label = document.createElement("label");
label.setAttribute("for", "qunit-filter-pass");
label.innerHTML = "Hide passed tests";
toolbar.appendChild( label );
}
var main = id('qunit-fixture');
if ( main ) {
config.fixture = main.innerHTML;
}
if (config.autostart) {
QUnit.start();
}
};
addEvent(window, "load", QUnit.load);
// addEvent(window, "error") gives us a useless event object
window.onerror = function( message, file, line ) {
if ( QUnit.config.current ) {
ok( false, message + ", " + file + ":" + line );
} else {
test( "global failure", function() {
ok( false, message + ", " + file + ":" + line );
});
}
};
function done() {
config.autorun = true;
// Log the last module results
if ( config.currentModule ) {
runLoggingCallbacks( 'moduleDone', QUnit, {
name: config.currentModule,
failed: config.moduleStats.bad,
passed: config.moduleStats.all - config.moduleStats.bad,
total: config.moduleStats.all
} );
}
var banner = id("qunit-banner"),
tests = id("qunit-tests"),
runtime = +new Date - config.started,
passed = config.stats.all - config.stats.bad,
html = [
'Tests completed in ',
runtime,
' milliseconds.<br/>',
'<span class="passed">',
passed,
'</span> tests of <span class="total">',
config.stats.all,
'</span> passed, <span class="failed">',
config.stats.bad,
'</span> failed.'
].join('');
if ( banner ) {
banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass");
}
if ( tests ) {
id( "qunit-testresult" ).innerHTML = html;
}
if ( config.altertitle && typeof document !== "undefined" && document.title ) {
// show ✖ for good, ✔ for bad suite result in title
// use escape sequences in case file gets loaded with non-utf-8-charset
document.title = [
(config.stats.bad ? "\u2716" : "\u2714"),
document.title.replace(/^[\u2714\u2716] /i, "")
].join(" ");
}
runLoggingCallbacks( 'done', QUnit, {
failed: config.stats.bad,
passed: passed,
total: config.stats.all,
runtime: runtime
} );
}
function validTest( name ) {
var filter = config.filter,
run = false;
if ( !filter ) {
return true;
}
var not = filter.charAt( 0 ) === "!";
if ( not ) {
filter = filter.slice( 1 );
}
if ( name.indexOf( filter ) !== -1 ) {
return !not;
}
if ( not ) {
run = true;
}
return run;
}
// so far supports only Firefox, Chrome and Opera (buggy)
// could be extended in the future to use something like https://github.com/csnover/TraceKit
function sourceFromStacktrace() {
try {
throw new Error();
} catch ( e ) {
if (e.stacktrace) {
// Opera
return e.stacktrace.split("\n")[6];
} else if (e.stack) {
// Firefox, Chrome
return e.stack.split("\n")[4];
} else if (e.sourceURL) {
// Safari, PhantomJS
// TODO sourceURL points at the 'throw new Error' line above, useless
//return e.sourceURL + ":" + e.line;
}
}
}
function escapeInnerText(s) {
if (!s) {
return "";
}
s = s + "";
return s.replace(/[\&<>]/g, function(s) {
switch(s) {
case "&": return "&";
case "<": return "<";
case ">": return ">";
default: return s;
}
});
}
function synchronize( callback, last ) {
config.queue.push( callback );
if ( config.autorun && !config.blocking ) {
process(last);
}
}
function process( last ) {
var start = new Date().getTime();
config.depth = config.depth ? config.depth + 1 : 1;
while ( config.queue.length && !config.blocking ) {
if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) {
config.queue.shift()();
} else {
window.setTimeout( function(){
process( last );
}, 13 );
break;
}
}
config.depth--;
if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) {
done();
}
}
function saveGlobal() {
config.pollution = [];
if ( config.noglobals ) {
for ( var key in window ) {
if ( !hasOwn.call( window, key ) ) {
continue;
}
config.pollution.push( key );
}
}
}
function checkPollution( name ) {
var old = config.pollution;
saveGlobal();
var newGlobals = diff( config.pollution, old );
if ( newGlobals.length > 0 ) {
ok( false, "Introduced global variable(s): " + newGlobals.join(", ") );
}
var deletedGlobals = diff( old, config.pollution );
if ( deletedGlobals.length > 0 ) {
ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") );
}
}
// returns a new Array with the elements that are in a but not in b
function diff( a, b ) {
var result = a.slice();
for ( var i = 0; i < result.length; i++ ) {
for ( var j = 0; j < b.length; j++ ) {
if ( result[i] === b[j] ) {
result.splice(i, 1);
i--;
break;
}
}
}
return result;
}
function fail(message, exception, callback) {
if ( typeof console !== "undefined" && console.error && console.warn ) {
console.error(message);
console.error(exception);
console.error(exception.stack);
console.warn(callback.toString());
} else if ( window.opera && opera.postError ) {
opera.postError(message, exception, callback.toString);
}
}
function extend(a, b) {
for ( var prop in b ) {
if ( b[prop] === undefined ) {
delete a[prop];
// Avoid "Member not found" error in IE8 caused by setting window.constructor
} else if ( prop !== "constructor" || a !== window ) {
a[prop] = b[prop];
}
}
return a;
}
function addEvent(elem, type, fn) {
if ( elem.addEventListener ) {
elem.addEventListener( type, fn, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, fn );
} else {
fn();
}
}
function id(name) {
return !!(typeof document !== "undefined" && document && document.getElementById) &&
document.getElementById( name );
}
function registerLoggingCallback(key){
return function(callback){
config[key].push( callback );
};
}
// Supports deprecated method of completely overwriting logging callbacks
function runLoggingCallbacks(key, scope, args) {
//debugger;
var callbacks;
if ( QUnit.hasOwnProperty(key) ) {
QUnit[key].call(scope, args);
} else {
callbacks = config[key];
for( var i = 0; i < callbacks.length; i++ ) {
callbacks[i].call( scope, args );
}
}
}
// Test for equality any JavaScript type.
// Author: Philippe Rathé <[email protected]>
QUnit.equiv = function () {
var innerEquiv; // the real equiv function
var callers = []; // stack to decide between skip/abort functions
var parents = []; // stack to avoiding loops from circular referencing
// Call the o related callback with the given arguments.
function bindCallbacks(o, callbacks, args) {
var prop = QUnit.objectType(o);
if (prop) {
if (QUnit.objectType(callbacks[prop]) === "function") {
return callbacks[prop].apply(callbacks, args);
} else {
return callbacks[prop]; // or undefined
}
}
}
var getProto = Object.getPrototypeOf || function (obj) {
return obj.__proto__;
};
var callbacks = function () {
// for string, boolean, number and null
function useStrictEquality(b, a) {
if (b instanceof a.constructor || a instanceof b.constructor) {
// to catch short annotaion VS 'new' annotation of a
// declaration
// e.g. var i = 1;
// var j = new Number(1);
return a == b;
} else {
return a === b;
}
}
return {
"string" : useStrictEquality,
"boolean" : useStrictEquality,
"number" : useStrictEquality,
"null" : useStrictEquality,
"undefined" : useStrictEquality,
"nan" : function(b) {
return isNaN(b);
},
"date" : function(b, a) {
return QUnit.objectType(b) === "date"
&& a.valueOf() === b.valueOf();
},
"regexp" : function(b, a) {
return QUnit.objectType(b) === "regexp"
&& a.source === b.source && // the regex itself
a.global === b.global && // and its modifers
// (gmi) ...
a.ignoreCase === b.ignoreCase
&& a.multiline === b.multiline;
},
// - skip when the property is a method of an instance (OOP)
// - abort otherwise,
// initial === would have catch identical references anyway
"function" : function() {
var caller = callers[callers.length - 1];
return caller !== Object && typeof caller !== "undefined";
},
"array" : function(b, a) {
var i, j, loop;
var len;
// b could be an object literal here
if (!(QUnit.objectType(b) === "array")) {
return false;
}
len = a.length;
if (len !== b.length) { // safe and faster
return false;
}
// track reference to avoid circular references
parents.push(a);
for (i = 0; i < len; i++) {
loop = false;
for (j = 0; j < parents.length; j++) {
if (parents[j] === a[i]) {
loop = true;// dont rewalk array
}
}
if (!loop && !innerEquiv(a[i], b[i])) {
parents.pop();
return false;
}
}
parents.pop();
return true;
},
"object" : function(b, a) {
var i, j, loop;
var eq = true; // unless we can proove it
var aProperties = [], bProperties = []; // collection of
// strings
// comparing constructors is more strict than using
// instanceof
if (a.constructor !== b.constructor) {
// Allow objects with no prototype to be equivalent to
// objects with Object as their constructor.
if (!((getProto(a) === null && getProto(b) === Object.prototype) ||
(getProto(b) === null && getProto(a) === Object.prototype)))
{
return false;
}
}
// stack constructor before traversing properties
callers.push(a.constructor);
// track reference to avoid circular references
parents.push(a);
for (i in a) { // be strict: don't ensures hasOwnProperty
// and go deep
loop = false;
for (j = 0; j < parents.length; j++) {
if (parents[j] === a[i])
loop = true; // don't go down the same path
// twice
}
aProperties.push(i); // collect a's properties
if (!loop && !innerEquiv(a[i], b[i])) {
eq = false;
break;
}
}
callers.pop(); // unstack, we are done
parents.pop();
for (i in b) {
bProperties.push(i); // collect b's properties
}
// Ensures identical properties name
return eq
&& innerEquiv(aProperties.sort(), bProperties
.sort());
}
};
}();
innerEquiv = function() { // can take multiple arguments
var args = Array.prototype.slice.apply(arguments);
if (args.length < 2) {
return true; // end transition
}
return (function(a, b) {
if (a === b) {
return true; // catch the most you can
} else if (a === null || b === null || typeof a === "undefined"
|| typeof b === "undefined"
|| QUnit.objectType(a) !== QUnit.objectType(b)) {
return false; // don't lose time with error prone cases
} else {
return bindCallbacks(a, callbacks, [ b, a ]);
}
// apply transition with (1..n) arguments
})(args[0], args[1])
&& arguments.callee.apply(this, args.splice(1,
args.length - 1));
};
return innerEquiv;
}();
/**
* jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com |
* http://flesler.blogspot.com Licensed under BSD
* (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008
*
* @projectDescription Advanced and extensible data dumping for Javascript.
* @version 1.0.0
* @author Ariel Flesler
* @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html}
*/
QUnit.jsDump = (function() {
function quote( str ) {
return '"' + str.toString().replace(/"/g, '\\"') + '"';
};
function literal( o ) {
return o + '';
};
function join( pre, arr, post ) {
var s = jsDump.separator(),
base = jsDump.indent(),
inner = jsDump.indent(1);
if ( arr.join )
arr = arr.join( ',' + s + inner );
if ( !arr )
return pre + post;
return [ pre, inner + arr, base + post ].join(s);
};
function array( arr, stack ) {
var i = arr.length, ret = Array(i);
this.up();
while ( i-- )
ret[i] = this.parse( arr[i] , undefined , stack);
this.down();
return join( '[', ret, ']' );
};
var reName = /^function (\w+)/;
var jsDump = {
parse:function( obj, type, stack ) { //type is used mostly internally, you can fix a (custom)type in advance
stack = stack || [ ];
var parser = this.parsers[ type || this.typeOf(obj) ];
type = typeof parser;
var inStack = inArray(obj, stack);
if (inStack != -1) {
return 'recursion('+(inStack - stack.length)+')';
}
//else
if (type == 'function') {
stack.push(obj);
var res = parser.call( this, obj, stack );
stack.pop();
return res;
}
// else
return (type == 'string') ? parser : this.parsers.error;
},
typeOf:function( obj ) {
var type;
if ( obj === null ) {
type = "null";
} else if (typeof obj === "undefined") {
type = "undefined";
} else if (QUnit.is("RegExp", obj)) {
type = "regexp";
} else if (QUnit.is("Date", obj)) {
type = "date";
} else if (QUnit.is("Function", obj)) {
type = "function";
} else if (typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined") {
type = "window";
} else if (obj.nodeType === 9) {
type = "document";
} else if (obj.nodeType) {
type = "node";
} else if (
// native arrays
toString.call( obj ) === "[object Array]" ||
// NodeList objects
( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) )
) {
type = "array";
} else {
type = typeof obj;
}
return type;
},
separator:function() {
return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? ' ' : ' ';
},
indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing
if ( !this.multiline )
return '';
var chr = this.indentChar;
if ( this.HTML )
chr = chr.replace(/\t/g,' ').replace(/ /g,' ');
return Array( this._depth_ + (extra||0) ).join(chr);
},
up:function( a ) {
this._depth_ += a || 1;
},
down:function( a ) {
this._depth_ -= a || 1;
},
setParser:function( name, parser ) {
this.parsers[name] = parser;
},
// The next 3 are exposed so you can use them
quote:quote,
literal:literal,
join:join,
//
_depth_: 1,
// This is the list of parsers, to modify them, use jsDump.setParser
parsers:{
window: '[Window]',
document: '[Document]',
error:'[ERROR]', //when no parser is found, shouldn't happen
unknown: '[Unknown]',
'null':'null',
'undefined':'undefined',
'function':function( fn ) {
var ret = 'function',
name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE
if ( name )
ret += ' ' + name;
ret += '(';
ret = [ ret, QUnit.jsDump.parse( fn, 'functionArgs' ), '){'].join('');
return join( ret, QUnit.jsDump.parse(fn,'functionCode'), '}' );
},
array: array,
nodelist: array,
arguments: array,
object:function( map, stack ) {
var ret = [ ];
QUnit.jsDump.up();
for ( var key in map ) {
var val = map[key];
ret.push( QUnit.jsDump.parse(key,'key') + ': ' + QUnit.jsDump.parse(val, undefined, stack));
}
QUnit.jsDump.down();
return join( '{', ret, '}' );
},
node:function( node ) {
var open = QUnit.jsDump.HTML ? '<' : '<',
close = QUnit.jsDump.HTML ? '>' : '>';
var tag = node.nodeName.toLowerCase(),
ret = open + tag;
for ( var a in QUnit.jsDump.DOMAttrs ) {
var val = node[QUnit.jsDump.DOMAttrs[a]];
if ( val )
ret += ' ' + a + '=' + QUnit.jsDump.parse( val, 'attribute' );
}
return ret + close + open + '/' + tag + close;
},
functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function
var l = fn.length;
if ( !l ) return '';
var args = Array(l);
while ( l-- )
args[l] = String.fromCharCode(97+l);//97 is 'a'
return ' ' + args.join(', ') + ' ';
},
key:quote, //object calls it internally, the key part of an item in a map
functionCode:'[code]', //function calls it internally, it's the content of the function
attribute:quote, //node calls it internally, it's an html attribute value
string:quote,
date:quote,
regexp:literal, //regex
number:literal,
'boolean':literal
},
DOMAttrs:{//attributes to dump from nodes, name=>realName
id:'id',
name:'name',
'class':'className'
},
HTML:false,//if true, entities are escaped ( <, >, \t, space and \n )
indentChar:' ',//indentation unit
multiline:true //if true, items in a collection, are separated by a \n, else just a space.
};
return jsDump;
})();
// from Sizzle.js
function getText( elems ) {
var ret = "", elem;
for ( var i = 0; elems[i]; i++ ) {
elem = elems[i];
// Get the text from text nodes and CDATA nodes
if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
ret += elem.nodeValue;
// Traverse everything else, except comment nodes
} else if ( elem.nodeType !== 8 ) {
ret += getText( elem.childNodes );
}
}
return ret;
};
//from jquery.js
function inArray( elem, array ) {
if ( array.indexOf ) {
return array.indexOf( elem );
}
for ( var i = 0, length = array.length; i < length; i++ ) {
if ( array[ i ] === elem ) {
return i;
}<|fim▁hole|>
return -1;
}
/*
* Javascript Diff Algorithm
* By John Resig (http://ejohn.org/)
* Modified by Chu Alan "sprite"
*
* Released under the MIT license.
*
* More Info:
* http://ejohn.org/projects/javascript-diff-algorithm/
*
* Usage: QUnit.diff(expected, actual)
*
* QUnit.diff("the quick brown fox jumped over", "the quick fox jumps over") == "the quick <del>brown </del> fox <del>jumped </del><ins>jumps </ins> over"
*/
QUnit.diff = (function() {
function diff(o, n) {
var ns = {};
var os = {};
for (var i = 0; i < n.length; i++) {
if (ns[n[i]] == null)
ns[n[i]] = {
rows: [],
o: null
};
ns[n[i]].rows.push(i);
}
for (var i = 0; i < o.length; i++) {
if (os[o[i]] == null)
os[o[i]] = {
rows: [],
n: null
};
os[o[i]].rows.push(i);
}
for (var i in ns) {
if ( !hasOwn.call( ns, i ) ) {
continue;
}
if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) {
n[ns[i].rows[0]] = {
text: n[ns[i].rows[0]],
row: os[i].rows[0]
};
o[os[i].rows[0]] = {
text: o[os[i].rows[0]],
row: ns[i].rows[0]
};
}
}
for (var i = 0; i < n.length - 1; i++) {
if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null &&
n[i + 1] == o[n[i].row + 1]) {
n[i + 1] = {
text: n[i + 1],
row: n[i].row + 1
};
o[n[i].row + 1] = {
text: o[n[i].row + 1],
row: i + 1
};
}
}
for (var i = n.length - 1; i > 0; i--) {
if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null &&
n[i - 1] == o[n[i].row - 1]) {
n[i - 1] = {
text: n[i - 1],
row: n[i].row - 1
};
o[n[i].row - 1] = {
text: o[n[i].row - 1],
row: i - 1
};
}
}
return {
o: o,
n: n
};
}
return function(o, n) {
o = o.replace(/\s+$/, '');
n = n.replace(/\s+$/, '');
var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/));
var str = "";
var oSpace = o.match(/\s+/g);
if (oSpace == null) {
oSpace = [" "];
}
else {
oSpace.push(" ");
}
var nSpace = n.match(/\s+/g);
if (nSpace == null) {
nSpace = [" "];
}
else {
nSpace.push(" ");
}
if (out.n.length == 0) {
for (var i = 0; i < out.o.length; i++) {
str += '<del>' + out.o[i] + oSpace[i] + "</del>";
}
}
else {
if (out.n[0].text == null) {
for (n = 0; n < out.o.length && out.o[n].text == null; n++) {
str += '<del>' + out.o[n] + oSpace[n] + "</del>";
}
}
for (var i = 0; i < out.n.length; i++) {
if (out.n[i].text == null) {
str += '<ins>' + out.n[i] + nSpace[i] + "</ins>";
}
else {
var pre = "";
for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) {
pre += '<del>' + out.o[n] + oSpace[n] + "</del>";
}
str += " " + out.n[i].text + nSpace[i] + pre;
}
}
}
return str;
};
})();
})(this);<|fim▁end|> | } |
<|file_name|>DtoImpl.java<|end_file_name|><|fim▁begin|>/*******************************************************************************
* Copyright (c) 2012-2014 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.dto.generator;
import org.eclipse.che.dto.shared.CompactJsonDto;
import org.eclipse.che.dto.shared.DTO;
import org.eclipse.che.dto.shared.DelegateTo;
import org.eclipse.che.dto.shared.JsonFieldName;
import org.eclipse.che.dto.shared.SerializationIndex;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** Abstract base class for the source generating template for a single DTO. */
abstract class DtoImpl {
protected static final String COPY_JSONS_PARAM = "copyJsons";
private final Class<?> dtoInterface;
private final DtoTemplate enclosingTemplate;
private final boolean compactJson;
private final String implClassName;
private final List<Method> dtoMethods;
DtoImpl(DtoTemplate enclosingTemplate, Class<?> dtoInterface) {
this.enclosingTemplate = enclosingTemplate;
this.dtoInterface = dtoInterface;
this.implClassName = dtoInterface.getSimpleName() + "Impl";
this.compactJson = DtoTemplate.implementsInterface(dtoInterface, CompactJsonDto.class);
this.dtoMethods = ImmutableList.copyOf(calcDtoMethods());
}
protected boolean isCompactJson() {
return compactJson;
}
public Class<?> getDtoInterface() {
return dtoInterface;
}
public DtoTemplate getEnclosingTemplate() {
return enclosingTemplate;
}
protected String getJavaFieldName(String getterName) {
String fieldName;
if (getterName.startsWith("get")) {
fieldName = getterName.substring(3);
} else {
// starts with "is", see method '#ignoreMethod(Method)'
fieldName = getterName.substring(2);
}
return normalizeIdentifier(Character.toLowerCase(fieldName.charAt(0)) + fieldName.substring(1));
}
private String normalizeIdentifier(String fieldName) {
// use $ prefix according to http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.8
switch (fieldName) {
case "default":
fieldName = "$" + fieldName;
break;
// add other keywords here
}
return fieldName;
}
private String getCamelCaseName(String fieldName) {
// see normalizeIdentifier method
if (fieldName.charAt(0) == '$') {
fieldName = fieldName.substring(1);
}
return Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
}
protected String getImplClassName() {
return implClassName;
}
protected String getSetterName(String fieldName) {
return "set" + getCamelCaseName(fieldName);
}
protected String getWithName(String fieldName) {
return "with" + getCamelCaseName(fieldName);
}
protected String getListAdderName(String fieldName) {
return "add" + getCamelCaseName(fieldName);
}
protected String getMapPutterName(String fieldName) {
return "put" + getCamelCaseName(fieldName);
}
protected String getClearName(String fieldName) {
return "clear" + getCamelCaseName(fieldName);
}
protected String getEnsureName(String fieldName) {
return "ensure" + getCamelCaseName(fieldName);
}
/**
* Get the canonical name of the field by deriving it from a getter method's name.
*/
protected String getFieldNameFromGetterName(String getterName) {
String fieldName;
if (getterName.startsWith("get")) {
fieldName = getterName.substring(3);
} else {
// starts with "is", see method '#ignoreMethod(Method)'
fieldName = getterName.substring(2);
}
return Character.toLowerCase(fieldName.charAt(0)) + fieldName.substring(1);
}
/**
* Get the name of the JSON field that corresponds to the given getter method in a DTO-annotated type.
*/
protected String getJsonFieldName(Method getterMethod) {
// First, check if a custom field name is defined for the getter
JsonFieldName fieldNameAnn = getterMethod.getAnnotation(JsonFieldName.class);
if (fieldNameAnn != null) {
String customFieldName = fieldNameAnn.value();
if (customFieldName != null && !customFieldName.isEmpty()) {
return customFieldName;
}
}
// If no custom name is given for the field, deduce it from the camel notation
return getFieldNameFromGetterName(getterMethod.getName());
}
/**
* Our super interface may implement some other interface (or not). We need to know because if it does then we need to directly extend
* said super interfaces impl class.
*/
protected Class<?> getSuperDtoInterface(Class<?> dto) {
Class<?>[] superInterfaces = dto.getInterfaces();
if (superInterfaces.length > 0) {
for (Class<?> superInterface : superInterfaces) {
if (superInterface.isAnnotationPresent(DTO.class)) {
return superInterface;
}
}
}
return null;
}
protected List<Method> getDtoGetters(Class<?> dto) {
final Map<String, Method> getters = new HashMap<>();
if (enclosingTemplate.isDtoInterface(dto)) {
addDtoGetters(dto, getters);
addSuperGetters(dto, getters);
}
return new ArrayList<>(getters.values());
}
/**
* Get the names of all the getters in the super DTO interface and upper ancestors.
*/
protected Set<String> getSuperGetterNames(Class<?> dto) {
final Map<String, Method> getters = new HashMap<>();
Class<?> superDto = getSuperDtoInterface(dto);
if (superDto != null) {
addDtoGetters(superDto, getters);
addSuperGetters(superDto, getters);
}
return getters.keySet();
}
/**
* Adds all getters from parent <b>NOT DTO</b> interfaces for given {@code dto} interface.
* Does not add method when it is already present in getters map.
*/
private void addSuperGetters(Class<?> dto, Map<String, Method> getters) {
for (Class<?> superInterface : dto.getInterfaces()) {
if (!superInterface.isAnnotationPresent(DTO.class)) {
for (Method method : superInterface.getDeclaredMethods()) {
//when method is already present in map then child interface
//overrides it, which means that it should not be put into getters
if (isDtoGetter(method) && !getters.containsKey(method.getName())) {
getters.put(method.getName(), method);
}
}
addSuperGetters(superInterface, getters);
}
}
}
protected List<Method> getInheritedDtoGetters(Class<?> dto) {
List<Method> getters = new ArrayList<>();
if (enclosingTemplate.isDtoInterface(dto)) {
Class<?> superInterface = getSuperDtoInterface(dto);
while (superInterface != null) {
addDtoGetters(superInterface, getters);
superInterface = getSuperDtoInterface(superInterface);
}
addDtoGetters(dto, getters);
}
return getters;
}
private void addDtoGetters(Class<?> dto, Map<String, Method> getters) {
for (Method method : dto.getDeclaredMethods()) {
if (!method.isDefault() && isDtoGetter(method)) {
getters.put(method.getName(), method);
}
}
}
private void addDtoGetters(Class<?> dto, List<Method> getters) {
for (Method method : dto.getDeclaredMethods()) {
if (!method.isDefault() && isDtoGetter(method)) {
getters.add(method);
}
}
}
/** Check is specified method is DTO getter. */
protected boolean isDtoGetter(Method method) {
if (method.isAnnotationPresent(DelegateTo.class)) {
return false;
}
String methodName = method.getName();
if ((methodName.startsWith("get") || methodName.startsWith("is")) && method.getParameterTypes().length == 0) {
if (methodName.startsWith("is") && methodName.length() > 2) {
return method.getReturnType() == Boolean.class || method.getReturnType() == boolean.class;
}
return methodName.length() > 3;
}
return false;
}
/** Tests whether or not a given generic type is allowed to be used as a generic. */
protected static boolean isWhitelisted(Class<?> genericType) {
return DtoTemplate.jreWhitelist.contains(genericType);
}
/** Tests whether or not a given return type is a number primitive or its wrapper type. */
protected static boolean isNumber(Class<?> returnType) {
final Class<?>[] numericTypes = {int.class, long.class, short.class, float.class, double.class, byte.class,
Integer.class, Long.class, Short.class, Float.class, Double.class, Byte.class};
for (Class<?> standardPrimitive : numericTypes) {
if (returnType.equals(standardPrimitive)) {
return true;
}
}
return false;
}
/** Tests whether or not a given return type is a boolean primitive or its wrapper type. */
protected static boolean isBoolean(Class<?> returnType) {
return returnType.equals(Boolean.class) || returnType.equals(boolean.class);
}
protected static String getPrimitiveName(Class<?> returnType) {
if (returnType.equals(Integer.class) || returnType.equals(int.class)) {
return "int";
} else if (returnType.equals(Long.class) || returnType.equals(long.class)) {
return "long";
} else if (returnType.equals(Short.class) || returnType.equals(short.class)) {
return "short";
} else if (returnType.equals(Float.class) || returnType.equals(float.class)) {
return "float";
} else if (returnType.equals(Double.class) || returnType.equals(double.class)) {
return "double";
} else if (returnType.equals(Byte.class) || returnType.equals(byte.class)) {
return "byte";
} else if (returnType.equals(Boolean.class) || returnType.equals(boolean.class)) {
return "boolean";
} else if (returnType.equals(Character.class) || returnType.equals(char.class)) {
return "char";
}
throw new IllegalArgumentException("Unknown wrapper class type.");
}
<|fim▁hole|> return returnType.equals(List.class);
}
/** Tests whether or not a given return type is a java.util.Map. */
public static boolean isMap(Class<?> returnType) {
return returnType.equals(Map.class);
}
public static boolean isAny(Class<?> returnType) {
return returnType.equals(Object.class);
}
/**
* Expands the type and its first generic parameter (which can also have a first generic parameter (...)).
* <p/>
* For example, JsonArray<JsonStringMap<JsonArray<SomeDto>>> would produce [JsonArray, JsonStringMap, JsonArray,
* SomeDto].
*/
public static List<Type> expandType(Type curType) {
List<Type> types = new LinkedList<>();
do {
types.add(curType);
if (curType instanceof ParameterizedType) {
Type[] genericParamTypes = ((ParameterizedType)curType).getActualTypeArguments();
Type rawType = ((ParameterizedType)curType).getRawType();
boolean map = rawType instanceof Class<?> && rawType == Map.class;
if (!map && genericParamTypes.length != 1) {
throw new IllegalStateException("Multiple type parameters are not supported (neither are zero type parameters)");
}
Type genericParamType = map ? genericParamTypes[1] : genericParamTypes[0];
if (genericParamType instanceof Class<?>) {
Class<?> genericParamTypeClass = (Class<?>)genericParamType;
if (isWhitelisted(genericParamTypeClass)) {
assert genericParamTypeClass.equals(
String.class) : "For JSON serialization there can be only strings or DTO types. ";
}
}
curType = genericParamType;
} else {
if (curType instanceof Class) {
Class<?> clazz = (Class<?>)curType;
if (isList(clazz) || isMap(clazz)) {
throw new DtoTemplate.MalformedDtoInterfaceException(
"JsonArray and JsonStringMap MUST have a generic type specified (and no... ? doesn't cut it!).");
}
}
curType = null;
}
} while (curType != null);
return types;
}
public static Class<?> getRawClass(Type type) {
return (Class<?>)((type instanceof ParameterizedType) ? ((ParameterizedType)type).getRawType() : type);
}
/**
* Returns public methods specified in DTO interface.
* <p/>
* <p>For compact DTO (see {@link org.eclipse.che.dto.shared.CompactJsonDto}) methods are ordered corresponding to {@link
* org.eclipse.che.dto.shared.SerializationIndex} annotation.
* <p/>
* <p>Gaps in index sequence are filled with {@code null}s.
*/
protected List<Method> getDtoMethods() {
return dtoMethods;
}
private Method[] calcDtoMethods() {
if (!compactJson) {
return dtoInterface.getMethods();
}
Map<Integer, Method> methodsMap = new HashMap<>();
int maxIndex = 0;
for (Method method : dtoInterface.getMethods()) {
SerializationIndex serializationIndex = method.getAnnotation(SerializationIndex.class);
Preconditions.checkNotNull(serializationIndex, "Serialization index is not specified for %s in %s",
method.getName(), dtoInterface.getSimpleName());
// "53" is the number of bits in JS integer.
// This restriction will allow to add simple bit-field
// "serialization-skipping-list" in the future.
int index = serializationIndex.value();
Preconditions.checkState(index > 0 && index <= 53, "Serialization index out of range [1..53] for %s in %s",
method.getName(), dtoInterface.getSimpleName());
Preconditions.checkState(!methodsMap.containsKey(index), "Duplicate serialization index for %s in %s",
method.getName(), dtoInterface.getSimpleName());
maxIndex = Math.max(index, maxIndex);
methodsMap.put(index, method);
}
Method[] result = new Method[maxIndex];
for (int index = 0; index < maxIndex; index++) {
result[index] = methodsMap.get(index + 1);
}
return result;
}
protected boolean isLastMethod(Method method) {
Preconditions.checkNotNull(method);
return method == dtoMethods.get(dtoMethods.size() - 1);
}
/**
* Create a textual representation of a string literal that evaluates to the given value.
*/
protected String quoteStringLiteral(String value) {
StringWriter sw = new StringWriter();
try (JsonWriter writer = new JsonWriter(sw)) {
writer.setLenient(true);
writer.value(value);
writer.flush();
} catch (IOException ex) {
throw new RuntimeException("Unexpected I/O failure: " + ex.getLocalizedMessage(), ex);
}
return sw.toString();
}
/**
* @return String representing the source definition for the DTO impl as an inner class.
*/
abstract String serialize();
}<|fim▁end|> | /** Tests whether or not a given return type is a java.util.List. */
public static boolean isList(Class<?> returnType) { |
<|file_name|>bitcoin_ro_RO.ts<|end_file_name|><|fim▁begin|><TS language="ro_RO" version="2.1">
<context>
<name>AddressBookPage</name>
<message>
<source>Right-click to edit address or label</source>
<translation>Click-dreapta pentru a edita adresa sau eticheta</translation>
</message>
<message>
<source>Create a new address</source>
<translation>Creează o adresă nouă</translation>
</message>
<message>
<source>&New</source>
<translation>&Nou</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copiază adresa selectată în clipboard</translation>
</message>
<message>
<source>&Copy</source>
<translation>&Copiază</translation>
</message>
<message>
<source>C&lose</source>
<translation>Închide</translation>
</message>
<message>
<source>Delete the currently selected address from the list</source>
<translation>Şterge adresele curent selectate din listă</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>Exportă datele din tab-ul curent într-un fişier</translation>
</message>
<message>
<source>&Export</source>
<translation>&Exportă</translation>
</message>
<message>
<source>&Delete</source>
<translation>&Şterge</translation>
</message>
<message>
<source>C&hoose</source>
<translation>&Alegeţi</translation>
</message>
<message>
<source>Sending addresses</source>
<translation>Adresa destinatarului</translation>
</message>
<message>
<source>Receiving addresses</source>
<translation>Adresa de primire</translation>
</message>
<message>
<source>These are your Chancoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Acestea sunt adresele tale Chancoin pentru efectuarea platilor. Intotdeauna verifica atent suma de plata si adresa beneficiarului inainte de a trimite monede.</translation>
</message>
<message>
<source>These are your Chancoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source>
<translation>Acestea sunt adresele tale Chancoin pentru receptionarea platilor. Este recomandat sa folosesti mereu o adresa noua pentru primirea platilor.</translation>
</message>
<message>
<source>&Copy Address</source>
<translation>&Copiază adresa</translation>
</message>
<message>
<source>Copy &Label</source>
<translation>Copiaza si eticheteaza</translation>
</message>
<message>
<source>&Edit</source>
<translation>&Editare</translation>
</message>
<message>
<source>Export Address List</source>
<translation>Exportă listă de adrese</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Fisier .csv cu separator - virgula</translation>
</message>
<message>
<source>Exporting Failed</source>
<translation>Exportarea a eșuat</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<source>Label</source>
<translation>Etichetă</translation>
</message>
<message>
<source>Address</source>
<translation>Adresă</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<source>Passphrase Dialog</source>
<translation>Dialogul pentru fraza de acces</translation>
</message>
<message>
<source>Enter passphrase</source>
<translation>Introduceţi fraza de acces</translation>
</message>
<message>
<source>New passphrase</source>
<translation>Frază de acces nouă</translation>
</message>
<message>
<source>Repeat new passphrase</source>
<translation>Repetaţi noua frază de acces</translation>
</message>
<message>
<source>Encrypt wallet</source>
<translation>Criptare portofel</translation>
</message>
<message>
<source>Unlock wallet</source>
<translation>Deblocare portofel</translation>
</message>
<message>
<source>Decrypt wallet</source>
<translation>Decriptare portofel</translation>
</message>
<message>
<source>Change passphrase</source>
<translation>Schimbă parola</translation>
</message>
<message>
<source>Confirm wallet encryption</source>
<translation>Confirmaţi criptarea portofelului</translation>
</message>
<message>
<source>Wallet encrypted</source>
<translation>Portofel criptat</translation>
</message>
</context>
<context>
<name>BanTableModel</name>
<message>
<source>IP/Netmask</source>
<translation>IP/Netmask</translation>
</message>
<message>
<source>Banned Until</source>
<translation>Banat până la</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<source>Sign &message...</source>
<translation>Semnează &mesaj...</translation>
</message>
<message>
<source>Synchronizing with network...</source>
<translation>Se sincronizează cu reţeaua...</translation>
</message>
<message>
<source>&Overview</source>
<translation>&Imagine de ansamblu</translation>
</message>
<message>
<source>Node</source>
<translation>Nod</translation>
</message>
<message>
<source>Show general overview of wallet</source>
<translation>Arată o stare generală de ansamblu a portofelului</translation>
</message>
<message>
<source>&Transactions</source>
<translation>&Tranzacţii</translation>
</message>
<message>
<source>Browse transaction history</source>
<translation>Răsfoire istoric tranzacţii</translation>
</message>
<message>
<source>E&xit</source>
<translation>Ieşire</translation>
</message>
<message>
<source>Quit application</source>
<translation>Închide aplicaţia</translation>
</message>
<message>
<source>About &Qt</source>
<translation>Despre &Qt</translation>
</message>
<message>
<source>Show information about Qt</source>
<translation>Arată informaţii despre Qt</translation>
</message>
<message>
<source>&Options...</source>
<translation>&Opţiuni...</translation>
</message>
<message>
<source>&Encrypt Wallet...</source>
<translation>Cript&ează portofelul...</translation>
</message>
<message>
<source>&Backup Wallet...</source>
<translation>Face o copie de siguranţă a portofelului...</translation>
</message>
<message>
<source>&Change Passphrase...</source>
<translation>S&chimbă parola...</translation>
</message>
<message>
<source>&Sending addresses...</source>
<translation>Adrese de trimitere...</translation>
</message>
<message>
<source>&Receiving addresses...</source>
<translation>Adrese de p&rimire...</translation>
</message>
<message>
<source>Open &URI...</source>
<translation>Deschide &URI...</translation>
</message>
<message>
<source>Reindexing blocks on disk...</source>
<translation>Se reindexează blocurile pe disc...</translation>
</message>
<message>
<source>Send coins to a Chancoin address</source>
<translation>Trimite monede către o adresă Chancoin</translation>
</message>
<message>
<source>Backup wallet to another location</source>
<translation>Creează o copie de rezervă a portofelului într-o locaţie diferită</translation>
</message>
<message>
<source>Change the passphrase used for wallet encryption</source>
<translation>Schimbă fraza de acces folosită pentru criptarea portofelului</translation>
</message>
<message>
<source>&Debug window</source>
<translation>Fereastra de &depanare</translation>
</message>
<message>
<source>Open debugging and diagnostic console</source>
<translation>Deschide consola de depanare şi diagnosticare</translation>
</message>
<message>
<source>&Verify message...</source>
<translation>&Verifică mesaj...</translation>
</message>
<message>
<source>Chancoin</source>
<translation>Chancoin</translation>
</message>
<message>
<source>Wallet</source>
<translation>Portofel</translation>
</message>
<message>
<source>&Send</source>
<translation>Trimite</translation>
</message>
<message>
<source>&Receive</source>
<translation>P&rimeşte</translation>
</message>
<message>
<source>&Show / Hide</source>
<translation>Arată/Ascunde</translation>
</message>
<message>
<source>Show or hide the main Window</source>
<translation>Arată sau ascunde fereastra principală</translation>
</message>
<message>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Criptează cheile private ale portofelului dvs.</translation>
</message>
<message>
<source>Sign messages with your Chancoin addresses to prove you own them</source>
<translation>Semnaţi mesaje cu adresa dvs. Chancoin pentru a dovedi că vă aparţin</translation>
</message>
<message>
<source>Verify messages to ensure they were signed with specified Chancoin addresses</source>
<translation>Verificaţi mesaje pentru a vă asigura că au fost semnate cu adresa Chancoin specificată</translation>
</message>
<message>
<source>&File</source>
<translation>&Fişier</translation>
</message>
<message>
<source>&Settings</source>
<translation>&Setări</translation>
</message>
<message>
<source>&Help</source>
<translation>A&jutor</translation>
</message>
<message>
<source>Tabs toolbar</source>
<translation>Bara de unelte</translation>
</message>
<message>
<source>Request payments (generates QR codes and chancoin: URIs)</source>
<translation>Cereţi plăţi (generează coduri QR şi chancoin-uri: URls)</translation>
</message>
<message>
<source>Show the list of used sending addresses and labels</source>
<translation>Arată lista de adrese trimise şi etichetele folosite.</translation>
</message>
<message>
<source>Show the list of used receiving addresses and labels</source>
<translation>Arată lista de adrese pentru primire şi etichetele</translation>
</message>
<message>
<source>Open a chancoin: URI or payment request</source>
<translation>Deschidere chancoin: o adresa URI sau o cerere de plată</translation>
</message>
<message>
<source>&Command-line options</source>
<translation>Opţiuni linie de &comandă</translation>
</message>
<message numerus="yes">
<source>%n active connection(s) to Chancoin network</source>
<translation><numerusform>%n conexiune activă către reţeaua Chancoin</numerusform><numerusform>%n conexiuni active către reţeaua Chancoin</numerusform><numerusform>%n de conexiuni active către reţeaua Chancoin</numerusform></translation>
</message>
<message numerus="yes">
<source>Processed %n block(s) of transaction history.</source>
<translation><numerusform>S-a procesat %n bloc din istoricul tranzacţiilor.</numerusform><numerusform>S-au procesat %n blocuri din istoricul tranzacţiilor.</numerusform><numerusform>S-au procesat %n de blocuri din istoricul tranzacţiilor.</numerusform></translation>
</message>
<message>
<source>%1 behind</source>
<translation>%1 în urmă</translation>
</message>
<message>
<source>Last received block was generated %1 ago.</source>
<translation>Ultimul bloc recepţionat a fost generat acum %1.</translation>
</message>
<message>
<source>Transactions after this will not yet be visible.</source>
<translation>Tranzacţiile după aceasta nu vor fi vizibile încă.</translation>
</message>
<message>
<source>Error</source>
<translation>Eroare</translation>
</message>
<message>
<source>Warning</source>
<translation>Avertisment</translation>
</message>
<message>
<source>Information</source>
<translation>Informaţie</translation>
</message>
<message>
<source>Up to date</source>
<translation>Actualizat</translation>
</message>
<message>
<source>Catching up...</source>
<translation>Se actualizează...</translation>
</message>
<message>
<source>Date: %1
</source>
<translation>Data: %1
</translation>
</message>
<message>
<source>Amount: %1
</source>
<translation>Sumă: %1
</translation>
</message>
<message>
<source>Type: %1
</source>
<translation>Tip: %1
</translation>
</message>
<message>
<source>Label: %1
</source>
<translation>Etichetă: %1
</translation>
</message>
<message>
<source>Address: %1
</source>
<translation>Adresă: %1
</translation>
</message>
<message>
<source>Sent transaction</source>
<translation>Tranzacţie expediată</translation>
</message>
<message>
<source>Incoming transaction</source>
<translation>Tranzacţie recepţionată</translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Portofelul este <b>criptat</b> iar în momentul de faţă este <b>deblocat</b></translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Portofelul este <b>criptat</b> iar în momentul de faţă este <b>blocat</b></translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Coin Selection</source>
<translation>Selectarea monedei</translation>
</message>
<message>
<source>Quantity:</source>
<translation>Cantitate:</translation>
</message>
<message>
<source>Bytes:</source>
<translation>Octeţi:</translation>
</message>
<message>
<source>Amount:</source>
<translation>Sumă:</translation>
</message>
<message>
<source>Fee:</source>
<translation>Taxă:</translation>
</message>
<message>
<source>Dust:</source>
<translation>Praf:</translation>
</message>
<message>
<source>After Fee:</source>
<translation>După taxă:</translation>
</message>
<message>
<source>Change:</source>
<translation>Schimb:</translation>
</message>
<message>
<source>(un)select all</source>
<translation>(de)selectare tot</translation>
</message>
<message>
<source>Tree mode</source>
<translation>Mod arbore</translation>
</message>
<message>
<source>List mode</source>
<translation>Mod listă</translation>
</message>
<message>
<source>Amount</source>
<translation>Sumă</translation>
</message>
<message>
<source>Received with label</source>
<translation>Primite cu eticheta</translation>
</message>
<message>
<source>Received with address</source>
<translation>Primite cu adresa</translation>
</message>
<message>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<source>Confirmations</source>
<translation>Confirmări</translation>
</message>
<message>
<source>Confirmed</source>
<translation>Confirmat</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<source>Edit Address</source>
<translation>Editează adresa</translation>
</message>
<message>
<source>&Label</source>
<translation>&Etichetă</translation>
</message>
<message>
<source>The label associated with this address list entry</source>
<translation>Eticheta asociată cu această intrare din listă.</translation>
</message>
<message>
<source>The address associated with this address list entry. This can only be modified for sending addresses.</source>
<translation>Adresa asociată cu această adresă din listă. Aceasta poate fi modificată doar pentru adresele de trimitere.</translation>
</message>
<message>
<source>&Address</source>
<translation>&Adresă</translation>
</message>
</context>
<context>
<name>FreespaceChecker</name>
<message>
<source>A new data directory will be created.</source>
<translation>Va fi creat un nou dosar de date.</translation>
</message>
<message>
<source>name</source>
<translation>nume</translation>
</message>
<message>
<source>Directory already exists. Add %1 if you intend to create a new directory here.</source>
<translation>Dosarul deja există. Adaugă %1 dacă intenţionaţi să creaţi un nou dosar aici.</translation>
</message>
<message>
<source>Path already exists, and is not a directory.</source>
<translation>Calea deja există şi nu este un dosar.</translation>
</message>
<message>
<source>Cannot create data directory here.</source>
<translation>Nu se poate crea un dosar de date aici.</translation>
</message>
</context>
<context>
<name>HelpMessageDialog</name>
<message>
<source>version</source>
<translation>versiunea</translation>
</message>
<message>
<source>(%1-bit)</source>
<translation>(%1-bit)</translation>
</message>
<message>
<source>About %1</source>
<translation>Despre %1</translation>
</message>
<message>
<source>Command-line options</source>
<translation>Opţiuni linie de comandă</translation>
</message>
<message>
<source>Usage:</source>
<translation>Uz:</translation>
</message>
<message>
<source>command-line options</source>
<translation>Opţiuni linie de comandă</translation>
</message>
<message>
<source>UI Options:</source>
<translation>Opţiuni UI:</translation>
</message>
<message>
<source>Choose data directory on startup (default: %u)</source>
<translation>Alege dosarul de date la pornire (implicit: %u)</translation>
</message>
<message>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Setează limba, de exemplu: "ro_RO" (implicit: sistem local)</translation>
</message>
<message>
<source>Start minimized</source>
<translation>Porniţi minimizat</translation>
</message>
<message>
<source>Set SSL root certificates for payment request (default: -system-)</source>
<translation>Setare rădăcină certificat SSL pentru cerere de plată (implicit: -sistem- )</translation>
</message>
<message>
<source>Show splash screen on startup (default: %u)</source>
<translation>Afişează ecran splash la pornire (implicit: %u)</translation>
</message>
</context>
<context>
<name>Intro</name>
<message>
<source>Welcome</source>
<translation>Bun venit</translation>
</message>
<message>
<source>Use the default data directory</source>
<translation>Foloseşte dosarul de date implicit</translation>
</message>
<message>
<source>Use a custom data directory:</source>
<translation>Foloseşte un dosar de date personalizat:</translation>
</message>
<message>
<source>Error: Specified data directory "%1" cannot be created.</source>
<translation>Eroare: Directorul datelor specificate "%1" nu poate fi creat.</translation>
</message>
<message>
<source>Error</source>
<translation>Eroare</translation>
</message>
<message numerus="yes">
<source>%n GB of free space available</source>
<translation><numerusform>%n GB de spaţiu liber disponibil</numerusform><numerusform>%n GB de spaţiu liber disponibil</numerusform><numerusform>%n GB de spaţiu liber disponibil</numerusform></translation>
</message>
<message numerus="yes">
<source>(of %n GB needed)</source>
<translation><numerusform>(din %n GB necesar)</numerusform><numerusform>(din %n GB necesari)</numerusform><numerusform>(din %n GB necesari)</numerusform></translation>
</message>
</context>
<context>
<name>ModalOverlay</name>
<message>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<source>Last block time</source>
<translation>Data ultimului bloc</translation>
</message>
<message>
<source>Hide</source>
<translation>Ascunde</translation>
</message>
</context>
<context>
<name>OpenURIDialog</name>
<message>
<source>Open URI</source>
<translation>Deschide URI</translation>
</message>
<message>
<source>Open payment request from URI or file</source>
<translation>Deschideţi cerere de plată prin intermediul adresei URI sau a fişierului</translation>
</message>
<message>
<source>URI:</source>
<translation>URI:</translation>
</message>
<message>
<source>Select payment request file</source>
<translation>Selectaţi fişierul cerere de plată</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<source>Options</source>
<translation>Opţiuni</translation>
</message>
<message>
<source>&Main</source>
<translation>Principal</translation>
</message>
<message>
<source>Size of &database cache</source>
<translation>Mărimea bazei de &date cache</translation>
</message>
<message>
<source>MB</source>
<translation>MB</translation>
</message>
<message>
<source>Number of script &verification threads</source>
<translation>Numărul de thread-uri de &verificare</translation>
</message>
<message>
<source>Accept connections from outside</source>
<translation>Acceptă conexiuni din exterior</translation>
</message>
<message>
<source>Allow incoming connections</source>
<translation>Permite conexiuni de intrare</translation>
</message>
<message>
<source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source>
<translation>Adresa IP a serverului proxy (de exemplu: IPv4: 127.0.0.1 / IPv6: ::1)</translation>
</message>
<message>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Exit in the menu.</source>
<translation>Minimizează fereastra în locul părăsirii programului în momentul închiderii ferestrei. Cînd acestă opţiune e activă, aplicaţia se va opri doar în momentul selectării comenzii 'Închide aplicaţia' din menu.</translation>
</message>
<message>
<source>Third party URLs (e.g. a block explorer) that appear in the transactions tab as context menu items. %s in the URL is replaced by transaction hash. Multiple URLs are separated by vertical bar |.</source>
<translation>URL-uri terţe părţi (de exemplu, un explorator de bloc), care apar în tab-ul tranzacţiilor ca elemente de meniu contextual. %s în URL este înlocuit cu hash de tranzacţie. URL-urile multiple sînt separate prin bară verticală |.</translation>
</message>
<message>
<source>Third party transaction URLs</source>
<translation>URL-uri tranzacţii terţe părţi</translation>
</message>
<message>
<source>Active command-line options that override above options:</source>
<translation>Opţiuni linie de comandă active care oprimă opţiunile de mai sus:</translation>
</message>
<message>
<source>Reset all client options to default.</source>
<translation>Resetează toate setările clientului la valorile implicite.</translation>
</message>
<message>
<source>&Reset Options</source>
<translation>&Resetează opţiunile</translation>
</message>
<message>
<source>&Network</source>
<translation>Reţea</translation>
</message>
<message>
<source>(0 = auto, <0 = leave that many cores free)</source>
<translation>(0 = automat, <0 = lasă atîtea nuclee libere)</translation>
</message>
<message>
<source>W&allet</source>
<translation>Portofel</translation>
</message>
<message>
<source>Expert</source>
<translation>Expert</translation>
</message>
<message>
<source>Enable coin &control features</source>
<translation>Activare caracteristici de control ale monedei</translation>
</message>
<message>
<source>If you disable the spending of unconfirmed change, the change from a transaction cannot be used until that transaction has at least one confirmation. This also affects how your balance is computed.</source>
<translation>Dacă dezactivaţi cheltuirea restului neconfirmat, restul dintr-o tranzacţie nu poate fi folosit pînă cînd tranzacţia are cel puţin o confirmare. Aceasta afectează de asemenea calcularea soldului.</translation>
</message>
<message>
<source>&Spend unconfirmed change</source>
<translation>Cheltuire rest neconfirmat</translation>
</message>
<message>
<source>Automatically open the Chancoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Deschide automat în router portul aferent clientului Chancoin. Funcţionează doar dacă routerul duportă UPnP şi e activat.</translation>
</message>
<message>
<source>Map port using &UPnP</source>
<translation>Mapare port folosind &UPnP</translation>
</message>
<message>
<source>Connect to the Chancoin network through a SOCKS5 proxy.</source>
<translation>Conectare la reţeaua Chancoin printr-un proxy SOCKS.</translation>
</message>
<message>
<source>&Connect through SOCKS5 proxy (default proxy):</source>
<translation>&Conectare printr-un proxy SOCKS (implicit proxy):</translation>
</message>
<message>
<source>Proxy &IP:</source>
<translation>Proxy &IP:</translation>
</message>
<message>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Portul proxy (de exemplu: 9050)</translation>
</message>
<message>
<source>IPv4</source>
<translation>IPv4</translation>
</message>
<message>
<source>IPv6</source>
<translation>IPv6</translation>
</message>
<message>
<source>Tor</source>
<translation>Tor</translation>
</message>
<message>
<source>&Window</source>
<translation>&Fereastră</translation>
</message>
<message>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Arată doar un icon în tray la ascunderea ferestrei</translation>
</message>
<message>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimizare în tray în loc de taskbar</translation>
</message>
<message>
<source>M&inimize on close</source>
<translation>M&inimizare fereastră în locul închiderii programului</translation>
</message>
<message>
<source>&Display</source>
<translation>&Afişare</translation>
</message>
<message>
<source>User Interface &language:</source>
<translation>&Limbă interfaţă utilizator</translation>
</message>
<message>
<source>&Unit to show amounts in:</source>
<translation>&Unitatea de măsură pentru afişarea sumelor:</translation>
</message>
<message>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Alegeţi subdiviziunea folosită la afişarea interfeţei şi la trimiterea de chancoin.</translation>
</message>
<message>
<source>Whether to show coin control features or not.</source>
<translation>Arată controlul caracteristicilor monedei sau nu.</translation>
</message>
<message>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<source>&Cancel</source>
<translation>Renunţă</translation>
</message>
<message>
<source>default</source>
<translation>iniţial</translation>
</message>
<message>
<source>none</source>
<translation>nimic</translation>
</message>
<message>
<source>Confirm options reset</source>
<translation>Confirmă resetarea opţiunilor</translation>
</message>
<message>
<source>Client restart required to activate changes.</source>
<translation>Este necesară repornirea clientului pentru a activa schimbările.</translation>
</message>
<message>
<source>Client will be shut down. Do you want to proceed?</source>
<translation>Clientul va fi închis. Doriţi să continuaţi?</translation>
</message>
<message>
<source>This change would require a client restart.</source>
<translation>Această schimbare necesită o repornire a clientului.</translation>
</message>
<message>
<source>The supplied proxy address is invalid.</source>
<translation>Adresa chancoin pe care aţi specificat-o nu este validă.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Chancoin network after a connection is established, but this process has not completed yet.</source>
<translation>Informaţiile afişate pot fi neactualizate. Portofelul dvs. se sincronizează automat cu reţeaua Chancoin după ce o conexiune este stabilită, dar acest proces nu a fost finalizat încă.</translation>
</message>
<message><|fim▁hole|> <message>
<source>Available:</source>
<translation>Disponibil:</translation>
</message>
<message>
<source>Your current spendable balance</source>
<translation>Balanţa dvs. curentă de cheltuieli</translation>
</message>
<message>
<source>Pending:</source>
<translation>În aşteptare:</translation>
</message>
<message>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source>
<translation>Totalul tranzacţiilor care nu sunt confirmate încă şi care nu sunt încă adunate la balanţa de cheltuieli</translation>
</message>
<message>
<source>Immature:</source>
<translation>Nematurizat:</translation>
</message>
<message>
<source>Mined balance that has not yet matured</source>
<translation>Balanţa minertită care nu s-a maturizat încă</translation>
</message>
<message>
<source>Balances</source>
<translation>Balanţă</translation>
</message>
<message>
<source>Total:</source>
<translation>Total:</translation>
</message>
<message>
<source>Your current total balance</source>
<translation>Balanţa totală curentă</translation>
</message>
<message>
<source>Your current balance in watch-only addresses</source>
<translation>Soldul dvs. curent în adresele doar-supraveghere</translation>
</message>
<message>
<source>Spendable:</source>
<translation>Cheltuibil:</translation>
</message>
<message>
<source>Recent transactions</source>
<translation>Tranzacţii recente</translation>
</message>
<message>
<source>Unconfirmed transactions to watch-only addresses</source>
<translation>Tranzacţii neconfirmate la adresele doar-supraveghere</translation>
</message>
<message>
<source>Mined balance in watch-only addresses that has not yet matured</source>
<translation>Balanţă minată în adresele doar-supraveghere care nu s-a maturizat încă</translation>
</message>
<message>
<source>Current total balance in watch-only addresses</source>
<translation>Soldul dvs. total în adresele doar-supraveghere</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
</context>
<context>
<name>PeerTableModel</name>
<message>
<source>User Agent</source>
<translation>Agent utilizator</translation>
</message>
<message>
<source>Node/Service</source>
<translation>Nod/Serviciu</translation>
</message>
</context>
<context>
<name>QObject</name>
<message>
<source>Amount</source>
<translation>Cantitate</translation>
</message>
<message>
<source>Enter a Chancoin address (e.g. %1)</source>
<translation>Introduceţi o adresă Chancoin (de exemplu %1)</translation>
</message>
<message>
<source>%1 d</source>
<translation>%1 z</translation>
</message>
<message>
<source>%1 h</source>
<translation>%1 h</translation>
</message>
<message>
<source>%1 m</source>
<translation>%1 m</translation>
</message>
<message>
<source>%1 s</source>
<translation>%1 s</translation>
</message>
<message>
<source>None</source>
<translation>Niciuna</translation>
</message>
<message>
<source>N/A</source>
<translation>N/A</translation>
</message>
<message>
<source>%1 ms</source>
<translation>%1 ms</translation>
</message>
<message>
<source>%1 and %2</source>
<translation>%1 şi %2</translation>
</message>
</context>
<context>
<name>QObject::QObject</name>
</context>
<context>
<name>QRImageWidget</name>
<message>
<source>&Save Image...</source>
<translation>&Salvează imaginea...</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<source>N/A</source>
<translation>indisponibil</translation>
</message>
<message>
<source>Client version</source>
<translation>Versiune client</translation>
</message>
<message>
<source>&Information</source>
<translation>&Informaţii</translation>
</message>
<message>
<source>Debug window</source>
<translation>Fereastra de depanare</translation>
</message>
<message>
<source>General</source>
<translation>General</translation>
</message>
<message>
<source>Using BerkeleyDB version</source>
<translation>Foloseşte BerkeleyDB versiunea</translation>
</message>
<message>
<source>Startup time</source>
<translation>Durata pornirii</translation>
</message>
<message>
<source>Network</source>
<translation>Reţea</translation>
</message>
<message>
<source>Name</source>
<translation>Nume</translation>
</message>
<message>
<source>Number of connections</source>
<translation>Numărul de conexiuni</translation>
</message>
<message>
<source>Block chain</source>
<translation>Lanţ de blocuri</translation>
</message>
<message>
<source>Current number of blocks</source>
<translation>Numărul curent de blocuri</translation>
</message>
<message>
<source>Current number of transactions</source>
<translation>Numărul curent de tranzacţii</translation>
</message>
<message>
<source>Memory usage</source>
<translation>Memorie folosită</translation>
</message>
<message>
<source>Received</source>
<translation>Recepţionat</translation>
</message>
<message>
<source>Sent</source>
<translation>Trimis</translation>
</message>
<message>
<source>&Peers</source>
<translation>&Parteneri</translation>
</message>
<message>
<source>Select a peer to view detailed information.</source>
<translation>Selectaţi un partener pentru a vedea informaţiile detaliate.</translation>
</message>
<message>
<source>Whitelisted</source>
<translation>Whitelisted</translation>
</message>
<message>
<source>Direction</source>
<translation>Direcţie</translation>
</message>
<message>
<source>Version</source>
<translation>Versiune</translation>
</message>
<message>
<source>Starting Block</source>
<translation>Bloc de început</translation>
</message>
<message>
<source>Synced Headers</source>
<translation>Headere Sincronizate</translation>
</message>
<message>
<source>Synced Blocks</source>
<translation>Blocuri Sincronizate</translation>
</message>
<message>
<source>User Agent</source>
<translation>Agent utilizator</translation>
</message>
<message>
<source>Services</source>
<translation>Servicii</translation>
</message>
<message>
<source>Connection Time</source>
<translation>Timp conexiune</translation>
</message>
<message>
<source>Last Send</source>
<translation>Ultima trimitere</translation>
</message>
<message>
<source>Last Receive</source>
<translation>Ultima primire</translation>
</message>
<message>
<source>Ping Time</source>
<translation>Timp ping</translation>
</message>
<message>
<source>Last block time</source>
<translation>Data ultimului bloc</translation>
</message>
<message>
<source>&Open</source>
<translation>&Deschide</translation>
</message>
<message>
<source>&Console</source>
<translation>&Consolă</translation>
</message>
<message>
<source>&Network Traffic</source>
<translation>Trafic reţea</translation>
</message>
<message>
<source>&Clear</source>
<translation>&Curăţă</translation>
</message>
<message>
<source>Totals</source>
<translation>Totaluri</translation>
</message>
<message>
<source>In:</source>
<translation>Intrare:</translation>
</message>
<message>
<source>Out:</source>
<translation>Ieşire:</translation>
</message>
<message>
<source>Debug log file</source>
<translation>Fişier jurnal depanare</translation>
</message>
<message>
<source>Clear console</source>
<translation>Curăţă consola</translation>
</message>
<message>
<source>1 &hour</source>
<translation>1 &oră</translation>
</message>
<message>
<source>1 &day</source>
<translation>1 &zi</translation>
</message>
<message>
<source>1 &week</source>
<translation>1 &săptămână</translation>
</message>
<message>
<source>1 &year</source>
<translation>1 &an</translation>
</message>
<message>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Folosiţi săgetile sus şi jos pentru a naviga în istoric şi <b>Ctrl-L</b> pentru a curăţa.</translation>
</message>
<message>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Scrieţi <b>help</b> pentru a vedea comenzile disponibile.</translation>
</message>
<message>
<source>%1 B</source>
<translation>%1 B</translation>
</message>
<message>
<source>%1 KB</source>
<translation>%1 KB</translation>
</message>
<message>
<source>%1 MB</source>
<translation>%1 MB</translation>
</message>
<message>
<source>%1 GB</source>
<translation>%1 GB</translation>
</message>
<message>
<source>via %1</source>
<translation>via %1</translation>
</message>
<message>
<source>never</source>
<translation>niciodată</translation>
</message>
<message>
<source>Inbound</source>
<translation>Intrare</translation>
</message>
<message>
<source>Outbound</source>
<translation>Ieşire</translation>
</message>
<message>
<source>Yes</source>
<translation>Da</translation>
</message>
<message>
<source>No</source>
<translation>Nu</translation>
</message>
<message>
<source>Unknown</source>
<translation>Necunoscut</translation>
</message>
</context>
<context>
<name>ReceiveCoinsDialog</name>
<message>
<source>&Amount:</source>
<translation>Sum&a:</translation>
</message>
<message>
<source>&Label:</source>
<translation>&Etichetă:</translation>
</message>
<message>
<source>&Message:</source>
<translation>&Mesaj:</translation>
</message>
<message>
<source>Reuse one of the previously used receiving addresses. Reusing addresses has security and privacy issues. Do not use this unless re-generating a payment request made before.</source>
<translation>Refoloseşte una din adresele de primire folosite anterior. Refolosirea adreselor poate crea probleme de securitate şi confidenţialitate. Nu folosiţi această opţiune decît dacă o cerere de regenerare a plăţii a fost făcută anterior.</translation>
</message>
<message>
<source>R&euse an existing receiving address (not recommended)</source>
<translation>R&efoloseşte o adresă de primire (nu este recomandat)</translation>
</message>
<message>
<source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the Chancoin network.</source>
<translation>Un mesaj opţional de ataşat la cererea de plată, care va fi afişat cînd cererea este deschisă. Notă: Acest mesaj nu va fi trimis cu plata către reţeaua Chancoin.</translation>
</message>
<message>
<source>An optional label to associate with the new receiving address.</source>
<translation>O etichetă opţională de asociat cu adresa de primire.</translation>
</message>
<message>
<source>Use this form to request payments. All fields are <b>optional</b>.</source>
<translation>Foloseşte acest formular pentru a solicita plăţi. Toate cîmpurile sînt <b>opţionale</b>.</translation>
</message>
<message>
<source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source>
<translation>O sumă opţională de cerut. Lăsaţi gol sau zero pentru a nu cere o sumă anume.</translation>
</message>
<message>
<source>Clear all fields of the form.</source>
<translation>Curăţă toate cîmpurile formularului.</translation>
</message>
<message>
<source>Clear</source>
<translation>Curăţă</translation>
</message>
<message>
<source>Requested payments history</source>
<translation>Istoricul plăţilor cerute</translation>
</message>
<message>
<source>&Request payment</source>
<translation>&Cerere plată</translation>
</message>
<message>
<source>Show the selected request (does the same as double clicking an entry)</source>
<translation>Arată cererea selectată (acelaşi lucru ca şi dublu-clic pe o înregistrare)</translation>
</message>
<message>
<source>Show</source>
<translation>Arată</translation>
</message>
<message>
<source>Remove the selected entries from the list</source>
<translation>Înlătură intrările selectate din listă</translation>
</message>
<message>
<source>Remove</source>
<translation>Înlătură</translation>
</message>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<source>QR Code</source>
<translation>Cod QR</translation>
</message>
<message>
<source>Copy &URI</source>
<translation>Copiază &URl</translation>
</message>
<message>
<source>Copy &Address</source>
<translation>Copiază &adresa</translation>
</message>
<message>
<source>&Save Image...</source>
<translation>&Salvează imaginea...</translation>
</message>
<message>
<source>Address</source>
<translation>Adresă</translation>
</message>
<message>
<source>Amount</source>
<translation>Cantitate</translation>
</message>
<message>
<source>Label</source>
<translation>Etichetă</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
<message>
<source>Label</source>
<translation>Etichetă</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>Send Coins</source>
<translation>Trimite monede</translation>
</message>
<message>
<source>Coin Control Features</source>
<translation>Caracteristici de control ale monedei</translation>
</message>
<message>
<source>Inputs...</source>
<translation>Intrări...</translation>
</message>
<message>
<source>automatically selected</source>
<translation>selecţie automată</translation>
</message>
<message>
<source>Insufficient funds!</source>
<translation>Fonduri insuficiente!</translation>
</message>
<message>
<source>Quantity:</source>
<translation>Cantitate:</translation>
</message>
<message>
<source>Bytes:</source>
<translation>Octeţi:</translation>
</message>
<message>
<source>Amount:</source>
<translation>Sumă:</translation>
</message>
<message>
<source>Fee:</source>
<translation>Taxă:</translation>
</message>
<message>
<source>After Fee:</source>
<translation>După taxă:</translation>
</message>
<message>
<source>Change:</source>
<translation>Rest:</translation>
</message>
<message>
<source>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</source>
<translation>Dacă este activat, dar adresa de rest este goală sau nevalidă, restul va fi trimis la o adresă nou generată.</translation>
</message>
<message>
<source>Custom change address</source>
<translation>Adresă personalizată de rest</translation>
</message>
<message>
<source>Transaction Fee:</source>
<translation>Taxă tranzacţie:</translation>
</message>
<message>
<source>Choose...</source>
<translation>Alegeţi...</translation>
</message>
<message>
<source>per kilobyte</source>
<translation>per kilooctet</translation>
</message>
<message>
<source>Hide</source>
<translation>Ascunde</translation>
</message>
<message>
<source>total at least</source>
<translation>total cel puţin</translation>
</message>
<message>
<source>Recommended:</source>
<translation>Recomandat:</translation>
</message>
<message>
<source>Custom:</source>
<translation>Personalizat:</translation>
</message>
<message>
<source>normal</source>
<translation>normal</translation>
</message>
<message>
<source>fast</source>
<translation>rapid</translation>
</message>
<message>
<source>Send to multiple recipients at once</source>
<translation>Trimite simultan către mai mulţi destinatari</translation>
</message>
<message>
<source>Add &Recipient</source>
<translation>Adaugă destinata&r</translation>
</message>
<message>
<source>Clear all fields of the form.</source>
<translation>Şterge toate cîmpurile formularului.</translation>
</message>
<message>
<source>Dust:</source>
<translation>Praf:</translation>
</message>
<message>
<source>Clear &All</source>
<translation>Curăţă to&ate</translation>
</message>
<message>
<source>Balance:</source>
<translation>Balanţă:</translation>
</message>
<message>
<source>Confirm the send action</source>
<translation>Confirmă operaţiunea de trimitere</translation>
</message>
<message>
<source>S&end</source>
<translation>Trimit&e</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<source>A&mount:</source>
<translation>Su&mă:</translation>
</message>
<message>
<source>Pay &To:</source>
<translation>Plăteşte că&tre:</translation>
</message>
<message>
<source>&Label:</source>
<translation>&Etichetă:</translation>
</message>
<message>
<source>Choose previously used address</source>
<translation>Alegeţi adrese folosite anterior</translation>
</message>
<message>
<source>This is a normal payment.</source>
<translation>Aceasta este o tranzacţie normală.</translation>
</message>
<message>
<source>The Chancoin address to send the payment to</source>
<translation>Adresa chancoin către care se face plata</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Lipeşte adresa din clipboard</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<source>Remove this entry</source>
<translation>Înlătură această intrare</translation>
</message>
<message>
<source>Message:</source>
<translation>Mesaj:</translation>
</message>
<message>
<source>Enter a label for this address to add it to the list of used addresses</source>
<translation>Introduceţi eticheta pentru ca această adresa să fie introdusă în lista de adrese folosite</translation>
</message>
<message>
<source>A message that was attached to the chancoin: URI which will be stored with the transaction for your reference. Note: This message will not be sent over the Chancoin network.</source>
<translation>un mesaj a fost ataşat la chancoin: URI care va fi stocat cu tranzacţia pentru referinţa dvs. Notă: Acest mesaj nu va fi trimis către reţeaua chancoin.</translation>
</message>
<message>
<source>Pay To:</source>
<translation>Plăteşte către:</translation>
</message>
<message>
<source>Memo:</source>
<translation>Memo:</translation>
</message>
</context>
<context>
<name>SendConfirmationDialog</name>
</context>
<context>
<name>ShutdownWindow</name>
<message>
<source>%1 is shutting down...</source>
<translation>%1 se închide</translation>
</message>
<message>
<source>Do not shut down the computer until this window disappears.</source>
<translation>Nu închide calculatorul pînă ce această fereastră nu dispare.</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<source>Signatures - Sign / Verify a Message</source>
<translation>Semnaturi - Semnează/verifică un mesaj</translation>
</message>
<message>
<source>&Sign Message</source>
<translation>&Semnează mesaj</translation>
</message>
<message>
<source>The Chancoin address to sign the message with</source>
<translation>Adresa cu care semnaţi mesajul</translation>
</message>
<message>
<source>Choose previously used address</source>
<translation>Alegeţi adrese folosite anterior</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Lipeşte adresa copiată din clipboard</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<source>Enter the message you want to sign here</source>
<translation>Introduceţi mesajul pe care vreţi să-l semnaţi, aici</translation>
</message>
<message>
<source>Signature</source>
<translation>Semnătură</translation>
</message>
<message>
<source>Copy the current signature to the system clipboard</source>
<translation>Copiază semnatura curentă în clipboard-ul sistemului</translation>
</message>
<message>
<source>Sign the message to prove you own this Chancoin address</source>
<translation>Semnează mesajul pentru a dovedi ca deţineţi acestă adresă Chancoin</translation>
</message>
<message>
<source>Sign &Message</source>
<translation>Semnează &mesaj</translation>
</message>
<message>
<source>Reset all sign message fields</source>
<translation>Resetează toate cîmpurile mesajelor semnate</translation>
</message>
<message>
<source>Clear &All</source>
<translation>Curăţă to&ate</translation>
</message>
<message>
<source>&Verify Message</source>
<translation>&Verifică mesaj</translation>
</message>
<message>
<source>The Chancoin address the message was signed with</source>
<translation>Introduceţi o adresă Chancoin</translation>
</message>
<message>
<source>Verify the message to ensure it was signed with the specified Chancoin address</source>
<translation>Verificaţi mesajul pentru a vă asigura că a fost semnat cu adresa Chancoin specificată</translation>
</message>
<message>
<source>Verify &Message</source>
<translation>Verifică &mesaj</translation>
</message>
<message>
<source>Reset all verify message fields</source>
<translation>Resetează toate cîmpurile mesajelor semnate</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<source>KB/s</source>
<translation>KB/s</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<source>Amount</source>
<translation>Cantitate</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<source>This pane shows a detailed description of the transaction</source>
<translation>Acest panou arată o descriere detaliată a tranzacţiei</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<source>Label</source>
<translation>Etichetă</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Fisier .csv cu separator - virgula</translation>
</message>
<message>
<source>Label</source>
<translation>Etichetă</translation>
</message>
<message>
<source>Address</source>
<translation>Adresă</translation>
</message>
<message>
<source>Exporting Failed</source>
<translation>Exportarea a eșuat</translation>
</message>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
<message>
<source>Unit to show amounts in. Click to select another unit.</source>
<translation>Unitatea în care sînt arătate sumele. Faceţi clic pentru a selecta o altă unitate.</translation>
</message>
</context>
<context>
<name>WalletFrame</name>
</context>
<context>
<name>WalletModel</name>
</context>
<context>
<name>WalletView</name>
</context>
<context>
<name>bitcoin-core</name>
<message>
<source>Options:</source>
<translation>Opţiuni:</translation>
</message>
<message>
<source>Specify data directory</source>
<translation>Specificaţi dosarul de date</translation>
</message>
<message>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Se conectează la un nod pentru a obţine adresele partenerilor, şi apoi se deconectează</translation>
</message>
<message>
<source>Specify your own public address</source>
<translation>Specificaţi adresa dvs. publică</translation>
</message>
<message>
<source>Accept command line and JSON-RPC commands</source>
<translation>Acceptă comenzi din linia de comandă şi comenzi JSON-RPC</translation>
</message>
<message>
<source>Run in the background as a daemon and accept commands</source>
<translation>Rulează în fundal ca un demon şi acceptă comenzi</translation>
</message>
<message>
<source>Chancoin Core</source>
<translation>Nucleul Chancoin</translation>
</message>
<message>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>Ataşaţi adresei date şi ascultaţi totdeauna pe ea. Folosiţi notaţia [host]:port pentru IPv6</translation>
</message>
<message>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Execută comanda cînd o tranzacţie a portofelului se schimbă (%s în cmd este înlocuit de TxID)</translation>
</message>
<message>
<source>Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)</source>
<translation>Setează numărul de thread-uri de verificare a script-urilor (%u la %d, 0 = auto, <0 = lasă atîtea nuclee libere, implicit: %d)</translation>
</message>
<message>
<source><category> can be:</source>
<translation><category> poate fi:</translation>
</message>
<message>
<source>Block creation options:</source>
<translation>Opţiuni creare bloc:</translation>
</message>
<message>
<source>Connection options:</source>
<translation>Opţiuni conexiune:</translation>
</message>
<message>
<source>Corrupted block database detected</source>
<translation>Bloc defect din baza de date detectat</translation>
</message>
<message>
<source>Debugging/Testing options:</source>
<translation>Opţiuni Depanare/Test:</translation>
</message>
<message>
<source>Do not load the wallet and disable wallet RPC calls</source>
<translation>Nu încarcă portofelul şi dezactivează solicitările portofel RPC</translation>
</message>
<message>
<source>Do you want to rebuild the block database now?</source>
<translation>Doriţi să reconstruiţi baza de date blocuri acum?</translation>
</message>
<message>
<source>Error initializing block database</source>
<translation>Eroare la iniţializarea bazei de date de blocuri</translation>
</message>
<message>
<source>Error initializing wallet database environment %s!</source>
<translation>Eroare la iniţializarea mediului de bază de date a portofelului %s!</translation>
</message>
<message>
<source>Error loading block database</source>
<translation>Eroare la încărcarea bazei de date de blocuri</translation>
</message>
<message>
<source>Error opening block database</source>
<translation>Eroare la deschiderea bazei de date de blocuri</translation>
</message>
<message>
<source>Error: Disk space is low!</source>
<translation>Eroare: Spaţiu pe disc redus!</translation>
</message>
<message>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Nu s-a reuşit ascultarea pe orice port. Folosiţi -listen=0 dacă vreţi asta.</translation>
</message>
<message>
<source>Importing...</source>
<translation>Import...</translation>
</message>
<message>
<source>Incorrect or no genesis block found. Wrong datadir for network?</source>
<translation>Incorect sau nici un bloc de geneza găsit. Directorul de retea greşit?</translation>
</message>
<message>
<source>Invalid -onion address: '%s'</source>
<translation>Adresa -onion nevalidă: '%s'</translation>
</message>
<message>
<source>Not enough file descriptors available.</source>
<translation>Nu sînt destule descriptoare disponibile.</translation>
</message>
<message>
<source>Only connect to nodes in network <net> (ipv4, ipv6 or onion)</source>
<translation>Se conectează doar la noduri în reţeaua <net> (ipv4, ipv6 sau onion)</translation>
</message>
<message>
<source>Set database cache size in megabytes (%d to %d, default: %d)</source>
<translation>Setează mărimea bazei de date cache în megaocteţi (%d la %d, implicit: %d)</translation>
</message>
<message>
<source>Set maximum block size in bytes (default: %d)</source>
<translation>Setaţi dimensiunea maximă a unui bloc în bytes (implicit: %d)</translation>
</message>
<message>
<source>Specify wallet file (within data directory)</source>
<translation>Specifică fişierul portofel (în dosarul de date)</translation>
</message>
<message>
<source>Use UPnP to map the listening port (default: %u)</source>
<translation>Foloseşte mapare UPnP pentru asculatere port (implicit: %u)</translation>
</message>
<message>
<source>Verifying blocks...</source>
<translation>Se verifică blocurile...</translation>
</message>
<message>
<source>Verifying wallet...</source>
<translation>Se verifică portofelul...</translation>
</message>
<message>
<source>Wallet %s resides outside data directory %s</source>
<translation>Portofelul %s se află în afara dosarului de date %s</translation>
</message>
<message>
<source>Wallet options:</source>
<translation>Opţiuni portofel:</translation>
</message>
<message>
<source>Allow JSON-RPC connections from specified source. Valid for <ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times</source>
<translation>Permite conexiunile JSON-RPC din sursa specificată. Valid pentru <ip> sînt IP singulare (ex. 1.2.3.4), o reţea/mască-reţea (ex. 1.2.3.4/255.255.255.0) sau o reţea/CIDR (ex. 1.2.3.4/24). Această opţiune poate fi specificată de mai multe ori</translation>
</message>
<message>
<source>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</source>
<translation>Execută comanda cînd o alertă relevantă este primită sau vedem o bifurcaţie foarte lungă (%s în cmd este înlocuit de mesaj)</translation>
</message>
<message>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: %d)</source>
<translation>Setează mărimea pentru tranzacţiile prioritare/taxe mici în octeţi (implicit: %d)</translation>
</message>
<message>
<source>(default: %u)</source>
<translation>(implicit: %u)</translation>
</message>
<message>
<source>Accept public REST requests (default: %u)</source>
<translation>Acceptă cererile publice REST (implicit: %u)</translation>
</message>
<message>
<source>Automatically create Tor hidden service (default: %d)</source>
<translation>Crează automat un serviciu Tor ascuns (implicit: %d)</translation>
</message>
<message>
<source>Connect through SOCKS5 proxy</source>
<translation>Conectare prin proxy SOCKS5</translation>
</message>
<message>
<source>Error reading from database, shutting down.</source>
<translation>Eroare la citirea bazei de date. Oprire.</translation>
</message>
<message>
<source>Information</source>
<translation>Informaţie</translation>
</message>
<message>
<source>Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)</source>
<translation>Sumă nevalidă pentru -paytxfee=<suma>: '%s' (trebuie să fie cel puţin %s)</translation>
</message>
<message>
<source>Invalid netmask specified in -whitelist: '%s'</source>
<translation>Mască reţea nevalidă specificată în -whitelist: '%s'</translation>
</message>
<message>
<source>Need to specify a port with -whitebind: '%s'</source>
<translation>Trebuie să specificaţi un port cu -whitebind: '%s'</translation>
</message>
<message>
<source>RPC server options:</source>
<translation>Opţiuni server RPC:</translation>
</message>
<message>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Trimite informaţiile trace/debug la consolă în locul fişierului debug.log</translation>
</message>
<message>
<source>Send transactions as zero-fee transactions if possible (default: %u)</source>
<translation>Trimitere tranzacţii ca tranzacţii taxă-zero dacă este posibil (implicit: %u)</translation>
</message>
<message>
<source>Show all debugging options (usage: --help -help-debug)</source>
<translation>Arată toate opţiunile de depanare (uz: --help -help-debug)</translation>
</message>
<message>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Micşorează fişierul debug.log la pornirea clientului (implicit: 1 cînd nu se foloseşte -debug)</translation>
</message>
<message>
<source>Signing transaction failed</source>
<translation>Nu s-a reuşit semnarea tranzacţiei</translation>
</message>
<message>
<source>This is experimental software.</source>
<translation>Acesta este un program experimental.</translation>
</message>
<message>
<source>Transaction amount too small</source>
<translation>Suma tranzacţionată este prea mică</translation>
</message>
<message>
<source>Transaction too large for fee policy</source>
<translation>Tranzacţie prea mare pentru politică gratis</translation>
</message>
<message>
<source>Transaction too large</source>
<translation>Tranzacţie prea mare</translation>
</message>
<message>
<source>Unable to bind to %s on this computer (bind returned error %s)</source>
<translation>Nu se poate lega la %s pe acest calculator. (Legarea a întors eroarea %s)</translation>
</message>
<message>
<source>Username for JSON-RPC connections</source>
<translation>Utilizator pentru conexiunile JSON-RPC</translation>
</message>
<message>
<source>Warning</source>
<translation>Avertisment</translation>
</message>
<message>
<source>Zapping all transactions from wallet...</source>
<translation>Şterge toate tranzacţiile din portofel...</translation>
</message>
<message>
<source>Password for JSON-RPC connections</source>
<translation>Parola pentru conexiunile JSON-RPC</translation>
</message>
<message>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Execută comanda cînd cel mai bun bloc se modifică (%s în cmd este înlocuit cu hash-ul blocului)</translation>
</message>
<message>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Permite căutări DNS pentru -addnode, -seednode şi -connect</translation>
</message>
<message>
<source>Loading addresses...</source>
<translation>Încărcare adrese...</translation>
</message>
<message>
<source>Output debugging information (default: %u, supplying <category> is optional)</source>
<translation>Produce toate informaţiile de depanare (implicit: %u <category> furnizată este opţională)</translation>
</message>
<message>
<source>(default: %s)</source>
<translation>(implicit: %s)</translation>
</message>
<message>
<source>How many blocks to check at startup (default: %u, 0 = all)</source>
<translation>Cîte blocuri verifică la pornire (implicit: %u, 0 = toate)</translation>
</message>
<message>
<source>Invalid -proxy address: '%s'</source>
<translation>Adresa -proxy nevalidă: '%s'</translation>
</message>
<message>
<source>Specify configuration file (default: %s)</source>
<translation>Specificaţi fişierul configuraţie (implicit: %s)</translation>
</message>
<message>
<source>Specify pid file (default: %s)</source>
<translation>Specifică fişierul pid (implicit: %s)</translation>
</message>
<message>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Reţeaua specificată în -onlynet este necunoscută: '%s'</translation>
</message>
<message>
<source>Insufficient funds</source>
<translation>Fonduri insuficiente</translation>
</message>
<message>
<source>Loading block index...</source>
<translation>Încărcare index bloc...</translation>
</message>
<message>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Adaugă un nod la care te poţi conecta pentru a menţine conexiunea deschisă</translation>
</message>
<message>
<source>Loading wallet...</source>
<translation>Încărcare portofel...</translation>
</message>
<message>
<source>Cannot downgrade wallet</source>
<translation>Nu se poate retrograda portofelul</translation>
</message>
<message>
<source>Cannot write default address</source>
<translation>Nu se poate scrie adresa implicită</translation>
</message>
<message>
<source>Rescanning...</source>
<translation>Rescanare...</translation>
</message>
<message>
<source>Done loading</source>
<translation>Încărcare terminată</translation>
</message>
<message>
<source>Error</source>
<translation>Eroare</translation>
</message>
</context>
</TS><|fim▁end|> | <source>Watch-only:</source>
<translation>Doar-supraveghere:</translation>
</message> |
<|file_name|>gawterm.py<|end_file_name|><|fim▁begin|># ------------------------------------------------------------------------
# Program : gawterm.py
# Author : Gerard Wassink
# Date : March 17, 2017
#
# Function : supply a terminal window with panes for remote control
# of my elevator, can also be used for other contraptions
#
# History : 20170317 - original version
#
# ------------------------------------------------------------------------
# GNU LICENSE CONDITIONS
# ------------------------------------------------------------------------
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# ------------------------------------------------------------------------
# Copyright (C) 2017 Gerard Wassink
# ------------------------------------------------------------------------
# ------------------------------------------------------------------------
# Libraries used
# ------------------------------------------------------------------------
import curses
import curses.textpad
import os
class term():
"""
Screen layout:
+--- staFrame -----------------++--- msgFrame -----------------+
|stawin ||msgwin |
| || |<|fim▁hole|> | || |
| || |
| || |
+--- cmdFrame -----------------+| |
|cmdwin || |
| || |
| || |
| || |
| || |
+------------------------------++------------------------------+
+--- inpFrame -------------------------------------------------+
|> inpwin |
+--------------------------------------------------------------+
"""
def __init__(self):
# ----------------------------------------------------------
# Get terminal size from system
# ----------------------------------------------------------
self.termHeight, self.termWidth = \
os.popen('stty size', 'r').read().split()
self.termWidth = int(self.termWidth)
self.termHeight = int(self.termHeight)
# ----------------------------------------------------------
# Calculate various sizes for windows
# ----------------------------------------------------------
self.colWidth = (self.termWidth - 4) / 2
self.colHeight = (self.termHeight - 5)
self.staHeight = 5
self.cmdHeight = self.colHeight - self.staHeight - 2
# ----------------------------------------------------------
# Initialize curses
# ----------------------------------------------------------
stdscr = curses.initscr()
curses.noecho()
# ----------------------------------------------------------
# Create frame for status window
# ----------------------------------------------------------
self.staFrame = curses.newwin(self.staHeight+2, self.colWidth+2, 0, 0)
self.staFrame.border()
self.staFrame.move(0, 5)
self.staFrame.addstr(" Status Window ")
self.staFrame.refresh()
# ----------------------------------------------------------
# Create status window
# ----------------------------------------------------------
self.stawin = curses.newwin(self.staHeight, self.colWidth, 1, 1)
# ----------------------------------------------------------
# Create frame for command window
# ----------------------------------------------------------
self.cmdFrame = curses.newwin(self.cmdHeight+2, \
self.colWidth+2, \
self.staHeight+2, 0)
self.cmdFrame.border()
self.cmdFrame.move(0, 5)
self.cmdFrame.addstr(" Command Window ")
self.cmdFrame.refresh()
# ----------------------------------------------------------
# Create command window
# ----------------------------------------------------------
self.cmdwin = curses.newwin(self.colHeight-(self.staHeight+2), self.colWidth, \
self.staHeight+3, 1)
# ----------------------------------------------------------
# Create frame for message window
# ----------------------------------------------------------
self.msgFrame = curses.newwin(self.colHeight+2, self.colWidth+2, \
0, self.colWidth+2)
self.msgFrame.border()
self.msgFrame.move(0, 5)
self.msgFrame.addstr(" Message Window ")
self.msgFrame.refresh()
# ----------------------------------------------------------
# Create message window
# ----------------------------------------------------------
self.msgwin = curses.newwin(self.colHeight, self.colWidth, \
1, self.colWidth+3)
# ----------------------------------------------------------
# Create frame for input window
# ----------------------------------------------------------
self.inpFrame = curses.newwin(3, 2*(self.colWidth+2), \
self.colHeight+2, 0)
self.inpFrame.border()
self.inpFrame.move(0, 5)
self.inpFrame.addstr(" Input: ")
self.inpFrame.move(1, 1)
self.inpFrame.addstr("> ")
self.inpFrame.refresh()
# ----------------------------------------------------------
# Create input window
# ----------------------------------------------------------
self.inpwin = curses.newwin(1, 2*(self.colWidth), self.colHeight+3, 3)
self.inpwin.refresh()
# ----------------------------------------------------------
# Create input Textbox
# ----------------------------------------------------------
self.inpbox = curses.textpad.Textbox(self.inpwin, insert_mode=True)
def inpRead(self):
self.inpwin.clear()
self.inpwin.move(0, 0)
self.inpbox.edit()
self.txt = self.inpbox.gather().strip()
return self.txt
def staPrint(self, text):
self.stawin.move(0,0)
self.stawin.deleteln()
try:
self.stawin.addstr(self.staHeight-1, 0, text)
except curses.error:
pass
self.stawin.refresh()
def staClear(self):
self.stawin.clear()
self.stawin.refresh()
def cmdPrint(self, text):
self.cmdwin.move(0,0)
self.cmdwin.deleteln()
try:
self.cmdwin.addstr(self.cmdHeight-1, 0, text)
except curses.error:
pass
self.cmdwin.refresh()
def cmdClear(self):
self.cmdwin.clear()
self.cmdwin.refresh()
def msgPrint(self, text):
self.msgwin.move(0,0)
self.msgwin.deleteln()
try:
self.msgwin.addstr(self.colHeight-1, 0, text)
except curses.error:
pass
self.msgwin.refresh()
def msgClear(self):
self.msgwin.clear()
self.msgwin.refresh()
def Close(self):
curses.echo()
curses.endwin()<|fim▁end|> | | || | |
<|file_name|>app_test.py<|end_file_name|><|fim▁begin|>import os
import unittest
os.environ['SIMULATE_HARDWARE'] = '1'
os.environ['LOCK_SETTINGS_PATH'] = 'test-settings'
import db
from app import app
primary_pin = '1234'
sub_pin = '0000'
class AppTestCase(unittest.TestCase):
def setUp(self):
app.testing = True
self.app = app.test_client()
db.read()
db.clear()
def test_empty_db(self):
rv = self.app.get('/')
assert b'Login' in rv.data
def test_login_logout(self):
rv = self.login('1234')
assert b'Profile' in rv.data
rv = self.logout()
assert b'Login' in rv.data
rv = self.login('1111')
assert b'PIN Invalid' in rv.data
def test_primary_lock_unlock(self):
self.login(primary_pin)
rv = self.app.post('/lock', follow_redirects=True)
assert b'Box has been locked for' in rv.data
rv = self.app.post('/unlock', follow_redirects=True)
assert b'Box is unlocked' in rv.data
def test_sub_lock_unlock(self):
self.login(sub_pin)
rv = self.app.post('/lock', follow_redirects=True)
assert b'Box has been locked for' in rv.data
rv = self.app.post('/unlock', follow_redirects=True)
assert b'Box is unlocked' in rv.data
def test_primary_lock_and_sub_cant_unlock(self):
self.login(primary_pin)<|fim▁hole|> self.login(sub_pin)
rv = self.app.post('/lock', follow_redirects=True)
assert b'Already locked' in rv.data
rv = self.app.post('/unlock', follow_redirects=True)
# still locked
assert b'Box has been locked for' in rv.data
def login(self, pin):
return self.app.post('/',
data={'inputPassword': pin},
follow_redirects=True)
def logout(self):
return self.app.get('/logout', follow_redirects=True)
if __name__ == '__main__':
unittest.main()<|fim▁end|> | self.app.post('/lock', follow_redirects=True)
self.logout()
|
<|file_name|>ToolbarDisplayOptions.java<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2014 The Android Open Source Project
*
* 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.example.android.supportv7.app;
import com.example.android.supportv7.R;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;<|fim▁hole|>import android.widget.Toast;
/**
* This demo shows how various action bar display option flags can be combined and their effects
* when used on a Toolbar-provided Action Bar
*/
public class ToolbarDisplayOptions extends ActionBarActivity
implements View.OnClickListener {
private View mCustomView;
private ActionBar.LayoutParams mCustomViewLayoutParams;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.toolbar_display_options);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
findViewById(R.id.toggle_home_as_up).setOnClickListener(this);
findViewById(R.id.toggle_show_home).setOnClickListener(this);
findViewById(R.id.toggle_use_logo).setOnClickListener(this);
findViewById(R.id.toggle_show_title).setOnClickListener(this);
findViewById(R.id.toggle_show_custom).setOnClickListener(this);
findViewById(R.id.cycle_custom_gravity).setOnClickListener(this);
findViewById(R.id.toggle_visibility).setOnClickListener(this);
// Configure several action bar elements that will be toggled by display options.
mCustomView = getLayoutInflater().inflate(R.layout.action_bar_display_options_custom, null);
mCustomViewLayoutParams = new ActionBar.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.display_options_actions, menu);
return true;
}
@Override
public boolean onSupportNavigateUp() {
finish();
return true;
}
@Override
public void onClick(View v) {
final ActionBar bar = getSupportActionBar();
int flags = 0;
switch (v.getId()) {
case R.id.toggle_home_as_up:
flags = ActionBar.DISPLAY_HOME_AS_UP;
break;
case R.id.toggle_show_home:
flags = ActionBar.DISPLAY_SHOW_HOME;
break;
case R.id.toggle_use_logo:
flags = ActionBar.DISPLAY_USE_LOGO;
getSupportActionBar().setLogo(R.drawable.ic_media_play);
break;
case R.id.toggle_show_title:
flags = ActionBar.DISPLAY_SHOW_TITLE;
break;
case R.id.toggle_show_custom:
flags = ActionBar.DISPLAY_SHOW_CUSTOM;
break;
case R.id.cycle_custom_gravity: {
ActionBar.LayoutParams lp = mCustomViewLayoutParams;
int newGravity = 0;
switch (lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.LEFT:
newGravity = Gravity.CENTER_HORIZONTAL;
break;
case Gravity.CENTER_HORIZONTAL:
newGravity = Gravity.RIGHT;
break;
case Gravity.RIGHT:
newGravity = Gravity.LEFT;
break;
}
lp.gravity = lp.gravity & ~Gravity.HORIZONTAL_GRAVITY_MASK | newGravity;
bar.setCustomView(mCustomView, lp);
return;
}
case R.id.toggle_visibility:
if (bar.isShowing()) {
bar.hide();
} else {
bar.show();
}
return;
}
int change = bar.getDisplayOptions() ^ flags;
bar.setDisplayOptions(change, flags);
}
}<|fim▁end|> | import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter; |
<|file_name|>aor-13.rs<|end_file_name|><|fim▁begin|>use std::cmp::min;
use std::cmp::max;
use std::collections::HashMap;
use std::io::prelude::*;
use std::fs::File;
use std::path::Path;
use std::cell::RefCell;
const INFTY: i32 = 1 << 30;
struct Node {
adj: Vec<(String, i32)>
}
struct Graph {
names: HashMap<String, usize>,
nodes: Vec<RefCell<Node>>
}
impl Node {
fn new() -> Node {
Node {
adj: Vec::new()
}
}
}
impl Graph {
fn new() -> Graph {
Graph {
names: HashMap::new(),
nodes: Vec::new()
}
}
fn spawn_if_missing(&mut self, name: String) {
if !self.names.contains_key(&name) {
let index = self.nodes.len();
self.nodes.push(RefCell::new(Node::new()));
self.names.insert(name, index);
}
}
fn add_edge(&mut self, from: String, to: String, dist: i32) {
self.spawn_if_missing(from.clone());
self.spawn_if_missing(to.clone());
let mut node_a = self.nodes[self.names[&from]].borrow_mut();
node_a.adj.push((to.clone(), dist));
}
fn get_tsp_length(&self) -> i32 {
let n = self.nodes.len();
let lim = 1 << n;
let mut dp = vec![vec![-INFTY; n]; lim];
dp[1][0] = 0;
for mask in 2..lim {
if mask % 2 == 1 {
for i in 1..n {
if (mask >> i) & 1 == 1 {
let neighbours = self.nodes[i].borrow().adj.clone();<|fim▁hole|> for neighbour in neighbours.iter() {
let j = self.names[&neighbour.0];
let weight = neighbour.1;
if (mask >> j) & 1 == 1 {
dp[mask][i] = max(dp[mask][i], dp[mask ^ (1 << i)][j] + weight);
}
}
}
}
}
}
let mut ret = -INFTY;
let neighbours = self.nodes[0].borrow().adj.clone();
for neighbour in neighbours.iter() {
let i = self.names[&neighbour.0];
let weight = neighbour.1;
ret = max(ret, dp[lim - 1][i] + weight);
}
ret
}
fn get_longest_ham_length(&self) -> i32 {
let n = self.nodes.len();
let lim = 1 << n;
let mut dp = vec![vec![-INFTY; n]; lim];
for i in 0..n {
dp[1 << i][i] = 0;
}
for mask in 0..lim {
for i in 0..n {
if (mask >> i) & 1 == 1 {
let neighbours = self.nodes[i].borrow().adj.clone();
for neighbour in neighbours.iter() {
let j = self.names[&neighbour.0];
let weight = neighbour.1;
if (mask >> j) & 1 == 1 {
dp[mask][i] = max(dp[mask][i], dp[mask ^ (1 << i)][j] + weight);
}
}
}
}
}
let mut ret = -INFTY;
for i in 0..n {
ret = max(ret, dp[lim - 1][i]);
}
ret
}
}
fn main() {
let mut f = File::open(Path::new("/Users/PetarV/rust-proj/advent-of-rust/target/input.txt"))
.ok()
.expect("Failed to open the input file!");
let mut input = String::new();
f.read_to_string(&mut input)
.ok()
.expect("Failed to read from the input file!");
let mut graph = Graph::new();
let mut edges: HashMap<(String, String), i32> = HashMap::new();
for line in input.lines() {
let parts: Vec<_> = line.split_whitespace().collect();
let a = parts[0].to_string();
let g = parts[2].to_string();
let d: i32 = parts[3].to_string().parse().ok().expect("Could not parse into an integer!");
let mut b = parts[10].to_string();
b.pop();
let w = if g == "gain" {
d
} else if g == "lose" {
-d
} else {
panic!("Something is wrong, no gain/lose in line!");
};
let key = (min(a.clone(), b.clone()), max(a.clone(), b.clone()));
if edges.contains_key(&key) {
let val = edges[&key];
edges.insert(key, val + w);
} else {
edges.insert(key, w);
}
}
for (key, w) in &edges {
let (a, b) = key.clone();
graph.add_edge(a.clone(), b.clone(), *w);
graph.add_edge(b.clone(), a.clone(), *w);
}
let ret = graph.get_tsp_length();
println!("The longest Hamiltonian cycle length is {}.", ret);
let ret = graph.get_longest_ham_length();
println!("The longest Hamiltonian path length is {}.", ret);
}<|fim▁end|> | |
<|file_name|>test-goldens.ts<|end_file_name|><|fim▁begin|>import * as firebaseFunctions from 'firebase-functions';
import * as firebaseAdmin from 'firebase-admin';
import * as path from 'path';
const gcs = require('@google-cloud/storage')();
/** The storage bucket to store the images. The bucket is also used by Firebase Storage. */
const bucket = gcs.bucket(firebaseFunctions.config().firebase.storageBucket);
/**
* Copy files from /screenshot/$prNumber/test/ to goldens/
* Only copy the files that test result is failure. Passed test images should be the same as<|fim▁hole|> */
export function copyTestImagesToGoldens(prNumber: string) {
return firebaseAdmin.database().ref(`screenshot/reports/${prNumber}/results`).once('value')
.then((snapshot: firebaseAdmin.database.DataSnapshot) => {
const failedFilenames: string[] = [];
let counter = 0;
snapshot.forEach(childSnapshot => {
if (childSnapshot.key && childSnapshot.val() === false) {
failedFilenames.push(childSnapshot.key);
}
counter++;
return counter === snapshot.numChildren();
});
return failedFilenames;
}).then((failedFilenames: string[]) => {
return bucket.getFiles({prefix: `screenshots/${prNumber}/test`}).then((data: any) => {
return Promise.all(data[0]
.filter((file: any) => failedFilenames.includes(
path.basename(file.name, '.screenshot.png')))
.map((file: any) => file.copy(`goldens/${path.basename(file.name)}`)));
});
});
}<|fim▁end|> | * goldens. |
<|file_name|>home.js<|end_file_name|><|fim▁begin|>'use strict';
<|fim▁hole|> });
});<|fim▁end|> | describe('Controller: HomeCtrl', function () {
it('should make a unit test ...', function () { |
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
from distutils.core import setup
with open('requirements.txt') as f:
requirements = f.read().splitlines()
setup(
name="wrtfreezer",<|fim▁hole|> url="https://github.com/shuhaowu/wrtfreezer",
packages=["wrtfreezer"],
scripts=["wrtbuild"],
requires=requirements,
)<|fim▁end|> | version="0.1",
description="A simple utility to mass build OpenWRT images.",
author="Shuhao Wu",
license="AGPL", |
<|file_name|>graph_gen.cpp<|end_file_name|><|fim▁begin|>//============================================================================
// Name : GraphGenerator.cpp
// Author : Sindre S. Fjermestad
// Version :
// Copyright : My copyright notice
// Description : Generator for graphs of a certain type
//============================================================================
#include <iostream>
#include <list>
#include <algorithm>
#include <vector>
#include <stdlib.h>
#include <time.h>
#include <boost/lexical_cast.hpp>
#include "kernelisation/graph_serialization.h"
using namespace std;
int main() {
const int num_vertices = 35;
const int num_sets = 5;
const int dencity_factor = 1;
vector<int> vertices;
vector<vector<int> > sets;
//1.PARTITIONING
int min = 0;
int max = num_vertices;
srand(time(0));
for (int i = 0; i < num_vertices; i++) {
vertices.push_back(i);
}
for (int i = 0; i < num_sets; i++) {
vector<int> set;
sets.push_back(set);
}
for (int i = 0; i < num_vertices; i++) {
int p = min + (rand() % (int) ((max - i) - min));
sets[i % num_sets].push_back(vertices[p]);
vertices.push_back(vertices[p]);
vertices.erase(vertices.begin() + p);
}
//2.IN SUBSET SELECTION
vector<int> exes; //pushing back will make the index here be the corresponding set
//HERE IS WHERE BOOST::GRAPH COMES IN!
vector<pair<int, int> > edges;
vector<pair<int, int> > ex_edges;
for (int i = 0; i < num_sets; i++) {
int p = (rand() % (sets[i].size()));
int xi = sets[i][p];
exes.push_back(xi);
//3.INSIDE/OUTSIDE SUBSET CONNECTION
for (int j = 0; j < sets[i].size(); j++) {
int yi = sets[i][j];
if (sets[i][j] != sets[i][p]) {
edges.push_back( { yi, xi });
}
}
}
//4.SUBSET CONNECTION
for (int i = 0; i < num_sets - 1; i++) {
int p;
if (num_sets >= 10) {
p = i + 1 + (rand() % 2);
} else {<|fim▁hole|> edges.push_back( { exes[i], exes[p] });
ex_edges.push_back( { exes[i], exes[p] });
}
//5.FILLING THE VOID
vector<pair<int, int> > none_edges;
for (int i = 0; i < num_sets; i++) { //all sets
vector<int> seti = sets[i];
for (int x = 0, setSize = seti.size(); x < setSize; x++) { // all vertices in set
int vx = seti[x];
for (int y = 0; y < setSize; y++) { //all other vertices in set
int vy = seti[y];
pair<int, int> edge( { vx, vy });
if (find(edges.begin(), edges.end(), edge) != edges.end()) { // if edge not actaully a none edge a.k.a. an edge!
continue;
}
if (edge.first == edge.second) { //if it's a self referencing edge
continue;
}
edge = {vy,vx};
if (find(edges.begin(), edges.end(), edge) != edges.end()) { // if edge has an alter ego!
continue;
}
none_edges.push_back( { vx, vy });
}
}
}
cout << "all the none edges in the graph after generating them = "
<< none_edges.size() << endl;
cout << "all the edges in the graph = " << edges.size() << endl;
bool foundOne = false;
cout << endl << endl;
for (int m = 0, dencity = none_edges.size() / dencity_factor; m < dencity;
m++) {
foundOne = false;
int p = rand() % none_edges.size();
pair<int, int> edgie = none_edges[p];
int vx = edgie.first;
int vy = edgie.second;
pair<int, int> alterEgo( { vy, vx });
if (find(edges.begin(), edges.end(), alterEgo) != edges.end()) { //if alter ego created at some point
none_edges.erase(none_edges.begin() + p); //remove edge from set
continue; // don't care about its
} else {
vector<int> seti;
for (int setsearch = 0, setcount = sets.size();
setsearch < setcount; setsearch++) {
seti = sets[setsearch];
if (find(seti.begin(), seti.end(), vx) != seti.end()) {
seti = sets[setsearch];
break;
}
}
for (int n = 0, setSize = seti.size(); n < setSize; n++) { //y's neighbourhood
int vn = seti[n]; //potential neighbour of vy
if (vn == vy || vn == vx
|| find(exes.begin(), exes.end(), vn) != exes.end()) {
continue;
}
edgie = {vy,vn}; //the hypotetical edge
if (find(edges.begin(), edges.end(), edgie) != edges.end()) { //is there actually an edge from vy to vn
edgie = {vn,vx}; //a hypothetical link back home
foundOne = false;
if (find(edges.begin(), edges.end(), edgie)
!= edges.end()) { //if vn points back to vx girth = 3, ignored
continue;
} else { //check vn's neighbourhood for girth = 4 links
for (int k = 0; k < setSize; k++) { //potential neighbourhood of vn
int vk = seti[k];//potentional neighbour of vn
if (vk == vy || vk == vx
|| find(exes.begin(), exes.end(), vk) != exes.end()) {
continue;
}
edgie = {vn,vk};
if (find(edges.begin(), edges.end(),
edgie) != edges.end()) { //there's actual an edge from vn to vk
edgie = {vk,vx};
foundOne = false;
if(find(edges.begin(),edges.end(),edgie) != edges.end()) { //if vk points back to vx girth = 4, ignored
} else { //should be guarantied a girth >= 5 here
foundOne = true;
}
} else {
foundOne = true;
}
}
}
} else {
foundOne = true;
}
}
}
if (foundOne) {
edges.push_back( { vx, vy });
foundOne = false;
}
none_edges.erase(none_edges.begin() + p);
}
cout << endl;
cout << endl << "all the none edges in the graph after selection= "
<< none_edges.size() << endl;
cout << "all the edges in the final graph (subset)= " << edges.size()
<< endl << endl;
int p = rand() % exes.size();
while (p <= exes.size() / 4) { //just so it's not COMPLETELY the same ex "clique"
p = rand() % exes.size();
}
for (int i = 0, excount = p; i < excount; i++) {
for (int j = i + 1; j < exes.size() - rand() % 3; j++) {
pair<int, int> edge( { exes[i], exes[j] });
if (find(ex_edges.begin(), ex_edges.end(), edge)
!= ex_edges.end()) {
} else {
edges.push_back(edge);
}
}
}
cout << "total edges in final graph: " << edges.size() << endl;
cout << endl << "in the set you'll find: " << endl;
for (int i = 0, setCount = sets.size(); i < setCount; i++) {
cout << "(";
for (int j = 0, setSize = sets[i].size(); j < setSize; j++) {
cout << sets[i][j] << ", ";
}
cout << ")" << endl;
}
cout << "with exes: ";
for (int i = 0, exCount = exes.size(); i < exCount; i++) {
cout << exes[i] << " ";
}
cout << endl << "and all the edges: " << endl;
for (int i = 0, edgeCount = edges.size(); i < edgeCount; i++) {
if (i > 22) {
if (i % num_sets == 0) {
cout << endl;
}
cout << "(" << edges[i].first << "," << edges[i].second << ") ";
}
}
cout << endl << endl << "this be good" << endl; // prints this be good
ofstream outputfile(boost::lexical_cast<std::string>(std::time(nullptr))+".dot");
outputGraph(outputfile, buildGraph(num_vertices, edges ));
return 0;
}<|fim▁end|> | p = i + 1;
} |
<|file_name|>Loader.js<|end_file_name|><|fim▁begin|>const fs = require('fs');
class Loader {
static extend (name, loader) {
return { name, loader };
}
static get (name, options) {
const item = options.loaders.find((loader) => name === loader.name);
if (!item) {
throw new Error(`Missing loader for ${name}`);
}
return item.loader;
}
static getFileContent (filename, options) {
return fs.readFileSync(filename, options).toString();
}
constructor (options) {
this.options = options;
}
/* istanbul ignore next */
/* eslint-disable-next-line class-methods-use-this */
load () {
throw new Error('Cannot call abstract Loader.load() method');
}
emitTemplate (source) {
this.options.source.template = source || '';
return Promise.resolve();
}
emitScript (source) {<|fim▁hole|> return Promise.resolve();
}
emitErrors (errors) {
this.options.source.errors.push(...errors);
return Promise.resolve();
}
pipe (name, source) {
const LoaderClass = Loader.get(name, this.options);
return new LoaderClass(this.options).load(source);
}
}
module.exports = Loader;<|fim▁end|> | this.options.source.script = source || '';
|
<|file_name|>ga_statistics.rs<|end_file_name|><|fim▁begin|>// Copyright 2016 Revolution Solid & Contributors.
// author(s): carlos-lopez-garces, sysnett
// rust-monster is licensed under an MIT License.
use std::cmp::Ordering::*;
use ::ga::ga_core::GAIndividual;
use ::ga::ga_population::{GAPopulation, GAPopulationStats, GAPopulationSortOrder};
pub struct GAStatistics<T: GAIndividual>
{
// All statistics collected after last reset.
num_selections: usize, // aka numsel
num_crossovers: usize, // aka numcro
num_mutations: usize, // aka nummut
num_replacements: usize, // aka numrep
num_ind_evaluations: usize, // aka numeval
num_pop_evaluations: usize, // aka numpeval
pub cur_generation: u32, // aka curgen
record_frequency: u32, // aka scoreFreq
record_diversity: bool, // aka dodiv
pub alltime_best_pop: Option<GAPopulation<T>>, // aka boa
pub alltime_max_score: f32, // aka maxever
pub alltime_min_score: f32, // aka minever
pub on_performance: f32, // aka on
pub off_max_performance: f32, // aka offmax
pub off_min_performance: f32, // aka offmin
// Call generation_statistics(1) instead.
// init_avg_score: f32, // aka aveInit
// init_max_score: f32, // aka maxInit
// init_min_score: f32, // aka minInit
// init_std_dev: f32, // aka devInit
// init_diversity: f32, // aka divInit
// Call generation_statistics(cur_generation) instead.
// cur_avg_score: f32, // aka aveCur
// cur_max_score: f32, // aka maxCur
// cur_min_score: f32, // aka minCur
// cur_std_dev: f32, // aka devCur
// cur_diversity: f32, // aka divCur
hist_stats: Vec<GAPopulationStats>,
// num_scores: u32, // aka Nscrs
// generations: Vec<i32>, // aka gen
// avg_scores: Vec<f32>, // aka aveScore
// max_scores: Vec<f32>, // aka maxScore
// min_scores: Vec<f32>, // aka minScore
// std_dev_scores: Vec<f32>, // aka devScore
// diversities: Vec<f32>, // aka divScore
}
impl<T: GAIndividual> GAStatistics<T>
{
fn new() -> GAStatistics<T>
{
GAStatistics
{
num_selections: 0,
num_crossovers: 0,
num_mutations: 0,
num_replacements: 0,
num_ind_evaluations: 0,
num_pop_evaluations: 0,
cur_generation: 0,
record_frequency: 1,
record_diversity: false,
alltime_best_pop: None,
alltime_max_score: 0.0,
alltime_min_score: 0.0,
on_performance: 0.0,
off_max_performance: 0.0,
off_min_performance: 0.0,
//init_avg_score: 0.0,
//init_max_score: 0.0,
//init_min_score: 0.0,
//init_std_dev: 0.0,
//init_diversity: -1.0,
// cur_avg_score: 0.0,
// cur_max_score: 0.0,
// cur_min_score: 0.0,
// cur_std_dev: 0.0,
// cur_diversity: -1.0,
hist_stats: Vec::new(),
// num_scores: 0,
// generations: Vec::new(),
// avg_scores: Vec::new(),
// max_scores: Vec::new(),
// min_scores: Vec::new(),
// std_dev_scores: Vec::new(),
// diversities: Vec::new(),
}
}
fn update(&mut self, pop: &mut GAPopulation<T>) where T: Clone + PartialEq
{
match pop.statistics()
{
None =>
{
// TODO: Handle.
},
Some(stats) =>
{
self.cur_generation += 1;
// TODO: Flush scores.
self.alltime_max_score = self.alltime_max_score.max(stats.raw_max);
self.alltime_min_score = self.alltime_min_score.min(stats.raw_min);
self.on_performance = (self.on_performance * (self.cur_generation-1) as f32 + stats.raw_avg) / self.cur_generation as f32;
self.off_max_performance = (self.off_max_performance * (self.cur_generation-1) as f32 + stats.raw_max) / self.cur_generation as f32;
self.off_min_performance = (self.off_min_performance * (self.cur_generation-1) as f32 + stats.raw_min) / self.cur_generation as f32;
// Store and compute diversity in GAPopulationStats.
// self.cur_diversity = if self.record_diversity { pop.diversity() } else { -1.0 };
// Update the alltime_best_pop with the input population.
self.update_best(pop);
// Archive this generation's statistics.
self.hist_stats.push(stats);
}
}
}
fn best(&self) -> Option<GAPopulation<T>> where T: Clone
{
self.alltime_best_pop.clone()
}
// Set generation #1. Or reset to new generation #1.
fn set_best(&mut self, mut pop: GAPopulation<T>)
{
match pop.statistics()
{
None =>
{
// TODO: Handle.
},
Some(stats) =>
{
self.cur_generation = 1;
self.alltime_max_score = self.alltime_max_score.max(stats.raw_max);
self.alltime_min_score = self.alltime_min_score.min(stats.raw_min);
self.on_performance = (self.on_performance * (self.cur_generation-1) as f32 + stats.raw_avg) / self.cur_generation as f32;
self.off_max_performance = (self.off_max_performance * (self.cur_generation-1) as f32 + stats.raw_max) / self.cur_generation as f32;
self.off_min_performance = (self.off_min_performance * (self.cur_generation-1) as f32 + stats.raw_min) / self.cur_generation as f32;
self.alltime_best_pop = Some(pop);
self.hist_stats.push(stats);
}
}
}
fn update_best(&mut self, pop: &GAPopulation<T>) where T: Clone + PartialEq
{
match self.alltime_best_pop
{
Some(ref mut best_pop) if best_pop.size() > 0 =>
{
let best_pop_size = best_pop.size();
if pop.order() != best_pop.order()
{
// This is what galib does.
// Why would the order change from one generation to another?
best_pop.set_order_and_sort(pop.order());
}
let order = best_pop.order();
if best_pop_size == 1
{
let mut best_pop_best_ind = best_pop.best_by_raw_score_mut();
let pop_best_ind = pop.best_by_raw_score();
if (order == GAPopulationSortOrder::LowIsBest
&& pop_best_ind.raw() < best_pop_best_ind.raw())
||
(order == GAPopulationSortOrder::HighIsBest
&& pop_best_ind.raw() > best_pop_best_ind.raw())
{
(*best_pop_best_ind).clone_from(pop_best_ind);
}
}
else
{
let mut i = 0;
let pop_size = pop.size();
// This closure compares the raw scores of 2 individuals
// and determines whether the left-hand-side is a better
// score than the right-hand-side according to the
// populations' order.
let cmp = |l_raw: f32, r_raw: f32|
{
match order
{
GAPopulationSortOrder::HighIsBest => l_raw.partial_cmp(&r_raw).unwrap(),
GAPopulationSortOrder::LowIsBest =>
{
match l_raw.partial_cmp(&r_raw).unwrap()
{
Equal => Equal,
Greater => Less,
Less => Greater
}
}
}
};
// Read Greater as Better.
while i < pop_size
&& cmp(pop.kth_best_by_raw_score(i).raw(),
best_pop.worst_by_raw_score().raw()) == Greater
{
let mut k = 0;
let pop_ith_best = pop.kth_best_by_raw_score(i);
let pop_ith_best_raw = pop_ith_best.raw();
// Read Less as Worse.
while cmp(pop_ith_best_raw, best_pop.kth_best_by_raw_score(k).raw()) == Less
&& k < best_pop_size
{
k = k+1;
}
for j in k..best_pop_size
{
let best_pop_jth_best_raw;
{
// Introduce a new scope. Otherwise, the later mutable
// borrow from worst_by_raw_score_mut() would not be
// allowed to co-exist with the immutable borrow from
// kth_best_by_raw_score().
let best_pop_jth_best = best_pop.kth_best_by_raw_score(j);
best_pop_jth_best_raw = best_pop_jth_best.raw();
if pop_ith_best == best_pop_jth_best
{
break;
}
}
// Read Greater as Better.
if cmp(pop_ith_best_raw, best_pop_jth_best_raw) == Greater
{
(*best_pop.worst_by_raw_score_mut()).clone_from(pop_ith_best);
best_pop.force_sort();
break;
}
}
i = i+1;
}
}
best_pop.reset_statistics();
best_pop.statistics();
},
_ =>
{
// Usage error. Client should call set_best() first, with a non-empty population.
// NOTE: This is what galib does in updateBestIndividual().
}
}
}
// Get the statistics of the nth generation (#1 is the first one).
fn generation_statistics(&mut self, nth_generation: usize) -> Option<GAPopulationStats>
{
if nth_generation > 0 && nth_generation <= self.hist_stats.len()
{
Some(self.hist_stats[nth_generation-1].clone())
}
else
{
None
}
}
// Get the statistics of the alltime-best individuals.
fn alltime_best_statistics(&mut self) -> Option<GAPopulationStats>
{
match self.alltime_best_pop
{
Some(ref mut best_pop) => best_pop.statistics(),
None => None
}
}
}
////////////////////////////////////////
// Tests
#[cfg(test)]
mod test
{
use std::f32;
use super::*;
use ::ga::ga_test::*;
use ::ga::ga_core::*;
use ::ga::ga_population::*;
use ::ga::ga_random::GARandomCtx;
#[test]
fn test_update_statistics()
{
ga_test_setup("ga_statistics::test_update_statistics");
// Generation 1.
let raw_scores_1: Vec<f32> = vec![-10.0, -8.0, -6.0, -4.0, -2.0, 0.1, 2.0, 4.0, 6.0, 8.0, 10.0];
let expected_sum_1 = raw_scores_1.iter().fold(0.0, |sum, rs| sum + rs);
let expected_avg_1 = expected_sum_1 / raw_scores_1.len() as f32;
let expected_max_1 = raw_scores_1.iter().cloned().fold(f32::NEG_INFINITY, |max, rs| max.max(rs));
let expected_min_1 = raw_scores_1.iter().cloned().fold(f32::INFINITY, |min, rs| min.min(rs));
let expected_var_1 = raw_scores_1.iter().fold(0.0, |var, rs| var + (rs - expected_avg_1).powi(2)) / (raw_scores_1.len()-1) as f32;
let expected_std_dev_1 = expected_var_1.sqrt();
let mut inds_1: Vec<GATestIndividual> = Vec::new();
for rs in raw_scores_1.iter().cloned()
{
inds_1.push(GATestIndividual::new(rs));
}
let mut pop_1 = GAPopulation::new(inds_1, GAPopulationSortOrder::LowIsBest);
pop_1.sort();
pop_1.statistics();
// Generation 2.
let raw_scores_2: Vec<f32> = vec![-9.0, -7.0, -5.0, -3.0, -1.0, 1.0, 3.0, 5.0, 7.0, 9.0, 11.0];
let expected_sum_2 = raw_scores_2.iter().fold(0.0, |sum, rs| sum + rs);
let expected_avg_2 = expected_sum_2 / raw_scores_2.len() as f32;
let expected_max_2 = raw_scores_2.iter().cloned().fold(f32::NEG_INFINITY, |max, rs| max.max(rs));
let expected_min_2 = raw_scores_2.iter().cloned().fold(f32::INFINITY, |min, rs| min.min(rs));
let expected_var_2 = raw_scores_2.iter().fold(0.0, |var, rs| var + (rs - expected_avg_2).powi(2)) / (raw_scores_2.len()-1) as f32;
let expected_std_dev_2 = expected_var_2.sqrt();
let mut inds_2: Vec<GATestIndividual> = Vec::new();
for rs in raw_scores_2.iter().cloned()
{
inds_2.push(GATestIndividual::new(rs));
}
let mut pop_2 = GAPopulation::new(inds_2, GAPopulationSortOrder::LowIsBest);
pop_2.sort();
pop_2.statistics();
// Statistics after generation 1.
let mut stats = GAStatistics::<GATestIndividual>::new();
stats.set_best(pop_1.clone());
let pop1_stats = pop_1.statistics().unwrap();
let gen1_stats = stats.generation_statistics(1).unwrap();
assert_eq!(stats.alltime_max_score == expected_max_1, true);
assert_eq!(stats.alltime_min_score == expected_min_1, true);
assert_eq!(gen1_stats == pop1_stats, true);
// Statistics after generation 2.
stats.update(&mut pop_2);
let pop2_stats = pop_2.statistics().unwrap();
let gen2_stats = stats.generation_statistics(2).unwrap();
assert_eq!(stats.alltime_max_score == expected_max_2, true);
assert_eq!(stats.alltime_min_score == expected_min_1, true);
assert_eq!(gen2_stats == pop2_stats, true);
ga_test_teardown();
}
#[test]
fn test_update_best_population()
{
let test_name = "ga_statistics::test_update_best_population";
ga_test_setup(test_name);
let mut fact = GATestFactory::new(0.0);
let rng_ctx = &mut GARandomCtx::new_unseeded(test_name.to_string());
{
/* Create 3 populations, each one better than the previous one. */
/* Each one should replace the previous as the all-time best. */
/* 1-individual populations, HighIsBest ranking. */
let mut pop = fact.random_population(1, GAPopulationSortOrder::HighIsBest, rng_ctx);
pop.sort();
pop.statistics();
let mut better_pop = fact.better_random_population_than(&pop);
better_pop.sort();
better_pop.statistics();
let mut even_better_pop = fact.better_random_population_than(&better_pop);
even_better_pop.sort();
even_better_pop.statistics();
let mut stats = GAStatistics::<GATestIndividual>::new();
stats.set_best(pop.clone());
stats.update_best(&better_pop);
let mut best_pop = stats.best().unwrap();
assert_eq!(best_pop == better_pop, true);
stats.update_best(&even_better_pop);
best_pop = stats.best().unwrap();
assert_eq!(best_pop == even_better_pop, true);
}
{
/* Create 3 populations, each one better than the previous one. */
/* Each one should replace the previous as the all-time best. */
/* 1-individual populations, LowIsBest ranking. */
let mut pop = fact.random_population(1, GAPopulationSortOrder::LowIsBest, rng_ctx);
pop.sort();
pop.statistics();
let mut better_pop = fact.better_random_population_than(&pop);
better_pop.sort();
better_pop.statistics();
let mut even_better_pop = fact.better_random_population_than(&better_pop);
even_better_pop.sort();
even_better_pop.statistics();
let mut stats = GAStatistics::<GATestIndividual>::new();
stats.set_best(pop.clone());
stats.update_best(&better_pop);
let mut best_pop = stats.best().unwrap();
assert_eq!(best_pop == better_pop, true);
stats.update_best(&even_better_pop);
best_pop = stats.best().unwrap();
assert_eq!(best_pop == even_better_pop, true);
}
{
/* Create 3 populations, each one better than the previous one. */
/* Each one should replace the previous as the all-time best. */
/* N-individual populations, N > 1, HighIsBest ranking. */
let mut pop = fact.random_population(5, GAPopulationSortOrder::HighIsBest, rng_ctx);
pop.sort();
pop.statistics();
let mut better_pop = fact.better_random_population_than(&pop);
better_pop.sort();
better_pop.statistics();
let mut even_better_pop = fact.better_random_population_than(&better_pop);
even_better_pop.sort();
even_better_pop.statistics();
let mut stats = GAStatistics::<GATestIndividual>::new();
stats.set_best(pop.clone());<|fim▁hole|> assert_eq!(best_pop == better_pop, true);
stats.update_best(&even_better_pop);
best_pop = stats.best().unwrap();
assert_eq!(best_pop == even_better_pop, true);
}
{
/* Create 3 populations, each one better than the previous one. */
/* Each one should replace the previous as the all-time best. */
/* N-individual populations, N > 1, LowIsBest ranking. */
let mut pop = fact.random_population(5, GAPopulationSortOrder::LowIsBest, rng_ctx);
pop.sort();
pop.statistics();
let mut better_pop = fact.better_random_population_than(&pop);
better_pop.sort();
better_pop.statistics();
let mut even_better_pop = fact.better_random_population_than(&better_pop);
even_better_pop.sort();
even_better_pop.statistics();
let mut stats = GAStatistics::<GATestIndividual>::new();
stats.set_best(pop.clone());
stats.update_best(&better_pop);
let mut best_pop = stats.best().unwrap();
assert_eq!(best_pop == better_pop, true);
stats.update_best(&even_better_pop);
best_pop = stats.best().unwrap();
assert_eq!(best_pop == even_better_pop, true);
}
{
// Scores were chosen so that the best population contain individuals
// from 2 different populations.
// HighIsBest ranking.
// Even scores.
let raw_scores_1: Vec<f32> = vec![-10.0, -8.0, -6.0, -4.0, -2.0, 0.1, 2.0, 4.0, 6.0, 8.0, 10.0];
// Odd scores.
let raw_scores_2: Vec<f32> = vec![-9.0, -7.0, -5.0, -3.0, -1.0, 1.0, 3.0, 5.0, 7.0, 9.0, 11.0];
let mut inds_1: Vec<GATestIndividual> = Vec::new();
for rs in raw_scores_1.iter().cloned()
{
inds_1.push(GATestIndividual::new(rs));
}
let mut pop_1 = GAPopulation::new(inds_1, GAPopulationSortOrder::HighIsBest);
pop_1.sort();
pop_1.statistics();
let mut inds_2: Vec<GATestIndividual> = Vec::new();
for rs in raw_scores_2.iter().cloned()
{
inds_2.push(GATestIndividual::new(rs));
}
let mut pop_2 = GAPopulation::new(inds_2, GAPopulationSortOrder::HighIsBest);
pop_2.sort();
pop_1.statistics();
let mut stats = GAStatistics::<GATestIndividual>::new();
stats.set_best(pop_1.clone());
stats.update_best(&pop_2);
let mut best_pop = stats.best().unwrap();
let best_raw_scores: Vec<f32> = vec![11.0, 10.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0];
let mut best_inds: Vec<GATestIndividual> = Vec::new();
for rs in best_raw_scores.iter().cloned()
{
best_inds.push(GATestIndividual::new(rs));
}
let mut expected_best_pop = GAPopulation::new(best_inds, GAPopulationSortOrder::HighIsBest);
expected_best_pop.sort();
expected_best_pop.statistics();
assert_eq!(best_pop == expected_best_pop, true);
}
{
// Scores were chosen so that the best population contain individuals
// from 2 different populations.
// LowIsBest ranking.
// Even scores.
let raw_scores_1: Vec<f32> = vec![-10.0, -8.0, -6.0, -4.0, -2.0, 0.1, 2.0, 4.0, 6.0, 8.0, 10.0];
// Raw scores.
let raw_scores_2: Vec<f32> = vec![-9.0, -7.0, -5.0, -3.0, -1.0, 1.0, 3.0, 5.0, 7.0, 9.0, 11.0];
let mut inds_1: Vec<GATestIndividual> = Vec::new();
for rs in raw_scores_1.iter().cloned()
{
inds_1.push(GATestIndividual::new(rs));
}
let mut pop_1 = GAPopulation::new(inds_1, GAPopulationSortOrder::LowIsBest);
pop_1.sort();
pop_1.statistics();
let mut inds_2: Vec<GATestIndividual> = Vec::new();
for rs in raw_scores_2.iter().cloned()
{
inds_2.push(GATestIndividual::new(rs));
}
let mut pop_2 = GAPopulation::new(inds_2, GAPopulationSortOrder::LowIsBest);
pop_2.sort();
pop_1.statistics();
let mut stats = GAStatistics::<GATestIndividual>::new();
stats.set_best(pop_1.clone());
stats.update_best(&pop_2);
let mut best_pop = stats.best().unwrap();
let best_raw_scores: Vec<f32> = vec![-10.0, -9.0, -8.0, -7.0, -6.0, -5.0, -4.0, -3.0, -2.0, -1.0, 0.1];
let mut best_inds: Vec<GATestIndividual> = Vec::new();
for rs in best_raw_scores.iter().cloned()
{
best_inds.push(GATestIndividual::new(rs));
}
let mut expected_best_pop = GAPopulation::new(best_inds, GAPopulationSortOrder::LowIsBest);
expected_best_pop.sort();
expected_best_pop.statistics();
assert_eq!(best_pop == expected_best_pop, true);
}
ga_test_teardown();
}
}<|fim▁end|> | stats.update_best(&better_pop);
let mut best_pop = stats.best().unwrap(); |
<|file_name|>merge_java_srcs.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Copyright (c) 2014 Intel Corporation. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import optparse
import os
import re
import sys
import shutil
def DoCopy(path, target_path):
if os.path.isfile(path):
package = ''
package_re = re.compile(
'^package (?P<package>([a-zA-Z0-9_]+.)*[a-zA-Z0-9_]+);$')
for line in open(path).readlines():
match = package_re.match(line)
if match:
package = match.group('package')
break
sub_path = os.path.sep.join(package.split('.'))
shutil.copy(path, os.path.join(target_path, sub_path))
return
for dirpath, _, files in os.walk(path):
if not files:
continue
sub_path = os.path.relpath(dirpath, path)
target_dirpath = os.path.join(target_path, sub_path)
if not os.path.isdir(target_dirpath):
os.makedirs(target_dirpath)
for f in files:
fpath = os.path.join(dirpath, f)
# "interface type;" is invalid for normal android project,
# It's only for chromium's build system, ignore these aidl files.
if f.endswith('.aidl'):
invalid_lines = []
for line in open(fpath).readlines():
if re.match('^interface .*;$', line):
invalid_lines.append(line)
if invalid_lines:
continue
elif not f.endswith('.java'):
continue
shutil.copy(fpath, target_dirpath)
def main():
parser = optparse.OptionParser()
info = ('The java source dirs to merge.')
parser.add_option('--dirs', help=info)
info = ('The target to place all the sources.')
parser.add_option('--target-path', help=info)
options, _ = parser.parse_args()
if os.path.isdir(options.target_path):
shutil.rmtree(options.target_path)
os.makedirs(options.target_path)
for path in options.dirs.split(' '):
if path.startswith('"') and path.endswith('"'):<|fim▁hole|>
if __name__ == '__main__':
sys.exit(main())<|fim▁end|> | path = eval(path)
DoCopy(path, options.target_path)
|
<|file_name|>WholeCellViz-visualizations.js<|end_file_name|><|fim▁begin|>/***********************
* WholeCellViz visualizations should extend the Visualization class using this template:
*
* var NewVisualization = Visualization2D.extend({
* getData: function(md){
* this.data = this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'attr_name'});
* },
*
* calcLayout: function(){
* },
*
* drawDynamicObjects: function(t){
* this.drawObject({
* 'strokeStyle': strokeStyle,
* 'fillStyle': fillStyle,
* 'data': getDataPoint(this.data, t),
* drawFunc: function(self, ctx, data){
* },
* tipFunc: function(self, data){
* },
* clickFunc: function(self, data){
* },
* });
* },
* });
*
* Author: Jonathan Karr, [email protected]
* Author: Ruby Lee
* Affiliation: Covert Lab, Department of Bioengineering, Stanford University
* Last updated:9/2/2012
************************/
var CellShapeVisualization = Visualization2D.extend({
arrowLength: 10,
arrowWidth: Math.PI / 8,
membraneColor: '#3d80b3',
cellColor: '#C9E7FF',
textColor: '#666666',
lineColor: '#666666',
getData: function(md){
this._super(md);
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Geometry', attr_name: 'width_1'}, 'width');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Geometry', attr_name: 'cylindricalLength_1'}, 'cylindricalLength');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Geometry', attr_name: 'pinchedDiameter_1'}, 'pinchedDiameter');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Geometry', attr_name: 'volume_1'}, 'volume');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Summary', attr_name: 'mass_1'}, 'mass');
},
getDataSuccess: function() {
if (undefined == this.data.width
|| undefined == this.data.cylindricalLength
|| undefined == this.data.pinchedDiameter
|| undefined == this.data.volume
|| undefined == this.data.mass
)
return;
this.data.width = this.data.width.data;
this.data.cylindricalLength = this.data.cylindricalLength.data;
this.data.pinchedDiameter = this.data.pinchedDiameter.data;
this.data.volume = this.data.volume.data;
this.data.mass = this.data.mass.data;
this.data.width[this.data.width.length-1] = this.data.width[this.data.width.length - 2];
this.data.cylindricalLength[this.data.cylindricalLength.length-1] = this.data.cylindricalLength[this.data.cylindricalLength.length-2];
this.data.pinchedDiameter[this.data.pinchedDiameter.length-1] = this.data.pinchedDiameter[this.data.pinchedDiameter.length-2];
this.timeMin = this.data.width[0][0];
this.timeMax = Math.max(
this.data.width[this.data.width.length - 1][0],
this.data.cylindricalLength[this.data.cylindricalLength.length - 1][0],
this.data.pinchedDiameter[this.data.pinchedDiameter.length - 1][0],
this.data.volume[this.data.volume.length - 1][0],
this.data.mass[this.data.mass.length - 1][0]);
this._super();
},
calcLayout: function(){
var maxWidth = 0;
var maxHeight = 0;
var w, pD, cL;
for (var t = this.timeMin; t <= this.timeMax; t+= 100){
w = getDataPoint(this.data.width, t);
pD = getDataPoint(this.data.pinchedDiameter, t);
cL = getDataPoint(this.data.cylindricalLength, t);
maxWidth = Math.max(maxWidth, w + cL + (w - pD));
maxHeight = Math.max(maxHeight, w);
}
w = this.data.width[this.data.width.length-1][1]
pD = this.data.pinchedDiameter[this.data.pinchedDiameter.length-1][1]
cL = this.data.cylindricalLength[this.data.cylindricalLength.length-1][1]
maxWidth = Math.max(maxWidth, w + cL + (w - pD));
maxHeight = Math.max(maxHeight, w);
this.scale = Math.min((this.width-4) / maxWidth, (this.height-4) / maxHeight);
},
drawDynamicObjects: function(t){
var data = {
width: getDataPoint(this.data.width, t),
pinchedDiameter: getDataPoint(this.data.pinchedDiameter, t),
cylindricalLength: getDataPoint(this.data.cylindricalLength, t),
volume: getDataPoint(this.data.volume, t),
mass: getDataPoint(this.data.mass, t),
};
data.septumLength = (data.width - data.pinchedDiameter) / 2;
this.drawCell(data);
this.drawCellMeasurements(data);
},
drawCell: function(data){
this.drawObject({
'strokeStyle': this.membraneColor,
'fillStyle': this.cellColor,
'data': data,
drawFunc: function(self, ctx, data){
var W = self.width;
var H = self.height;
var w = self.scale * data.width;
var sL = self.scale * data.septumLength;
var cL = self.scale * data.cylindricalLength;
ctx.lineWidth = 2;
ctx.moveTo(W / 2 + sL, H / 2 - w / 2);
//right-top cylinder and spherical cap
ctx.arcTo2(
W / 2 + sL + cL / 2 + w / 2, H / 2 - w / 2,
W / 2 + sL + cL / 2 + w / 2, H / 2,
w / 2,
W / 2 + sL + cL / 2, H / 2 - w / 2,
W / 2 + sL + cL / 2 + w / 2, H / 2);
ctx.arcTo2(
W / 2 + sL + cL / 2 + w / 2, H / 2 + w / 2,
W / 2 + sL + cL / 2, H / 2 + w / 2,
w / 2,
W / 2 + sL + cL / 2 + w / 2, H / 2,
W / 2 + sL + cL / 2, H / 2 + w / 2);
if (sL > 0){
//bottom-right cylinder
ctx.lineTo(W / 2 + sL, H / 2 + w / 2);
//bottom septum
ctx.arcTo2(
W / 2, H / 2 + w / 2,
W / 2, H / 2 + w / 2 - sL,
sL,
W / 2 + sL, H / 2 + w / 2,
W / 2, H / 2 + w / 2 - sL);
ctx.arcTo2(
W / 2, H / 2 + w / 2,
W / 2 - sL, H / 2 + w / 2,
sL,
W / 2, H / 2 + w / 2 - sL,
W / 2 - sL, H / 2 + w / 2);
//bottom-left cylinder
ctx.lineTo(W / 2 - sL - cL / 2, H / 2 + w / 2);
}else{
//bottom cylinder
ctx.lineTo(W / 2 - sL - cL / 2, H / 2 + w / 2);
}
//left spherical cap
ctx.arcTo2(
W / 2 - sL - cL / 2 - w / 2, H / 2 + w / 2,
W / 2 - sL - cL / 2 - w / 2, H / 2,
w / 2,
W / 2 - sL - cL / 2, H / 2 + w / 2,
W / 2 - sL - cL / 2 - w/2, H / 2);
ctx.arcTo2(
W / 2 - sL - cL / 2 - w / 2, H / 2 - w / 2,
W / 2 - sL - cL / 2, H / 2 - w / 2,
w / 2,
W / 2 - sL - cL / 2 - w/2, H / 2,
W / 2 - sL - cL / 2, H / 2 - w/2);
if (sL > 0){
//top-left cylinder
ctx.lineTo(W / 2 - sL, H / 2 - w / 2);
//top septum
ctx.arcTo2(
W / 2, H / 2 - w / 2,
W / 2, H / 2 - w / 2 + sL,
sL,
W / 2 - sL, H / 2 - w / 2,
W / 2, H / 2 - w / 2 + sL);
ctx.arcTo2(
W / 2, H / 2 - w / 2,
W / 2 + sL, H / 2 - w / 2,
sL,
W / 2, H / 2 - w / 2 + sL,
W / 2 + sL, H / 2 - w / 2);
//top-right cylinder
ctx.moveTo(W / 2 + sL + w / 2, H / 2 - w / 2);
}
//close path
ctx.closePath();
},
});
},
drawCellMeasurements: function(data){
this.drawObject({
isLabel:false,
'strokeStyle': this.lineColor,
'fillStyle': this.lineColor,
'data': data,
drawFunc: function(self, ctx, data){
var W = self.width;
var H = self.height;
var w = self.scale * data.width;
var sL = self.scale * data.septumLength;
var cL = self.scale * data.cylindricalLength;
var pD = self.scale * data.pinchedDiameter;
var x1, x2, x3, x4, labelX;
ctx.lineWidth = 1;
ctx.font = self.bigFontSize + "px " + self.fontFamily;
//height
txt = Math.round(data.width * 1e9) + ' nm';
var showHeight = - sL - cL / 2 + self.bigFontSize / 2 < - ctx.measureText(txt).width / 2 - 4;
if (showHeight){
ctx.arrowTo(
W / 2 - sL - cL / 2, H / 2 + (ctx.measureText(txt).width/2 + 4),
W / 2 - sL - cL / 2, H / 2 + (w / 2 - 4),
0, 1, self.arrowWidth, self.arrowLength, 2);
ctx.arrowTo(
W / 2 - sL - cL / 2, H / 2 - (ctx.measureText(txt).width/2 + 4),
W / 2 - sL - cL / 2, H / 2 - (w / 2 - 4),
0, 1, self.arrowWidth, self.arrowLength, 2);
}
//pinched diameter
if (data.pinchedDiameter < 0.95 * data.width && pD > 40){
txt = Math.round(data.pinchedDiameter * 1e9) + ' nm';
ctx.arrowTo(
W / 2, H / 2 + (ctx.measureText(txt).width/2 + 4),
W / 2, H / 2 + pD / 2,
0, 1, self.arrowWidth, self.arrowLength, 2);
ctx.arrowTo(
W / 2, H / 2 - (ctx.measureText(txt).width/2 + 4),
W / 2, H / 2 - pD / 2,
0, 1, self.arrowWidth, self.arrowLength, 2);
}
//width
var labelX;
if (data.pinchedDiameter < 0.95 * data.width && pD > 40){
labelX = W / 2 + (sL + cL / 2 + w / 2) / 2;
}else{
labelX = W / 2;
}
var txtWidth = Math.max(
ctx.measureText(Math.round((data.width + data.cylindricalLength + 2 * data.septumLength) * 1e9) + ' nm').width,
ctx.measureText((data.volume * 1e18).toFixed(1) + ' aL').width,
ctx.measureText((data.mass * 5.61).toFixed(1) + ' fg').width
);
x1 = W / 2 - (sL + cL / 2 + self.bigFontSize / 2 + 4);
x2 = W / 2 - (txtWidth / 2 + 4);
ctx.arrowTo(
(showHeight ? Math.min(x1, x2) : x2), H / 2,
W / 2 - (sL + cL / 2 + w / 2 - 4), H / 2,
0, 1, self.arrowWidth, self.arrowLength, 2);
x1 = W / 2 - (sL + cL / 2 - self.bigFontSize / 2 - 4);
x2 = labelX - (txtWidth / 2 + 4);
if (data.pinchedDiameter < 0.95 * data.width && pD > 40){
x3 = W / 2 - (self.bigFontSize / 2 + 4);
x4 = W / 2 + (self.bigFontSize / 2 + 4);
ctx.dashedLine(x1, H / 2, x3, H / 2, 2);
ctx.dashedLine(x4, H / 2, x2, H / 2, 2);
}else if(x1 < x2){
ctx.dashedLine(x1, H / 2, x2, H / 2, 2);
}
ctx.arrowTo(
labelX + (txtWidth / 2 + 4), H / 2,
W / 2 + (sL + cL / 2 + w / 2 - 4), H / 2,
0, 1, self.arrowWidth, self.arrowLength, 2);
},
});
this.drawObject({
isLabel:false,
'fillStyle': this.textColor,
'data': data,
drawFunc: function(self, ctx, data){
var W = self.width;
var H = self.height;
var w = self.scale * data.width;
var sL = self.scale * data.septumLength;
var cL = self.scale * data.cylindricalLength;
var pD = self.scale * data.pinchedDiameter;
var labelX;
ctx.font = self.bigFontSize + "px " + self.fontFamily;
//height
txt = Math.round(data.width * 1e9) + ' nm';
if (- sL - cL / 2 + self.bigFontSize / 2 < - ctx.measureText(txt).width / 2 - 4){
ctx.save();
ctx.translate(W / 2 - sL - cL / 2, H / 2);
ctx.rotate(-Math.PI / 2);
ctx.fillText(txt, -ctx.measureText(txt).width / 2, 0.3 * self.bigFontSize);
ctx.restore();
}
//pinched diameter
if (data.pinchedDiameter < 0.95 * data.width && pD > 40){
txt = Math.round(data.pinchedDiameter * 1e9) + ' nm';
ctx.save();
ctx.translate(W / 2, H / 2);
ctx.rotate(-Math.PI / 2);
ctx.fillText(txt, -ctx.measureText(txt).width / 2, 0.3 * self.bigFontSize);
ctx.restore();
}
//width
if (data.pinchedDiameter < 0.95 * data.width && pD > 40){
labelX = W / 2 + (sL + cL / 2 + w / 2) / 2;
}else{
labelX = W / 2;
}
txt = Math.round((data.width + data.cylindricalLength + 2 * data.septumLength) * 1e9) + ' nm';
ctx.fillText(txt, labelX - ctx.measureText(txt).width / 2, H / 2 + 0.3 * self.bigFontSize);
txt = (data.volume * 1e19).toFixed(1) + ' aL';
ctx.fillText(txt, labelX - ctx.measureText(txt).width / 2, H / 2 + 0.3 * self.bigFontSize - (self.bigFontSize + 2));
txt = (data.mass * 5.61).toFixed(1) + ' fg';
ctx.fillText(txt, labelX - ctx.measureText(txt).width / 2, H / 2 + 0.3 * self.bigFontSize + (self.bigFontSize + 2));
},
});
},
});
var CellShapeVisualization3D = Visualization3D.extend({
cameraOffX:0,
cameraOffY:0,
getData: function(md){
this._super(md);
this.data = {metadata: md};
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Geometry', attr_name: 'width_1'}, 'width');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Geometry', attr_name: 'cylindricalLength_1'}, 'cylindricalLength');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Geometry', attr_name: 'pinchedDiameter_1'}, 'pinchedDiameter');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Geometry', attr_name: 'volume_1'}, 'volume');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Summary', attr_name: 'mass_1'}, 'mass');
},
getDataSuccess: function () {
if (undefined == this.data.width
|| undefined == this.data.cylindricalLength
|| undefined == this.data.pinchedDiameter
|| undefined == this.data.volume
|| undefined == this.data.mass)
return;
this.data.width = this.data.width.data;
this.data.cylindricalLength = this.data.cylindricalLength.data;
this.data.pinchedDiameter = this.data.pinchedDiameter.data;
this.data.volume = this.data.volume.data;
this.data.mass = this.data.mass.data;
this.data.width[this.data.width.length-1] = this.data.width[this.data.width.length-2];
this.data.cylindricalLength[this.data.cylindricalLength.length-1] = this.data.cylindricalLength[this.data.cylindricalLength.length-2];
this.data.pinchedDiameter[this.data.pinchedDiameter.length-1] = this.data.pinchedDiameter[this.data.pinchedDiameter.length-2];
this.timeMin = this.data.width[0][0];
this.timeMax = Math.max(
this.data.width[this.data.width.length - 1][0],
this.data.cylindricalLength[this.data.cylindricalLength.length - 1][0],
this.data.pinchedDiameter[this.data.pinchedDiameter.length - 1][0],
this.data.volume[this.data.volume.length - 1][0],
this.data.mass[this.data.mass.length - 1][0]);
this.maxWidth = 0;
this.maxHeight = 0;
var w, pD, cL;
for (var t = this.timeMin; t <= this.timeMax; t+= 100){
w = getDataPoint(this.data.width, t);
pD = getDataPoint(this.data.pinchedDiameter, t);
cL = getDataPoint(this.data.cylindricalLength, t);
this.maxWidth = Math.max(this.maxWidth, w + cL + (w - pD));
this.maxHeight = Math.max(this.maxHeight, w);
}
w = this.data.width[this.data.width.length-1][1]
pD = this.data.pinchedDiameter[this.data.pinchedDiameter.length-1][1]
cL = this.data.cylindricalLength[this.data.cylindricalLength.length-1][1]
this.maxWidth = Math.max(this.maxWidth, w + cL + (w - pD));
this.maxHeight = Math.max(this.maxHeight, w);
//super
this._super();
},
initCamera: function(){
this.camera = new THREE.PerspectiveCamera(45, 1, 0.1, 20000);
this.scene.add(this.camera);
this.camera.lookAt(this.scene.position);
},
initLights: function(){
this.lights = {
point: [],
spot: [],
};
//point lights
for (var i = 0; i < 4; i++){
var light = new THREE.PointLight(0xffffff);
this.scene.add(light);
this.lights.point.push(light);
}
//spotlight
var light = new THREE.SpotLight(0xffffff);
light.shadowCameraVisible = false;
light.shadowDarkness = 0.25;
light.intensity = 0.1;
light.castShadow = true;
this.scene.add(light);
this.lights.spot.push(light);
},
initControls: function(){
this.controls = new THREE.TrackballControls( this.camera );
},
enableControls: function(){
if (!this.isEnabled)
return
var that = this;
requestAnimationFrame(function (){
that.enableControls();
if (~$('#timeline').timeline('getPlaying'))
that.drawDynamicContent(that.time);
});
},
calcLayout: function(){
//renderer
$(this.renderer.domElement).css({position: 'absolute', left: 0, top: -3});
this.renderer.setSize(this.width, this.height);
//camera
this.camera.aspect = this.width / this.height;
this.camera.position.set(this.cameraOffX, this.cameraOffY, 200);
this.camera.updateProjectionMatrix();
//lights
this.lights.point[0].position.set(0, 200, 200);
this.lights.point[1].position.set(0, 200, -200);
this.lights.point[2].position.set(0, -200, -200);
this.lights.point[3].position.set(0, -200, 200);
this.lights.spot[0].position.set(0, 500, 0);
},
drawStaticObjects: function(){
//remove old background
if (this.background)
this.scene.remove(this.background);
//add background
var geometry = new THREE.PlaneGeometry(1000, 1000, 100, 100);
var material = new THREE.MeshBasicMaterial({color: 0xffffff});
this.background = new THREE.Mesh(geometry, material);
this.background.doubleSided = false;
this.background.receiveShadow = true;
this.background.position.y = -50;
this.scene.add(this.background);
},
drawDynamicObjects: function(t){
//clear
if (this.cellObjects3d){
for (var i = 0; i < this.cellObjects3d.length; i++){
this.scene.remove(this.cellObjects3d[i]);
}
}
//add cell
this.cellObjects3d = [];
var mesh;
var scene = this.scene;
//offset
var offY = 20;
//sizes
scale = 200 / this.maxWidth;
label = this.data.metadata.sim_name;
w = scale * getDataPoint(this.data.width, t);
pD = scale * getDataPoint(this.data.pinchedDiameter, t);
cL = scale * getDataPoint(this.data.cylindricalLength, t);
v = getDataPoint(this.data.volume, t);
m = getDataPoint(this.data.mass, t);
sL = (w - pD) / 2;
//cell
mesh = new THREE.Mesh(
new CellGeometry(w, cL, pD, sL),
new THREE.MeshLambertMaterial({
'color': 0x3d80b3,
transparent:true,
opacity:0.8,
})
);
mesh.castShadow = true;
mesh.position.set(0, offY, 0);
scene.add(mesh);
this.cellObjects3d.push(mesh);
if (!$('#config').config('getShowLabels'))
return;
//measures
var mesh = THREE.addText(this.scene,
Math.round(w/scale * 1e9) + ' nm',
3, -(sL + cL/2), 10+offY, 0, true);
this.cellObjects3d.push(mesh);
textW = mesh.geometry.boundingBox.max.x - mesh.geometry.boundingBox.min.x;
this.cellObjects3d = this.cellObjects3d.concat(THREE.addArrow(this.scene,
-(sL + cL/2), -w/2 + offY, 0,
-(sL + cL/2), -(textW/2 + 2)+10 + offY, 0,
true, false));
this.cellObjects3d = this.cellObjects3d.concat(THREE.addArrow(this.scene,
-(sL + cL/2), (textW/2 + 2)+10 + offY, 0,
-(sL + cL/2), w/2 + offY, 0,
false, true));
if (sL > 0.1 * w){
var mesh = THREE.addText(this.scene,
Math.round((w - 2 * sL) / scale * 1e9) + ' nm',
3, 0, offY, 0, true);
this.cellObjects3d.push(mesh);
textW = mesh.geometry.boundingBox.max.x - mesh.geometry.boundingBox.min.x;
this.cellObjects3d = this.cellObjects3d.concat(THREE.addArrow(this.scene,
0, -(w/2 - sL) + offY, 0,
0, -(textW/2 + 2) + offY, 0,
true, false));
this.cellObjects3d = this.cellObjects3d.concat(THREE.addArrow(this.scene,
0, (textW/2 + 2) + offY, 0,
0, (w/2 - sL) + offY, 0,
false, true));
var mesh = THREE.addText(this.scene,
Math.round((w + cL + 2 * sL) / scale * 1e9) + ' nm',
3, (sL + cL/2 + w/2) / 2, offY, 0, false);
this.cellObjects3d.push(mesh);
textW = mesh.geometry.boundingBox.max.x - mesh.geometry.boundingBox.min.x;
this.cellObjects3d = this.cellObjects3d.concat(THREE.addArrow(this.scene,
-(sL + cL/2 + w/2), offY, 0,
-3, offY, 0,
true, false));
this.cellObjects3d = this.cellObjects3d.concat(THREE.addArrow(this.scene,
3, offY, 0,
(sL + cL/2 + w/2) / 2 - (textW/2 + 2), offY, 0,
false, false));
this.cellObjects3d = this.cellObjects3d.concat(THREE.addArrow(this.scene,
(sL + cL/2 + w/2) / 2 + (textW/2 + 2), offY, 0,
(sL + cL/2 + w/2), offY, 0,
false, true));
}else{
var mesh = THREE.addText(this.scene,
Math.round((w + cL + 2 * sL) / scale * 1e9) + ' nm',
3, (sL + cL/2 + w/2) / 2, offY, 0, false);
this.cellObjects3d.push(mesh);
textW = mesh.geometry.boundingBox.max.x - mesh.geometry.boundingBox.min.x;
this.cellObjects3d = this.cellObjects3d.concat(THREE.addArrow(this.scene,
-(sL + cL/2 + w/2), offY, 0,
(sL + cL/2 + w/2) / 2 - (textW/2 + 2), offY, 0,
true, false));
this.cellObjects3d = this.cellObjects3d.concat(THREE.addArrow(this.scene,
(sL + cL/2 + w/2) / 2 + (textW/2 + 2), offY, 0,
(sL + cL/2 + w/2), offY, 0,
false, true));
}
//label
this.cellObjects3d.push(THREE.addText(scene,
label,
3, 0, -w / 2 - 5 + offY, 0, false));
this.cellObjects3d.push(THREE.addText(scene,
(v * 1e18).toFixed(1) + ' aL, ' + (m * 5.61).toFixed(1) + ' fg',
2, 0, -w / 2 - 9 + offY, 0, false));
}
});
var CellShapeVisualization3DIntro = CellShapeVisualization3D.extend({
cameraOffX:-100,
cameraOffY: 100,
getData: function(md){
this._super(md);
this.timeMin = 29000;
this.timeMax = 29000;
},
});
var CellGeometry = function ( w, cL, pD, sL ) {
THREE.Geometry.call( this );
///////////////////////////
// geometry
///////////////////////////
this.cell = {
width: w,
cyclindricalLength: cL,
pinchedDiameter: pD,
septumLength: sL,
totalLength: w + cL + 2 * sL,
};
///////////////////////////
//vertices
//////////////////////////
var vertices = [], uvs = [], thetas = [];
//left-sphere
var tmp = this.calcRings(-sL - cL/2 - w/2, -sL - cL/2, 20, false);
vertices = vertices.concat(tmp.vertices);
uvs = uvs.concat(tmp.uvs);
thetas = thetas.concat(tmp.thetas);
//left-cylinder
var tmp = this.calcRings(-sL -cL/2, -sL, 1, true);
vertices = vertices.concat(tmp.vertices);
uvs = uvs.concat(tmp.uvs);
thetas = thetas.concat(tmp.thetas);
//left-septum
var tmp = this.calcRings(-sL, 0, 20, true);
vertices = vertices.concat(tmp.vertices);
uvs = uvs.concat(tmp.uvs);
thetas = thetas.concat(tmp.thetas);
//right-septum
var tmp = this.calcRings(0, sL, 20, true);
vertices = vertices.concat(tmp.vertices);
uvs = uvs.concat(tmp.uvs);
thetas = thetas.concat(tmp.thetas);
//right-cylinder
var tmp = this.calcRings(sL, sL + cL/2, 1, true);
vertices = vertices.concat(tmp.vertices);
uvs = uvs.concat(tmp.uvs);
thetas = thetas.concat(tmp.thetas);
//right-sphere
var tmp = this.calcRings(sL + cL/2, sL + cL/2 + w/2, 20, true);
vertices = vertices.concat(tmp.vertices);
uvs = uvs.concat(tmp.uvs);
thetas = thetas.concat(tmp.thetas);
///////////////////////////
//faces
///////////////////////////
for (var i = 0; i < vertices.length - 1; i ++ ) {
for (var j = 0; j < vertices[i].length - 1; j ++ ) {
var u = j / (vertices[i].length - 1);
var u2 = (j + 1) / (vertices[i].length - 1);
var v1 = vertices[ i ][ j ];
var v2 = vertices[ i + 1 ][ j ];
var v3 = vertices[ i + 1 ][ j + 1 ];
var v4 = vertices[ i ][ j + 1 ];
var n1 = new THREE.Vector3(Math.tan(thetas[i]), Math.sin( u * Math.PI * 2 ), Math.cos( u * Math.PI * 2 )).normalize();
var n2 = new THREE.Vector3(Math.tan(thetas[i + 1]), Math.sin( u * Math.PI * 2 ), Math.cos( u * Math.PI * 2 )).normalize();
var n3 = new THREE.Vector3(Math.tan(thetas[i + 1]), Math.sin( u2 * Math.PI * 2 ), Math.cos( u2 * Math.PI * 2 )).normalize();
var n4 = new THREE.Vector3(Math.tan(thetas[i]), Math.sin( u2 * Math.PI * 2 ), Math.cos( u2 * Math.PI * 2 )).normalize();
var uv1 = uvs[ i ][ j ].clone();
var uv2 = uvs[ i + 1 ][ j ].clone();
var uv3 = uvs[ i + 1 ][ j + 1 ].clone();
var uv4 = uvs[ i ][ j + 1 ].clone();
this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
}
}
///////////////////////////
// superclass stuff
///////////////////////////
this.computeCentroids();
this.computeFaceNormals();
}
CellGeometry.prototype = Object.create( THREE.Geometry.prototype );
CellGeometry.prototype.calcRings = function (x1, x2, nSegments, i1){
var totLen = this.cell.totalLength;
var vertices = [], uvs = [], thetas = [];
for (var i = i1; i <= nSegments; i ++ ) {
var x = x1 + (x2 - x1) * i / nSegments;
var tmp = this.calcRingVertices(x);
vertices.push(tmp.vertices );
uvs.push(tmp.uvs);
thetas.push(tmp.theta);
}
return {
'vertices': vertices,
'uvs': uvs,
'thetas': thetas,
};
}
CellGeometry.prototype.calcRingVertices = function (x){
var totLen = this.cell.totalLength;
var radius = this.calcRadius(x);
var v = (x + totLen / 2) / totLen;
var nSegments = 32;
var vertices = [];
var uvs = [];
for (var j = 0; j <= nSegments; j ++ ) {
var u = j / nSegments;
var vertex = new THREE.Vector3();
vertex.x = x;
vertex.y = radius * Math.sin( u * Math.PI * 2 );
vertex.z = radius * Math.cos( u * Math.PI * 2 );
this.vertices.push( vertex );
vertices.push( this.vertices.length - 1 );
uvs.push( new THREE.UV( u, 1 - v ) );
}
return {
'vertices': vertices,
'uvs': uvs,
'theta': this.calcTheta(x),
};
}
CellGeometry.prototype.calcRadius = function (x){
var w = this.cell.width;
var cL = this.cell.cyclindricalLength;
var sL = this.cell.septumLength;
var absX = Math.abs(x);
if (absX <= sL)
return (w / 2 - sL) + Math.sqrt( Math.pow(sL, 2) - Math.pow(sL - absX, 2) );
else if (absX <= sL + cL / 2)
return w / 2;
else
return Math.sqrt( Math.pow(w / 2, 2) - Math.pow(absX - sL - cL / 2, 2) );
}
CellGeometry.prototype.calcTheta = function (x){
var w = this.cell.width;
var cL = this.cell.cyclindricalLength;
var sL = this.cell.septumLength;
var absX = Math.abs(x);
if (absX <= sL)
return Math.sign(x) * Math.asin((sL - absX) / sL);
else if (absX <= sL + cL / 2)
return 0;
else
return Math.sign(x) * Math.asin((absX - sL - cL / 2) / (w / 2));
}
var ChromosomeVisualization = Visualization2D.extend({
//options
chrLen: 580076,
ntPerSegment: 1e5,
segmentLabelWidth: 40,
segmentLabelMargin: 2,
chrSpacing: 1,
segmentSpacing: 0.25,
dataRelHeight: 0.75,
chrRelHeight: 1,
chrDataSpacing: 0.25,
getData: function(md){
this._super(md);
this.data = {md: md};
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'singleStrandedRegions'}, 'ssData');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'doubleStrandedRegions'}, 'dsData');
switch (md.attr_name){
case 'DNA_replication_with_proteins_and_damage':
this.showDataTracks = true;
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'monomerBoundSites'}, 'monData');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'complexBoundSites'}, 'cpxData');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'strandBreaks'}, 'strndBreakData');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'damagedBases'}, 'dmgBasesData');
break;
case 'DNA_replication':
default:
this.showDataTracks = false;
break;
}
},
getDataSuccess: function (){
if (undefined == this.data.ssData
|| undefined == this.data.dsData)
return;
if (this.data.md.attr_name == 'DNA_replication_with_proteins_and_damage' &&
(undefined == this.data.monData
|| undefined == this.data.cpxData
|| undefined == this.data.strndBreakData
|| undefined == this.data.dmgBasesData))
return
this.ssData = this.data.ssData;
this.dsData = this.data.dsData;
this.monData = this.data.monData;
this.cpxData = this.data.cpxData;
this.strndBreakData = this.data.strndBreakData;
this.dmgBasesData = this.data.dmgBasesData;
this.timeMin = this.dsData[0].time[0];
this.timeMax = this.dsData[this.dsData.length-1].time[0];
this._super();
},
exportData: function(){
var data = {
ssData: this.ssData,
dsData: this.dsData,
};
switch (md.attr_name){
case 'DNA_replication_with_proteins_and_damage':
data['monData'] = this.monData;
data['cpxData'] = this.cpxData;
data['strndBreakData'] = this.strndBreakData;
data['dmgBasesData'] = this.dmgBasesData;
break;
case 'DNA_replication':
default:
break;
}
return data;
},
calcLayout: function(){
this.numSegments = Math.ceil(this.chrLen / this.ntPerSegment);
this.segmentHeight = this.height / (this.chrSpacing + 2 * (this.numSegments + this.segmentSpacing * (this.numSegments - 1)));<|fim▁hole|>
this.chrWidth = this.legendX - 5 - this.segmentLabelWidth - this.segmentLabelMargin;
this.ntLength = this.chrWidth / this.ntPerSegment;
if (this.showDataTracks){
var scale = this.segmentHeight / (2 * this.dataRelHeight + 2 * this.chrDataSpacing + this.chrRelHeight);
this.dataHeight = scale * this.dataRelHeight
this.dataTrackY1 = -1;
this.chrSegmentY = scale * (this.dataRelHeight + this.chrDataSpacing);
this.dataTrackY2 = scale * (this.dataRelHeight + 2 * this.chrDataSpacing + this.chrRelHeight) - 1;
this.chrHeight = scale * this.chrRelHeight;
}else{
this.dataHeight = 0;
this.dataTrackY1 = 0;
this.dataTrackY2 = 0;
this.chrSegmentY = 0;
this.chrHeight = this.segmentHeight;
}
},
drawDynamicObjects: function(t){
var chrStyle;
//chromosome
this.drawChromosomes();
//single stranded regions
this.drawPolymerizedRegions(getDataPoint(this.ssData, t), ['#3d80b3', '#C9E7FF'], 1,
[this.chrSegmentY-0.5, this.chrSegmentY+0.5]);
//double stranded regions
this.drawPolymerizedRegions(getDataPoint(this.dsData, t), ['#3d80b3', '#C9E7FF'], this.chrHeight/2,
[this.chrSegmentY-this.chrHeight/4, this.chrSegmentY+this.chrHeight/4]);
//selected attribute
if (this.showDataTracks){
this.drawDataTrack(getDataPoint(this.monData, t), '#3db34a', this.dataHeight, [this.dataTrackY1, this.dataTrackY2], 500);
this.drawDataTrack(getDataPoint(this.cpxData, t), '#3db34a', this.dataHeight, [this.dataTrackY1, this.dataTrackY2], 500);
this.drawDataTrack(getDataPoint(this.strndBreakData, t), '#cd0a0a', this.dataHeight, [this.dataTrackY1, this.dataTrackY2], 200);
this.drawDataTrack(getDataPoint(this.dmgBasesData, t), '#e78f08', this.dataHeight, [this.dataTrackY1, this.dataTrackY2], 200);
}
//legend
this.drawLegendEntry(t, 0, 'Mother', '#3d80b3', 5);
this.drawLegendEntry(t, 1, 'Daughter', '#C9E7FF', 5);
this.drawLegendEntry(t, 2, 'ssDNA', '#3d80b3', 1);
this.drawLegendEntry(t, 3, 'dsDNA', '#3d80b3', 5);
if (this.showDataTracks){
this.drawLegendEntry(t, 4, 'Methylation', '#e78f08', 5);
this.drawLegendEntry(t, 5, 'Protein', '#3db34a', 5);
this.drawLegendEntry(t, 6, 'Strand break', '#cd0a0a', 5);
}
},
drawChromosomes: function(){
this.drawObject({
strokeStyle: '#e8e8e8',
fillStyle: '#222222',
drawFunc: function(self, ctx, data){
var txt;
ctx.lineWidth = 2;
for (var i = 0; i < 2; i++){
for (var j = 0; j < self.numSegments; j++){
var y = i * self.chrSeparation + j * self.segmentSeparation + self.chrSegmentY + self.chrHeight / 2;
//draw chromosome
ctx.moveTo(self.segmentLabelWidth + self.segmentLabelMargin, y);
ctx.lineTo(self.segmentLabelWidth + self.segmentLabelMargin + (((Math.min((j + 1) * self.ntPerSegment, self.chrLen) - 1) % self.ntPerSegment) + 1) / self.ntPerSegment * self.chrWidth, y);
//position label
txt = (j * self.ntPerSegment + 1).toString();
ctx.font = self.smallFontSize + "px " + self.fontFamily;
ctx.fillText(txt, self.segmentLabelWidth - ctx.measureText(txt).width, y + 0.4 * self.smallFontSize);
}
txt = 'Chromosome ' + (i+1);
y = i * self.chrSeparation + (self.segmentSeparation * (self.numSegments - 1) + self.segmentHeight) / 2;
ctx.save();
ctx.font = self.bigFontSize + "px " + self.fontFamily;
ctx.translate(self.bigFontSize / 2, y);
ctx.rotate(-Math.PI / 2);
ctx.fillText(txt, -ctx.measureText(txt).width / 2, 0.4 * self.bigFontSize);
ctx.restore();
}
},
});
},
drawPolymerizedRegions: function(data, fillStyle, trackHeight, trackOffY) {
if (data == undefined)
return;
var strandArr = data.strand;
var posArr = data.pos;
var valArr = data.val;
var offX = this.segmentLabelWidth + this.segmentLabelMargin;
var sX = 1 / this.ntPerSegment * this.chrWidth;
for (var i = 0; i < strandArr.length; i++) {
var offY = Math.floor((strandArr[i] - 1) / 2) * this.chrSeparation + trackOffY[(strandArr[i]-1) % 2];
var elWidth = valArr[i];
jMin = Math.floor(posArr[i] / this.ntPerSegment);
jMax = Math.ceil((posArr[i] + elWidth) / this.ntPerSegment);
for (var j = jMin; j < jMax; j++){
var y = offY + j * this.segmentSeparation;
var x1, x2;
if (j == jMin)
x1 = offX + (((posArr[i] - 1) % this.ntPerSegment) + 1) * sX;
else
x1 = offX;
if (j == jMax - 1)
x2 = offX + (((posArr[i] + elWidth - 1) % this.ntPerSegment) + 1) * sX;
else
x2 = offX + this.chrWidth;
var thisFillStyle;
if ((strandArr[i] == 2 &&
((strandArr.length == 4 && posArr[i] == 1 && valArr[i] == this.chrLen) ||
(strandArr.length > 2 && (posArr[i] == 1 || posArr[i] + valArr[i] - 1 == this.chrLen || (posArr[i] < this.chrLen/2 && valArr[i] < 5000))))) ||
strandArr[i] == 3){
thisFillStyle = fillStyle[1];
}else{
thisFillStyle = fillStyle[0];
}
this.drawObject({
'fillStyle': thisFillStyle,
'data': {'x': x1, 'y': y + (this.chrHeight - trackHeight) / 2, 'w': x2 - x1, 'h': trackHeight},
'drawFunc': function(self, ctx, data){
ctx.rect(data.x, data.y, data.w, data.h);
},
});
}
}
},
drawDataTrack: function(data, fillStyle, trackHeight, trackOffY, elDefaultWidth) {
if (data == undefined)
return;
this.drawObject({
'fillStyle': fillStyle,
'data': {'data': data, 'trackHeight': trackHeight},
'drawFunc': function(self, ctx, data){
var strandArr = data.data.strand;
var posArr = data.data.pos;
var valArr = data.data.val;
var offX = self.segmentLabelWidth + self.segmentLabelMargin;
var sX = 1 / self.ntPerSegment * self.chrWidth;
var elWidth = elDefaultWidth;
for (var i = 0; i < strandArr.length; i++) {
var offY = Math.floor((strandArr[i] - 1) / 2) * self.chrSeparation + trackOffY[(strandArr[i]-1) % 2];
if (elDefaultWidth == undefined)
elWidth = valArr[i];
jMin = Math.floor(posArr[i] / self.ntPerSegment);
jMax = Math.ceil((posArr[i] + elWidth) / self.ntPerSegment);
for (var j = jMin; j < jMax; j++){
var y = offY + j * self.segmentSeparation;
var x1, x2;
if (j == jMin)
x1 = offX + (((posArr[i] - 1) % self.ntPerSegment) + 1) * sX;
else
x1 = offX;
if (j == jMax - 1)
x2 = offX + (((posArr[i] + elWidth - 1) % self.ntPerSegment) + 1) * sX;
else
x2 = offX + self.chrWidth;
ctx.fillRect(x1, y + (self.chrHeight - trackHeight) / 2, x2 - x1, data.trackHeight);
}
}
},
});
},
drawLegendEntry: function(t, row, txt, strokeStyle, lineWidth){
this.drawObject({
'strokeStyle': strokeStyle,
fillStyle: '#222222',
data: {'t': t, 'row': row, 'txt': txt, 'lineWidth': lineWidth},
drawFunc: function(self, ctx, data){
var x = self.legendX;
var y = data.row * self.bigFontSize * 1.2 + 0.25 * self.bigFontSize;
ctx.lineWidth = data.lineWidth;
ctx.moveTo(x, y);
ctx.lineTo(x + 5, y);
ctx.font = self.bigFontSize + "px " + self.fontFamily;
ctx.fillText(data.txt,
x + 8,
y + 0.3 * self.bigFontSize);
},
});
},
});
var ChromosomeCircleVisualization = Visualization2D.extend({
//options
chrLen: 580076,
relChrRadius: 1,
relChrHalfHeight: 0.1,
relChrDataSpacing: 0.01,
relDataHeight: 0.1,
relChrSpacing: 0.05,
getData: function(md){
this._super(md);
this.getSeriesData('getKBData.php', {'type': 'Metabolite'}, 'metabolites');
this.getSeriesData('getKBData.php', {'type': 'ProteinMonomer'}, 'proteinMonomers');
this.getSeriesData('getKBData.php', {'type': 'ProteinComplex'}, 'proteinComplexs');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'singleStrandedRegions'}, 'ssData');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'doubleStrandedRegions'}, 'dsData');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'monomerBoundSites'}, 'monData');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'complexBoundSites'}, 'cpxData');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'strandBreaks'}, 'strndBreakData');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'damagedBases'}, 'dmgBasesData');
},
getDataSuccess: function () {
if (undefined == this.data.metabolites
|| undefined == this.data.proteinMonomers
|| undefined == this.data.proteinComplexs
|| undefined == this.data.ssData
|| undefined == this.data.dsData
|| undefined == this.data.monData
|| undefined == this.data.cpxData
|| undefined == this.data.strndBreakData
|| undefined == this.data.dmgBasesData)
return;
this.metabolites = this.data.metabolites;
this.proteinMonomers = this.data.proteinMonomers;
this.proteinComplexs = this.data.proteinComplexs;
this.ssData = this.data.ssData;
this.dsData = this.data.dsData;
this.monData = this.data.monData;
this.cpxData = this.data.cpxData;
this.strndBreakData = this.data.strndBreakData;
this.dmgBasesData = this.data.dmgBasesData
this.timeMin = this.dsData[0].time[0];
this.timeMax = this.dsData[this.dsData.length-1].time[0];
this._super();
},
exportData: function(){
return {
ssData: this.ssData,
dsData: this.dsData,
monData: this.monData,
cpxData: this.cpxData,
strndBreakData: this.strndBreakData,
dmgBasesData: this.dmgBasesData,
};
},
calcLayout: function(){
var scale = Math.min(
this.height / 2 / (this.relChrRadius + this.relChrHalfHeight + this.relChrDataSpacing + this.relDataHeight),
this.width / (4 * (this.relChrRadius + this.relChrHalfHeight + this.relChrDataSpacing + this.relDataHeight) + this.relChrSpacing)
);
this.chrRadius = scale * this.relChrRadius;
this.chrHalfHeight = scale * this.relChrHalfHeight;
this.chrDataSpacing = scale * this.relChrDataSpacing;
this.dataHeight = scale * this.relDataHeight;
this.chrSpacing = scale * this.relChrSpacing;
this.chrX = [
this.width / 2 - (this.chrSpacing / 2 + this.chrRadius + this.chrHalfHeight + this.chrDataSpacing + this.dataHeight),
this.width / 2 + (this.chrSpacing / 2 + this.chrRadius + this.chrHalfHeight + this.chrDataSpacing + this.dataHeight),
];
this.chrRadii = [
this.chrRadius + this.chrHalfHeight / 2,
this.chrRadius - this.chrHalfHeight / 2,
];
this.dataRadii = [
this.chrRadius + (this.chrHalfHeight + this.chrDataSpacing + this.dataHeight / 2),
this.chrRadius - (this.chrHalfHeight + this.chrDataSpacing + this.dataHeight / 2),
];
},
drawDynamicObjects: function(t){
var chrStyle;
//chromosome
this.drawChromosomes();
//single stranded regions
var ssChrLens = this.drawPolymerizedRegions(getDataPoint(this.ssData, t), ['#3d80b3', '#C9E7FF'], 1, function(self, data){
return sprintf('single-stranded polymerized region at position %d of length %d on (%s) strand', data.pos, data.val, (data.strand % 2 == 0 ? '-' : '+'));
});
//double stranded regions
var dsChrLens = this.drawPolymerizedRegions(getDataPoint(this.dsData, t), ['#3d80b3', '#C9E7FF'], this.chrHalfHeight, function(self, data){
return sprintf('double-stranded polymerized region at position %d of length %d', data.pos, data.val);
});
//print chromosome labels
this.drawChromosomeLabels(t, ssChrLens, dsChrLens);
//selected attribute
this.drawDataTrack(getDataPoint(this.strndBreakData, t), '#cd0a0a', 200, function (self, data){
return sprintf('Strand break at position %d (%s)', data.pos, (data.strand % 2 == 0 ? '-' : '+'));
});
this.drawDataTrack(getDataPoint(this.dmgBasesData, t), '#e78f08', 200, function(self, data){
return sprintf('Damaged base %s at position %d (%s)', self.metabolites[data.val].name, data.pos, (data.strand % 2 == 0 ? '-' : '+'));
});
this.drawDataTrack(getDataPoint(this.monData, t), '#3db34a', 500, function (self, data){
return sprintf('Bound protein %s at position %d (%s)', self.proteinComplexs[data.val].name, data.pos, (data.strand % 2 == 0 ? '-' : '+'));
});
this.drawDataTrack(getDataPoint(this.cpxData, t), '#3db34a', 500, function (self, data){
return sprintf('Bound protein %s at position %d (%s)', self.proteinComplexs[data.val].name, data.pos, (data.strand % 2 == 0 ? '-' : '+'));
});
},
drawChromosomes: function(){
for (var i = 0; i < 2; i++){
this.drawObject({
strokeStyle: '#e8e8e8',
data: i,
drawFunc: function(self, ctx, i){
ctx.lineWidth = 1;
ctx.arc(self.chrX[i], self.height / 2, self.chrRadius, 0, 2 * Math.PI);
},
});
}
},
drawChromosomeLabels: function(t, ssChrLens, dsChrLens){
var y = [
this.height / 2 - 1.7 * this.bigFontSize - 2,
this.height / 2 - 0.7 * this.bigFontSize - 1,
this.height / 2 + 0.3 * this.bigFontSize - 0,
this.height / 2 + 1.3 * this.bigFontSize + 1,
this.height / 2 + 2.3 * this.bigFontSize + 2,
];
this.drawLegendEntry(t, this.chrX[0], 0, y[0], 'Chromosome 1', undefined, 0, this.bigFontSize);
this.drawLegendEntry(t, this.chrX[1], 0, y[0], 'Chromosome 2', undefined, 0, this.bigFontSize);
this.drawLegendEntry(t, this.chrX[0], -1, y[1], 'Mother', '#3d80b3', 5, this.smallFontSize);
this.drawLegendEntry(t, this.chrX[0], -1, y[2], 'Daughter', '#C9E7FF', 5, this.smallFontSize);
this.drawLegendEntry(t, this.chrX[0], 1, y[1], 'ssDNA', '#3d80b3', 1, this.smallFontSize);
this.drawLegendEntry(t, this.chrX[0], 1, y[2], 'dsDNA', '#3d80b3', 5, this.smallFontSize);
this.drawLegendEntry(t, this.chrX[0], -1, y[3], 'Methylation', '#e78f08', 5, this.smallFontSize);
this.drawLegendEntry(t, this.chrX[0], 1, y[3], 'Protein', '#3db34a', 5, this.smallFontSize);
this.drawLegendEntry(t, this.chrX[0], -1, y[4], 'Strand break', '#cd0a0a', 5, this.smallFontSize);
},
drawLegendEntry: function(t, x, col, y, txt, strokeStyle, lineWidth, fontSize){
this.drawObject({
isLabel:true,
'strokeStyle': strokeStyle,
fillStyle: '#222222',
data: {'t': t, 'x': x, 'col': col, 'y': y, 'txt': txt, 'lineWidth': lineWidth, 'fontSize': fontSize},
drawFunc: function(self, ctx, data){
ctx.font = data.fontSize + "px " + self.fontFamily;
var offX = 0;
switch (data.col){
case -1:
offX = -(
+ 5
+ 3
+ ctx.measureText('Strand break').width
+ 10
+ 5
+ 3
+ ctx.measureText('Protein').width
) / 2;
break;
case 0:
offX = - ctx.measureText(data.txt).width / 2;
break;
case 1:
offX = -(
+ 5
+ 3
+ ctx.measureText('Strand break').width
+ 10
+ 5
+ 3
+ ctx.measureText('Protein').width
) / 2
+ 5
+ 3
+ ctx.measureText('Strand break').width
+ 10;
break;
}
if (data.lineWidth > 0){
ctx.lineWidth = data.lineWidth;
ctx.moveTo(offX + data.x, data.y);
ctx.lineTo(offX + data.x + 5, data.y);
}
ctx.fillText(data.txt,
data.x + (data.lineWidth > 0 ? 8 : 0) + offX,
data.y + 0.3 * data.fontSize);
},
});
},
drawPolymerizedRegions: function(data, strokeStyle, lineWidth, tipFunc) {
var chrLens = [0, 0];
if (data == undefined)
return chrLens;
var strandArr = data.strand;
var posArr = data.pos;
var valArr = data.val;
for (var i = 0; i < strandArr.length; i++) {
var thisStrokeStyle;
if ((strandArr[i] == 2 &&
((strandArr.length == 4 && posArr[i] == 1 && valArr[i] == this.chrLen) ||
(strandArr.length > 2 && (posArr[i] == 1 || posArr[i] + valArr[i] - 1 == this.chrLen || (posArr[i] < this.chrLen/2 && valArr[i] < 5000))))) ||
strandArr[i] == 3){
thisStrokeStyle = strokeStyle[1];
}else{
thisStrokeStyle = strokeStyle[0];
}
chrLens[Math.ceil(strandArr[i] / 2) - 1] += valArr[i];
this.drawObject({
'strokeStyle': thisStrokeStyle,
'data': {strand: strandArr[i], pos: posArr[i], val: valArr[i], 'lineWidth': lineWidth},
'drawFunc': function(self, ctx, data){
ctx.lineWidth = data.lineWidth;
ctx.arc(
self.chrX[Math.floor((data.strand - 1) / 2)], self.height / 2,
self.chrRadius - (2 * ((data.strand - 1) % 2) - 1) * lineWidth / 2,
data.pos / self.chrLen * 2 * Math.PI,
(data.pos + data.val) / self.chrLen * 2 * Math.PI);
},
'tipFunc': tipFunc,
});
}
return chrLens;
},
drawDataTrack: function(data, strokeStyle, elDefaultLength, tipFunc) {
if (data == undefined)
return;
var strandArr = data.strand;
var posArr = data.pos;
var valArr = data.val;
for (var i = 0; i < strandArr.length; i++) {
this.drawObject({
'strokeStyle': strokeStyle,
'data': {strand: strandArr[i], pos: posArr[i], val: valArr[i], len: Math.max(elDefaultLength, valArr[i])},
'drawFunc': function(self, ctx, data){
ctx.lineWidth = self.dataHeight;
ctx.arc(
self.chrX[Math.floor((data.strand - 1) / 2)], self.height / 2,
self.dataRadii[(data.strand - 1) % 2],
data.pos / self.chrLen * 2 * Math.PI,
(data.pos + data.len) / self.chrLen * 2 * Math.PI);
},
'tipFunc': tipFunc,
});
}
},
});
var ChromosomeSpaceTimeVisualization = Visualization2D.extend({
chrLen: 580076,
axisLeft: 30,
axisRight: 0,
axisTop: 5,
axisBottom: 25,
axisLineWidth: 0.5,
timeStep: 100,
getData: function(md){
this._super(md);
//genes
this.getSeriesData('getKBData.php', {type: 'Gene'}, 'genes');
//replisome dynamics
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Summary', attr_name: 'replisome_1'}, 'replisome1');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Summary', attr_name: 'replisome_2'}, 'replisome2');
//DnaA dynamics
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Summary', attr_name: 'dnaAFunctionalBoxes_' + 1}, 'dnaA1');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Summary', attr_name: 'dnaAFunctionalBoxes_' + 2}, 'dnaA2');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Summary', attr_name: 'dnaAFunctionalBoxes_' + 3}, 'dnaA3');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Summary', attr_name: 'dnaAFunctionalBoxes_' + 4}, 'dnaA4');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Summary', attr_name: 'dnaAFunctionalBoxes_' + 5}, 'dnaA5');
},
getDataSuccess: function () {
if (undefined == this.data.genes
|| undefined == this.data.replisome1
|| undefined == this.data.replisome2
|| undefined == this.data.dnaA1
|| undefined == this.data.dnaA2
|| undefined == this.data.dnaA3
|| undefined == this.data.dnaA4
|| undefined == this.data.dnaA5)
return;
//genes
this.genes = this.data.genes;
this.genes.sort(function(a, b){
return parseInt(a.coordinate) - parseInt(b.coordinate);
});
//dynamics
this.data = {
dnaPol: [
this.data.replisome1.data,
this.data.replisome2.data,
],
dnaA: [
this.data.dnaA1.data,
this.data.dnaA2.data,
this.data.dnaA3.data,
this.data.dnaA4.data,
this.data.dnaA5.data,
],
dnaATotal: [],
};
this.timeMin = Math.min(this.data.dnaPol[0][0][0], this.data.dnaPol[1][0][0]);
this.timeMax = Math.max(this.data.dnaPol[0][this.data.dnaPol[0].length-1][0], this.data.dnaPol[1][this.data.dnaPol[1].length-1][0])
this.timeMin = Math.floor(this.timeMin / 2 / 3600) * 2 * 3600;
for (var t = this.timeMin; t <= this.timeMax; t += this.timeStep){
var cnt = 0;
for (var i = 0; i < this.data.dnaA.length; i++){
cnt += getDataPoint(this.data.dnaA[i], t, true);
}
this.data.dnaATotal.push([t, cnt]);
}
//super
this._super();
},
calcLayout: function(){
this.axisX = this.axisLeft + this.axisLineWidth / 2;
this.axisY = this.axisTop + this.axisLineWidth / 2;
this.axisWidth = this.width - this.axisLeft - this.axisLineWidth;
this.axisHeight = this.height - this.axisTop - this.axisBottom - this.axisLineWidth;
},
drawStaticObjects: function(){
//DnaA
for (var t = this.timeMin; t <= this.timeMax; t += this.timeStep){
var cnt = 0;
for (var i = 0; i < this.data.dnaA.length; i++){
cnt += getDataPoint(this.data.dnaA[i], t, true);
}
if (cnt == 0)
continue;
var r = 61 * cnt / 29 + 255 * (29 - cnt) / 29;
var g = 179 * cnt / 29 + 255 * (29 - cnt) / 29;
var b = 74 * cnt / 29 + 255 * (29 - cnt) / 29;
this.drawObject({
strokeStyle: sprintf('rgb(%d,%d,%d)', r, g, b),
data: t,
drawFunc: function(self, ctx, data){
ctx.lineWidth = 2;
ctx.moveTo(
self.axisX + self.axisWidth * Math.max(0, (t - self.timeStep / 2 - self.timeMin) / (self.timeMax - self.timeMin)),
self.axisY + self.axisHeight / 2);
ctx.lineTo(
self.axisX + self.axisWidth * Math.min(1, (t + self.timeStep / 2 - self.timeMin) / (self.timeMax - self.timeMin)),
self.axisY + self.axisHeight / 2);
},
tipFunc: function(self, t){
var txt = 'Time: ' + formatTime(t, '') + '<br/>';
for (var i = 0; i < self.data.dnaA.length; i++){
txt += sprintf('R%d: %d<br/>', i + 1, Math.round(getDataPoint(self.data.dnaA[i], t, true)));
}
return txt;
},
});
}
//DNA pol
var x1 = undefined;
var x2 = undefined;
var y1 = undefined;
var y2 = undefined;
for (var i = 0; i < this.data.dnaPol.length; i++){
var datai = this.data.dnaPol[i];
for (var t = this.timeMin; t <= this.timeMax; t += this.timeStep){
var pos = Math.round(getDataPoint(datai, t, true));
if (pos == 0){
x2 = undefined;
y2 = undefined;
}else{
x2 = this.axisX + this.axisWidth * (t - this.timeMin) / (this.timeMax - this.timeMin);
if (i % 2 == 0)
y2 = this.axisY + this.axisHeight * (pos - this.chrLen / 2) / this.chrLen;
else
y2 = this.axisY + this.axisHeight * (pos + this.chrLen / 2) / this.chrLen;
if (x1 != undefined){
//hit detection
this.drawObject({
strokeStyle: '#000000',
globalAlpha: 0,
data: {'t': t, 'strand':i, 'pos':pos, 'x1': x1, 'y1': y1, 'x2': x2, 'y2': y2},
drawFunc: function(self, ctx, data){
ctx.lineWidth = data.x2 - data.x1;
ctx.moveTo((data.x1+data.x2)/2, Math.min(data.y1, data.y2)-10)
ctx.lineTo((data.x1+data.x2)/2, Math.max(data.y1, data.y2)+10);
},
tipFunc: function(self, data){
var gene = getGeneByPos(self.genes, data.pos);
var txt = '';
txt += 'Time: ' + formatTime(data.t, '') + '<br/>';
txt += 'Strand: ' + (data.strand == 0 ? '-' : '+') + '<br/>';
txt += 'Position: ' + data.pos + '<br/>';
txt += 'TU: ' + (gene ? gene.transcription_units[0] : 'N/A') + '<br/>';
txt += 'Gene: ' + (gene ? gene.name : 'N/A') + '<br/>';
return txt;
},
});
//data
this.drawObject({
strokeStyle: '#3d80b3',
data: {'t': t, 'x1': x1, 'y1': y1, 'x2': x2, 'y2': y2},
drawFunc: function(self, ctx, data){
ctx.lineWidth = 1;
ctx.moveTo(data.x1, data.y1);
ctx.lineTo(data.x2, data.y2);
},
});
}
}
x1 = x2;
y1 = y2;
}
}
//axis
this.drawObject({
'strokeStyle': '#222222',
drawFunc: function(self, ctx, data){
var txt, x, y;
ctx.lineWidth = self.axisLineWidth;
ctx.rect(self.axisX, self.axisY,
self.axisWidth, self.axisHeight);
//y-axis
txt = 'Position';
ctx.save();
ctx.font = self.bigFontSize + "px " + self.fontFamily;
ctx.translate(self.bigFontSize / 2, self.axisHeight / 2);
ctx.rotate(-Math.PI / 2);
ctx.fillText(txt, -ctx.measureText(txt).width / 2, 0.3 * self.bigFontSize);
ctx.restore();
ctx.font = self.smallFontSize + "px " + self.fontFamily;
var labels = [[0, 'terC'], [self.chrLen/2, 'oriC'], [self.chrLen, 'terC']];
for (var i = 0; i < labels.length; i++){
x = self.axisX;
y = self.axisY + self.axisHeight * labels[i][0] / self.chrLen;
ctx.moveTo(x, y);
ctx.lineTo(x-3, y);
txt = labels[i][1];
ctx.fillText(txt,
x - 5 - ctx.measureText(txt).width,
y + 0.3 * self.smallFontSize);
}
//x-axis
txt = 'Time (h)';
ctx.font = self.bigFontSize + "px " + self.fontFamily;
ctx.fillText(txt,
self.axisX + self.axisWidth / 2 - ctx.measureText(txt).width / 2,
self.height - 0.2 * self.bigFontSize);
ctx.font = self.smallFontSize + "px " + self.fontFamily;
for (var t = self.timeMin; t <= Math.floor(self.timeMax / (2 * 3600)) * 2 * 3600; t += 2 * 3600){
x = self.axisX + self.axisWidth * (t - self.timeMin) / (self.timeMax - self.timeMin);
y = self.axisY + self.axisHeight;
ctx.moveTo(x, y);
ctx.lineTo(x, y+3);
txt = (t / 3600).toString();
ctx.fillText(txt,
x - ctx.measureText(txt).width / 2,
y + 5 + 0.7 * self.smallFontSize);
}
},
});
},
drawDynamicObjects: function(t){
if (t < this.timeMin || t > this.timeMax)
return;
//DNA Pol
this.drawObject({
isLabel:true,
strokeStyle: '#3d80b3',
fillStyle: '#222222',
data: t,
drawFunc: function(self, ctx, t){
var x = self.axisX + 5;
var y = self.axisY + 5 + 0.35 * self.bigFontSize;
ctx.lineWidth = 5;
ctx.moveTo(x, y);
ctx.lineTo(x + 5, y);
var val1 = Math.round(getDataPoint(self.data.dnaPol[1], t, true));
var val2 = Math.round(getDataPoint(self.data.dnaPol[1], t, true));
if (val1 == 0)
val1 = 'N/A';
if (val2 == 0)
val2 = 'N/A';
ctx.font = self.bigFontSize + "px " + self.fontFamily;
ctx.fillText('DNA Pol (+' + val1 + ', -' + val2 + ')', x + 8, y + 0.35 * self.bigFontSize);
},
});
//DnaA
this.drawObject({
isLabel:true,
strokeStyle: 'rgb(61,179,74)',
fillStyle: '#222222',
data: t,
drawFunc: function(self, ctx, t){
var x = self.axisX + 5;
var y = self.axisY + 5 + 0.35 * self.bigFontSize + self.bigFontSize * 1.2;
ctx.lineWidth = 5;
ctx.moveTo(x, y)
ctx.lineTo(x + 5, y);
var val = [];
for (var i = 0; i < self.data.dnaA.length; i++){
val.push('R' + (i + 1) + ': ' + Math.round(getDataPoint(self.data.dnaA[i], t, true)));
}
ctx.font = self.bigFontSize + "px " + self.fontFamily;
ctx.fillText('DnaA (' + val.join(', ') + ')', x + 8, y + 0.35 * self.bigFontSize);
},
});
//progress line
this.drawObject({
strokeStyle: '#cd0a0a',
data: t,
drawFunc: function(self, ctx, t){
//red vertical line
var x = self.axisX + self.axisWidth * (t - self.timeMin) / (self.timeMax - self.timeMin);
ctx.lineWidth = 1;
ctx.moveTo(x, self.axisY);
ctx.lineTo(x, self.axisY + self.axisHeight);
},
});
},
});
var DnaAVisualization = Visualization2D.extend({
getData: function(md){
this._super(md);
for (var i = 1; i <= 5; i++) {
this.getSeriesData('getSeriesData.php', {
'sim_id': md.sim_id,
'class_name': 'Summary',
'attr_name': 'dnaAFunctionalBoxes_' + i,
}, i);
}
},
getDataSuccess: function () {
for (var i = 1; i <= 5; i++) {
if (this.data[i] == undefined)
return;
}
var tmp = this.data;
this.data = [];
for (var i = 1; i <= 5; i++) {
this.data.push(tmp[i].data);
}
this.timeMin = this.data[0][0][0];
this.timeMax = this.data[0][this.data[0].length-1][0];
this._super();
},
calcLayout: function(){
this.chrH = this.height * 0.8;
this.chrX = this.width / 12;
},
drawDynamicObjects: function(t){
// draw chromosome
this.drawObject({
strokeStyle: '#aaaaaa',
drawFunc: function(self, ctx, dataPt){
ctx.lineWidth = 2;
ctx.moveTo(0, self.chrH);
ctx.lineTo(self.width, self.chrH);
},
});
// label functional boxes
this.drawObject({
strokeStyle: '#3d80b3',
fillStyle: '#222222',
drawFunc: function(self, ctx, dataPt){
for (var i = 1; i <= 5; i++) {
var x = self.width / 6 * (6 - i);
ctx.lineWidth = 4;
ctx.font = "10px " + self.fontFamily;
ctx.moveTo(x, self.chrH);
ctx.lineTo(x + 20, self.chrH);
ctx.fillText('R' + i.toString(), x + 5, self.chrH + 12);
}
},
});
// label oriC
this.drawObject({
strokeStyle: '#222222',
fillStyle: '#222222',
drawFunc: function(self, ctx, dataPt){
ctx.lineWidth = 4;
ctx.font = "10px " + self.fontFamily;
ctx.moveTo(self.chrX, self.chrH - 5);
ctx.lineTo(self.chrX, self.chrH + 5);
ctx.fillText('oriC', self.chrX - 8, self.chrH + 15);
},
});
// draw dnaA proteins
for (var i = 0; i < 5; i++) {
var cnt = Math.round(getDataPoint(this.data[i], t, true));
var x = this.width / 6 * (5 - i) + 10;
for (var j = 1; j <= cnt; j++) {
this.drawObject({
data:{'x': x, 'y': this.chrH - j * 10},
strokeStyle: '#222222',
fillStyle: '#3d80b3',
drawFunc: function(self, ctx, data){
ctx.lineWidth = 1;
ctx.arc(data.x, data.y, 5, 0, 2 * Math.PI, false);
ctx.closePath();
},
});
}
}
},
});
var FtsZRingVisualization = Visualization2D.extend({
thickStrokeWidth:5,
thinStrokeWidth:1,
getData: function(md){
this._super(md);
this.getSeriesData('getSeriesData.php', {sim_id: md.sim_id, class_name: md.class_name, attr_name: 'animation'}, 'ring');
this.getSeriesData('getSeriesData.php', {sim_id: md.sim_id, class_name:'Geometry', attr_name: 'width_1'}, 'width');
this.getSeriesData('getSeriesData.php', {sim_id: md.sim_id, class_name: 'Geometry', attr_name: 'pinchedDiameter_1'}, 'pinchedDiameter');
this.getSeriesData('getSeriesData.php', {sim_id: md.sim_id, class_name: 'Geometry', attr_name: 'cylindricalLength_1'}, 'cylindricalLength');
},
getDataSuccess: function () {
if (undefined == this.data.ring
|| undefined == this.data.width
|| undefined == this.data.pinchedDiameter
|| undefined == this.data.cylindricalLength)
return;
this.data = {
ring: this.data.ring,
width: this.data.width.data,
pinchedDiameter: this.data.pinchedDiameter.data,
cylindricalLength: this.data.cylindricalLength.data,
};
this.timeMax = Math.max(
this.data.width[this.data.width.length - 1][0] - 1,
this.data.pinchedDiameter[this.data.pinchedDiameter.length - 1][0],
this.data.cylindricalLength[this.data.cylindricalLength.length - 1][0]
);
this.timeMin = Math.min(this.timeMax, this.data.ring.start_time);
this._super();
},
calcLayout: function(){
//to correct for scaling from data generation
this.scale = 1.15 * Math.min((this.width - this.thickStrokeWidth) / 520, (this.height - this.thickStrokeWidth) / 250);
this.xOffset = - 520 / 2 * this.scale + this.width / 2;
this.yOffset = - 250 / 2 * this.scale + this.height / 2;
//septum radius
this.radius = (Math.min(this.width, this.height) - this.thickStrokeWidth) / 2;
},
drawDynamicObjects: function(t){
t = Math.min(t, this.timeMax);
//cell membrane
var width = Math.max(this.data.width[0][1], getDataPoint(this.data.width, t, false));
var pD = getDataPoint(this.data.pinchedDiameter, t, true);
var cL = getDataPoint(this.data.cylindricalLength, t, true);
this.drawObject({
data: this.radius * width / this.data.width[0][1],
strokeStyle: '#cccccc',
drawFunc: function(self, ctx, radius){
ctx.lineWidth = 1;
ctx.arc(self.width / 2, self.height / 2, radius, 0, 2 * Math.PI);
},
});
//get FtsZ data
var dataPt = getDataPoint(this.data.ring.data, t);
if (dataPt == undefined){
dataPt = {
angles_edges_one_bent: [],
angles_edges_two_bent: [],
coords_edges_one_straight: [],
coords_edges_two_straight: [],
};
}else{
//radius
var r = this.scale * dataPt.r;
// draw edges with one straight filament
this.drawObject({
data: dataPt,
strokeStyle: '#3d80b3',
drawFunc: function(self, ctx, dataPt){
ctx.lineWidth = self.thinStrokeWidth;
for (var i = 0; i < dataPt.coords_edges_one_straight.length; i++) {
ctx.moveTo(
self.scale * dataPt.coords_edges_one_straight[i][0] + self.xOffset,
self.scale * dataPt.coords_edges_one_straight[i][1] + self.yOffset);
ctx.lineTo(
self.scale * dataPt.coords_edges_one_straight[i][2] + self.xOffset,
self.scale * dataPt.coords_edges_one_straight[i][3] + self.yOffset);
}
},
});
// draw edges with two straight filaments
this.drawObject({
data: dataPt,
strokeStyle: "#3d80b3",
drawFunc: function(self, ctx, dataPt){
ctx.lineWidth = self.thickStrokeWidth;
for (var i = 0; i < dataPt.coords_edges_two_straight.length; i++) {
ctx.moveTo(
self.scale * dataPt.coords_edges_two_straight[i][0] + self.xOffset,
self.scale * dataPt.coords_edges_two_straight[i][1] + self.yOffset);
ctx.lineTo(
self.scale * dataPt.coords_edges_two_straight[i][2] + self.xOffset,
self.scale * dataPt.coords_edges_two_straight[i][3] + self.yOffset);
}
},
});
// draw edges with one bent filament
for (var i = 0; i < dataPt.angles_edges_one_bent.length; i++) {
this.drawObject({
data: {'r': r, 'edge': dataPt.angles_edges_one_bent[i]},
strokeStyle: "#aaaaaa",
drawFunc: function(self, ctx, data){
ctx.lineWidth = self.thinStrokeWidth;
ctx.arc(self.width/2, self.height/2, data.r, data.edge[0], data.edge[1], false);
},
});
}
// draw edges with two bent filaments
for (var i = 0; i < dataPt.angles_edges_two_bent.length; i++) {
this.drawObject({
data: {'r': r, 'edge': dataPt.angles_edges_two_bent[i]},
strokeStyle: "#aaaaaa",
drawFunc: function(self, ctx, data){
ctx.lineWidth = self.thickStrokeWidth;
ctx.arc(self.width/2, self.height/2, data.r, data.edge[0], data.edge[1], false);
},
});
}
}
//write status
this.drawObject({
isLabel:true,
data: [
'Width: ' + (width * 1e9).toFixed(1) + ' nm',
'Length: ' + ((2 * width + cL + pD) * 1e9).toFixed(1) + ' nm',
'Septum: ' + (pD * 1e9).toFixed(1) + ' nm',
'FtsZ Bent: ' + dataPt.angles_edges_one_bent.length + '/' + dataPt.angles_edges_two_bent.length,
'FtsZ Straight: ' + dataPt.coords_edges_one_straight.length + '/' + dataPt.coords_edges_two_straight.length,
],
fillStyle: '#222222',
drawFunc: function(self, ctx, txt){
ctx.font = self.bigFontSize + "px " + self.fontFamily;
for (var i = 0; i < txt.length; i++){
ctx.fillText(txt[i],
self.width / 2 - ctx.measureText(txt[i]).width / 2,
self.height / 2 + 0.4 * self.bigFontSize + i * (self.bigFontSize + 2) - ((self.bigFontSize + 2) * txt.length) / 2);
}
},
});
},
});
var GeneExpressionHeatmapVisualization = HeatmapVisualization.extend({
axisTitle: ['RNA', 'Prot Mmr', 'Prot Cpx'],
axisTipFuncs: [
function(self, data){
var rna = self.rnas[data.row];
return sprintf('<h1>%s</h1>%sTime: %s<br/>Copy number: %d',
rna.wid, (rna.name ? rna.name + '<br/>' : ''), formatTime(data.time, ''), data.val);
},
function(self, data){
var pm = self.proteinMonomers[data.row];
return sprintf('<h1>%s</h1>%sTime: %s<br/>Copy number: %d',
pm.wid, (pm.name ? pm.name + '<br/>' : ''), formatTime(data.time, ''), data.val);
},
function(self, data){
var pc = self.proteinComplexs[data.row];
return sprintf('<h1>%s</h1>%sTime: %s<br/>Copy number: %d',
pc.wid, (pc.name ? pc.name + '<br/>' : ''), formatTime(data.time, ''), data.val);
},
],
getData: function(md){
this._super(md);
this.getSeriesData('getKBData.php', {'type': 'TranscriptonUnit'}, 'rnas');
this.getSeriesData('getKBData.php', {'type': 'ProteinMonomer'}, 'proteinMonomers');
this.getSeriesData('getKBData.php', {'type': 'ProteinComplex'}, 'proteinComplexs');
this.getSeriesData('getSeriesData.php', {
sim_id:md.sim_id,
class_name: 'Rna',
attr_name: 'counts_*',
attr_min: 694,
attr_max:1040,
}, 'rnaDynamics');
this.getSeriesData('getSeriesData.php', {
sim_id: md.sim_id,
class_name: 'ProteinMonomer',
attr_name: 'counts_*',
attr_min: 2411,
attr_max:2892,
}, 'monDynamics');
this.getSeriesData('getSeriesData.php', {
sim_id:md.sim_id,
class_name: 'ProteinComplex',
attr_name: 'counts_*',
attr_min: 202,
attr_max:402,
}, 'cpxDynamics');
},
getDataSuccess: function () {
if (undefined == this.data.rnas
|| undefined == this.data.proteinMonomers
|| undefined == this.data.proteinComplexs
|| undefined == this.data.rnaDynamics
|| undefined == this.data.monDynamics
|| undefined == this.data.cpxDynamics)
return;
this.rnas = this.data.rnas;
this.proteinMonomers = this.data.proteinMonomers;
this.proteinComplexs = this.data.proteinComplexs;
this.data = [
this.data.rnaDynamics.data,
this.data.monDynamics.data,
this.data.cpxDynamics.data,
];
this._super();
},
});
var RNAExpressionMapVisualization = ChromosomeMapVisualization.extend({
getData: function(md){
this._super(md);
//structural data
this.getSeriesData('getKBData.php', {'type': 'Gene'}, 'genes');
this.getSeriesData('getKBData.php', {'type': 'TranscriptonUnit'}, 'tus');
//dynamic data
this.getSeriesData('getSeriesData.php', {
sim_id:md.sim_id,
class_name: 'Rna',
attr_name: 'counts_*',
attr_min: 694,
attr_max:1040,
}, 'dynamics');
},
getDataSuccess: function (){
if (this.data.genes == undefined || this.data.tus == undefined || this.data.dynamics == undefined)
return;
//genes
var tmp = this.data.genes;
var genes = [];
for (var i = 0; i < tmp.length; i++){
genes[tmp[i].wid] = tmp[i];
}
//tus
var tus = this.data.tus;
this.objects = [];
for (var i = 0; i < tus.length; i++){
if (genes[tus[i].genes[0]].type == 'mRNA'){
var startCoord = NaN;
var endCoord = NaN;
for (var j = 0; j < tus[i].genes.length; j++){
var gene = genes[tus[i].genes[j]];
startCoord = Math.nanmin(startCoord, parseInt(gene.coordinate));
endCoord = Math.nanmax(endCoord, parseInt(gene.coordinate) + parseInt(gene.length) - 1);
}
this.objects.push($.extend(tus[i], {
'coordinate': startCoord,
'length': endCoord - startCoord + 1,
'direction': genes[tus[i].genes[0]].direction,
}));
}else{
for (var j = 0; j < tus[i].genes.length; j++){
this.objects.push(genes[tus[i].genes[j]]);
}
}
}
//dynamics
this.data = this.data.dynamics.data;
this._super();
},
});
var NascentRNAExpressionMapVisualization = ChromosomeMapVisualization.extend({
timeStep: 100,
getData: function(md){
this._super(md);
//structural data
this.getSeriesData('getKBData.php', {'type': 'Gene'}, 'genes');
this.getSeriesData('getKBData.php', {'type': 'TranscriptonUnit'}, 'tus');
//dynamic data
this.getSeriesData('getSeriesData.php', {
sim_id:md.sim_id,
class_name: 'Transcript',
attr_name: 'boundTranscriptionUnits_*',
}, 'boundTUs');
this.getSeriesData('getSeriesData.php', {
sim_id:md.sim_id,
class_name: 'Transcript',
attr_name: 'boundTranscriptProgress_*',
}, 'boundProgs');
},
getDataSuccess: function () {
if (undefined == this.data.genes
|| undefined == this.data.tus
|| undefined == this.data.boundTUs
|| undefined == this.data.boundProgs)
return;
//genes
var tmp = this.data.genes;
var genes = [];
for (var i = 0; i < tmp.length; i++){
genes[tmp[i].wid] = tmp[i];
}
//tus
var tus = this.data.tus;
this.objects = [];
for (var i = 0; i < tus.length; i++){
var startCoord = NaN;
var endCoord = NaN;
for (var j = 0; j < tus[i].genes.length; j++){
var gene = genes[tus[i].genes[j]];
startCoord = Math.nanmin(startCoord, parseInt(gene.coordinate));
endCoord = Math.nanmax(endCoord, parseInt(gene.coordinate) + parseInt(gene.length) - 1);
}
this.objects.push($.extend(tus[i], {
'coordinate': startCoord,
'length': endCoord - startCoord + 1,
'direction': genes[tus[i].genes[0]].direction,
}));
}
//dynamics
var boundTUs = this.data.boundTUs.data;
var boundProgs = this.data.boundProgs.data;
var timeMin = boundTUs[0][0][0];
var timeMax = boundTUs[0][boundTUs[0].length - 1][0];
this.data = [];
for (var i = 0; i < this.objects.length; i++){
var datai = [];
for (var t = timeMin; t <= timeMax; t += this.timeStep){
datai.push([t, 0]);
}
this.data.push(datai);
}
for (var i = 0; i < boundTUs.length; i++){
var j = -1;
for (var t = timeMin; t <= timeMax; t += this.timeStep){
j++;
bnd = getDataPoint(boundTUs[i], t, false);
prog = getDataPoint(boundProgs[i], t, false);
if (!bnd || !prog)
continue;
this.data[bnd - 1][j][1]++;
}
}
//super
this._super();
},
});
var ProteinMonomerExpressionMapVisualization = ChromosomeMapVisualization.extend({
getData: function(md){
this._super(md);
//structural data
this.getSeriesData('getKBData.php', {'type': 'Gene'}, 'genes');
this.getSeriesData('getKBData.php', {'type': 'ProteinMonomer'}, 'mons');
//dynamic data
this.getSeriesData('getSeriesData.php', {
sim_id:md.sim_id,
class_name: 'ProteinMonomer',
attr_name: 'counts_*',
attr_min: 2411,
attr_max: 2892,
}, 'dynamics');
},
getDataSuccess: function(){
if (undefined == this.data.genes
|| undefined == this.data.mons
|| undefined == this.data.dynamics)
return;
//genes
var tmp = this.data.genes;
var genes = [];
for (var i = 0; i < tmp.length; i++){
genes[tmp[i].wid] = tmp[i];
}
//monomers
var mons = this.data.mons;
this.objects = [];
for (var i = 0; i < mons.length; i++){
this.objects.push(genes[mons[i].gene]);
}
//dynamics
this.data = this.data.dynamics.data;
//super class method
this._super();
},
});
var NascentProteinMonomerExpressionMapVisualization = ChromosomeMapVisualization.extend({
timeStep: 100,
getData: function(md){
this._super(md);
//structural data
this.getSeriesData('getKBData.php', {'type': 'Gene'}, 'genes');
this.getSeriesData('getKBData.php', {'type': 'ProteinMonomer'}, 'mons');
//dynamic data
this.getSeriesData('getSeriesData.php', {
sim_id:md.sim_id,
class_name: 'Ribosome',
attr_name: 'boundMRNAs_*'
}, 'dynamics');
},
getDataSuccess: function() {
if (undefined == this.data.genes
|| undefined == this.data.mons
|| undefined == this.data.dynamics
)
return;
//genes
var tmp = this.data.genes;
var genes = [];
for (var i = 0; i < tmp.length; i++){
genes[tmp[i].wid] = tmp[i];
}
//monomers
var mons = this.data.mons;
this.objects = [];
for (var i = 0; i < mons.length; i++){
this.objects.push(genes[mons[i].gene]);
}
//dynamics
var boundMRNAs = this.data.dynamics.data;
var timeMin = boundMRNAs[0][0][0];
var timeMax = boundMRNAs[0][boundMRNAs[0].length - 1][0];
this.data = [];
for (var i = 0; i < this.objects.length; i++){
var datai = [];
for (var t = timeMin; t <= timeMax; t += this.timeStep){
datai.push([t, 0]);
}
this.data.push(datai);
}
for (var i = 0; i < boundMRNAs.length; i++){
var j = -1;
for (var t = timeMin; t <= timeMax; t += this.timeStep){
j++;
bnd = getDataPoint(boundMRNAs[i], t, false);
if (!bnd)
continue;
this.data[bnd - 1][j][1]++;
}
}
//super class method
this._super();
},
});
var EnergyHeatmapVisualization = Visualization2D.extend({
getData: function(md){
this._super(md);
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: md.class_name, attr_name: 'attr_name'});
},
calcLayout: function(){
},
drawDynamicObjects: function(t){
/*this.drawObject({
'strokeStyle': strokeStyle,
'fillStyle': fillStyle,
'data': getDataPoint(this.data, t),
drawFunc: function(self, ctx, data){
},
tipFunc: function(self, data){
},
clickFunc: function(self, data){
},
});*/
},
});
var MetabolicMapVisualization = Visualization2D.extend({
maxMetConc: 100, //uM
maxRxnFlux: 1e3, //Hz
getData: function(md){
this._super(md);
//KB data
this.getSeriesData('getKBData.php', {'type': 'Metabolite'}, 'metabolites');
this.getSeriesData('getKBData.php', {'type': 'Reaction'}, 'reactions');
//map
this.getSeriesData('data/metabolicMap.json', undefined, 'map');
//concentrations and fluxes
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Geometry', attr_name: 'volume_1'}, 'volume');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Metabolite', attr_name: 'counts_*'}, 'metaboliteConcs');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'MetabolicReaction', attr_name: 'fluxs_*'}, 'reactionFluxs');
},
getDataSuccess: function () {
if (undefined == this.data.metabolites
|| undefined == this.data.reactions
|| undefined == this.data.map
|| undefined == this.data.volume
|| undefined == this.data.metaboliteConcs
|| undefined == this.data.reactionFluxs)
return;
//kb
this.metabolites = this.data.metabolites;
this.reactions = this.data.reactions;
//map
this.map = this.data.map;
var minX = NaN;
var maxX = NaN;
var minY = NaN;
var maxY = NaN;
for (var i = 0; i < this.map.metabolites.length; i++){
minX = Math.nanmin(minX, this.map.metabolites[i].x);
maxX = Math.nanmax(maxX, this.map.metabolites[i].x);
minY = Math.nanmin(minY, this.map.metabolites[i].y);
maxY = Math.nanmax(maxY, this.map.metabolites[i].y);
}
for (var i = 0; i < this.map.reactions.length; i++){
var path, tmp, x1, x2, y1, y2;
path = this.map.reactions[i].path.split(' ');
tmp = path[1].split(', ');
x1 = parseInt(tmp[0]);
y1 = parseInt(tmp[1]);
tmp = path[path.length - 1].split(', ');
x2 = parseInt(tmp[0]);
y2 = parseInt(tmp[1]);
minX = Math.nanmin(minX, Math.min(x1, x2));
maxX = Math.nanmax(maxX, Math.max(x1, x2));
minY = Math.nanmin(minY, Math.min(y1, y2));
maxY = Math.nanmax(maxY, Math.max(y1, y2));
}
this.minX = minX;
this.maxX = maxX;
this.minY = minY;
this.maxY = maxY;
//dynamics
this.volume = this.data.volume.data;
this.metaboliteConcs = this.data.metaboliteConcs.data;
this.reactionFluxs = this.data.reactionFluxs.data;
this.timeMin = this.volume[0][0];
this.timeMax = this.volume[this.volume.length-1][0];
//super
this._super();
},
exportData: function(){
return {
volume: this.volume,
metaboliteConcs: this.metaboliteConcs,
reactionFluxs: this.reactionFluxs,
};
},
calcLayout: function(){
this.legendW = 10;
this.legendX = this.width - this.legendW;
this.legendTop = this.bigFontSize + 3;
this.legendBottom = this.height - this.bigFontSize - 3;
this.legendH = this.legendBottom - this.legendTop;
this.metMaxR = 3;
this.metConcScale = this.metMaxR / this.maxMetConc;
this.mapX = this.metMaxR + 1;
this.mapY = this.metMaxR + 1;
this.mapW = (this.legendX - 5) - 2 * (this.metMaxR + 1);
this.mapH = this.height - 2 * (this.metMaxR + 1);
this.scaleX = this.mapW / (this.maxX - this.minX);
this.scaleY = this.mapH / (this.maxY - this.minY);
this.arrowWidth = Math.PI / 8;
this.arrowLen = (this.legendX - 5) / 100;
},
drawStaticObjects: function(){
this.drawColorScale(
this.legendX, this.legendTop, this.legendW, this.legendH,
{r: 61, g: 128, b: 179},
{r: 240, g: 240, b: 240},
true);
},
drawDynamicObjects: function(t){
//metabolites
var V = getDataPoint(this.volume, t, true);
for (var i = 0; i < this.map.metabolites.length; i++){
conc = getDataPoint(this.metaboliteConcs[this.map.metabolites[i].idx - 1], t, true) / 6.022e23 / V * 1e6;
this.drawObject({
'strokeStyle': '#3d80b3',
'fillStyle': '#C9E7FF',
'data': {'map': this.map.metabolites[i], 'conc':conc},
drawFunc: function(self, ctx, data){
ctx.lineWidth = 1;
ctx.arc(
self.mapX + self.scaleX * (data.map.x - self.minX),
self.mapY + self.scaleY * (data.map.y - self.minY),
Math.max(1, Math.min(self.metMaxR, self.metConcScale * data.conc)), 0, 2 * Math.PI);
},
tipFunc: function(self, data){
return sprintf('<b>%s</b><br/><span style="white-space:nowrap;">Compartment: %s<br/>Concentration: %s μM</span>',
self.metabolites[data.map.idx - 1].name, data.map.c_wid, data.conc.toFixed(2));
},
});
this.drawObject({
isLabel:true,
'fillStyle': '#222222',
'data': {'map': this.map.metabolites[i], 'conc':conc},
drawFunc: function(self, ctx, data){
wid = self.metabolites[data.map.idx - 1].wid;
ctx.font = self.smallFontSize + "px " + self.fontFamily;
ctx.fillText(wid,
self.mapX + self.scaleX * (data.map.x - self.minX) - ctx.measureText(wid).width/2,
self.mapY + self.scaleY * (data.map.y - self.minY) + 0.4 * self.smallFontSize);
},
tipFunc: function(self, data){
return sprintf('<b>%s</b><br/><span style="white-space:nowrap;">Compartment: %s<br/>Concentration: %s μM</span>',
self.metabolites[data.map.idx - 1].name, data.map.c_wid, data.conc.toFixed(2));
},
});
}
//reactions
for (var i = 0; i < this.map.reactions.length; i++){
var val = getDataPoint(this.reactionFluxs[this.map.reactions[i].met_idx - 1], t, true);
if (val == 0){
var style = '#E1E1E1';
}else if (val < 0){
var f = Math.max(0, Math.min(1, Math.log(-val) / Math.log(this.maxRxnFlux)));
var style = 'rgb('
+ Math.round(f * 61 + (1-f) * 240) + ','
+ Math.round(f * 128 + (1-f) * 240) + ','
+ Math.round(f * 179 + (1-f) * 240) + ')';
}else{
var f = Math.max(0, Math.min(1, Math.log(val) / Math.log(this.maxRxnFlux)));
var style = 'rgb('
+ Math.round(f * 61 + (1-f) * 240) + ','
+ Math.round(f * 128 + (1-f) * 240) + ','
+ Math.round(f * 179 + (1-f) * 240) + ')';
}
this.drawReaction(this.map.reactions[i], val, style, undefined);
this.drawReaction(this.map.reactions[i], val, undefined, style);
}
},
drawReaction: function(map, val, strokeStyle, fillStyle){
this.drawObject({
'strokeStyle': strokeStyle,
'fillStyle': fillStyle,
'data': {'map': map, 'val':val, 'fill': fillStyle != undefined},
drawFunc: function(self, ctx, data){
ctx.lineWidth = 1;
segments = data.map.path.match(/([MLC])( ([0-9]+,[0-9]+))+/g);
var x, y, dy, dx;
for (var j = 0; j < segments.length; j++){
var tmp = segments[j].substr(2).split(/[ ,]/);
var pts = [];
for (var k = 0; k < tmp.length; k += 2){
pts.push([
self.mapX + self.scaleX * (parseFloat(tmp[k]) - self.minX),
self.mapY + self.scaleY * (parseFloat(tmp[k + 1]) - self.minY),
]);
}
switch (segments[j].substr(0, 1)){
case 'M':
ctx.moveTo(pts[0][0], pts[0][1]);
break;
case 'L':
if (!data.fill){
ctx.lineTo(pts[0][0], pts[0][1]);
}else if (j == segments.length - 1 && data.val > 0){
dx = pts[0][0] - x;
dy = pts[0][1] - y;
ctx.arrowTo(pts[0][0]-dx*1e-2, pts[0][1]-dy*1e-2, pts[0][0], pts[0][1], 0, 1, self.arrowWidth, self.arrowLen);
}else if (j == 1 && data.val < 0){
dx = x - pts[0][0];
dy = y - pts[0][1];
ctx.arrowTo(x-dx*1e-2, y-dy*1e-2, x, y, 0, 1, self.arrowWidth, self.arrowLen);
}
break;
case 'C':
if (!data.fill){
ctx.bezierCurveTo(pts[0][0], pts[0][1], pts[1][0], pts[1][1], pts[2][0], pts[2][1]);
}else if (j == segments.length - 1 && data.val > 0){
dx = -3 * pts[1][0] + 3 * pts[2][0];
dy = -3 * pts[1][1] + 3 * pts[2][1];
ctx.arrowTo(pts[2][0]-dx*1e-2, pts[2][1]-dy*1e-2, pts[2][0], pts[2][1], 0, 1, self.arrowWidth, self.arrowLen);
}else if (j == 1 && data.val < 0){
dx = x - pts[0][0];
dy = y - pts[0][1];
ctx.arrowTo(x-dx*1e-2, y-dy*1e-2, x, y, 0, 1, self.arrowWidth, self.arrowLen);
}
break;
}
x = pts[pts.length - 1][0];
y = pts[pts.length - 1][1];
}
},
tipFunc: function(self, data){
return sprintf('<b>%s</b><br/><span style="white-space:nowrap;">Flux: %s Hz</span>',
self.reactions[data.map.idx - 1].name,
data.val.toFixed(1));
},
});
this.drawObject({
isLabel:true,
'fillStyle': '#222222',
'data': {'map': map, 'val':val, 'fill': fillStyle != undefined},
drawFunc: function(self, ctx, data){
segments = data.map.path.match(/([MLC])( ([0-9]+,[0-9]+))+/g);
var tmp = segments[0].substr(2).split(/[ ,]/);
var x0 = tmp[0];
var y0 = tmp[1];
var tmp = segments[segments.length-1].substr(2).split(/[ ,]/);
var x1 = tmp[tmp.length-2];
var y1 = tmp[tmp.length-1];
x0 = self.mapX + self.scaleX * (parseFloat(x0) - self.minX)
x1 = self.mapX + self.scaleX * (parseFloat(x1) - self.minX)
y0 = self.mapY + self.scaleY * (parseFloat(y0) - self.minY)
y1 = self.mapY + self.scaleY * (parseFloat(y1) - self.minY)
var x = (x0 + x1) / 2;
var y = (y0 + y1) / 2;
wid = self.reactions[data.map.idx - 1].wid;
ctx.font = self.smallFontSize + "px " + self.fontFamily;
ctx.fillText(wid,
x - ctx.measureText(wid).width / 2,
y + 0.4 * self.smallFontSize);
},
tipFunc: function(self, data){
return sprintf('<b>%s</b><br/><span style="white-space:nowrap;">Flux: %s Hz</span>',
self.reactions[data.map.idx - 1].name,
data.val.toFixed(1));
},
});
},
});
var TranslationVisualization = ChromosomeMapVisualization.extend({
timeStep:100,
legendW:19,
getData: function(md){
this._super(md);
//structural data
this.getSeriesData('getKBData.php', {'type': 'Gene'}, 'genes');
this.getSeriesData('getKBData.php', {'type': 'ProteinMonomer'}, 'proteinMonomers');
//dynamic data
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Ribosome', attr_name: 'boundMRNAs_*'}, 'boundMRNAs');
this.getSeriesData('getSeriesData.php', {sim_id:md.sim_id, class_name: 'Ribosome', attr_name: 'mRNAPositions_*'}, 'mRNAPositions');
},
getDataSuccess: function () {
if (undefined == this.data.genes
|| undefined == this.data.proteinMonomers
|| undefined == this.data.boundMRNAs
|| undefined == this.data.mRNAPositions
)
return;
//genes
var tmp = this.data.genes;
var genes = [];
for (var i = 0; i < tmp.length; i++){
genes[tmp[i].wid] = tmp[i];
}
//monomers
this.proteinMonomers = this.data.proteinMonomers;
this.objects = [];
for (var i = 0; i < this.proteinMonomers.length; i++){
this.objects.push(genes[this.proteinMonomers[i].gene]);
}
//dynamics
var boundMRNAs = this.data.boundMRNAs.data;
var mRNAPositions = this.data.mRNAPositions.data;
this.timeMin = boundMRNAs[0][0][0];
this.timeMax = boundMRNAs[0][boundMRNAs[0].length - 1][0];
this.data = [];
for (var i = 0; i < this.objects.length; i++){
var datai = [];
for (var t = this.timeMin; t <= this.timeMax; t += this.timeStep){
datai.push([0, 0]);
}
this.data.push(datai);
}
var maxVal = 0;
for (var i = 0; i < boundMRNAs.length; i++){
var j = -1;
for (var t = this.timeMin; t <= this.timeMax; t += this.timeStep){
j++;
bnd = getDataPoint(boundMRNAs[i], t, false);
if (!bnd)
continue;
mR = getDataPoint(mRNAPositions[i], t, true);
this.data[bnd - 1][j][0] = Math.max(this.data[bnd - 1][j][0], mR);
this.data[bnd - 1][j][1]++;
maxVal = Math.max(maxVal, this.data[bnd - 1][j][1]);
}
}
//////////////////
//super
/////////////////
this.parent.parent().panel('clearPanelLoadingIndicator');
//set time
var timeline = $('#timeline');
timeline.timeline('updateTimeRange');
this.time = timeline.timeline('getTime');
if (isNaN(this.time))
this.time = this.timeMin;
//resize canvases
this.resize(this.parent.width(), this.parent.height(), true);
//set data loaded
this.dataLoaded = true;
},
getDataPoint: function(row, t){
if (t < this.timeMin || t > this.timeMax)
return undefined;
var idx = Math.floor((t - this.timeMin) / this.timeStep);
var v1 = this.data[row][idx];
if (this.data[row].length <= idx + 1){
return v1;
}else{
var v2 = this.data[row][idx + 1];
var dt = (t - this.timeMin) % this.timeStep;
//return closer value -- do this because averaging throws an error for an unknown reason
if (dt < this.timeStep / 2)
return v1
else
return v2;
//average
return [
(v1[0] * (this.timeStep - dt) + v2[0] * dt) / this.timeStep,
(v1[1] * (this.timeStep - dt) + v2[1] * dt) / this.timeStep,
];
}
},
drawObjectForward: function(ctx, x, y, w, h, row, val){
var len = this.objects[row].length / 3;
ctx.lineWidth = 0.25;
if ((this.isDrawingForExport || this.isDrawingForDisplay) && val && val[0]){
ctx.rect(x, y, w * Math.min(1, val[0] / len), h);
}
if (this.isDrawingForExport || this.isDrawingStaticContent){
ctx.rect(x, y, w, h);
}
},
drawObjectReverse: function(ctx, x, y, w, h, row, val){
this.drawObjectForward(ctx, x, y, w, h, row, val);
},
getObjectFillStyle: function(row, val){
if (!val || val[1] == 0)
return undefined;
if (val[1] == 1)
return '#3d80b3';
return '#3db34a';
},
drawColorScale: function(x, y, w, h, cLo, cHi, noShowBlack, labelLo, labelHi, nSegments){
this.drawObject({
fillStyle: '#222222',
data: {'x': x, 'y': y, 'w': w},
drawFunc: function (self, ctx, data) {
var w = data.w - 3 - ctx.measureText('>1').width;
ctx.font = self.smallFontSize + "px " + self.fontFamily;
ctx.fillText('1', data.x + data.w - ctx.measureText('1').width,
data.y + w/2);
},
});
this.drawObject({
strokeStyle: '#222222',
fillStyle: '#3d80b3',
data: {'x': x, 'y': y, 'w': w},
drawFunc: function (self, ctx, data) {
var w = data.w - 3 - ctx.measureText('>1').width;
ctx.rect(data.x, data.y, w, w);
},
});
this.drawObject({
fillStyle: '#222222',
data: {'x': x, 'y': y, 'w': w},
drawFunc: function (self, ctx, data) {
var w = data.w - 3 - ctx.measureText('>1').width;
var spcg = 3/2 * w;
ctx.font = self.smallFontSize + "px " + self.fontFamily;
ctx.fillText('>1', data.x + data.w - ctx.measureText('>1').width,
data.y + w/2 + spcg);
},
});
this.drawObject({
strokeStyle: '#222222',
fillStyle: '#3db34a',
data: {'x': x, 'y': y, 'w': w},
drawFunc: function (self, ctx, data) {
var w = data.w - 3 - ctx.measureText('>1').width;
var spcg = 3/2 * w;
ctx.rect(data.x, data.y + spcg, w, w);
},
});
}
});
/* helper functions */
function getGeneByPos(genes, pos, iMin, iMax){
if (iMin == undefined)
iMin = 0;
if (iMax == undefined)
iMax = genes.length - 1;
if (iMin == iMax){
var gene = genes[iMin];
if (pos >= gene.coordinate && pos <= gene.coordinate + gene.length)
return gene;
else
return undefined;
}
if (iMax - iMin == 1){
return getGeneByPos(genes, pos, iMin, iMin) || getGeneByPos(genes, pos, iMax, iMax);
}
var i = Math.floor((iMin + iMax) / 2);
if (pos < genes[i].coordinate)
return getGeneByPos(genes, pos, iMin, i - 1);
else
return getGeneByPos(genes, pos, i, iMax);
}<|fim▁end|> | this.segmentSeparation = (1 + this.segmentSpacing) * this.segmentHeight;
this.chrSeparation = (this.chrSpacing + 1 * (this.numSegments + this.segmentSpacing * (this.numSegments - 1))) * this.segmentHeight;
this.legendX = this.width - 57; |
<|file_name|>8.py<|end_file_name|><|fim▁begin|># Created by PyCharm Pro Edition
# User: Kaushik Talukdar
# Date: 01-04-17
# Time: 03:10 AM
# Using continue
# continue will send the loop back to its root
nos = 0<|fim▁hole|> print(nos)
# AVOID INFINITE LOOP
# if the loop has no condition that can end, the loop will run infinitely
# here if we forgot to add "nos += 1, the loop will become infinite loop<|fim▁end|> | while nos < 10:
nos += 1
if nos%2 == 0:
continue |
<|file_name|>emotiv.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Emotiv acquisition :
Reverse engineering and original crack code written by
Cody Brocious (http://github.com/daeken)
Kyle Machulis (http://github.com/qdot)
Many thanks for their contribution.
Need python-crypto.
"""
import multiprocessing as mp
import numpy as np
import msgpack
import time
from collections import OrderedDict
from .base import DeviceBase
import platform
WINDOWS = (platform.system() == "Windows")
try:
import pywinusb.hid as hid
except:
pass
import os
from subprocess import check_output
from Crypto.Cipher import AES
from Crypto import Random
import Queue
tasks = Queue.Queue()
_channel_names = [ 'F3', 'F4', 'P7', 'FC6', 'F7', 'F8','T7','P8','FC5','AF4','T8','O2','O1','AF3']
sensorBits = {
'F3': [10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7],
'FC5': [28, 29, 30, 31, 16, 17, 18, 19, 20, 21, 22, 23, 8, 9],
'AF3': [46, 47, 32, 33, 34, 35, 36, 37, 38, 39, 24, 25, 26, 27],
'F7': [48, 49, 50, 51, 52, 53, 54, 55, 40, 41, 42, 43, 44, 45],
'T7': [66, 67, 68, 69, 70, 71, 56, 57, 58, 59, 60, 61, 62, 63],
'P7': [84, 85, 86, 87, 72, 73, 74, 75, 76, 77, 78, 79, 64, 65],
'O1': [102, 103, 88, 89, 90, 91, 92, 93, 94, 95, 80, 81, 82, 83],
'O2': [140, 141, 142, 143, 128, 129, 130, 131, 132, 133, 134, 135, 120, 121],
'P8': [158, 159, 144, 145, 146, 147, 148, 149, 150, 151, 136, 137, 138, 139],
'T8': [160, 161, 162, 163, 164, 165, 166, 167, 152, 153, 154, 155, 156, 157],
'F8': [178, 179, 180, 181, 182, 183, 168, 169, 170, 171, 172, 173, 174, 175],
'AF4': [196, 197, 198, 199, 184, 185, 186, 187, 188, 189, 190, 191, 176, 177],
'FC6': [214, 215, 200, 201, 202, 203, 204, 205, 206, 207, 192, 193, 194, 195],
'F4': [216, 217, 218, 219, 220, 221, 222, 223, 208, 209, 210, 211, 212, 213]
}
quality_bits = [99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112]
def create_analog_subdevice_param(channel_names):
n = len(channel_names)
d = {
'type' : 'AnalogInput',
'nb_channel' : n,
'params' :{ },
'by_channel_params' : {
'channel_indexes' : range(n),
'channel_names' : channel_names,
}
}
return d
def get_info(device):
info = { }
info['class'] = 'EmotivMultiSignals'
if WINDOWS:
# EMOTIV
info['device_path'] = device.device_path
info['board_name'] = '{} #{}'.format(device.vendor_name, device.serial_number).replace('\n', '').replace('\r', '')
info['serial'] = device.serial_number
info['hid'] = device
<|fim▁hole|> info['device_path'] = device
name = device_path.strip('/dev/')
realInputPath = os.path.realpath("/sys/class/hidraw/" + name)
path = '/'.join(realInputPath.split('/')[:-4])
with open(path + "/manufacturer", 'r') as f:
manufacturer = f.readline()
with open(path + "/serial", 'r') as f:
serial = f.readline().strip()
info['board_name'] = '{} #{}'.format(manufacturer, serial).replace('\n', '').replace('\r', '')
info['serial'] = serial
# PYACQ
info['global_params'] = {'buffer_length' : 60.,}
info['subdevices'] = [ ]
info['subdevices'].append(create_analog_subdevice_param(_channel_names))
quality_name = ['Quality {}'.format(n) for n in _channel_names]
info['subdevices'].append(create_analog_subdevice_param(quality_name))
info['subdevices'].append(create_analog_subdevice_param([ 'X','Y']))
return info
def dump(obj):
for attr in dir(obj):
print "obj.%s = %s" % (attr, getattr(obj, attr))
class EmotivMultiSignals(DeviceBase):
def __init__(self, **kargs):
DeviceBase.__init__(self, **kargs)
@classmethod
def get_available_devices(cls):
devices = OrderedDict()
if WINDOWS:
try:
for device in hid.find_all_hid_devices():
print "device : ", device
if (device.product_name == 'Emotiv RAW DATA' or device.product_name == 'EPOC BCI'):
devices['Emotiv '+device.serial_number] = get_info(device)
finally:
pass
else:
serials = { }
for name in os.listdir("/sys/class/hidraw"):
realInputPath = os.path.realpath("/sys/class/hidraw/" + name)
path = '/'.join(realInputPath.split('/')[:-4])
try:
with open(path + "/manufacturer", 'r') as f:
manufacturer = f.readline()
if "emotiv" in manufacturer.lower():
with open(path + "/serial", 'r') as f:
serial = f.readline().strip()
if serial not in serials:
serials[serial] = [ ]
serials[serial].append(name)
except IOError as e:
print "Couldn't open file: %s" % e
for serial, names in serials.items():
device_path = '/dev/'+names[1]
info = get_info(device_path)
devices['Emotiv '+device_path] = info
return devices
def configure(self, buffer_length = 60,
subdevices = None,
):
self.params = {'buffer_length' : buffer_length,
'subdevices' : subdevices,
}
self.__dict__.update(self.params)
self.configured = True
def initialize(self):
devices = EmotivMultiSignals.get_available_devices()
self.device = devices.values()[0]
if self.subdevices is None:
self.subdevices = self.device['subdevices']
self.sampling_rate = 128.
self.packet_size = 1
l = int(self.sampling_rate*self.buffer_length)
self.buffer_length = (l - l%self.packet_size)/self.sampling_rate
self.name = '{}'.format(self.device['board_name'])
self.streams = [ ]
for s, sub in enumerate(self.subdevices):
stream = self.streamhandler.new_AnalogSignalSharedMemStream(name = self.name+str(s) , sampling_rate = self.sampling_rate,
nb_channel = sub['nb_channel'], buffer_length = self.buffer_length,
packet_size = self.packet_size, dtype = np.float64,
channel_names = sub['by_channel_params']['channel_names'],
channel_indexes = sub['by_channel_params']['channel_indexes'],
)
self.streams.append(stream)
def start(self):
self.stop_flag = mp.Value('i', 0) #flag pultiproc = global
self.process = mp.Process(target = emotiv_mainLoop, args=(self.stop_flag, self.streams, self.device) )
self.process.start()
print 'FakeMultiAnalogChannel started:', self.name
self.running = True
def stop(self):
self.stop_flag.value = 1
self.process.join()
print 'FakeMultiAnalogChannel stopped:', self.name
self.running = False
def close(self):
if WINDOWS:
self.device['hid'].close()
else:
pass
# for ii in self.streams:
# self.streams[ii].stop()
def setupCrypto(serial):
type = 0 #feature[5]
type &= 0xF
type = 0
#I believe type == True is for the Dev headset, I'm not using that. That's the point of this library in the first place I thought.
k = ['\0'] * 16
k[0] = serial[-1]
k[1] = '\0'
k[2] = serial[-2]
if type:
k[3] = 'H'
k[4] = serial[-1]
k[5] = '\0'
k[6] = serial[-2]
k[7] = 'T'
k[8] = serial[-3]
k[9] = '\x10'
k[10] = serial[-4]
k[11] = 'B'
else:
k[3] = 'T'
k[4] = serial[-3]
k[5] = '\x10'
k[6] = serial[-4]
k[7] = 'B'
k[8] = serial[-1]
k[9] = '\0'
k[10] = serial[-2]
k[11] = 'H'
k[12] = serial[-3]
k[13] = '\0'
k[14] = serial[-4]
k[15] = 'P'
#It doesn't make sense to have more than one greenlet handling this as data needs to be in order anyhow. I guess you could assign an ID or something
#to each packet but that seems like a waste also or is it? The ID might be useful if your using multiple headsets or usb sticks.
key = ''.join(k)
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_ECB, iv)
return cipher
def get_level(data, bits):
level = 0
for i in range(13, -1, -1):
level <<= 1
b, o = (bits[i] / 8) + 1, bits[i] % 8
level |= (ord(data[b]) >> o) & 1
return level
def emotiv_mainLoop(stop_flag, streams, device):
import zmq
abs_pos = pos = 0
#setup cryto
cipher = setupCrypto(device['serial'])
streamChan, streamImp, streamGyro = streams
#Data channels socket
context = zmq.Context()
socket_chan = context.socket(zmq.PUB)
socket_chan.bind("tcp://*:{}".format(streamChan['port']))
#Impedance channels socket
socket_imp = context.socket(zmq.PUB)
socket_imp.bind("tcp://*:{}".format(streamImp['port']))
#Gyro channels socket
socket_gyro = context.socket(zmq.PUB)
socket_gyro.bind("tcp://*:{}".format(streamGyro['port']))
packet_size = streamChan['packet_size']
sampling_rate = streamChan['sampling_rate']
np_arr_chan = streamChan['shared_array'].to_numpy_array()
np_arr_imp = streamImp['shared_array'].to_numpy_array()
np_arr_gyro = streamGyro['shared_array'].to_numpy_array()
half_size = np_arr_chan.shape[1]/2 # same for the others
impedance_qualities = { }
for name in _channel_names + ['X', 'Y', 'Unknown']:
impedance_qualities[name] = 0.
if WINDOWS:
device['hid'].open()
device['hid'].set_raw_data_handler(emotiv_handler)
else:
hidraw = open(device['device_path'])
while True:
# READ DATA
if WINDOWS:
crypted_data = tasks.get(True)
else:
crypted_data = hidraw.read(32)
# PROCESS
data = cipher.decrypt(crypted_data[:16]) + cipher.decrypt(crypted_data[16:])
# current impedance quality
sensor_num = ord(data[0])
num_to_name = { 0 : 'F3', 1:'FC5', 2 : 'AF3', 3 : 'F7', 4:'T7', 5 : 'P7',
6 : 'O1', 7 : 'O2', 8: 'P8', 9 : 'T8', 10: 'F8', 11 : 'AF4',
12 : 'FC6', 13: 'F4', 14 : 'F8', 15:'AF4',
64 : 'F3', 65 : 'FC5', 66 : 'AF3', 67 : 'F7', 68 : 'T7', 69 : 'P7',
70 : 'O1', 71 : 'O2', 72: 'P8', 73 : 'T8', 74: 'F8', 75 : 'AF4',
76 : 'FC6', 77: 'F4', 78 : 'F8', 79:'AF4',
80 : 'FC6',
}
if sensor_num in num_to_name:
sensor_name = num_to_name[sensor_num]
impedance_qualities[sensor_name] = get_level(data, quality_bits) / 540
for c, channel_name in enumerate(_channel_names):
bits = sensorBits[channel_name]
# channel value
value = get_level(data, bits)
np_arr_chan[c,pos] = value
np_arr_chan[c,pos+half_size] = value
#channel qualities
np_arr_imp[c,pos] = impedance_qualities[channel_name]
np_arr_imp[c,pos+half_size] = impedance_qualities[channel_name]
gyroX = ord(data[29]) - 106
gyroY = ord(data[30]) - 105
np_arr_gyro[:,pos] = [gyroX, gyroY]
np_arr_gyro[:,pos+half_size] = [gyroX, gyroY]
abs_pos += packet_size
pos = abs_pos%half_size
socket_chan.send(msgpack.dumps(abs_pos))
socket_imp.send(msgpack.dumps(abs_pos))
socket_gyro.send(msgpack.dumps(abs_pos))
if stop_flag.value:
print 'will stop'
break
# Windows handler
def emotiv_handler(data):
"""
Receives packets from headset for Windows. Sends them to the crypto process
"""
assert data[0] == 0
tasks.put_nowait(''.join(map(chr, data[1:])))
return True
Emotiv = EmotivMultiSignals<|fim▁end|> | else: |
<|file_name|>message_builder.rs<|end_file_name|><|fim▁begin|>use session::{Session, ReceiptRequest, OutstandingReceipt};
use frame::Frame;
use option_setter::OptionSetter;
pub struct MessageBuilder<'a> {
pub session: &'a mut Session,
pub frame: Frame,
pub receipt_request: Option<ReceiptRequest>
}
impl<'a> MessageBuilder<'a> {
pub fn new(session: &'a mut Session, frame: Frame) -> Self {
MessageBuilder {
session: session,
frame: frame,
receipt_request: None
}
}
#[allow(dead_code)]
pub fn send(self) {
if self.receipt_request.is_some() {
let request = self.receipt_request.unwrap();
self.session.state.outstanding_receipts.insert(
request.id,
OutstandingReceipt::new(
self.frame.clone()
)
);
}
self.session.send_frame(self.frame)
}
#[allow(dead_code)]
pub fn with<T>(self, option_setter: T) -> MessageBuilder<'a>
where T: OptionSetter<MessageBuilder<'a>>
{
option_setter.set_option(self)<|fim▁hole|>}<|fim▁end|> | } |
<|file_name|>sankey_definition.py<|end_file_name|><|fim▁begin|>from textwrap import dedent
from pprint import pformat
from collections import OrderedDict
import attr
from . import sentinel
from .ordering import Ordering
# adapted from https://stackoverflow.com/a/47663099/1615465
def no_default_vals_in_repr(cls):
"""Class decorator on top of attr.s that omits attributes from repr that
have their default value"""
defaults = OrderedDict()
for attribute in cls.__attrs_attrs__:
if isinstance(attribute.default, attr.Factory):
assert attribute.default.takes_self == False, 'not implemented'
defaults[attribute.name] = attribute.default.factory()
else:
defaults[attribute.name] = attribute.default
def repr_(self):
real_cls = self.__class__
qualname = getattr(real_cls, "__qualname__", None)
if qualname is not None:
class_name = qualname.rsplit(">.", 1)[-1]
else:
class_name = real_cls.__name__
attributes = defaults.keys()
return "{0}({1})".format(
class_name,
", ".join(
name + "=" + repr(getattr(self, name))
for name in attributes
if getattr(self, name) != defaults[name]))
cls.__repr__ = repr_
return cls
# SankeyDefinition
def _convert_bundles_to_dict(bundles):
if not isinstance(bundles, dict):
bundles = {k: v for k, v in enumerate(bundles)}
return bundles
def _convert_ordering(ordering):
if isinstance(ordering, Ordering):
return ordering
else:
return Ordering(ordering)
def _validate_bundles(instance, attribute, bundles):
# Check bundles
for k, b in bundles.items():
if not b.from_elsewhere:
if b.source not in instance.nodes:
raise ValueError('Unknown source "{}" in bundle {}'.format(
b.source, k))
if not isinstance(instance.nodes[b.source], ProcessGroup):
raise ValueError(
'Source of bundle {} is not a process group'.format(k))
if not b.to_elsewhere:
if b.target not in instance.nodes:
raise ValueError('Unknown target "{}" in bundle {}'.format(
b.target, k))
if not isinstance(instance.nodes[b.target], ProcessGroup):
raise ValueError(
'Target of bundle {} is not a process group'.format(k))
for u in b.waypoints:
if u not in instance.nodes:
raise ValueError('Unknown waypoint "{}" in bundle {}'.format(
u, k))
if not isinstance(instance.nodes[u], Waypoint):
raise ValueError(
'Waypoint "{}" of bundle {} is not a waypoint'.format(u,
k))
def _validate_ordering(instance, attribute, ordering):
for layer_bands in ordering.layers:
for band_nodes in layer_bands:
for u in band_nodes:
if u not in instance.nodes:
raise ValueError('Unknown node "{}" in ordering'.format(u))
@attr.s(slots=True, frozen=True)
class SankeyDefinition(object):
nodes = attr.ib()
bundles = attr.ib(converter=_convert_bundles_to_dict,
validator=_validate_bundles)
ordering = attr.ib(converter=_convert_ordering, validator=_validate_ordering)
flow_selection = attr.ib(default=None)
flow_partition = attr.ib(default=None)
time_partition = attr.ib(default=None)
def copy(self):
return self.__class__(self.nodes.copy(), self.bundles.copy(),
self.ordering, self.flow_partition,
self.flow_selection, self.time_partition)
def to_code(self):
nodes = "\n".join(
" %s: %s," % (repr(k), pformat(v)) for k, v in self.nodes.items()
)
ordering = "\n".join(
" %s," % repr([list(x) for x in layer]) for layer in self.ordering.layers
# convert to list just because it looks neater
)
bundles = "\n".join(
" %s," % pformat(bundle) for bundle in self.bundles.values()
)
if self.flow_selection is not None:
flow_selection = "flow_selection = %s\n\n" % pformat(self.flow_selection)
else:
flow_selection = ""
if self.flow_partition is not None:
flow_partition = "flow_partition = %s\n\n" % pformat(self.flow_partition)
else:
flow_partition = ""
if self.time_partition is not None:
time_partition = "time_partition = %s\n\n" % pformat(self.time_partition)
else:
time_partition = ""
code = dedent("""
from floweaver import (
ProcessGroup,
Waypoint,
Partition,
Group,
Elsewhere,
Bundle,
SankeyDefinition,
)
nodes = {
%s
}
ordering = [
%s
]
bundles = [
%s
]
%s%s%ssdd = SankeyDefinition(nodes, bundles, ordering%s%s%s)
""") % (
nodes,
ordering,
bundles,
flow_selection,
flow_partition,
time_partition,
(", flow_selection=flow_selection" if flow_selection else ""),
(", flow_partition=flow_partition" if flow_partition else ""),
(", time_partition=time_parititon" if time_partition else "")
)
return code
# ProcessGroup
def _validate_direction(instance, attribute, value):
if value not in 'LR':
raise ValueError('direction must be L or R')
@no_default_vals_in_repr
@attr.s(slots=True)
class ProcessGroup(object):
"""A ProcessGroup represents a group of processes from the underlying dataset.
The processes to include are defined by the `selection`. By default they
are all lumped into one node in the diagram, but by defining a `partition`
this can be controlled.
Attributes
----------
selection : list or string
If a list of strings, they are taken as process ids.
If a single string, it is taken as a Pandas query string run against the
process table.
partition : Partition, optional
Defines how to split the ProcessGroup into subgroups.
direction : 'R' or 'L'
Direction of flow, default 'R' (left-to-right).
title : string, optional
Label for the ProcessGroup. If not set, the ProcessGroup id will be used.
"""
selection = attr.ib(default=None)
partition = attr.ib(default=None)
direction = attr.ib(validator=_validate_direction, default='R')
title = attr.ib(
default=None,
validator=attr.validators.optional(attr.validators.instance_of(str)))
# Waypoint
@no_default_vals_in_repr
@attr.s(slots=True)
class Waypoint(object):
"""A Waypoint represents a control point along a :class:`Bundle` of flows.
There are two reasons to define Waypoints: to control the routing of
:class:`Bundle` s of flows through the diagram, and to split flows according
to some attributes by setting a `partition`.
Attributes
----------
partition : Partition, optional
Defines how to split the Waypoint into subgroups.
direction : 'R' or 'L'
Direction of flow, default 'R' (left-to-right).
title : string, optional
Label for the Waypoint. If not set, the Waypoint id will be used.
"""
partition = attr.ib(default=None)
direction = attr.ib(validator=_validate_direction, default='R')
title = attr.ib(
default=None,
validator=attr.validators.optional(attr.validators.instance_of(str)))
# Bundle
Elsewhere = sentinel.create('Elsewhere')
def _validate_flow_selection(instance, attribute, value):
if instance.source == instance.target and not value:
raise ValueError('flow_selection is required for bundle with same '
'source and target')
@no_default_vals_in_repr
@attr.s(frozen=True, slots=True)
class Bundle(object):
"""A Bundle represents a set of flows between two :class:`ProcessGroup`s.
Attributes
----------
source : string
The id of the :class:`ProcessGroup` at the start of the Bundle.
target : string
The id of the :class:`ProcessGroup` at the end of the Bundle.
waypoints : list of strings
Optional list of ids of :class:`Waypoint`s the Bundle should pass through.
flow_selection : string, optional
Query string to filter the flows included in this Bundle.
flow_partition : Partition, optional
Defines how to split the flows in the Bundle into sub-flows. Often you want
the same Partition for all the Bundles in the diagram, see
:attr:`SankeyDefinition.flow_partition`.
default_partition : Partition, optional
Defines the Partition applied to any Waypoints automatically added to route
the Bundle across layers of the diagram.
"""
source = attr.ib()
target = attr.ib()
waypoints = attr.ib(default=attr.Factory(tuple), converter=tuple)
flow_selection = attr.ib(default=None, validator=_validate_flow_selection)
flow_partition = attr.ib(default=None)
default_partition = attr.ib(default=None)
@property
def to_elsewhere(self):
"""True if the target of the Bundle is Elsewhere (outside the system
boundary)."""<|fim▁hole|> @property
def from_elsewhere(self):
"""True if the source of the Bundle is Elsewhere (outside the system
boundary)."""
return self.source is Elsewhere<|fim▁end|> | return self.target is Elsewhere
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from Operators.Mutation.Mutator import Mutator<|fim▁hole|>from Operators.Mutation.DisplacementMutator import DisplacementMutator
from Operators.Mutation.InversionMutator import InversionMutator<|fim▁end|> | |
<|file_name|>CardMenu.java<|end_file_name|><|fim▁begin|>package fr.fablabmars.model;
import java.util.ArrayList;
import fr.fablabmars.observer.Observable;
import fr.fablabmars.observer.Observer;
/**
* Observable contenant le menu courant.
*
* @author Guillaume Perouffe
* @see Observable
*/
public class CardMenu implements Observable {
/**
* Liste des observateurs de cet observable.
*/
private ArrayList<Observer> listObserver = new ArrayList<Observer>();
/**
* Indice du menu courant
*/
private int panel;
/**
* Constructeur de l'observable
* <p>
* On initialise le menu sur le 'panel' par défaut,
* d'indice 0.
* </p>
*
* @see CardMenu#panel
*/
public CardMenu(){
panel = 0;
}
/**
* Change le panneau courant et notifie les observateurs.
*
* @param panel
* Indice du nouveau menu.
*
* @see CardMenu#panel
* @see Observable#notifyObservers()
*/
public void setPanel(int panel){
this.panel = panel;
notifyObservers();
}
@Override
public void addObserver(Observer obs) {
listObserver.add(obs);
}
@Override
public void removeObserver(Observer obs) {
listObserver.remove(obs);
}
@Override
public void notifyObservers() {
for(Observer obs:listObserver){
obs.update(this);
}
}
/**
* Retourne le menu courant
*
* @return Menu courant
*
* @see CardMenu#panel
*/
@Override
<|fim▁hole|>}<|fim▁end|> | public int getState(){
return panel;
}
|
<|file_name|>asm-out-assign-imm.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-fast #[feature] doesn't work with check-fast
#![feature(asm)]
fn foo(x: int) { println!("{}", x); }
#[cfg(target_arch = "x86")]
#[cfg(target_arch = "x86_64")]
#[cfg(target_arch = "arm")]
pub fn main() {
let x: int;
x = 1; //~ NOTE prior assignment occurs here
foo(x);
unsafe {
asm!("mov $1, $0" : "=r"(x) : "r"(5u)); //~ ERROR re-assignment of immutable variable `x`
}
foo(x);<|fim▁hole|><|fim▁end|> | }
#[cfg(not(target_arch = "x86"), not(target_arch = "x86_64"), not(target_arch = "arm"))]
pub fn main() {} |
<|file_name|>conf.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# complexity documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
cwd = os.getcwd()
parent = os.path.dirname(cwd)
sys.path.insert(0, parent)
import lensDES
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.coverage', 'sphinx.ext.mathjax', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'DESlens'
copyright = u'2015, ETH Zurich, Institute for Astronomy'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = lensDES.__version__
# The full version, including alpha/beta/rc tags.
release = lensDES.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False<|fim▁hole|>
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
# html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'lensDESdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'lensDES.tex', u'DESlens Documentation',
u'Simon Birrer', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'lensDES', u'DESlens Documentation',
[u'Simon Birrer'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'lensDES', u'DESlens Documentation',
u'Simon Birrer', 'lensDES', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
try:
import sphinx_eth_theme
html_theme = "sphinx_eth_theme"
html_theme_path = [sphinx_eth_theme.get_html_theme_path()]
except ImportError:
html_theme = 'default'<|fim▁end|> | |
<|file_name|>address.js<|end_file_name|><|fim▁begin|>define(['jquery','config','base','ajax','checkInput','serializeJson'],function($,config,base,AjaxFunUtils){
var defaultAddr = '';
var init = function(){
getAddress(defaultAddr);
};
//加载模板
var loadhtml = function(){
var telhtml = '<div id="addressbox" class="addressbox">'+
'<form id="addressform" method="post">'+
'<div id="add_headerbox" class="headerbox">'+
'<div class="rowbox searchbox">'+
'<div class="top_l"> <a href="javascript:void(0);" id="back-address" class="back-address rel" data-level="0"> <span class="b_ico ico-back-h"></span> </a> </div>'+
'<div class="row-flex1 text-center h2_title">收货地址管理</div>'+
'</div>'+
'<div id="address_cont" class="address_cont">'+
'<ul id="addressedit" class="jsbox f16 color-333 jsbox_mt0" style="display:none">'+
'<li id="address_row" class="rowbox">'+
'<div class="row-flex1">'+
'<p id="add_str_text">广东省广州市天河区</p>'+
'<p class="f12 color-999 edit_text">所在地区</p>'+
'<input id="add_str" name="add_str" type="hidden" />'+
'<input id="add_ids" name="add_ids" type="hidden" />'+
'</div>'+
'<div class="ico ico-jt mt-10"></div>'+
'</li>'+
'<li id="townSelRow" class="rowbox">'+
'<div class="row-flex1">'+
'<input id="add_str_2" class="noborder edit_input" name="add_str_2" type="text" placeholder="请选择街道" style="padding-left:0" readonly />'+
'<p class="f12 color-999 edit_text">街道</p>'+
'</div>'+
'<div class="ico ico-jt mt-10"></div>'+
'</li>'+
'<li class="rowbox li_edit">'+
'<div class="row-flex1">'+
'<input id="add_more" name="add_more" type="text" value="" placeholder="请输入详细地址" class="noborder edit_input" style="padding-left:0" data-validate="isempty" />'+
'<p class="f12 color-999 edit_text">详细地址</p>'+
'</div>'+
'<div class="ico ico-jt mt-10"></div>'+
'</li>'+
'<li class="rowbox li_edit">'+
'<div class="row-flex1">'+
'<input id="addressee" name="addressee" type="text" value="" placeholder="请输入收货人姓名" class="noborder edit_input" style="padding-left:0" data-validate="isempty" />'+
'<p class="f12 color-999 edit_text">收货人姓名</p>'+
'</div>'+
'<div class="ico ico-jt mt-10"></div>'+
'</li>'+
'<li class="rowbox li_edit">'+
'<div class="row-flex1">'+
'<input type="text" id="cellphone" name="cellphone" value="" placeholder="请输入收货人手机号码" class="noborder edit_input" style="padding-left:0" data-validate="Mobile" />'+
'<p class="f12 color-999 edit_text">收货人手机号码</p>'+
'</div>'+
'<div class="ico ico-jt mt-10"></div>'+
'</li>'+
'<li class="rowbox li_edit">'+
'<div class="row-flex1">'+
'<input type="text" id="zip" name="zip" value="" placeholder="请输入邮编" class="noborder edit_input" style="padding-left:0" />'+
'<p class="f12 color-999 edit_text">邮编</p>'+
'</div>'+
'<div class="ico ico-jt mt-10"></div>'+
'</li>'+
'<li class="rowbox" for="sedefault">'+
'<div class="row-flex1">'+
'<label><input type="checkbox" name="sedefault" id="sedefault" style="width:20px;padding:0; margin-bottom:-10px"/>设置为默认收货地址</label>'+
'<p class="f12 color-999 edit_text">默认收货地址</p>'+
'</div>'+
'<div class="ico ico-jt mt-10"></div>'+
'</li>'+
'</ul>'+
'<ul id="townSelRow_list" class="jsbox jsbox_mt0" style="display:none"></ul>'+
'<div id="divsionSelect" style="display:none">'+
'<ul id="selected" class="jsbox jsbox_mt0" style="display:none"></ul>'+
'<ul id="forselect" class="jsbox jsbox_mt0"></ul>'+
'</div>'+
'</div>'+
'</div>'+
'<div class="footerbox rowbox" style="padding:10px 0;z-index:99999">'+
'<input id="addrid_edt" name="addrid" type="hidden" />'+
'<div class="row-flex1 text-left">'+
'<button id="delBtn" type="button" class="btn w150">删除</button>'+
'</div>'+
'<div class="row-flex1 text-right">'+
'<button type="button" class="btn btn-danger w150 address_sub_btn">保存</button>'+
'</div>'+
'</div>'+
'</form>'+
'</div>';
$("body").append(telhtml);
var bodyh=config.base.getHeightBody();
$("#add_headerbox").css({"height":bodyh,"z-index":99998});
$("#address_cont").css({"height":bodyh-60});
};
//添加,编辑,删除收货地址
var addedtAddress = function(opt){
//加载模板
loadhtml();
//加载,编辑地址
if(opt.act == 'add'){
$("#add_headerbox").addClass("address_add");
//省级地址获取
siondatalist();
//提交绑定
subaddress({act:opt.act});
}else{
$("#add_headerbox").addClass("address_edt");
//编辑提取数据
edtaddress({
act:opt.act,
addrid:opt.addrid,
callback:function(res3){
//提交绑定
subaddress({act:'edt'});
}
});
}
//被选中li
selectedclik();
//所在地区行click
address_row();
//街道选择
townSelRow();
//详细地址,收货人姓名等
$("#addressedit").on("click",".li_edit",function(){
$(this).addClass("li_edit_current");
$(this).siblings(".li_edit").removeClass("li_edit_current");
$(this).find(".edit_input").focus();
});
//关闭地址弹框
$("#back-address").on("click",function(){
var level = $(this).attr("data-level");
var stateid = $(this).attr("data-state");
var cityid = $(this).attr("data-city");
if(level == 0 || level == 3){
$("#addressbox").remove();
}else if(level == 1){
if(opt.act == 'add'){
//省级地址获取
siondatalist();
$(this).attr("data-level",0);
$("#selected").html('').hide();
}else{
$(this).attr("data-level",0);
$("#addressedit").show();
$("#divsionSelect").hide();
}
}else if(level == 2){
$(this).attr("data-level",1);
$("#selected").find(".li_click").each(function(index, element) {
var li_level = $(this).attr("data-level");
if(li_level == 2){
$(this).remove();
}
});
//市级地址获取
getcityaddress({thisId:stateid});
}
});
};
var selectedclik = function(){
//被选中li
$("#selected").on("click",'.li_click',function(){
var parentid = $(this).attr("data-parentid");
var level = $(this).attr("data-level");
$("#back-address").attr("data-level",level-1);
if(parentid > 0){
getcityaddress({thisId:parentid});
$(this).remove();
}else{
siondatalist();
$("#selected").html('').hide();
}
$("#add_str_2").attr("data-id",'');
$("#add_str_2").val('');
$("#townSelRow_list").hide();
$("#divsionSelect").show();
$("#addressedit").hide();
})
};
//所在地区行click
var address_row = function(){
//所在地区行click
$("#address_row").off("click").on("click",function(){
var state = $(this).attr("data-state");
var city = $(this).attr("data-city");
var county = $(this).attr("data-county");
$("#back-address").attr("data-level",2);
if(state > 0){
$("#selected").html('');
getdataaddress({
callback:function(res3){
$.each(res3.data,function(index,ooo){
if(ooo.id == state){
var lihtml3 = '<li class="li_click" data-level="'+ooo.level+'" data-name="'+ooo.name+'" data-id="'+ooo.id+'" data-parentid="0">'+ooo.name+'</li>'
$("#selected").append(lihtml3);
return;
}
});
getdataaddress({
upid:state,
callback:function(res3){
$.each(res3.data,function(index,ooo){
if(ooo.id == city){
var lihtml3 = '<li class="li_click" data-level="'+ooo.level+'" data-name="'+ooo.name+'" data-id="'+ooo.id+'" data-parentid="'+state+'">'+ooo.name+'</li>'
$("#selected").append(lihtml3);
return;
}
});
getdataaddress({
upid:city,
callback:function(res3){
if(res3.data.length<=0){
$("#forselect").hide();
}else{
$("#forselect").show();
}
var lihtml3 = '';
$.each(res3.data,function(index,ooo){
lihtml3 += '<li class="li_click" data-level="'+ooo.level+'" data-name="'+ooo.name+'" data-id="'+ooo.id+'" data-parentid="'+city+'">'+ooo.name+'</li>'
});
$("#forselect").html(lihtml3);
}
});
}
});
}
})
$("#divsionSelect,#selected").show();
$("#addressedit").hide();
forselectclick();
}else{
//省级地址获取
siondatalist();
//提交绑定
subaddress({act:'edt'});
}
})
};
//街道选择
var townSelRow = function(){
//街道click
$("#townSelRow").off("click").on("click",function(e){
var upid = $(this).attr("data-townid");
if(upid<=0){
return false;
}
getdataaddress({
upid:upid,
callback:function(res){
var lihtml = '';
$.each(res.data,function(index,o){
lihtml += '<li class="li_click" data-level="'+o.level+'" data-name="'+o.name+'" data-id="'+o.id+'" data-isleaf="0">'+o.name+'</li>';
});
$("#townSelRow_list").html(lihtml).show();
$("#divsionSelect").hide();
$("#addressedit").hide();
$("#townSelRow_list").off("click").on("click",'.li_click',function(){
var thisname = $(this).attr("data-name");
var thisid = $(this).attr("data-id");
$("#add_str_2").attr("data-id",thisid);
$("#add_str_2").val(thisname);
var newadd_ids = $("#address_row").attr("data-state")+"_"+$("#address_row").attr("data-city")+"_"+$("#address_row").attr("data-county")+"_"+thisid;
$("#add_ids").val(newadd_ids);
$("#townSelRow_list").hide();
$("#divsionSelect").hide();
$("#addressedit").show();
});
}
});
});
};
//准备选择li
var forselectclick = function(){
$("#forselect").off("click").on('click','.li_click',function(){
var thisId = $(this).attr("data-id");
var thislevel = $(this).attr("data-level");
var thisname = $(this).attr("data-name");
var $this = $(this);
$("#back-address").attr("data-level",thislevel);
if(thislevel == 1){
$("#address_row,#back-address").attr("data-state",thisId);
}else if(thislevel == 2){
$("#address_row,#back-address").attr("data-city",thisId);
}else if(thislevel == 3){
$("#address_row,#back-address").attr("data-county",thisId);
$("#add_str_2").val('');
$("#add_str_2").attr("data-id",'');
}
getcityaddress({
thisId:thisId,
thislevel:thislevel,
callback:function(resin){
if(resin.data.length <=0 || thislevel>2){
$("#divsionSelect").hide();
$("#addressedit").show();
var add_str_text = '';
var add_str_id = '';
$("#selected").find("li").each(function(index, element) {
var thisinname = $(this).attr("data-name");
var thisinid = $(this).attr("data-id");
add_str_text += thisinname;
add_str_id += thisinid+'_';
});
add_str_text += thisname;
add_str_id += thisId+'_'
$("#townSelRow").attr("data-townid",thisId);
$("#add_ids").val(add_str_id);
$("#add_str_text,#add_str").text(add_str_text);
$("#add_str").val(add_str_text);
if(resin.data.length <=0){
$("#forselect").hide();
$("#townSelRow").hide();
}else{
$("#forselect").show();
$("#townSelRow").show();
}
}else{
$("#selected").append($this).show();
}
}
});
});
}
//获取省级数据
var siondatalist = function(opt){
getdataaddress({
callback:function(res){
if(res.status == 1){<|fim▁hole|> $.each(res.data,function(index,o){
lihtml += '<li class="li_click" data-level="'+o.level+'" data-name="'+o.name+'" data-id="'+o.id+'" data-parentid="0" data-isleaf="0">'+o.name+'</li>';
});
$("#forselect").html(lihtml).show();
$("#divsionSelect").show();
$("#addressedit").hide();
forselectclick();
}else{
config.tip.tips({
htmlmsg:'<div style="padding:30px">'+res.msg+'</div>',
w:"96%",
type:0
});
}
}
});
};
//获取省级以下数据列表
var getcityaddress = function(opt){
getdataaddress({
upid:opt.thisId,
callback:function(res){
var lihtml = '';
$.each(res.data,function(index,o){
lihtml += '<li class="li_click" data-level="'+o.level+'" data-name="'+o.name+'" data-id="'+o.id+'" data-parentid="'+opt.thisId+'" data-isleaf="0">'+o.name+'</li>';
});
$("#forselect").html(lihtml).show();
if(opt.callback){
opt.callback(res);
}
}
});
};
//统一获取地址
var getdataaddress = function(opt){
AjaxFunUtils.ajaxInit({
"url":"/common/district_son.html",
"params":{upid:opt.upid},
"callback":function (res) {
if(opt.callback){
opt.callback(res);
}
}
});
};
//编辑地址,获取当前编辑地址数据
var edtaddress = function(optin){
AjaxFunUtils.ajaxInit({
url:"/myorder/address.html",
params:{act:"get",addrid:optin.addrid},
callback:function(resin){
if(resin.status == 1){
$("#addressedit").show();
$("#addrid_edt").val(optin.addrid);
$("#addressee").val(resin.data.addressee);
$("#add_str_text").text(resin.data.address1);
$("#add_str").val(resin.data.address1);
$("#add_ids").val(resin.data.state+'_'+resin.data.city+'_'+resin.data.county+'_'+resin.data.town);
$("#add_more").val(resin.data.more);
$("#zip").val(resin.data.zip);
$("#cellphone").val(resin.data.cellphone);
if(resin.data.town){
$("#add_str_2").val(resin.data.address2);
}else{
$("#townSelRow").hide();
}
if(resin.data.addrid == defaultAddr){
$("#sedefault").attr("checked","checked");
}
$("#address_row").attr("data-state",resin.data.state);
$("#address_row").attr("data-city",resin.data.city);
$("#address_row").attr("data-county",resin.data.county);
$("#townSelRow").attr("data-townid",resin.data.county);
//删除地址
$("#delBtn").show().unbind("click").bind("click",function(){
AjaxFunUtils.ajaxInit({
url:"/myorder/address.html",
params:{act:"del",addrid:optin.addrid},
callback:function (result) {
if(result.status == 1){
getAddress();//删除完成刷新地址列表
config.tip.tips({
htmlmsg:'<div style="padding:30px">'+result.msg+'</div>',
w:"96%",
type:0
});
$("#addressbox").remove();
}else{
config.tip.tips({
htmlmsg:'<div style="padding:30px">'+result.msg+'</div>',
w:"96%",
type:0
});
}
}
});
});
if(optin.callback){
optin.callback(resin);
}
}
}
});
};
//获取送货地址
var getAddress = function(odz){
AjaxFunUtils.ajaxInit({
url:"/myorder/address.html",
params:{act:'list' },
callback:function(res){
var addresslist = res.data;
if(addresslist.length<=0){
$("#addrid").html('<p id="newaddress" class="addAddressBtn" data-address="0" data-act="add" style="padding:0 5px; margin:5px 0">请填写收货人信息</p>');
addAddressBtn();
return false;
}
var html = '';
$.each(addresslist,function(index,o){
var newaddress = o.address1+' '+o.address2 + ' ' + o.more + ' ' + o.addressee + ' ' + o.cellphone;
var checked = '';
if(o.default == 1){
checked = 'checked="checked"';
defaultAddr = o.addrid;
}
var addVal = '<li class="rowbox mt-5"><div class="row-flex1 rowbox"><input name="addrid" id="'+o.addrid+'" type="radio" value="'+o.addrid+'" '+checked+'><label style="line-height:20px" for="'+o.addrid+'">'+newaddress+'</label></div><div class="w100 text-right"><a href="javascript:void(0);" class="addAddressBtn" data-address="1" data-addrid="'+o.addrid+'" data-act="edt">编辑<div class="ico ico-jt ml-5"></div></a></div></li>';
html +=addVal;
});
$("#addrid").html(html);
addAddressBtn();
}
});
};
//提交添加,编辑地址
var subaddress = function(opt){
$("#addressform").checkInput({
button:'.address_sub_btn',
submitBtnFn: function (from) {
var dataFrom = from.serializeJson();
dataFrom.act = opt.act;
AjaxFunUtils.ajaxInit({
"url":"/myorder/address.html",
"params":dataFrom,
"callback":function (res) {
if(res.status == 1){
config.tip.tips({
htmlmsg:'<div style="padding:30px">'+res.msg+'</div>',
w:"96%",
type:0,
callback:function(){
getAddress();//添加,编辑完成刷新地址列表
$("#addressbox").remove();
}
});
}else{
config.tip.tips({
htmlmsg:'<div style="padding:30px">'+res.msg+'</div>',
w:"96%",
type:0
});
}
}
});
}
});
};
//增加地址,编辑地址绑定
var addAddressBtn = function(){
$(".addAddressBtn").unbind("click").bind("click",function(){
var typeId = $(this).attr("data-address");
var thisaddrid = $(this).attr("data-addrid");
var act = $(this).attr("data-act");
addedtAddress({act:act,addrid:thisaddrid});
});
//获取微信地址
$(".wxAddressBtn").unbind("click").bind("click",function(){
var thisaddrid = $(this).attr("data-addrid");
AjaxFunUtils.ajaxInit({
"url":"/myorder/address.html?act=weixin_sign",
"params":{},
"callback":function (res) {
if(res.status == 1){
var sign_info = res.data.sign_info;
get_addres();
//获取微信地址
function get_addresinfo(){
WeixinJSBridge.invoke(
'editAddress',
sign_info,
function(res){
var resData = {};
resData.act = "add";
resData.nickname = res.username;
resData.cellphone = res.telNumber;
resData.zip = res.addressPostalCode;
resData.address1 = res.addressCitySecondStageName +" "+res.addressCountiesThirdStageName+" "+res.addressDetailInfo;
AjaxFunUtils.ajaxInit({
"url":"/myorder/address.html",
"params":resData,
"callback":function (res3) {
if(res3.status == 1){
if($("#sedefault").attr("checked")){
//defaultAddr = thisaddrid;
}
//address.getAddress();//添加,编辑完成刷新地址s列表
}else{
config.tip.tips({
htmlmsg:'<div style="padding:30px">'+res3.msg+'</div>',
w:"96%",
type:0
});
}
}
});
}
);
};
function get_addres(){
if (typeof WeixinJSBridge == "undefined"){
if( document.addEventListener ){
document.addEventListener('WeixinJSBridgeReady', get_addresinfo, false);
}else if (document.attachEvent){
document.attachEvent('WeixinJSBridgeReady', get_addresinfo);
document.attachEvent('onWeixinJSBridgeReady', get_addresinfo);
}
}else{
get_addresinfo();
}
};
}
}
});
});
};
return {init:init,getAddress:getAddress};
});<|fim▁end|> | var lihtml = ''; |
<|file_name|>softmax_op_test.py<|end_file_name|><|fim▁begin|># Copyright 2015 Google 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
#<|fim▁hole|># 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.
# ==============================================================================
"""Tests for SoftmaxOp and LogSoftmaxOp."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import numpy as np
import tensorflow as tf
class SoftmaxTest(tf.test.TestCase):
def _npSoftmax(self, features, log=False):
batch_dim = 0
class_dim = 1
batch_size = features.shape[batch_dim]
e = np.exp(features -
np.reshape(np.amax(features, axis=class_dim), [batch_size, 1]))
softmax = e / np.reshape(np.sum(e, axis=class_dim), [batch_size, 1])
if log:
return np.log(softmax)
else:
return softmax
def _testSoftmax(self, np_features, log=False, use_gpu=False):
np_softmax = self._npSoftmax(np_features, log=log)
with self.test_session(use_gpu=use_gpu):
if log:
tf_softmax = tf.nn.log_softmax(np_features)
else:
tf_softmax = tf.nn.softmax(np_features)
out = tf_softmax.eval()
self.assertAllClose(np_softmax, out)
self.assertShapeEqual(np_softmax, tf_softmax)
if not log:
# Bonus check: the softmaxes should add to one in each
# batch element.
self.assertAllClose(np.ones(out.shape[0]),
np.sum(out, axis=1))
def _testAll(self, features):
self._testSoftmax(features, use_gpu=False)
self._testSoftmax(features, log=True, use_gpu=False)
self._testSoftmax(features, use_gpu=True)
self._testSoftmax(features, log=True, use_gpu=True)
self._testOverflow(use_gpu=True)
def testNpSoftmax(self):
features = [[1., 1., 1., 1.], [1., 2., 3., 4.]]
# Batch 0: All exps are 1. The expected result is
# Softmaxes = [0.25, 0.25, 0.25, 0.25]
# LogSoftmaxes = [-1.386294, -1.386294, -1.386294, -1.386294]
#
# Batch 1:
# exps = [1., 2.718, 7.389, 20.085]
# sum = 31.192
# Softmaxes = exps / sum = [0.0320586, 0.08714432, 0.23688282, 0.64391426]
# LogSoftmaxes = [-3.44019 , -2.44019 , -1.44019 , -0.44019]
np_sm = self._npSoftmax(np.array(features))
self.assertAllClose(
np.array([[0.25, 0.25, 0.25, 0.25],
[0.0320586, 0.08714432, 0.23688282, 0.64391426]]),
np_sm,
rtol=1.e-5, atol=1.e-5)
np_lsm = self._npSoftmax(np.array(features), log=True)
self.assertAllClose(
np.array([[-1.386294, -1.386294, -1.386294, -1.386294],
[-3.4401897, -2.4401897, -1.4401897, -0.4401897]]),
np_lsm,
rtol=1.e-5, atol=1.e-5)
def testShapeMismatch(self):
with self.assertRaises(ValueError):
tf.nn.softmax([0., 1., 2., 3.])
with self.assertRaises(ValueError):
tf.nn.log_softmax([0., 1., 2., 3.])
def _testOverflow(self, use_gpu=False):
if use_gpu:
type = np.float32
else:
type = np.float64
max = np.finfo(type).max
features = np.array(
[[1., 1., 1., 1.],
[max, 1., 2., 3.]]).astype(type)
with self.test_session(use_gpu=use_gpu):
tf_log_softmax = tf.nn.log_softmax(features)
out = tf_log_softmax.eval()
self.assertAllClose(
np.array([[-1.386294, -1.386294, -1.386294, -1.386294],
[0, -max, -max, -max]]),
out,
rtol=1.e-5, atol=1.e-5)
def testFloat(self):
self._testAll(
np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float32))
def testDouble(self):
self._testSoftmax(
np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float64),
use_gpu=False)
self._testOverflow(use_gpu=False)
def testEmpty(self):
with self.test_session():
x = tf.constant([[]], shape=[0, 3])
self.assertEqual(0, tf.size(x).eval())
expected_y = np.array([]).reshape(0, 3)
np.testing.assert_array_equal(expected_y, tf.nn.softmax(x).eval())
if __name__ == "__main__":
tf.test.main()<|fim▁end|> | |
<|file_name|>check-suite-view.test.js<|end_file_name|><|fim▁begin|>import React from 'react';
import {shallow} from 'enzyme';
import {BareCheckSuiteView} from '../../lib/views/check-suite-view';
import CheckRunView from '../../lib/views/check-run-view';
import checkSuiteQuery from '../../lib/views/__generated__/checkSuiteView_checkSuite.graphql';
import {checkSuiteBuilder} from '../builder/graphql/timeline';
describe('CheckSuiteView', function() {
function buildApp(override = {}) {<|fim▁hole|> ...override,
};
return <BareCheckSuiteView {...props} />;
}
it('renders the summarized suite information', function() {
const checkSuite = checkSuiteBuilder(checkSuiteQuery)
.app(a => a.name('app'))
.status('COMPLETED')
.conclusion('SUCCESS')
.build();
const wrapper = shallow(buildApp({checkSuite}));
const icon = wrapper.find('Octicon');
assert.strictEqual(icon.prop('icon'), 'check');
assert.isTrue(icon.hasClass('github-PrStatuses--success'));
assert.strictEqual(wrapper.find('.github-PrStatuses-list-item-context strong').text(), 'app');
});
it('omits app information when the app is no longer present', function() {
const checkSuite = checkSuiteBuilder(checkSuiteQuery)
.nullApp()
.build();
const wrapper = shallow(buildApp({checkSuite}));
assert.isTrue(wrapper.exists('Octicon'));
assert.isFalse(wrapper.exists('.github-PrStatuses-list-item-context'));
});
it('renders a CheckRun for each run within the suite', function() {
const checkRuns = [{id: 0}, {id: 1}, {id: 2}];
const wrapper = shallow(buildApp({checkRuns}));
assert.deepEqual(wrapper.find(CheckRunView).map(v => v.prop('checkRun')), checkRuns);
});
});<|fim▁end|> | const props = {
checkSuite: checkSuiteBuilder(checkSuiteQuery).build(),
checkRuns: [],
switchToIssueish: () => {}, |
<|file_name|>util.go<|end_file_name|><|fim▁begin|>package sourcemap
import (
"io"
)
type (
RuneReader interface {
ReadRune() (r rune, size int, err error)
}
RuneWriter interface {
WriteRune(r rune) (size int, err error)
}
Segment struct {
GeneratedLine int
GeneratedColumn int
SourceIndex int
SourceLine int
SourceColumn int
NameIndex int
}
)
var (
hexc = "0123456789abcdef"
)
func encodeString(rw RuneWriter, rr RuneReader) error {
for {
r, _, err := rr.ReadRune()
if err == io.EOF {
return nil
} else if err != nil {
return err
}
switch r {
case '\\', '"':
rw.WriteRune('\\')
_, err = rw.WriteRune(r)
case '\n':
rw.WriteRune('\\')
_, err = rw.WriteRune('n')
case '\r':
rw.WriteRune('\\')
_, err = rw.WriteRune('r')
case '\t':
rw.WriteRune('\\')
_, err = rw.WriteRune('t')
case '\u2028':
rw.WriteRune('\\')
rw.WriteRune('u')
rw.WriteRune('2')
rw.WriteRune('0')
rw.WriteRune('2')
_, err = rw.WriteRune('8')
case '\u2029':
rw.WriteRune('\\')
rw.WriteRune('u')
rw.WriteRune('2')
rw.WriteRune('0')
rw.WriteRune('2')
_, err = rw.WriteRune('9')
default:
if r < 0x20 {
rw.WriteRune('\\')
rw.WriteRune('u')
rw.WriteRune('0')
rw.WriteRune('0')<|fim▁hole|> } else {
_, err = rw.WriteRune(r)
}
}
if err != nil {
return err
}
}
}<|fim▁end|> | rw.WriteRune(rune(hexc[byte(r)>>4]))
_, err = rw.WriteRune(rune(hexc[byte(r)&0xF])) |
<|file_name|>qcustomplot.cpp<|end_file_name|><|fim▁begin|>/**************************************************************************
** **
** 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())
{<|fim▁hole|> }
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;
}<|fim▁end|> | qDebug() << Q_FUNC_INFO << "requested point distance on graph" << mName << "without data";
return 500; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.