prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>Utils.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python
"""
Copyright [1999-2018] EMBL-European Bioinformatics Institute
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.
"""
"""
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
"""
from postgap.DataModel import *
from pprint import pformat
from postgap.Finemap import *
def summarise(obj, **kwparams):
if type(obj) == list:
return summarise_list(obj, **kwparams)
if type(obj) == GWAS_Cluster:
return summarise_gwas_cluster(obj, **kwparams)
if type(obj) == SNP:
return summarise_snp(obj, **kwparams)
if type(obj) == GWAS_SNP:
return summarise_gwas_snp(obj, **kwparams)
if type(obj) == GWAS_Association:
return summarise_generic(obj, **kwparams)
if type(obj) == Cisregulatory_Evidence:
return summarise_generic(obj, **kwparams)
if type(obj) == OneDConfigurationSample:
return str(obj)
if type(obj) == TwoDConfigurationSample:
return str(obj)
raise Exception("Don't know how to summarise a " + str(type(obj)))
def summarise_list(list_of_objects, leadstring = "", **kwparams):
string = leadstring + " * List:\n"
for index, current_object in enumerate(list_of_objects):
string += leadstring + " ** Item " + str(index) + ":\n"
string += summarise(current_object, leadstring = leadstring + " *******") + "\n"
string += leadstring + " ******"
return string
def summarise_gwas_cluster(gwas_cluster, leadstring = ""):
string = "GWAS_Cluster\n"<|fim▁hole|> string += " Gwas snps:\n"
string += " ----------\n"
string += summarise(gwas_cluster.gwas_snps, leadstring = leadstring + " ")
string += "\n"
string += " LD snps:\n"
string += " --------\n"
string += summarise(gwas_cluster.ld_snps, leadstring = leadstring + " ")
return string
def summarise_snp(snp, leadstring = ""):
return leadstring + pformat( snp )
def summarise_generic(obj, leadstring = ""):
return leadstring + pformat( obj )
def summarise_gwas_snp(gwas_snp, leadstring = ""):
string = leadstring + "=============\n"
string += leadstring + "|GWAS_SNP\n"
string += leadstring + "| " + "SNP: " + summarise(gwas_snp.snp, leadstring = "") + "\n"
string += leadstring + "| " + "pvalue: " + str(gwas_snp.pvalue) + "\n"
string += leadstring + "| " + "z_score: " + str(gwas_snp.z_score) + "\n"
string += leadstring + "| " + "evidence:\n"
string += summarise(gwas_snp.evidence, leadstring = leadstring + "| " + " ") + "\n"
string += leadstring + "============="
return string
def concatenate(list):
"""
Shorthand to concatenate a list of lists
Args: [[]]
Returntype: []
"""
return sum(filter(lambda elem: elem is not None, list), [])
def concatenate_hashes(list):
"""
Shorthand to concatenate a list of lists
Args: [[]]
Returntype: []
"""
return dict(sum(map(lambda X: X.items(), filter(lambda elem: elem is not None, list)), []))
def chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i+n]
def isnamedtupleinstance(x):
_type = type(x)
bases = _type.__bases__
if len(bases) != 1 or bases[0] != tuple:
return False
fields = getattr(_type, '_fields', None)
if not isinstance(fields, tuple):
return False
return all(type(i)==str for i in fields)
def objectToDict(obj):
if isinstance(obj, dict):
return {key: objectToDict(value) for key, value in obj.items()}
elif isinstance(obj, list):
return [objectToDict(value) for value in obj]
elif isnamedtupleinstance(obj):
return {key: objectToDict(value) for key, value in obj._asdict().items()}
elif isinstance(obj, tuple):
return tuple(objectToDict(value) for value in obj)
else:
return obj<|fim▁end|>
|
string += "============\n"
string += "\n"
|
<|file_name|>pessoa_cpp.cpp<|end_file_name|><|fim▁begin|>#include "pessoa_cpp.hpp"
Pessoa::Pessoa() {
}
Pessoa::Pessoa(QString nome, int idade, float altura) {
this->setNome(nome);
this->idade = idade;
this->altura = altura;
}
Pessoa::~Pessoa() {
qDebug() << "Deletando a pessoa " << this;
}
void Pessoa::setNome(QString nome) {
this->nome = nome + "Foi!";
}
void Pessoa::setIdade(int idade) {
this->idade = idade;
}
void Pessoa::setAltura(float altura) {
this->altura = altura;
}
Pessoa * Pessoa::casar(const Pessoa * other) {
Pessoa * resultado = new Pessoa(this->nome + other->nome,
this->idade + other->idade,
this->altura + other->altura);
return resultado;
}
#ifndef QT_NO_DEBUG
void Pessoa::print() {
qDebug() << ":: Pessoa ::";
qDebug() << "Endereco: " << this;
qDebug() << "Nome: " << this->nome;<|fim▁hole|> qDebug() << "Altura: " << this->altura;
qDebug() << ":: -------------- ::";
}
#endif<|fim▁end|>
|
qDebug() << "Idade: " << this->idade;
|
<|file_name|>test_linux.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Linux specific tests."""
import contextlib
import errno
import io
import os
import pprint
import re
import shutil
import socket
import struct
import tempfile
import textwrap
import time
import warnings
try:
from unittest import mock # py3
except ImportError:
import mock # requires "pip install mock"
import psutil
from psutil import LINUX
from psutil._compat import PY3
from psutil._compat import u
from psutil.tests import call_until
from psutil.tests import get_kernel_version
from psutil.tests import importlib
from psutil.tests import MEMORY_TOLERANCE
from psutil.tests import pyrun
from psutil.tests import reap_children
from psutil.tests import retry_before_failing
from psutil.tests import run_test_module_by_name
from psutil.tests import sh
from psutil.tests import skip_on_not_implemented
from psutil.tests import TESTFN
from psutil.tests import TRAVIS
from psutil.tests import unittest
from psutil.tests import which
HERE = os.path.abspath(os.path.dirname(__file__))
SIOCGIFADDR = 0x8915
SIOCGIFCONF = 0x8912
SIOCGIFHWADDR = 0x8927
# =====================================================================
# utils
# =====================================================================
def get_ipv4_address(ifname):
import fcntl
ifname = ifname[:15]
if PY3:
ifname = bytes(ifname, 'ascii')
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
with contextlib.closing(s):
return socket.inet_ntoa(
fcntl.ioctl(s.fileno(),
SIOCGIFADDR,
struct.pack('256s', ifname))[20:24])
def get_mac_address(ifname):
import fcntl
ifname = ifname[:15]
if PY3:
ifname = bytes(ifname, 'ascii')
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
with contextlib.closing(s):
info = fcntl.ioctl(
s.fileno(), SIOCGIFHWADDR, struct.pack('256s', ifname))
if PY3:
def ord(x):
return x
else:
import __builtin__
ord = __builtin__.ord
return ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1]
def free_swap():
"""Parse 'free' cmd and return swap memory's s total, used and free
values.
"""
lines = sh('free').split('\n')
for line in lines:
if line.startswith('Swap'):
_, total, used, free = line.split()
return (int(total) * 1024, int(used) * 1024, int(free) * 1024)
def free_physmem():
"""Parse 'free' cmd and return physical memory's total, used
and free values.
"""
lines = sh('free').split('\n')
for line in lines:
if line.startswith('Mem'):
total, used, free, shared, buffers, cached = \
[int(x) * 1024 for x in line.split()[1:]]
return (total, used, free, shared, buffers, cached)
# =====================================================================
# system memory
# =====================================================================
@unittest.skipUnless(LINUX, "not a Linux system")
class TestSystemMemory(unittest.TestCase):
def test_vmem_total(self):
total, used, free, shared, buffers, cached = free_physmem()
self.assertEqual(total, psutil.virtual_memory().total)
@retry_before_failing()
def test_vmem_used(self):
total, used, free, shared, buffers, cached = free_physmem()
self.assertAlmostEqual(used, psutil.virtual_memory().used,
delta=MEMORY_TOLERANCE)
@retry_before_failing()
def test_vmem_free(self):
total, used, free, shared, buffers, cached = free_physmem()
self.assertAlmostEqual(free, psutil.virtual_memory().free,
delta=MEMORY_TOLERANCE)
@retry_before_failing()
def test_vmem_buffers(self):
buffers = int(sh('vmstat').split('\n')[2].split()[4]) * 1024
self.assertAlmostEqual(buffers, psutil.virtual_memory().buffers,
delta=MEMORY_TOLERANCE)
@retry_before_failing()
def test_vmem_cached(self):
cached = int(sh('vmstat').split('\n')[2].split()[5]) * 1024
self.assertAlmostEqual(cached, psutil.virtual_memory().cached,
delta=MEMORY_TOLERANCE)
def test_swapmem_total(self):
total, used, free = free_swap()
return self.assertAlmostEqual(total, psutil.swap_memory().total,
delta=MEMORY_TOLERANCE)
@retry_before_failing()
def test_swapmem_used(self):
total, used, free = free_swap()
return self.assertAlmostEqual(used, psutil.swap_memory().used,
delta=MEMORY_TOLERANCE)
@retry_before_failing()
def test_swapmem_free(self):
total, used, free = free_swap()
return self.assertAlmostEqual(free, psutil.swap_memory().free,
delta=MEMORY_TOLERANCE)
# --- mocked tests
def test_virtual_memory_mocked_warnings(self):
with mock.patch('psutil._pslinux.open', create=True) as m:
with warnings.catch_warnings(record=True) as ws:
warnings.simplefilter("always")
ret = psutil._pslinux.virtual_memory()
assert m.called
self.assertEqual(len(ws), 1)
w = ws[0]
self.assertTrue(w.filename.endswith('psutil/_pslinux.py'))
self.assertIn(
"'cached', 'active' and 'inactive' memory stats couldn't "
"be determined", str(w.message))
self.assertEqual(ret.cached, 0)
self.assertEqual(ret.active, 0)
self.assertEqual(ret.inactive, 0)
def test_swap_memory_mocked_warnings(self):
with mock.patch('psutil._pslinux.open', create=True) as m:
with warnings.catch_warnings(record=True) as ws:
warnings.simplefilter("always")
ret = psutil._pslinux.swap_memory()
assert m.called
self.assertEqual(len(ws), 1)
w = ws[0]
self.assertTrue(w.filename.endswith('psutil/_pslinux.py'))
self.assertIn(
"'sin' and 'sout' swap memory stats couldn't "
"be determined", str(w.message))
self.assertEqual(ret.sin, 0)
self.assertEqual(ret.sout, 0)
def test_swap_memory_mocked_no_vmstat(self):
# see https://github.com/giampaolo/psutil/issues/722
with mock.patch('psutil._pslinux.open', create=True,
side_effect=IOError) as m:
with warnings.catch_warnings(record=True) as ws:
warnings.simplefilter("always")
ret = psutil.swap_memory()
assert m.called
self.assertEqual(len(ws), 1)
w = ws[0]
self.assertTrue(w.filename.endswith('psutil/_pslinux.py'))
self.assertIn(
"'sin' and 'sout' swap memory stats couldn't "
"be determined and were set to 0",
str(w.message))
self.assertEqual(ret.sin, 0)
self.assertEqual(ret.sout, 0)
# =====================================================================
# system CPU
# =====================================================================
@unittest.skipUnless(LINUX, "not a Linux system")
class TestSystemCPU(unittest.TestCase):
@unittest.skipIf(TRAVIS, "unknown failure on travis")
def test_cpu_times(self):
fields = psutil.cpu_times()._fields
kernel_ver = re.findall('\d+\.\d+\.\d+', os.uname()[2])[0]
kernel_ver_info = tuple(map(int, kernel_ver.split('.')))
if kernel_ver_info >= (2, 6, 11):
self.assertIn('steal', fields)
else:
self.assertNotIn('steal', fields)
if kernel_ver_info >= (2, 6, 24):
self.assertIn('guest', fields)
else:
self.assertNotIn('guest', fields)
if kernel_ver_info >= (3, 2, 0):
self.assertIn('guest_nice', fields)
else:
self.assertNotIn('guest_nice', fields)
@unittest.skipUnless(which("nproc"), "nproc utility not available")
def test_cpu_count_logical_w_nproc(self):
num = int(sh("nproc --all"))
self.assertEqual(psutil.cpu_count(logical=True), num)
@unittest.skipUnless(which("lscpu"), "lscpu utility not available")
def test_cpu_count_logical_w_lscpu(self):
out = sh("lscpu -p")
num = len([x for x in out.split('\n') if not x.startswith('#')])
self.assertEqual(psutil.cpu_count(logical=True), num)
def test_cpu_count_logical_mocked(self):
import psutil._pslinux
original = psutil._pslinux.cpu_count_logical()
# Here we want to mock os.sysconf("SC_NPROCESSORS_ONLN") in
# order to cause the parsing of /proc/cpuinfo and /proc/stat.
with mock.patch(
'psutil._pslinux.os.sysconf', side_effect=ValueError) as m:
self.assertEqual(psutil._pslinux.cpu_count_logical(), original)
assert m.called
# Let's have open() return emtpy data and make sure None is
# returned ('cause we mimick os.cpu_count()).
with mock.patch('psutil._pslinux.open', create=True) as m:
self.assertIsNone(psutil._pslinux.cpu_count_logical())
self.assertEqual(m.call_count, 2)
# /proc/stat should be the last one
self.assertEqual(m.call_args[0][0], '/proc/stat')
# Let's push this a bit further and make sure /proc/cpuinfo
# parsing works as expected.
with open('/proc/cpuinfo', 'rb') as f:
cpuinfo_data = f.read()
fake_file = io.BytesIO(cpuinfo_data)
with mock.patch('psutil._pslinux.open',
return_value=fake_file, create=True) as m:
self.assertEqual(psutil._pslinux.cpu_count_logical(), original)
def test_cpu_count_physical_mocked(self):
# Have open() return emtpy data and make sure None is returned
# ('cause we want to mimick os.cpu_count())
with mock.patch('psutil._pslinux.open', create=True) as m:
self.assertIsNone(psutil._pslinux.cpu_count_physical())
assert m.called
# =====================================================================
# system network
# =====================================================================
@unittest.skipUnless(LINUX, "not a Linux system")
class TestSystemNetwork(unittest.TestCase):
def test_net_if_addrs_ips(self):
for name, addrs in psutil.net_if_addrs().items():
for addr in addrs:
if addr.family == psutil.AF_LINK:
self.assertEqual(addr.address, get_mac_address(name))
elif addr.family == socket.AF_INET:
self.assertEqual(addr.address, get_ipv4_address(name))
# TODO: test for AF_INET6 family
@unittest.skipUnless(which('ip'), "'ip' utility not available")
@unittest.skipIf(TRAVIS, "skipped on Travis")
def test_net_if_names(self):
out = sh("ip addr").strip()
nics = [x for x in psutil.net_if_addrs().keys() if ':' not in x]
found = 0
for line in out.split('\n'):
line = line.strip()
if re.search("^\d+:", line):
found += 1
name = line.split(':')[1].strip()
self.assertIn(name, nics)
self.assertEqual(len(nics), found, msg="%s\n---\n%s" % (
pprint.pformat(nics), out))
@mock.patch('psutil._pslinux.socket.inet_ntop', side_effect=ValueError)
@mock.patch('psutil._pslinux.supports_ipv6', return_value=False)
def test_net_connections_ipv6_unsupported(self, supports_ipv6, inet_ntop):
# see: https://github.com/giampaolo/psutil/issues/623
try:
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
self.addCleanup(s.close)
s.bind(("::1", 0))
except socket.error:
pass
psutil.net_connections(kind='inet6')
# =====================================================================
# system disk
# =====================================================================
@unittest.skipUnless(LINUX, "not a Linux system")
class TestSystemDisks(unittest.TestCase):
@unittest.skipUnless(
hasattr(os, 'statvfs'), "os.statvfs() function not available")
@skip_on_not_implemented()
def test_disk_partitions_and_usage(self):
# test psutil.disk_usage() and psutil.disk_partitions()
# against "df -a"
def df(path):
out = sh('df -P -B 1 "%s"' % path).strip()
lines = out.split('\n')
lines.pop(0)
line = lines.pop(0)
dev, total, used, free = line.split()[:4]
if dev == 'none':
dev = ''
total, used, free = int(total), int(used), int(free)
return dev, total, used, free
for part in psutil.disk_partitions(all=False):
usage = psutil.disk_usage(part.mountpoint)
dev, total, used, free = df(part.mountpoint)
self.assertEqual(usage.total, total)
# 10 MB tollerance
if abs(usage.free - free) > 10 * 1024 * 1024:
self.fail("psutil=%s, df=%s" % (usage.free, free))
if abs(usage.used - used) > 10 * 1024 * 1024:
self.fail("psutil=%s, df=%s" % (usage.used, used))
def test_disk_partitions_mocked(self):
# Test that ZFS partitions are returned.
with open("/proc/filesystems", "r") as f:
data = f.read()
if 'zfs' in data:
for part in psutil.disk_partitions():
if part.fstype == 'zfs':
break
else:
self.fail("couldn't find any ZFS partition")
else:
# No ZFS partitions on this system. Let's fake one.
fake_file = io.StringIO(u("nodev\tzfs\n"))
with mock.patch('psutil._pslinux.open',
return_value=fake_file, create=True) as m1:
with mock.patch(
'psutil._pslinux.cext.disk_partitions',
return_value=[('/dev/sdb3', '/', 'zfs', 'rw')]) as m2:
ret = psutil.disk_partitions()
assert m1.called
assert m2.called
assert ret
self.assertEqual(ret[0].fstype, 'zfs')
# =====================================================================
# misc
# =====================================================================
@unittest.skipUnless(LINUX, "not a Linux system")
class TestMisc(unittest.TestCase):
@mock.patch('psutil.traceback.print_exc')
def test_no_procfs_on_import(self, tb):
my_procfs = tempfile.mkdtemp()
with open(os.path.join(my_procfs, 'stat'), 'w') as f:
f.write('cpu 0 0 0 0 0 0 0 0 0 0\n')
f.write('cpu0 0 0 0 0 0 0 0 0 0 0\n')
f.write('cpu1 0 0 0 0 0 0 0 0 0 0\n')
try:
orig_open = open
def open_mock(name, *args):
if name.startswith('/proc'):
raise IOError(errno.ENOENT, 'rejecting access for test')
return orig_open(name, *args)
patch_point = 'builtins.open' if PY3 else '__builtin__.open'
with mock.patch(patch_point, side_effect=open_mock):
importlib.reload(psutil)
assert tb.called
self.assertRaises(IOError, psutil.cpu_times)
self.assertRaises(IOError, psutil.cpu_times, percpu=True)
self.assertRaises(IOError, psutil.cpu_percent)
self.assertRaises(IOError, psutil.cpu_percent, percpu=True)<|fim▁hole|>
psutil.PROCFS_PATH = my_procfs
self.assertEqual(psutil.cpu_percent(), 0)
self.assertEqual(sum(psutil.cpu_times_percent()), 0)
# since we don't know the number of CPUs at import time,
# we awkwardly say there are none until the second call
per_cpu_percent = psutil.cpu_percent(percpu=True)
self.assertEqual(sum(per_cpu_percent), 0)
# ditto awkward length
per_cpu_times_percent = psutil.cpu_times_percent(percpu=True)
self.assertEqual(sum(map(sum, per_cpu_times_percent)), 0)
# much user, very busy
with open(os.path.join(my_procfs, 'stat'), 'w') as f:
f.write('cpu 1 0 0 0 0 0 0 0 0 0\n')
f.write('cpu0 1 0 0 0 0 0 0 0 0 0\n')
f.write('cpu1 1 0 0 0 0 0 0 0 0 0\n')
self.assertNotEqual(psutil.cpu_percent(), 0)
self.assertNotEqual(
sum(psutil.cpu_percent(percpu=True)), 0)
self.assertNotEqual(sum(psutil.cpu_times_percent()), 0)
self.assertNotEqual(
sum(map(sum, psutil.cpu_times_percent(percpu=True))), 0)
finally:
shutil.rmtree(my_procfs)
importlib.reload(psutil)
self.assertEqual(psutil.PROCFS_PATH, '/proc')
@unittest.skipUnless(
get_kernel_version() >= (2, 6, 36),
"prlimit() not available on this Linux kernel version")
def test_prlimit_availability(self):
# prlimit() should be available starting from kernel 2.6.36
p = psutil.Process(os.getpid())
p.rlimit(psutil.RLIMIT_NOFILE)
# if prlimit() is supported *at least* these constants should
# be available
self.assertTrue(hasattr(psutil, "RLIM_INFINITY"))
self.assertTrue(hasattr(psutil, "RLIMIT_AS"))
self.assertTrue(hasattr(psutil, "RLIMIT_CORE"))
self.assertTrue(hasattr(psutil, "RLIMIT_CPU"))
self.assertTrue(hasattr(psutil, "RLIMIT_DATA"))
self.assertTrue(hasattr(psutil, "RLIMIT_FSIZE"))
self.assertTrue(hasattr(psutil, "RLIMIT_LOCKS"))
self.assertTrue(hasattr(psutil, "RLIMIT_MEMLOCK"))
self.assertTrue(hasattr(psutil, "RLIMIT_NOFILE"))
self.assertTrue(hasattr(psutil, "RLIMIT_NPROC"))
self.assertTrue(hasattr(psutil, "RLIMIT_RSS"))
self.assertTrue(hasattr(psutil, "RLIMIT_STACK"))
@unittest.skipUnless(
get_kernel_version() >= (3, 0),
"prlimit constants not available on this Linux kernel version")
def test_resource_consts_kernel_v(self):
# more recent constants
self.assertTrue(hasattr(psutil, "RLIMIT_MSGQUEUE"))
self.assertTrue(hasattr(psutil, "RLIMIT_NICE"))
self.assertTrue(hasattr(psutil, "RLIMIT_RTPRIO"))
self.assertTrue(hasattr(psutil, "RLIMIT_RTTIME"))
self.assertTrue(hasattr(psutil, "RLIMIT_SIGPENDING"))
def test_boot_time_mocked(self):
with mock.patch('psutil._pslinux.open', create=True) as m:
self.assertRaises(
RuntimeError,
psutil._pslinux.boot_time)
assert m.called
def test_users_mocked(self):
# Make sure ':0' and ':0.0' (returned by C ext) are converted
# to 'localhost'.
with mock.patch('psutil._pslinux.cext.users',
return_value=[('giampaolo', 'pts/2', ':0',
1436573184.0, True)]) as m:
self.assertEqual(psutil.users()[0].host, 'localhost')
assert m.called
with mock.patch('psutil._pslinux.cext.users',
return_value=[('giampaolo', 'pts/2', ':0.0',
1436573184.0, True)]) as m:
self.assertEqual(psutil.users()[0].host, 'localhost')
assert m.called
# ...otherwise it should be returned as-is
with mock.patch('psutil._pslinux.cext.users',
return_value=[('giampaolo', 'pts/2', 'foo',
1436573184.0, True)]) as m:
self.assertEqual(psutil.users()[0].host, 'foo')
assert m.called
def test_procfs_path(self):
tdir = tempfile.mkdtemp()
try:
psutil.PROCFS_PATH = tdir
self.assertRaises(IOError, psutil.virtual_memory)
self.assertRaises(IOError, psutil.cpu_times)
self.assertRaises(IOError, psutil.cpu_times, percpu=True)
self.assertRaises(IOError, psutil.boot_time)
# self.assertRaises(IOError, psutil.pids)
self.assertRaises(IOError, psutil.net_connections)
self.assertRaises(IOError, psutil.net_io_counters)
self.assertRaises(IOError, psutil.net_if_stats)
self.assertRaises(IOError, psutil.disk_io_counters)
self.assertRaises(IOError, psutil.disk_partitions)
self.assertRaises(psutil.NoSuchProcess, psutil.Process)
finally:
psutil.PROCFS_PATH = "/proc"
os.rmdir(tdir)
# =====================================================================
# test process
# =====================================================================
@unittest.skipUnless(LINUX, "not a Linux system")
class TestProcess(unittest.TestCase):
def test_memory_maps(self):
src = textwrap.dedent("""
import time
with open("%s", "w") as f:
time.sleep(10)
""" % TESTFN)
sproc = pyrun(src)
self.addCleanup(reap_children)
call_until(lambda: os.listdir('.'), "'%s' not in ret" % TESTFN)
p = psutil.Process(sproc.pid)
time.sleep(.1)
maps = p.memory_maps(grouped=False)
pmap = sh('pmap -x %s' % p.pid).split('\n')
# get rid of header
del pmap[0]
del pmap[0]
while maps and pmap:
this = maps.pop(0)
other = pmap.pop(0)
addr, _, rss, dirty, mode, path = other.split(None, 5)
if not path.startswith('[') and not path.endswith(']'):
self.assertEqual(path, os.path.basename(this.path))
self.assertEqual(int(rss) * 1024, this.rss)
# test only rwx chars, ignore 's' and 'p'
self.assertEqual(mode[:3], this.perms[:3])
def test_memory_addrspace_info(self):
src = textwrap.dedent("""
import time
with open("%s", "w") as f:
time.sleep(10)
""" % TESTFN)
sproc = pyrun(src)
self.addCleanup(reap_children)
call_until(lambda: os.listdir('.'), "'%s' not in ret" % TESTFN)
p = psutil.Process(sproc.pid)
time.sleep(.1)
mem = p.memory_addrspace_info()
maps = p.memory_maps(grouped=False)
self.assertEqual(
mem.uss, sum([x.private_dirty + x.private_clean for x in maps]))
self.assertEqual(
mem.pss, sum([x.pss for x in maps]))
self.assertEqual(
mem.swap, sum([x.swap for x in maps]))
def test_open_files_file_gone(self):
# simulates a file which gets deleted during open_files()
# execution
p = psutil.Process()
files = p.open_files()
with tempfile.NamedTemporaryFile():
# give the kernel some time to see the new file
call_until(p.open_files, "len(ret) != %i" % len(files))
with mock.patch('psutil._pslinux.os.readlink',
side_effect=OSError(errno.ENOENT, "")) as m:
files = p.open_files()
assert not files
assert m.called
# also simulate the case where os.readlink() returns EINVAL
# in which case psutil is supposed to 'continue'
with mock.patch('psutil._pslinux.os.readlink',
side_effect=OSError(errno.EINVAL, "")) as m:
self.assertEqual(p.open_files(), [])
assert m.called
# --- mocked tests
def test_terminal_mocked(self):
with mock.patch('psutil._pslinux._psposix._get_terminal_map',
return_value={}) as m:
self.assertIsNone(psutil._pslinux.Process(os.getpid()).terminal())
assert m.called
def test_num_ctx_switches_mocked(self):
with mock.patch('psutil._pslinux.open', create=True) as m:
self.assertRaises(
NotImplementedError,
psutil._pslinux.Process(os.getpid()).num_ctx_switches)
assert m.called
def test_num_threads_mocked(self):
with mock.patch('psutil._pslinux.open', create=True) as m:
self.assertRaises(
NotImplementedError,
psutil._pslinux.Process(os.getpid()).num_threads)
assert m.called
def test_ppid_mocked(self):
with mock.patch('psutil._pslinux.open', create=True) as m:
self.assertRaises(
NotImplementedError,
psutil._pslinux.Process(os.getpid()).ppid)
assert m.called
def test_uids_mocked(self):
with mock.patch('psutil._pslinux.open', create=True) as m:
self.assertRaises(
NotImplementedError,
psutil._pslinux.Process(os.getpid()).uids)
assert m.called
def test_gids_mocked(self):
with mock.patch('psutil._pslinux.open', create=True) as m:
self.assertRaises(
NotImplementedError,
psutil._pslinux.Process(os.getpid()).gids)
assert m.called
def test_cmdline_mocked(self):
# see: https://github.com/giampaolo/psutil/issues/639
p = psutil.Process()
fake_file = io.StringIO(u('foo\x00bar\x00'))
with mock.patch('psutil._pslinux.open',
return_value=fake_file, create=True) as m:
p.cmdline() == ['foo', 'bar']
assert m.called
fake_file = io.StringIO(u('foo\x00bar\x00\x00'))
with mock.patch('psutil._pslinux.open',
return_value=fake_file, create=True) as m:
p.cmdline() == ['foo', 'bar', '']
assert m.called
def test_io_counters_mocked(self):
with mock.patch('psutil._pslinux.open', create=True) as m:
self.assertRaises(
NotImplementedError,
psutil._pslinux.Process(os.getpid()).io_counters)
assert m.called
def test_readlink_path_deleted_mocked(self):
with mock.patch('psutil._pslinux.os.readlink',
return_value='/home/foo (deleted)'):
self.assertEqual(psutil.Process().exe(), "/home/foo")
self.assertEqual(psutil.Process().cwd(), "/home/foo")
if __name__ == '__main__':
run_test_module_by_name(__file__)<|fim▁end|>
|
self.assertRaises(IOError, psutil.cpu_times_percent)
self.assertRaises(
IOError, psutil.cpu_times_percent, percpu=True)
|
<|file_name|>lib.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/. */
#![feature(custom_attribute, custom_derive, plugin)]<|fim▁hole|>extern crate euclid;
extern crate heapsize;
extern crate hyper;
extern crate ipc_channel;
extern crate layers;
extern crate rustc_serialize;
extern crate serde;
extern crate url;
extern crate util;
extern crate webrender_traits;
pub mod constellation_msg;
pub mod webdriver_msg;<|fim▁end|>
|
#![plugin(heapsize_plugin, serde_macros, plugins)]
#[macro_use]
extern crate bitflags;
|
<|file_name|>ARTarget.cpp<|end_file_name|><|fim▁begin|>/*
* ARTarget.cpp
* ARToolKit5
*
* This file generate a special actor who defines a NFT target
* File descriptions: ARTarget contains very important features like size of the target,
* the offset calcultation for the NFT track point, a plane to display the target just for editor mode
*
* ARToolKit is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ARToolKit 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 ARToolKit. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent modules, and to
* copy and distribute the resulting executable under terms of your choice,
* provided that you also meet, for each linked independent module, the terms and
* conditions of the license of that module. An independent module is a module
* which is neither derived from nor based on this library. If you modify this
* library, you may extend this exception to your version of the library, but you
* are not obligated to do so. If you do not wish to do so, delete this exception
* statement from your version.
*
* Copyright 2015 Daqri, LLC.
* Copyright 2010-2015 ARToolworks, Inc.
*
* Author(s): Philip Lamb, Julian Looser.
*
* Plugin Author(s): Jorge CR (AKA karmakun)
*
* Special Thanks: tgraupmann (your android knowledge helps a lot)
*/
#include "ARPrivatePCH.h"
#include "ARTarget.h"
#include "FileManagerGeneric.h"
// Fix WinBase.h override
#undef UpdateResource
#define UpdateResource UpdateResource
DEFINE_LOG_CATEGORY_STATIC(LogARToolKits, Log, All);
AARTarget::AARTarget()
{
//create components
targetPivot = CreateDefaultSubobject<USceneComponent>("Target Pivot");
targetPivot->SetMobility(EComponentMobility::Static);
RootComponent = targetPivot;
#if WITH_EDITOR
//Editor only: create static mesh component and display plane
plane = CreateDefaultSubobject<UStaticMeshComponent>("Target Plane");
plane->SetupAttachment(targetPivot);
UMaterial* targetMat = Cast<UMaterial>(StaticLoadObject(UMaterial::StaticClass(), NULL, TEXT("/AR/targetMat")));
if (targetMat != NULL)
{
plane->SetMaterial(0, targetMat);
}
// set dummy texture by default
UStaticMesh* myMeshPlane = Cast<UStaticMesh>(StaticLoadObject(UStaticMesh::StaticClass(), NULL, TEXT("/AR/Plane")));
if (myMeshPlane != NULL)
{
plane->SetStaticMesh(myMeshPlane);
plane->SetRelativeScale3D(FVector(1, sizeMM.X, sizeMM.Y));
plane->SetRelativeRotation(FQuat(FRotator(-90, 0, 0)));
plane->SetMobility(EComponentMobility::Static);
}
defaultTexture = Cast<UTexture2D>(StaticLoadObject(UTexture2D::StaticClass(), NULL, TEXT("/AR/icon128")));
#endif
//create shadow plane component
shadowPlane = CreateDefaultSubobject<UStaticMeshComponent>("shadow plane");
shadowPlane->SetupAttachment(RootComponent);
UStaticMesh* myMeshPlane2 = Cast<UStaticMesh>(StaticLoadObject(UStaticMesh::StaticClass(), NULL, TEXT("/AR/Plane")));
if (myMeshPlane2 != NULL)
{
shadowPlane->SetStaticMesh(myMeshPlane2);
shadowPlane->SetRelativeScale3D(FVector(1, shadowPlaneScale, shadowPlaneScale));
shadowPlane->SetRelativeRotation(FQuat(FRotator(-90, 0, 0)));
shadowPlane->SetRelativeLocation(FVector(0, 0, 1));
UMaterial* shadowMat = Cast<UMaterial>(StaticLoadObject(UMaterial::StaticClass(), NULL, TEXT("/AR/shadowPlane_mat")));
if (shadowMat != NULL)
{
shadowPlane->SetMaterial(0, shadowMat);
}
}
}
void AARTarget::OnConstruction(const FTransform& Transform)
{
Super::OnConstruction(Transform);
//set scale based on custom value
SetActorScale3D(FVector(scale, scale, scale));
#if WITH_EDITOR
if (targetName != "" && prevAcceptTargetName != targetName)
{
//load target from content
FString thisTarget = FPaths::GameContentDir() + "AR/" + targetName;
if (FPaths::FileExists(thisTarget + ".iset"))
{
AR2ImageSetT* imageSet = ar2ReadImageSet(TCHAR_TO_ANSI(*thisTarget));
if (imageSet != NULL)
{
//int32 halfIndex = imageSet->num / 2;
int32 halfIndex = 0;
int32 w = imageSet->scale[halfIndex]->xsize;
int32 h = imageSet->scale[halfIndex]->ysize;
int32 dpi = imageSet->scale[0]->dpi;
//UE_LOG(LogARToolKits, Log, TEXT("target size found: %i , %i , %i"), imageSet->scale[i]->xsize, imageSet->scale[i]->ysize, imageSet->scale[i]->dpi);
unsigned char* RawData = imageSet->scale[halfIndex]->imgBW;
targetTexture = UTexture2D::CreateTransient(w, h, PF_B8G8R8A8);
TArray<FColor> rawData;
rawData.Init(FColor(0, 0, 0, 255), w* h);
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
int i = x + (y * w);
rawData[i].B = RawData[i];
rawData[i].G = RawData[i];
rawData[i].R = RawData[i];
}
}
FTexture2DMipMap& Mip = targetTexture->PlatformData->Mips[0];
void* Data = Mip.BulkData.Lock(LOCK_READ_WRITE);
FMemory::Memcpy(Data,rawData.GetData(), w * h * 4);
Mip.BulkData.Unlock();
targetTexture->UpdateResource();
UMaterialInstanceDynamic* materialInstance = plane->CreateDynamicMaterialInstance(0);
if (materialInstance != NULL)
{
materialInstance->SetTextureParameterValue("tex", targetTexture);
sizeMM.X = w;
sizeMM.Y = h;
UE_LOG(LogARToolKits, Log, TEXT("target found name: %s, pixel size: (w: %i , h: %i), UE real size: (w: %f , h: %f)"), *targetName, w,h,pixels2millimeter(w), pixels2millimeter(h));
prevAcceptTargetName = targetName;
}
}
}
else
{
UMaterialInstanceDynamic* materialInstance = plane->CreateDynamicMaterialInstance(0);
if (materialInstance != NULL)
{
materialInstance->SetTextureParameterValue("tex", defaultTexture);
sizeMM.X = defaultTexture->GetSizeX() * 40;
sizeMM.Y = defaultTexture->GetSizeY() * 40;
UE_LOG(LogARToolKits, Warning, TEXT("this name is not found in AR content folder, check if really exists!"));
prevAcceptTargetName = "";
}
}
}
//set plane size based on image target
plane->SetRelativeScale3D(FVector(1, pixels2millimeter(sizeMM.X), pixels2millimeter(sizeMM.Y)));
#endif<|fim▁hole|>
//set shadow plane sacle
shadowPlane->SetRelativeScale3D(FVector(1, shadowPlaneScale, shadowPlaneScale));
}
void AARTarget::BeginPlay()
{
Super::BeginPlay();
if (!AllowShadowPlane)
{
shadowPlane->DestroyComponent();
}
else
{
//if plane exist set camera texture
UMaterialInstanceDynamic* shadowDynamicMaterial = shadowPlane->CreateDynamicMaterialInstance(0);
if (shadowDynamicMaterial != NULL)
{
shadowDynamicMaterial->SetTextureParameterValue("tex", IARModule::Get().GetARToolKit()->getTexture());
}
}
}
void AARTarget::setTargetActorsHiddenInGame(bool bHidden)
{
TArray<USceneComponent*> childs;
targetPivot->GetChildrenComponents(true, childs);
for (auto& child : childs)
{
if (child != NULL && child != plane)
{
child->SetHiddenInGame(bHidden);
}
}
for (auto& movable : movableObjectList)
{
if (movable != NULL) movable->SetActorHiddenInGame(bHidden);
}
plane->SetHiddenInGame(true, false);
}
FRotator AARTarget::getTargetRotation()
{
return GetActorRotation();
}<|fim▁end|>
|
//toogle shadow plane
shadowPlane->SetVisibility(AllowShadowPlane);
|
<|file_name|>api.py<|end_file_name|><|fim▁begin|>from utils.api_factory import ApiFactory
<|fim▁hole|>
if __name__ == '__main__':
api.run(host='0.0.0.0', port=8000)<|fim▁end|>
|
api = ApiFactory.get_instance()
|
<|file_name|>development_tools_config_settings.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
###############################################################################
# License, author and contributors information in: #
# __openerp__.py file at the root folder of this module. #
###############################################################################
from openerp import models, fields, api
from openerp.tools.translate import _
from openerp.tools.safe_eval import safe_eval
from logging import getLogger
_logger = getLogger(__name__)
class DevelopmentToolsConfigSettings(models.TransientModel):
""" Module config settings
Fields:
email_to (Char): Address will be used to send captured email messages
email_capture (Boolean): Check it to capture outgoing email messages
developing_modules_enabled (Boolean): Sets the filter as default filter
in Local modules views
developing_module_ids (Many2many): Select items you want to display by
default Local modules views
search_default_app (Boolean): Enable search_default_app filter in the
Local modules view
"""
_name = 'development_tools.config.settings'
_description = u'Development tools config settings'
_inherit = ['res.config.settings']
_rec_name = 'id'
_order = 'id ASC'
# ---------------------------- ENTITY FIELDS ------------------------------
email_to = fields.Char(
string='Email to',
required=False,
readonly=False,
index=False,
help='Address will be used to send captured email messages',
size=50,
translate=False,
default='[email protected]',
)
email_capture = fields.Boolean(
string='Capture emails',
required=False,
readonly=False,
index=False,
default=True,
help='Check it to capture outgoing email messages',
)
developing_modules_enabled = fields.Boolean(
string='Set as default filter',
required=False,
readonly=False,
index=False,
default=False, # filter_model_name_whithout_module_development_modules
help='Sets the filter as default filter in Local modules views'
)
developing_module_ids = fields.Many2many(
string='Modules shown',
required=False,
readonly=False,
index=False,
default=None,
help='Select items you want to display by default Local modules views',
comodel_name='ir.module.module',
domain=[],
context={},
limit=None,
manual=True,
compute=lambda self: self._compute_developing_module_ids(),
inverse=lambda self: self._inverse_developing_module_ids()
)
search_default_app = fields.Boolean(
string='Search default app filter',
required=False,
readonly=False,
index=False,
default=False,
help='Enable search_default_app filter in the Local modules view'
)
development_mode = fields.Boolean(
string='Development mode as default',
required=False,
readonly=False,
index=False,
default=True,
help='Set development mode by default'
)
# ----------------------- COMPUTED FIELD METHODS --------------------------
def _compute_developing_module_ids(self):
for record in self:
record.developing_module_ids = record.get_developing_module_ids()
def _inverse_developing_module_ids(self):
try:
ids = [module.id for module in self.developing_module_ids]
name = 'filter_model_name_whithout_module_development_modules'
filter_set = self.env.ref('{}.{}'.format(self._module, name))
filter_set.domain = unicode([('id', 'in', ids or [-1])])
except Exception as ex:
_logger.error('_inverse_developing_module_ids: %s' % ex)
# --------------------- RES.CONFIG.SETTINGS METHODS -----------------------
@api.model
def get_default_values(self, values):
return dict(
email_to=self.get_email_to(),
email_capture=self.get_email_capture(),
developing_modules_enabled=self.get_developing_modules_enabled(),
developing_module_ids=self.get_developing_module_ids(),
search_default_app=self.get_search_default_app(),
development_mode=self.get_debug_mode(),
)
@api.one
def set_default_values(self):
self._set_email_to()
self._set_email_capture()
self._set_developing_modules_enabled()
self._set_developing_module_ids()
self._set_search_default_app()
self._set_debug_mode()
# ------------------------- GETTERS AND SETTERS ---------------------------
def get_email_to(self):
param = self._get_parameter('email_to')
return param.value if param else self._defaults['email_to']
def _set_email_to(self):
param = self._get_parameter('email_to', force=True)
param.value = self.email_to
def get_email_capture(self):
param = self._get_parameter('email_capture')
if param:
value = self._safe_eval(param.value, bool)
else:
value = self._defaults['email_capture']
return value
def _set_email_capture(self):
param = self._get_parameter('email_capture', force=True)
param.value = unicode(self.email_capture)
def get_developing_modules_enabled(self):
value = False
try:
name = 'filter_model_name_whithout_module_development_modules'
filter_set = self.env.ref('{}.{}'.format(self._module, name))
value = filter_set.is_default
except Exception as ex:
msg = self._not_retrieved.format('developing_modules_enabled', ex)
_logger.error(msg)
return value
def _set_developing_modules_enabled(self):
try:
name = 'filter_model_name_whithout_module_development_modules'
filter_set = self.env.ref('{}.{}'.format(self._module, name))
filter_set.is_default = self.developing_modules_enabled
except Exception as ex:
msg = self._not_set('developing_modules_enabled', ex)
_logger.error(msg)
def get_developing_module_ids(self):
value = None
try:
name = 'filter_model_name_whithout_module_development_modules'
filter_set = self.env.ref('{}.{}'.format(self._module, name))
domain = self._safe_eval(filter_set.domain, list)
value = filter(lambda x: x > 0, domain[0][2])
except Exception as ex:
msg = self._not_retrieved.format('developing_module_ids', ex)
_logger.error(msg)
return value
def _set_developing_module_ids(self):
try:
ids = [module.id for module in self.developing_module_ids]
name = 'filter_model_name_whithout_module_development_modules'
filter_set = self.env.ref('{}.{}'.format(self._module, name))
filter_set.domain = unicode([('id', 'in', ids or [-1])])
except Exception as ex:
msg = self._not_set('developing_module_ids', ex)
_logger.error(msg)
def get_search_default_app(self):
value = None
try:
action_set = self.env.ref('base.open_module_tree')
context = self._safe_eval(action_set.context, dict)
if 'search_default_app' in context:
value = context['search_default_app'] in [1, True]
else:
value = False
except Exception as ex:
msg = self._not_retrieved.format('search_default_app', ex)
_logger.error(msg)
return value
def _set_search_default_app(self):
try:
action_set = self.env.ref('base.open_module_tree')
context = self._safe_eval(action_set.context, dict)
value = 1 if self.search_default_app else 0
context.update({'search_default_app': value})
action_set.context = unicode(context)
except Exception as ex:
msg = self._not_set.format('search_default_app', ex)
_logger.error(msg)
def get_debug_mode(self):
param = self._get_parameter('development_mode')
if param:
value = self._safe_eval(param.value, bool)
else:
value = self._defaults['development_mode']
return value
def _set_debug_mode(self):
param = self._get_parameter('development_mode', force=True)
param.value = unicode(self.development_mode)
# --------------------------- #PUBLIC METHODS -----------------------------
def get_value(self, field_name):
""" Calls the appropiate method to retrieve the value of the field
with the given name and returns its value
:param field_name (char): name of the field
:returns: returns retrieved value or None
"""
result = None
try:
method_name = 'get_{}'.format(field_name)
method = getattr(self, method_name)
result = method()
except Exception as ex:
msg = self._not_value.format(field_name, ex)
_logger.error(msg)
return result
# -------------------------- AUXILIARY METHODS ----------------------------
def _get_parameter(self, field_name, force=False, default=u''):
""" Gets the ir.config_parameter for the field
:param field_name (char): name of the field
:force (bool): create record if not exists
:default (basestring): default parameter value if it is creted new
:return (ir.config_parameter): recordset with a record or empty
:note: Parameters could be searched by their external ids but if
they are created anew, then they could not be found
:note: Limit the search is not needed because the `key`column has
unique index constraint
:note: If there is not any matching record, the returned set will
be empty<|fim▁hole|> """
param_name = u'{}.{}'.format(self._module, field_name)
param_domain = [('key', '=', param_name)]
param_obj = self.env['ir.config_parameter']
param_set = param_obj.search(param_domain)
if not param_set and force:
param_set = param_obj.create(
{'key': param_name, 'value': default}
)
return param_set
def _safe_eval(self, value_str, types=None):
""" Try to convert an string in a value of one of the given types
:param value_str (basestring): string to be converted
:param types (type): type or iterable set of them
:return: value of one of the types if it could be converted or None
"""
value = None
try:
types = self._iterable(types)
value = safe_eval(value_str)
if not type(value) in types:
msg = self._check_type_msg.format(value_str, types)
_logger.error(msg)
value = None
except Exception as ex:
_logger.error(self._safe_eval_msg.format(value_str, ex))
return value
def _iterable(self, item):
""" Ensures the given item is iterable
:param: item to be tested
:return: item if it's iterable or the item within a list
"""
try:
iter(item)
item.__iter__()
except:
return [item]
else:
return item or [None]
# ----------------------- LONG CHARACTER STRINGS --------------------------
_safe_eval_msg = _(
u'Value \'{}\' could not be evaluated\n'
u'System has said: {}'
)
_check_type_msg = _(
u'Wrong type value `{}`, one of the following was expected: `{}`'
)
_not_retrieved = _(
u'The value `{}` could not be retrieved\n'
u'System has said: {}'
)
_not_set = _(
u'The value `{}` could not be set\n'
u'System has said: {}'
)
_not_value = _(
u'Could not retrive value for field `{}`\n'
u'System has said: {}'
)<|fim▁end|>
| |
<|file_name|>traits.rs<|end_file_name|><|fim▁begin|>// * This file is part of the uutils coreutils package.
// *
// * (c) 2020 Alex Lyon <[email protected]>
// * (c) 2020 nicoo <[email protected]>
// *
// * For the full copyright and license information, please view the LICENSE file
// * that was distributed with this source code.
pub(crate) use num_traits::{
identities::{One, Zero},
ops::overflowing::OverflowingAdd,
};
use num_traits::{
int::PrimInt,
ops::wrapping::{WrappingMul, WrappingNeg, WrappingSub},
};
use std::fmt::{Debug, Display};
pub(crate) trait Int:
Display + Debug + PrimInt + OverflowingAdd + WrappingNeg + WrappingSub + WrappingMul
{
fn as_u64(&self) -> u64;
fn from_u64(n: u64) -> Self;
<|fim▁hole|>pub(crate) trait DoubleInt: Int {
/// An integer type with twice the width of `Self`.
/// In particular, multiplications (of `Int` values) can be performed in
/// `Self::DoubleWidth` without possibility of overflow.
type DoubleWidth: Int;
fn as_double_width(self) -> Self::DoubleWidth;
fn from_double_width(n: Self::DoubleWidth) -> Self;
}
macro_rules! int {
( $x:ty ) => {
impl Int for $x {
fn as_u64(&self) -> u64 {
*self as u64
}
fn from_u64(n: u64) -> Self {
n as _
}
#[cfg(debug_assertions)]
fn as_u128(&self) -> u128 {
*self as u128
}
}
};
}
macro_rules! double_int {
( $x:ty, $y:ty ) => {
int!($x);
impl DoubleInt for $x {
type DoubleWidth = $y;
fn as_double_width(self) -> $y {
self as _
}
fn from_double_width(n: $y) -> Self {
n as _
}
}
};
}
double_int!(u32, u64);
double_int!(u64, u128);
int!(u128);
/// Helper macro for instantiating tests over u32 and u64
#[cfg(test)]
#[macro_export]
macro_rules! parametrized_check {
( $f:ident ) => {
paste::item! {
#[test]
fn [< $f _ u32 >]() {
$f::<u32>()
}
#[test]
fn [< $f _ u64 >]() {
$f::<u64>()
}
}
};
}<|fim▁end|>
|
#[cfg(debug_assertions)]
fn as_u128(&self) -> u128;
}
|
<|file_name|>filter_games_controller.py<|end_file_name|><|fim▁begin|>'''
This module controls the dialog to set filter criteria
'''
from PyQt5 import QtCore, Qt, QtWidgets
from views.filter_dialog import Ui_FilterDialog
class FilterGamesController(QtWidgets.QDialog):
'''
Controller object for the filter games dialog.
'''
def __init__(self, table, parent=None):
QtWidgets.QDialog.__init__(self, parent)
self.user_interface = Ui_FilterDialog()
self.user_interface.setupUi(self)
self.table = table
self.canceled = False
self.filtering_all = True
self.initialize_ui()
self.setup_signals()
def initialize_ui(self):
'''
Connects interface's sections with their corresponding models
'''
def assign_model(model, list_widget):
'''
Private function to populate a specific section in the
dialog with the values stored in a model
parameters:
- model: the model assigned to the dialog section
- list_widget: the list widget to be populated
'''
model_qt = Qt.QStandardItemModel()
values_list = model.get_list()
for value in values_list:
item = Qt.QStandardItem(value)
item.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
item.setData(QtCore.Qt.Checked, QtCore.Qt.CheckStateRole)
if model.get_filtered(value):
item.setCheckState(QtCore.Qt.Unchecked)
model_qt.appendRow(item)
list_widget.setModel(model_qt)
assign_model(self.table.models['system_list_model'], self.user_interface.listSystem)
assign_model(self.table.models['status_list_model'], self.user_interface.listStatus)
assign_model(self.table.models['label_list_model'], self.user_interface.listLabel)
assign_model(self.table.models['difficulty_list_model'], self.user_interface.listDifficulty)
def setup_signals(self):
'''
Connects interface's widgets signals to the corresponding slots
'''
def select_all(list_view):
'''
Generic callback for a 'select all' button
parameters:
-list_view: the list affected when the user clicks 'select all'
'''
model_qt = list_view.model()
for index in range(model_qt.rowCount()):
item = model_qt.item(index)
if item.isCheckable() and item.checkState() == QtCore.Qt.Unchecked:
item.setCheckState(QtCore.Qt.Checked)
def deselect_all(list_view):
'''
Generic callback for a 'deselect all' button
parameters:
- list_view: the list affected when the user clicks 'deselect all'
'''
model_qt = list_view.model()
for index in range(model_qt.rowCount()):
item = model_qt.item(index)
if item.isCheckable() and item.checkState() == QtCore.Qt.Checked:
item.setCheckState(QtCore.Qt.Unchecked)
self.user_interface.pushButtonSelectAllSystem.clicked.connect(
lambda: select_all(self.user_interface.listSystem))
self.user_interface.pushButtonDeselectAllSystem.clicked.connect(
lambda: deselect_all(self.user_interface.listSystem))
self.user_interface.pushButtonSelectAllStatus.clicked.connect(
lambda: select_all(self.user_interface.listStatus))
self.user_interface.pushButtonDeselectAllStatus.clicked.connect(
lambda: deselect_all(self.user_interface.listStatus))
self.user_interface.pushButtonSelectAllLabel.clicked.connect(
lambda: select_all(self.user_interface.listLabel))
self.user_interface.pushButtonDeselectAllLabel.clicked.connect(
lambda: deselect_all(self.user_interface.listLabel))
self.user_interface.pushButtonSelectAllDifficulty.clicked.connect(
lambda: select_all(self.user_interface.listDifficulty))
self.user_interface.pushButtonDeselectAllDifficulty.clicked.connect(
lambda: deselect_all(self.user_interface.listDifficulty))
self.user_interface.pushButtonOk.clicked.connect(self.ok_clicked)
self.user_interface.pushButtonCancel.clicked.connect(self.cancel_clicked)
def ok_clicked(self):
'''
Callback for when the user clicks the 'ok' button. The dialog is closed and
the parent is informed by means of an attribute that the changes have to
take effect
'''
self.canceled = False
self.hide()
def cancel_clicked(self):
'''
Callback for when the user clicks the 'cancel' button. The dialog is closed
and the parent is informed by means of an attribute that changes shouldn't
take effect
'''
self.canceled = True
self.hide()
def closeEvent(self, event):
'''
Overriding the closeEvent from the QDialog class. This tells the main window
controller to behave as if the Cancel button was pressed.
parameters:
- event: the passed event (not used in this overriden version)
'''
# pylint: disable=invalid-name
# pylint: disable=unused-argument
self.canceled = True
def apply_filtering(self):
'''
Updates the models with information about which values to be filted
'''
def apply_filtering_per_type(model, list_widget):
'''
Updates a specific model<|fim▁hole|> - model: the model to be updated
- list_widget: the list associated to that model
'''
model_qt = list_widget.model()
for index in range(model_qt.rowCount()):
item = model_qt.item(index)
model.set_filtered(str(item.text()), item.checkState() != QtCore.Qt.Checked)
if not self.canceled:
apply_filtering_per_type(
self.table.models['system_list_model'],
self.user_interface.listSystem)
apply_filtering_per_type(
self.table.models['status_list_model'],
self.user_interface.listStatus)
apply_filtering_per_type(
self.table.models['label_list_model'],
self.user_interface.listLabel)
apply_filtering_per_type(
self.table.models['difficulty_list_model'],
self.user_interface.listDifficulty)
self.table.hide_rows()
models = [self.table.models['system_list_model'],
self.table.models['status_list_model'],
self.table.models['label_list_model'],
self.table.models['difficulty_list_model']]
model = 0
while model < len(models) and not models[model].is_any_filtered():
model = model + 1
self.filtering_all = model >= len(models)<|fim▁end|>
|
parameters:
|
<|file_name|>autotag.py<|end_file_name|><|fim▁begin|>""" Contains a few template tags relating to autotags
Specifically, the autotag tag itself, and the filters epoch and cstag.
"""
from django import template
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
from tags.models import Tag
import datetime
import calendar
import types
register = template.Library()
@register.inclusion_tag("autotags/autotag.html")
def autotag(autotag, untag=None, **kwargs):
""" Displays an autotag as a block
An autotag block is a HTML element with the class "block", surprisingly enough, and consists of a head and a body.
The head is always visible, but the body is only visible when you click the button, and contains buttons to edit the
autotag.
"""
kwargs["at"] = autotag
kwargs["tags"] = Tag.expand_implies_check(autotag.tags.all())
kwargs["colour"] = "white"
for (t, _) in kwargs["tags"]:
if t.colour != "white":
kwargs["colour"] = t.colour
break
return kwargs<|fim▁hole|>
@register.filter(expects_localtime=True)
def epoch(value):
""" Convert datetime object into seconds from epoch """
if isinstance(value, datetime.datetime):
return int(calendar.timegm(value.timetuple()))
return ''
@register.filter()
def cstag(value):
""" Return the tags for this bookmark as a comma seperated list """
return ",".join(map((lambda t: t.slug.replace(",", "")), Tag.expand_implies(value.tags.all())))<|fim▁end|>
| |
<|file_name|>__init__.js<|end_file_name|><|fim▁begin|>(function(){
if ( window.xataface == undefined ) window.xataface = {};
if ( window.xataface.modules == undefined ) window.xataface.modules = {};<|fim▁hole|><|fim▁end|>
|
if ( window.xataface.modules.htmlreports == undefined ) window.xataface.modules.htmlreports = {};
})();
|
<|file_name|>db.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import pymongo<|fim▁hole|>
client = pymongo.MongoClient(MONGO_STRING, tz_aware=True)
db = client['yo-water']<|fim▁end|>
|
from config import MONGO_STRING
|
<|file_name|>dataAnalysis.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#encoding=utf8
#Copyright [2014] [Wei Zhang]
#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.
###################################################################
# Date: 2014/6/15 #
# Providing various functions for data analysis. These results #
# support our final model choice. #
###################################################################
import sys, csv, json, argparse, datetime
from collections import defaultdict
with open("../SETTINGS.json") as fp:
settings = json.loads(fp.read())
def cnt_num_attendant(eventinfo_path, staresult_path):
''' count the distribution of number of attendants '''
num_attendant = defaultdict(int)
total_num = 0
for i, line in enumerate(open(eventinfo_path)):
try:
num = int(line.strip("\r\t\n").split(",")[9])
num_attendant[num] += 1
total_num += 1
except:
print line
print i
sys.exit(1)
cum_prob = 0.0
num_attendant = sorted(num_attendant.items(), key=lambda x:x[0])
wfd = open(staresult_path, "w")
for pair in num_attendant:
cum_prob += 1.0*pair[1]/total_num
wfd.write("%d %d %.4f\n" % (pair[0], pair[1], cum_prob))
wfd.close()
def cnt_attendant_for_category(eventinfo_path, staresult_path):
''' count number of categories and the distribution of number of
attendants for each category
'''
category_numevents = defaultdict(int)
category_numattendants = defaultdict(int)
for i, line in enumerate(open(eventinfo_path)):
category = line.strip("\r\t\n").split(",")[6]
num_participants = int(line.strip("\r\t\n").split(",")[9])
category_numevents[category] += 1
category_numattendants[category] += num_participants
print "Category statistics information--------\n"
print "\tNumber of categories: %d" % len(category_numevents)
wfd = open(staresult_path, "w")
for category in category_numevents:
wfd.write("%s %d %f\n" % (category, 1.0*category_numattendants[category]/category_numevents[category]))
print 'Average number of attendants for each category can be seen in (staresult.txt)'
def cnt_attendant_for_location(eventinfo_path, staresult_path):
''' count number of locations and the average of number of
attendants for each location
'''
location_numevents = defaultdict(int)
location_numattendants = defaultdict(int)
for i, line in enumerate(open(eventinfo_path)):
location = line.strip("\r\t\n").split(",")[2]
num_participants = int(line.strip("\r\t\n").split(",")[9])
location_numevents[location] += 1
location_numattendants[location] += num_participants
print "Location statistics information--------\n"
print "\tNumber of categories: %d" % len(location_numevents)
wfd = open(staresult_path, "w")
for location in location_numevents:
wfd.write("%s %d %f\n" % (location, location_numevents[location],
1.0*location_numattendants[location]/location_numevents[location]))
print 'Average number of attendants for each location can be seen in (staresult.txt)'
def cnt_attendant_for_organizer(eventinfo_path, staresult_path):
''' count number of organizors and the average of number of
attendants for each organizor
'''
organizor_numevents = defaultdict(int)
organizor_numattendants = defaultdict(int)
for i, line in enumerate(open(eventinfo_path)):
organizor = line.strip("\r\t\n").split(",")[5]
num_participants = int(line.strip("\r\t\n").split(",")[9])
organizor_numevents[organizor] += 1
organizor_numattendants[organizor] += num_participants
print "Organizor statistics information--------\n"
print "\tNumber of categories: %d" % len(organizor_numevents)
wfd = open(staresult_path, "w")
for organizor in organizor_numevents:
wfd.write("%s %d %f\n" % (organizor, organizor_numevents[organizor],
1.0*organizor_numattendants[organizor]/organizor_numevents[organizor]))
print 'Average number of attendants for each organizor can be seen in (staresult.txt)'
def cnt_attendant_for_time(eventinfo_path, staresult_path):
''' count the number of attendants for each time period:
(morning, afternoon, evening, other) * (weekday, weekend) + multiple days
+ multiple weeks + multiple month.
More specifically, (morning, weekday):0, (afternoon, weekday):1, ...
'''
timeperiod_numevents = defaultdict(int)<|fim▁hole|> for i, line in enumerate(open(eventinfo_path)):
start_time = line.strip("\r\t\n").split(",")[7]
end_time = line.strip("\r\t\n").split(",")[8]
num_participants = int(line.strip("\r\t\n").split(",")[9])
timeidx = getIdOfTimePeriod(start_time, end_time)
timeperiod_numevents[timeidx] += 1
timeperiod_numattendants[timeidx] += num_participants
print "Time statistics information--------\n"
print "\tNumber of categories: %d" % len(timeperiod_numevents)
wfd = open(staresult_path, "w")
for timeperiod in timeperiod_numevents:
wfd.write("%s %d %f\n" % (timeperiod, timeperiod_numevents[timeperiod],
1.0*timeperiod_numattendants[timeperiod]/timeperiod_numevents[timeperiod]))
print 'Average number of attendants for each timeperiod can be seen in (staresult.txt)'
dt = datetime.datetime.now()
def getIdOfTimePeriod(start_time, end_time):
time1 = dt.strptime(start_time, '%Y-%m-%dT%H:%M:%S+08:00')
time2 = dt.strptime(end_time, '%Y-%m-%dT%H:%M:%S+08:00')
year1 = time1.year
year2 = time2.year
#day1 = time1.day
#day2 = time2.day
day1 = int(time1.strftime('%j'))
day2 = int(time2.strftime('%j'))
if year1 == year2:
if day2-day1 > 30:
return 10
elif day2-day1 > 7:
return 9
elif day2-day1 > 0:
return 8
elif day2 == day1:
idx1= 0
idx2= 0
hour1 = time1.hour
#hour2 = time2.hour
weekday1 = time1.isoweekday()
if weekday1 == 6 or weekday1 == 7:
idx1 = 1
if 8 <= hour1 and hour1 < 12:
idx2 = 0
elif 12 <= hour1 and hour1 < 18:
idx2 = 1
elif 18 <= hour1 and hour1 < 24:
idx2 = 2
else:
idx2 = 3
return idx1*4+idx2
elif year1+1 == year2:
if day2+366-day1 > 30:
return 10
elif day2+366-day1 > 7:
return 9
elif day2+366-day1 > 0:
return 8
else:
print 'Error in getting id of time period'
sys.exit(1)
else:
return 10
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-d', type=str, action='store',
dest='data_num', help='choose which data set to use')
parser.add_argument('-f', type=int, action='store',
dest='function_num', help='choose which data analysis function to use')
if len(sys.argv) != 5:
print 'Command e.g.: python segmentData.py -d 1(11,12,...) -f 1(2,3,...)'
sys.exit(1)
para = parser.parse_args()
if para.data_num == "1":
eventinfo_path = settings["ROOT_PATH"] + settings["SRC_DATA_FILE1_1"]
staresult_path = "./staresult.txt"
elif para.data_num == "11":
eventinfo_path = settings["ROOT_PATH"] + settings["SRC_DATA_FILE1_CITY1"]
staresult_path = "./staresult.txt"
elif para.data_num == "12":
eventinfo_path = settings["ROOT_PATH"] + settings["SRC_DATA_FILE1_CITY2"]
staresult_path = "./staresult.txt"
else:
print 'Invalid choice of dataset'
sys.exit(1)
if para.function_num == 1:
cnt_num_attendant(eventinfo_path, staresult_path)
elif para.function_num == 2:
cnt_attendant_for_category(eventinfo_path, staresult_path)
elif para.function_num == 3:
cnt_attendant_for_location(eventinfo_path, staresult_path)
elif para.function_num == 4:
cnt_attendant_for_organizer(eventinfo_path, staresult_path)
elif para.function_num == 5:
cnt_attendant_for_time(eventinfo_path, staresult_path)
if __name__ == "__main__":
main()<|fim▁end|>
|
timeperiod_numattendants = defaultdict(int)
|
<|file_name|>observations.js<|end_file_name|><|fim▁begin|>const iNaturalistAPI = require( "../inaturalist_api" );
const ControlledTerm = require( "../models/controlled_term" );
const Observation = require( "../models/observation" );
const Project = require( "../models/project" );
const Taxon = require( "../models/taxon" );
const User = require( "../models/user" );
const observations = class observations {
static create( params, options ) {
return iNaturalistAPI.post( "observations", params, options )
.then( Observation.typifyInstanceResponse );
}
static update( params, options ) {
return iNaturalistAPI.put( "observations/:id", params, options )
.then( Observation.typifyInstanceResponse );
}
static delete( params, options ) {
return iNaturalistAPI.delete( "observations/:id", params, options );
}
static fave( params, options ) {
return observations.vote( params, options );
}
static unfave( params, options ) {
return observations.unvote( params, options );
}
static vote( params, options ) {
let endpoint = "votes/vote/observation/:id";
if ( iNaturalistAPI.apiURL && iNaturalistAPI.apiURL.match( /\/v2/ ) ) {
endpoint = "observations/:id/vote";
}
return iNaturalistAPI.post( endpoint, params, options )
.then( Observation.typifyInstanceResponse );
}
static unvote( params, options ) {
let endpoint = "votes/unvote/observation/:id";
if ( iNaturalistAPI.apiURL && iNaturalistAPI.apiURL.match( /\/v2/ ) ) {
endpoint = "observations/:id/vote";
}
return iNaturalistAPI.delete( endpoint, params, options );
}
static subscribe( params, options ) {
if ( iNaturalistAPI.apiURL && iNaturalistAPI.apiURL.match( /\/v2/ ) ) {
return iNaturalistAPI.put( "observations/:id/subscription", params, options );
}
return iNaturalistAPI.post( "subscriptions/Observation/:id/subscribe", params, options );
}
static review( params, options ) {
const p = Object.assign( { }, params );
p.reviewed = "true";
return iNaturalistAPI.post( "observations/:id/review", p, options );
}
static unreview( params, options ) {
const p = Object.assign( { }, params );
return iNaturalistAPI.delete( "observations/:id/review", p, options );
}
static qualityMetrics( params, options ) {
return iNaturalistAPI.get( "observations/:id/quality_metrics", params, options );
}
static setQualityMetric( params, options ) {
return iNaturalistAPI.post( "observations/:id/quality/:metric", params, options );
}
static deleteQualityMetric( params, options ) {
return iNaturalistAPI.delete( "observations/:id/quality/:metric", params, options );
}
static fetch( ids, params ) {
return iNaturalistAPI.fetch( "observations", ids, params )
.then( Observation.typifyResultsResponse );
}
static search( params, opts = { } ) {
return iNaturalistAPI.get( "observations", params, { ...opts, useAuth: true } )
.then( Observation.typifyResultsResponse );
}
static identifiers( params ) {
return iNaturalistAPI.get( "observations/identifiers", params )
.then( response => {
if ( response.results ) {
response.results = response.results.map( r => (
Object.assign( { }, r, { user: new User( r.user ) } )
) );
}
return response;
} );
}
static observers( params ) {
return iNaturalistAPI.get( "observations/observers", params )
.then( response => {
if ( response.results ) {
response.results = response.results.map( r => (
Object.assign( { }, r, { user: new User( r.user ) } )
) );
}
return response;
} );
}
static speciesCounts( params, opts = { } ) {
return iNaturalistAPI.get( "observations/species_counts", params, { ...opts, useAuth: true } )
.then( response => {
if ( response.results ) {
response.results = response.results.map( r => (
Object.assign( { }, r, { taxon: new Taxon( r.taxon ) } )
) );
}
return response;
} );
}
static iconicTaxaCounts( params, opts = { } ) {
return iNaturalistAPI.get( "observations/iconic_taxa_counts", params, { ...opts, useAuth: true } )
.then( response => {
if ( response.results ) {
response.results = response.results.map( r => (
Object.assign( { }, r, { taxon: new Taxon( r.taxon ) } )
) );
}
return response;
} );
}
static iconicTaxaSpeciesCounts( params, opts = { } ) {
return iNaturalistAPI.get( "observations/iconic_taxa_species_counts", params, { ...opts, useAuth: true } )
.then( response => {
if ( response.results ) {
response.results = response.results.map( r => (
Object.assign( { }, r, { taxon: new Taxon( r.taxon ) } )
) );
}
return response;
} );
}
static popularFieldValues( params ) {
return iNaturalistAPI.get( "observations/popular_field_values", params )
.then( response => {
if ( response.results ) {
response.results = response.results.map( res => {
const r = Object.assign( { }, res );
r.controlled_attribute = new ControlledTerm( r.controlled_attribute );
r.controlled_value = new ControlledTerm( r.controlled_value );
return r;
} );
}
return response;
} );
}
static umbrellaProjectStats( params ) {
return iNaturalistAPI.get( "observations/umbrella_project_stats", params )
.then( response => {
if ( response.results ) {
response.results = response.results.map( r => (
Object.assign( { }, r, { project: new Project( r.project ) } )
) );
}
return response;
} );
}
static histogram( params ) {
return iNaturalistAPI.get( "observations/histogram", params );
}
static qualityGrades( params ) {
return iNaturalistAPI.get( "observations/quality_grades", params );
}
static subscriptions( params, options ) {
return iNaturalistAPI.get( "observations/:id/subscriptions", params,
iNaturalistAPI.optionsUseAuth( options ) );
}
static taxonSummary( params ) {
return iNaturalistAPI.get( "observations/:id/taxon_summary", params );
}
static updates( params, options ) {
return iNaturalistAPI.get( "observations/updates", params,
iNaturalistAPI.optionsUseAuth( options ) );
}
static viewedUpdates( params, options ) {
return iNaturalistAPI.put( "observations/:id/viewed_updates", params,
iNaturalistAPI.optionsUseAuth( options ) );
}
static identificationCategories( params ) {
return iNaturalistAPI.get( "observations/identification_categories", params );
}
static taxonomy( params ) {
return iNaturalistAPI.get( "observations/taxonomy", params )
.then( Taxon.typifyResultsResponse );
}
static similarSpecies( params, opts ) {
const options = Object.assign( { }, opts || { } );
options.useAuth = true;
return iNaturalistAPI.get( "observations/similar_species", params, options )
.then( response => {
if ( response.results ) {
response.results = response.results.map( r => (
Object.assign( { }, r, { taxon: new Taxon( r.taxon ) } )
) );<|fim▁hole|>
static taxa( params ) {
return iNaturalistAPI.get( "observations/taxa", params );
}
};
module.exports = observations;<|fim▁end|>
|
}
return response;
} );
}
|
<|file_name|>onedstate.go<|end_file_name|><|fim▁begin|>// Copyright 2016 The Gofem Authors. All rights reserved.
// Use of this source code is governed by a BSD-style<|fim▁hole|>
import "github.com/cpmech/gosl/chk"
// OnedState holds data for 1D models
type OnedState struct {
// essential
Sig float64 // σ: Cauchy stress component
// for plasticity
Alp []float64 // α: internal variables of rate type [nalp]
Dgam float64 // Δγ: increment of Lagrange multiplier (for plasticity only)
Loading bool // unloading flag (for plasticity only)
// additional internal variables
Phi []float64 // additional internal variables; e.g. for holding Δσ in the general stress updater
// for large deformation
F float64 // deformation gradient
}
// NewOnedState allocates 1D state structure for small or large deformation analyses
// large -- large deformation analyses; otherwise small strains
func NewOnedState(nalp, nphi int) *OnedState {
var state OnedState
if nalp > 0 {
state.Alp = make([]float64, nalp)
}
if nphi > 0 {
state.Phi = make([]float64, nphi)
}
return &state
}
// Set copies states
// Note: 1) this and other states must have been pre-allocated with the same sizes
// 2) this method does not check for errors
func (o *OnedState) Set(other *OnedState) {
o.Sig = other.Sig
o.Dgam = other.Dgam
o.Loading = other.Loading
chk.IntAssert(len(o.Alp), len(other.Alp))
chk.IntAssert(len(o.Phi), len(other.Phi))
copy(o.Alp, other.Alp)
copy(o.Phi, other.Phi)
o.F = other.F
}
// GetCopy returns a copy of this state
func (o *OnedState) GetCopy() *OnedState {
other := NewOnedState(len(o.Alp), len(o.Phi))
other.Set(o)
return other
}<|fim▁end|>
|
// license that can be found in the LICENSE file.
package solid
|
<|file_name|>preloader.js<|end_file_name|><|fim▁begin|>'use strict';
angular.module('mpApp')
.factory(
'preloader',
function($q, $rootScope) {
// I manage the preloading of image objects. Accepts an array of image URLs.
function Preloader(imageLocations) {
// I am the image SRC values to preload.
this.imageLocations = imageLocations;
// As the images load, we'll need to keep track of the load/error
// counts when announing the progress on the loading.
this.imageCount = this.imageLocations.length;
this.loadCount = 0;
this.errorCount = 0;
// I am the possible states that the preloader can be in.
this.states = {
PENDING: 1,
LOADING: 2,
RESOLVED: 3,
REJECTED: 4
};
// I keep track of the current state of the preloader.
this.state = this.states.PENDING;
// When loading the images, a promise will be returned to indicate
// when the loading has completed (and / or progressed).
this.deferred = $q.defer();
this.promise = this.deferred.promise;
}
// ---<|fim▁hole|> // STATIC METHODS.
// ---
// I reload the given images [Array] and return a promise. The promise
// will be resolved with the array of image locations. 111111
Preloader.preloadImages = function(imageLocations) {
var preloader = new Preloader(imageLocations);
return (preloader.load());
};
// ---
// INSTANCE METHODS.
// ---
Preloader.prototype = {
// Best practice for "instnceof" operator.
constructor: Preloader,
// ---
// PUBLIC METHODS.
// ---
// I determine if the preloader has started loading images yet.
isInitiated: function isInitiated() {
return (this.state !== this.states.PENDING);
},
// I determine if the preloader has failed to load all of the images.
isRejected: function isRejected() {
return (this.state === this.states.REJECTED);
},
// I determine if the preloader has successfully loaded all of the images.
isResolved: function isResolved() {
return (this.state === this.states.RESOLVED);
},
// I initiate the preload of the images. Returns a promise. 222
load: function load() {
// If the images are already loading, return the existing promise.
if (this.isInitiated()) {
return (this.promise);
}
this.state = this.states.LOADING;
for (var i = 0; i < this.imageCount; i++) {
this.loadImageLocation(this.imageLocations[i]);
}
// Return the deferred promise for the load event.
return (this.promise);
},
// ---
// PRIVATE METHODS.
// ---
// I handle the load-failure of the given image location.
handleImageError: function handleImageError(imageLocation) {
this.errorCount++;
// If the preload action has already failed, ignore further action.
if (this.isRejected()) {
return;
}
this.state = this.states.REJECTED;
this.deferred.reject(imageLocation);
},
// I handle the load-success of the given image location.
handleImageLoad: function handleImageLoad(imageLocation) {
this.loadCount++;
// If the preload action has already failed, ignore further action.
if (this.isRejected()) {
return;
}
// Notify the progress of the overall deferred. This is different
// than Resolving the deferred - you can call notify many times
// before the ultimate resolution (or rejection) of the deferred.
this.deferred.notify({
percent: Math.ceil(this.loadCount / this.imageCount * 100),
imageLocation: imageLocation
});
// If all of the images have loaded, we can resolve the deferred
// value that we returned to the calling context.
if (this.loadCount === this.imageCount) {
this.state = this.states.RESOLVED;
this.deferred.resolve(this.imageLocations);
}
},
// I load the given image location and then wire the load / error
// events back into the preloader instance.
// --
// NOTE: The load/error events trigger a $digest. 333
loadImageLocation: function loadImageLocation(imageLocation) {
var preloader = this;
// When it comes to creating the image object, it is critical that
// we bind the event handlers BEFORE we actually set the image
// source. Failure to do so will prevent the events from proper
// triggering in some browsers.
var image = angular.element(new Image())
.bind('load', function(event) {
// Since the load event is asynchronous, we have to
// tell AngularJS that something changed.
$rootScope.$apply(
function() {
preloader.handleImageLoad(event.target.src);
// Clean up object reference to help with the
// garbage collection in the closure.
preloader = image = event = null;
}
);
})
.bind('error', function(event) {
// Since the load event is asynchronous, we have to
// tell AngularJS that something changed.
$rootScope.$apply(
function() {
preloader.handleImageError(event.target.src);
// Clean up object reference to help with the
// garbage collection in the closure.
preloader = image = event = null;
}
);
})
.attr('src', imageLocation);
}
};
// Return the factory instance.
return (Preloader);
}
);<|fim▁end|>
| |
<|file_name|>UserInput.py<|end_file_name|><|fim▁begin|>import os
import atexit
import string
import importlib
import threading
import socket
from time import sleep
def BYTE(message):
return bytes("%s\r\n" % message, "UTF-8")
class UserInput(threading.Thread):
isRunning = False
parent = None
def __init__(self, bot):
super().__init__()
self.parent = bot<|fim▁hole|> self.isRunning = False
self.start()
def createMessage(self, message):
temp = ""
for i in range(len(message)):
if (i != len(message) - 1):
temp += message[i] + " "
else:
temp += message[i]
return temp
def run(self):
self.isRunning = True
while (self.isRunning):
try:
message = input()
message = message.split(" ")
if (message[0] != ""):
if (message[0] == "/r" or message[0] == "/reload"):
self.parent.reloadAll()
elif (message[0] == "/q" or message[0] == "/quit"):
print("Quitting.")
self.parent.quit()
self.isRunning = False
elif (message[0] == "/j" or message[0] == "/join"):
if (len(message) < 2 or len(message) > 2):
print("Incorrect usage.")
else:
self.parent.switch(message[1])
elif (message[0] == "/l" or message[0] == "/leave"):
if (len(message) >= 2):
if (len(message) > 2):
for i in range(1, len(message)):
self.parent.leave(message[i], False)
if (len(self.parent.channels) > 0):
self.parent.focusedChannel = self.parent.channels[0]
print("Left channels. Focusing on %s" % self.parent.focusedChannel)
else:
print("No channels left.")
else:
self.parent.leave(message[1], False)
if (len(self.parent.channels) > 0):
self.parent.focusedChannel = self.parent.channels[0]
print("Left %s. Focusing on %s" % (message[1], self.parent.focusedChannel))
else:
print("No channels left.")
else:
print("Incorrect usage.")
elif (message[0] == "/?" or message[0] == "/help"):
print("1. Type anything to chat with others in %s." % self.parent.focusedChannel)
print("2. /? or /help -- Bring up the bot commands.")
print("3. /j or /join -- Join a new channel. Channel focus will switch over.")
print("4. /l or /leave -- Leave channel. Channel focus will change.")
print("5. /r or /reload -- Reload all plugins. (Hotswapping is supported.)")
print("6. /q or /quit -- Quit the bot.")
else:
self.parent.s.send(BYTE("PRIVMSG %s :%s" % (self.parent.focusedChannel, self.createMessage(message))))
except WindowsError as winError:
print(winError)
if (self.parent.s != None):
self.parent.s.close(socket.SHUT_RDWR)
self.parent.s = None
self.parent.connect()
except Exception as error:
print(error)<|fim▁end|>
|
self.setDaemon(True)
|
<|file_name|>hook-wx.lib.activex.py<|end_file_name|><|fim▁begin|>#-----------------------------------------------------------------------------
# Copyright (c) 2013-2016, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception<|fim▁hole|>#-----------------------------------------------------------------------------
from PyInstaller.utils.hooks import exec_statement
# This needed because comtypes wx.lib.activex generates some stuff.
exec_statement("import wx.lib.activex")<|fim▁end|>
|
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this software.
|
<|file_name|>commonUtils.js<|end_file_name|><|fim▁begin|>import dateformat from 'dateformat';
import { map } from "underscore";
import { getAccountById } from 'routes/root/routes/Banking/routes/Accounts/modules/accounts';
import { getCreditCardById, getPrepaidCardById } from 'routes/root/routes/Banking/routes/Cards/modules/cards';
import { getLoanById } from 'routes/root/routes/Banking/routes/Loans/modules/loans';
export const getDebitAccount = (debitAccountType, debitAccountId) => {
switch (debitAccountType) {
case "isAccount":
getAccountById(debitAccountId)
break;
case "isLoan":
getLoanById(debitAccountId)
break;
case "isCreditCard":
getCreditCardById(debitAccountId)
break;
case "isPrepaidCard":
getPrepaidCardById(debitAccountId)
break;
}
}
const findDebitAccount = (debitAccountType, debitAccountId, state) => {
let debitAccount = {};
switch (debitAccountType) {
case "isAccount":
debitAccount = state.accounts.accounts.filter((account) => account.id == debitAccountId)[0]
break;
case "isLoan":
debitAccount = state.loans.loans.filter((loan) => loan.id == debitAccountId)[0]
break;
case "isCreditCard":
debitAccount = state.cards.creditCards.filter((creditCard) => creditCard.id == debitAccountId)[0]
break;
case "isPrepaidCard":
debitAccount = state.cards.prepaidCards.filter((prepaidCard) => prepaidCard.id == debitAccountId)[0]
break;
}
return debitAccount;
}
export const getDebitAccountAvailableBalance = (debitAccountType, debitAccountId, state) => {
const debitAccount = findDebitAccount(debitAccountType, debitAccountId, state);
return getProductAvailableBalance(debitAccount, debitAccountType);
}
export const getProductAvailableBalance = (debitAccount, debitAccountType) => {
let availableBalance = 0;
switch (debitAccountType) {
case "isAccount":
availableBalance = debitAccount.ledgerBalance;
break;
case "isLoan":
case "isCreditCard":
case "isPrepaidCard":
availableBalance = debitAccount.availableBalance;
break;
}
return availableBalance;
}
export const getDebitAccountCurrency = (debitAccountType, debitAccountId, state) => {<|fim▁hole|> return new Date(date).setHours(0,0,0,0) >= new Date(dateformat()).setHours(0,0,0,0)
}
export const isValidInstallmentPaymentAmount = (product, amount, availableBalance) => {
return amount > 0 &&
(parseFloat(amount) <= product.nextInstallmentAmount ||
parseFloat(amount) <= product.debt) &&
parseFloat(amount) <= availableBalance
}
export const isValidInstallmentPaymentForm = (transactionForm) => {
return transactionForm.debitAccount.correct &&
transactionForm.amount.correct &&
transactionForm.date.correct
}
export const getPaymentType = (paymentMethod) => {
let paymentType = '';
switch (paymentMethod) {
case 'ΚΑΡΤΑ AGILE BANK':
paymentType = 'isCreditCardAgile';
break;
case 'ΚΑΡΤΑ ΑΛΛΗΣ ΤΡΑΠΕΖΗΣ':
paymentType = 'isCreditCardThirdParty';
break;
case 'ΔΑΝΕΙΟ AGILE BANK':
paymentType = 'isLoan';
break;
default:
paymentType = 'thirdPartyPayment';
}
return paymentType;
}
export const getCustomerName = (fullCustomerName) => {
return (fullCustomerName.firstName + ' ' + fullCustomerName.lastName)
.replace('ά', 'α')
.replace('έ', 'ε')
.replace('ί', 'ι')
.replace('ή', 'η')
.replace('ό', 'ο')
.replace('ύ', 'υ')
.replace('ώ', 'ω');
}
export const getActualFullName = (fullName, currentFullName) => {
const correctPattern = new RegExp("^[A-Za-zΑ-Ωα-ω ]+$");
return fullName = (correctPattern.test(fullName) || fullName == '' ? fullName : currentFullName).toUpperCase();
}
export const isValidFullName = (fullName) => fullName.split(' ').length == 2
export const isValidDebitAmount = (amount, availableBalance) => {
return amount > 0 && (parseFloat(amount)) <= availableBalance
}
export const isValidChargesBeneficiary = (beneficiary) => {
return beneficiary == 'both' || beneficiary == 'sender' || beneficiary == 'beneficiary'
}
export const findPaymentCharges = (paymentMethods, paymentName) => {
return map(paymentMethods, (paymentMethod) => paymentMethod.map(method => method))
.flatMap(paymentMethod => paymentMethod)
.filter(payment => payment.name == paymentName)[0].charges
}
export const findTransferCharges = (beneficiary) => {
let charges = 0;
switch (beneficiary) {
case 'both':
charges = 3;
break;
case 'sender':
charges = 6;
break;
case 'beneficiary':
charges = 0;
break;
}
return charges;
}
export const getImmediateText = (language) => {
let immediateText = '';
switch (language) {
case 'greek':
immediateText = 'ΑΜΕΣΑ';
break;
case 'english':
immediateText = 'IMMEDIATE';
break;
}
return immediateText;
}
export const formatCardNumber = (cardNumber) => {
return [...cardNumber].map(((num, key) => key % 4 == 0 && key != 0 ? ' ' + num : num ))
}<|fim▁end|>
|
return findDebitAccount(debitAccountType, debitAccountId, state).currency;
}
export const isValidDate = (date) => {
|
<|file_name|>format_ctree.rs<|end_file_name|><|fim▁begin|>use itertools::Itertools;
use std::fmt::Display;
use std::fs::OpenOptions;
use std::io::Write;
use std::ops::AddAssign;
use std::path::PathBuf;
use error::{Error, ResultExt};
use types::{CCode, CTree, Field, ToC};
#[derive(Debug, Default)]
pub struct CFilePair {
pub h: CCode, // for header file
pub c: CCode, // for cpp file
}
////////////////////////////////////////////////////////////////////////////////
impl CTree {
pub fn format(&self, file_name_base: &str) -> Result<CFilePair, Error> {
Ok(match *self {
CTree::IncludeH { ref path } => format_include_h(path),
CTree::IncludeSelf => format_include_self(file_name_base),
CTree::LiteralH(ref text) => CFilePair::with_h(text),
CTree::LiteralC(ref text) => CFilePair::with_c(text),
CTree::Group(ref vec) => format_group(vec, file_name_base)?,
CTree::Define {
ref name,
ref value,
} => format_define(name, value),
CTree::DefineIf {
ref name,
is_defined,
} => {
if is_defined {
format_define(name, &CCode::new())
} else {
CFilePair::new()
}
}
CTree::Ifndef {
ref conditional,
ref contents,
} => format_ifndef(conditional, contents, file_name_base)?,
CTree::ConstVar {
ref name,
ref value,
ref c_type,
is_extern,
} => format_const_var(name, value, c_type, is_extern),
CTree::Array {
ref name,
ref values,
ref c_type,
is_extern,
} => format_array(name, values, c_type, is_extern, false),
CTree::StdArray {
ref name,
ref values,
ref c_type,
is_extern,
} => format_array(name, values, c_type, is_extern, true),
CTree::EnumDecl {<|fim▁hole|> ref variants,
ref size,
} => format_enum_decl(name, variants, size),
CTree::StructInstance {
ref name,
ref c_type,
ref fields,
is_extern,
} => format_struct_instance(name, c_type, fields, is_extern),
CTree::Namespace {
ref name,
ref contents,
} => format_namespace(name, contents, file_name_base)?,
})
}
pub fn initializer(&self) -> CCode {
// TODO reorganize this. Is it really the best way to get struct
// initializers (for arrays of structs)?
match *self {
CTree::StructInstance { ref fields, .. } => {
format_struct_initializer(fields)
}
CTree::IncludeH { .. }
| CTree::IncludeSelf
| CTree::LiteralH(..)
| CTree::LiteralC(..)
| CTree::Group(..)
| CTree::Define { .. }
| CTree::DefineIf { .. }
| CTree::Ifndef { .. }
| CTree::ConstVar { .. }
| CTree::Array { .. }
| CTree::StdArray { .. }
| CTree::EnumDecl { .. }
| CTree::Namespace { .. } => unimplemented!(),
}
}
}
fn format_enum_decl(
name: &CCode,
variants: &[CCode],
size: &Option<CCode>,
) -> CFilePair {
let contents = variants
.iter()
.enumerate()
.fold(String::new(), |acc, (index, field)| {
format!("{} {} = {},\n", acc, field, index)
});
let inheritance = if let Some(ref parent_type) = size {
format!(" : {} ", parent_type)
} else {
String::new()
};
CFilePair {
h: CCode(format!(
"enum class {}{}{{\n{}}};\n\n",
name, inheritance, contents
)),
c: CCode::new(),
}
}
fn format_define(name: &CCode, value: &CCode) -> CFilePair {
// Name will be written in all-caps.
CFilePair {
h: CCode(format!("#define {} {}\n", name.to_uppercase(), value)),
c: CCode::new(),
}
}
fn format_include_h(path: &CCode) -> CFilePair {
CFilePair::with_h(format!("#include {}\n", path))
}
fn format_include_self(file_name_base: &str) -> CFilePair {
CFilePair::with_c(format!("#include \"{}.h\"\n", file_name_base))
}
fn format_ifndef(
conditional: &CCode,
contents: &CTree,
file_name_base: &str,
) -> Result<CFilePair, Error> {
let mut f = CFilePair::new();
f += CFilePair::with_h(format!("\n#ifndef {}\n", conditional));
f += contents.format(file_name_base)?;
f += CFilePair::with_h(format!("#endif // ifndef {}\n\n", conditional));
Ok(f)
}
fn format_namespace(
name: &CCode,
contents: &CTree,
file_name_base: &str,
) -> Result<CFilePair, Error> {
let open = format!("namespace {} {{\n", name).to_c();
let close = format!("\n}} // end namespace {}\n", name).to_c();
let mut f = CFilePair::with(&open);
f += contents.format(file_name_base)?;
f += CFilePair::with(&close);
Ok(f)
}
fn format_group(v: &[CTree], file_name_base: &str) -> Result<CFilePair, Error> {
let mut f = CFilePair::new();
for node in v {
f += node.format(file_name_base)?
}
Ok(f)
}
fn format_const_var(
name: &CCode,
value: &CCode,
c_type: &CCode,
is_extern: bool,
) -> CFilePair {
CFilePair {
h: if is_extern {
format!("extern const {} {};\n", c_type, name).to_c()
} else {
CCode::new()
},
c: CCode(format!("const {} {} = {};\n\n", c_type, name, value)),
}
}
fn format_struct_instance(
name: &CCode,
c_type: &CCode,
fields: &[Field],
is_extern: bool,
) -> CFilePair {
format_const_var(
name,
&format_struct_initializer(fields),
c_type,
is_extern,
)
}
fn format_struct_initializer(fields: &[Field]) -> CCode {
let mut lines = Vec::new();
lines.push("{".into());
for field in fields {
lines.push(format!(" {}, // {}", field.value, field.name));
}
lines.push("}".into());
CCode(lines.join("\n"))
}
fn format_array(
name: &CCode,
values: &[CCode],
c_type: &CCode,
is_extern: bool,
is_std: bool,
) -> CFilePair {
let length = values.len();
let h = if is_extern {
if is_std {
format!(
"extern const std::array<{},{}> {};\n",
c_type, length, name,
)
} else {
format!("extern const {} {}[{}];\n", c_type, name, length)
}
.to_c()
} else {
CCode::new()
};
let initializer = make_c_array_contents(values);
let c = if is_std {
format!(
"const std::array<{},{}> {} = {};\n",
c_type, length, name, initializer
)
} else {
format!(
"const {} {}[{}] = {};\n\n",
c_type, name, length, initializer
)
}
.to_c();
CFilePair { h, c }
}
fn make_c_array_contents<T>(v: &[T]) -> CCode
where
T: Display,
{
let lines = wrap_in_braces(&to_code_vec(v));
CCode::join(&lines, "\n")
}
fn wrap_in_braces(lines: &[CCode]) -> Vec<CCode> {
let mut new: Vec<_> =
lines.iter().map(|s| CCode(format!(" {}", s))).collect();
new.insert(0, "{".to_c());
new.push("}".to_c());
new
}
fn to_code_vec<T>(v: &[T]) -> Vec<CCode>
where
T: Display,
{
// TODO rename
let items_per_line = 4;
let mut lines: Vec<String> = Vec::new();
// TODO use slice chunks instead of itertools?
let chunks = &v.iter().map(|x| x.to_string()).chunks(items_per_line);
for chunk in chunks {
let tmp: Vec<_> = chunk.collect();
lines.push(tmp.join(", ") + ", ");
}
let code_lines: Vec<_> = lines.into_iter().map(CCode).collect();
code_lines
}
fn write_to_file(full_path: PathBuf, s: &CCode) -> Result<(), Error> {
// let path = Path::new(full_path);
let mut file = OpenOptions::new()
.create(true)
.write(true)
.open(full_path)
.context("Failed to open output file")?;
file.set_len(0).context("Failed to clear output file")?;
file.write_all(s.to_string().as_bytes())
.context("Failed to write to output file")?;
Ok(())
}
impl CFilePair {
pub fn new() -> Self {
Self {
h: CCode::new(),
c: CCode::new(),
}
}
pub fn with_c<T>(contents: T) -> Self
where
T: ToC,
{
Self {
h: CCode::new(),
c: contents.to_c(),
}
}
pub fn with_h<T>(contents: T) -> Self
where
T: ToC,
{
Self {
h: contents.to_c(),
c: CCode::new(),
}
}
pub fn with<T>(contents: T) -> Self
where
T: ToC,
{
let contents = contents.to_c();
Self {
h: contents.clone(),
c: contents,
}
}
pub fn append(&mut self, other: &Self) {
self.h += &other.h;
self.c += &other.c;
}
pub fn save(
&self,
directory: &PathBuf,
name_base: &str,
) -> Result<Vec<PathBuf>, Error> {
let mut path_base = directory.to_owned();
path_base.push(name_base);
let mut saved_paths = Vec::new();
// TODO if the c file tries to include an empty h file, it will fail to
// compile...
// TODO share code between c and h?
if !self.h.is_empty() {
let mut path = path_base.clone();
path.set_extension("h");
write_to_file(path.clone(), &self.h)?;
saved_paths.push(path);
}
if !self.c.is_empty() {
let mut path = path_base.clone();
path.set_extension("cpp");
write_to_file(path.clone(), &self.c)?;
saved_paths.push(path);
}
Ok(saved_paths)
}
}
impl AddAssign<CFilePair> for CFilePair {
fn add_assign(&mut self, rhs: CFilePair) {
self.append(&rhs)
}
}
impl<'a> AddAssign<&'a CFilePair> for CFilePair {
fn add_assign(&mut self, rhs: &'a CFilePair) {
self.append(rhs)
}
}<|fim▁end|>
|
ref name,
|
<|file_name|>test_api.py<|end_file_name|><|fim▁begin|># Copyright (c) 2014 Ben Swartzlander. All rights reserved.
# Copyright (c) 2014 Navneet Singh. All rights reserved.
# Copyright (c) 2014 Clinton Knight. All rights reserved.
# Copyright (c) 2014 Alex Meade. All rights reserved.
# Copyright (c) 2014 Bob Callaway. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Tests for NetApp API layer
"""
import ddt
from lxml import etree
import mock
from oslo_utils import netutils
import paramiko
import six
from six.moves import urllib
from cinder import exception
from cinder.i18n import _
from cinder import test
from cinder.tests.unit.volume.drivers.netapp.dataontap.client import (
fakes as zapi_fakes)
from cinder.volume.drivers.netapp.dataontap.client import api as netapp_api
@ddt.ddt
class NetAppApiServerTests(test.TestCase):
"""Test case for NetApp API server methods"""
def setUp(self):
self.root = netapp_api.NaServer('127.0.0.1')
super(NetAppApiServerTests, self).setUp()
@ddt.data(None, 'ftp')
def test_set_transport_type_value_error(self, transport_type):
"""Tests setting an invalid transport type"""
self.assertRaises(ValueError, self.root.set_transport_type,
transport_type)
@ddt.data({'params': {'transport_type': 'http',
'server_type_filer': 'filer'}},
{'params': {'transport_type': 'http',
'server_type_filer': 'xyz'}},
{'params': {'transport_type': 'https',
'server_type_filer': 'filer'}},
{'params': {'transport_type': 'https',
'server_type_filer': 'xyz'}})
@ddt.unpack
def test_set_transport_type_valid(self, params):
"""Tests setting a valid transport type"""
self.root._server_type = params['server_type_filer']
mock_invoke = self.mock_object(self.root, 'set_port')
self.root.set_transport_type(params['transport_type'])
expected_call_args = zapi_fakes.FAKE_CALL_ARGS_LIST
self.assertIn(mock_invoke.call_args, expected_call_args)
@ddt.data('stor', 'STORE', '')
def test_set_server_type_value_error(self, server_type):
"""Tests Value Error on setting the wrong server type"""
self.assertRaises(ValueError, self.root.set_server_type, server_type)
@ddt.data('!&', '80na', '')
def test_set_port__value_error(self, port):
"""Tests Value Error on trying to set port with a non-integer"""
self.assertRaises(ValueError, self.root.set_port, port)
@ddt.data('!&', '80na', '')
def test_set_timeout_value_error(self, timeout):
"""Tests Value Error on trying to set port with a non-integer"""
self.assertRaises(ValueError, self.root.set_timeout, timeout)
@ddt.data({'params': {'major': 1, 'minor': '20a'}},
{'params': {'major': '20a', 'minor': 1}},
{'params': {'major': '!*', 'minor': '20a'}})
@ddt.unpack
def test_set_api_version_value_error(self, params):
"""Tests Value Error on setting non-integer version"""
self.assertRaises(ValueError, self.root.set_api_version, **params)
def test_set_api_version_valid(self):
"""Tests Value Error on setting non-integer version"""
args = {'major': '20', 'minor': 1}
expected_call_args_list = [mock.call('20'), mock.call(1)]
mock_invoke = self.mock_object(six, 'text_type', return_value='str')
self.root.set_api_version(**args)
self.assertEqual(expected_call_args_list, mock_invoke.call_args_list)
@ddt.data({'params': {'result': zapi_fakes.FAKE_RESULT_API_ERR_REASON}},
{'params': {'result': zapi_fakes.FAKE_RESULT_API_ERRNO_INVALID}},
{'params': {'result': zapi_fakes.FAKE_RESULT_API_ERRNO_VALID}})
@ddt.unpack
def test_invoke_successfully_naapi_error(self, params):
"""Tests invoke successfully raising NaApiError"""
self.mock_object(self.root, 'send_http_request',
return_value=params['result'])
self.assertRaises(netapp_api.NaApiError,
self.root.invoke_successfully,
zapi_fakes.FAKE_NA_ELEMENT)
def test_invoke_successfully_no_error(self):
"""Tests invoke successfully with no errors"""
self.mock_object(self.root, 'send_http_request',
return_value=zapi_fakes.FAKE_RESULT_SUCCESS)
self.assertEqual(zapi_fakes.FAKE_RESULT_SUCCESS.to_string(),
self.root.invoke_successfully(
zapi_fakes.FAKE_NA_ELEMENT).to_string())
def test__create_request(self):
"""Tests method _create_request"""
self.root._ns = zapi_fakes.FAKE_XML_STR
self.root._api_version = '1.20'
self.mock_object(self.root, '_enable_tunnel_request')
self.mock_object(netapp_api.NaElement, 'add_child_elem')
self.mock_object(netapp_api.NaElement, 'to_string',
return_value=zapi_fakes.FAKE_XML_STR)
mock_invoke = self.mock_object(urllib.request, 'Request')
self.root._create_request(zapi_fakes.FAKE_NA_ELEMENT, True)
self.assertTrue(mock_invoke.called)
@ddt.data({'params': {'server': zapi_fakes.FAKE_NA_SERVER_API_1_5}},
{'params': {'server': zapi_fakes.FAKE_NA_SERVER_API_1_14}})
@ddt.unpack
def test__enable_tunnel_request__value_error(self, params):
"""Tests value errors with creating tunnel request"""
self.assertRaises(ValueError, params['server']._enable_tunnel_request,
'test')
def test__enable_tunnel_request_valid(self):
"""Tests creating tunnel request with correct values"""
netapp_elem = zapi_fakes.FAKE_NA_ELEMENT
server = zapi_fakes.FAKE_NA_SERVER_API_1_20
mock_invoke = self.mock_object(netapp_elem, 'add_attr')
expected_call_args = [mock.call('vfiler', 'filer'),
mock.call('vfiler', 'server')]
server._enable_tunnel_request(netapp_elem)
self.assertEqual(expected_call_args, mock_invoke.call_args_list)
def test__parse_response__naapi_error(self):
"""Tests NaApiError on no response"""
self.assertRaises(netapp_api.NaApiError,
self.root._parse_response, None)
def test__parse_response_no_error(self):
"""Tests parse function with appropriate response"""
mock_invoke = self.mock_object(etree, 'XML', return_value='xml')
self.root._parse_response(zapi_fakes.FAKE_XML_STR)
mock_invoke.assert_called_with(zapi_fakes.FAKE_XML_STR)
def test__build_opener_not_implemented_error(self):
"""Tests whether certificate style authorization raises Exception"""
self.root._auth_style = 'not_basic_auth'
self.assertRaises(NotImplementedError, self.root._build_opener)
def test__build_opener_valid(self):
"""Tests whether build opener works with valid parameters"""
self.root._auth_style = 'basic_auth'
mock_invoke = self.mock_object(urllib.request, 'build_opener')
self.root._build_opener()
self.assertTrue(mock_invoke.called)
@ddt.data(None, zapi_fakes.FAKE_XML_STR)
def test_send_http_request_value_error(self, na_element):
"""Tests whether invalid NaElement parameter causes error"""
self.assertRaises(ValueError, self.root.send_http_request, na_element)
def test_send_http_request_http_error(self):
"""Tests handling of HTTPError"""
na_element = zapi_fakes.FAKE_NA_ELEMENT
self.mock_object(self.root, '_create_request',
return_value=('abc', zapi_fakes.FAKE_NA_ELEMENT))
self.mock_object(netapp_api, 'LOG')
self.root._opener = zapi_fakes.FAKE_HTTP_OPENER
self.mock_object(self.root, '_build_opener')
self.mock_object(self.root._opener, 'open',
side_effect=urllib.error.HTTPError(url='', hdrs='',
fp=None,
code='401',
msg='httperror'))
self.assertRaises(netapp_api.NaApiError, self.root.send_http_request,
na_element)
def test_send_http_request_unknown_exception(self):
"""Tests handling of Unknown Exception"""
na_element = zapi_fakes.FAKE_NA_ELEMENT
self.mock_object(self.root, '_create_request',
return_value=('abc', zapi_fakes.FAKE_NA_ELEMENT))
mock_log = self.mock_object(netapp_api, 'LOG')
self.root._opener = zapi_fakes.FAKE_HTTP_OPENER
self.mock_object(self.root, '_build_opener')
self.mock_object(self.root._opener, 'open', side_effect=Exception)
self.assertRaises(netapp_api.NaApiError, self.root.send_http_request,
na_element)
self.assertEqual(1, mock_log.exception.call_count)
def test_send_http_request_valid(self):
"""Tests the method send_http_request with valid parameters"""
na_element = zapi_fakes.FAKE_NA_ELEMENT
self.mock_object(self.root, '_create_request',
return_value=('abc', zapi_fakes.FAKE_NA_ELEMENT))
self.mock_object(netapp_api, 'LOG')
self.root._opener = zapi_fakes.FAKE_HTTP_OPENER
self.mock_object(self.root, '_build_opener')
self.mock_object(self.root, '_get_result',
return_value=zapi_fakes.FAKE_NA_ELEMENT)
opener_mock = self.mock_object(self.root._opener, 'open')
opener_mock.read.side_effect = ['resp1', 'resp2']
self.root.send_http_request(na_element)
@ddt.data('192.168.1.0', '127.0.0.1', '0.0.0.0',
'::ffff:8', 'fdf8:f53b:82e4::53', '2001::1',
'fe80::200::abcd', '2001:0000:4136:e378:8000:63bf:3fff:fdd2')
def test__get_url(self, host):
port = '80'
root = netapp_api.NaServer(host, port=port)
protocol = root.TRANSPORT_TYPE_HTTP
url = root.URL_FILER
if netutils.is_valid_ipv6(host):
host = netutils.escape_ipv6(host)
result = '%s://%s:%s/%s' % (protocol, host, port, url)
url = root._get_url()
self.assertEqual(result, url)
class NetAppApiElementTransTests(test.TestCase):
"""Test case for NetApp API element translations."""
def test_translate_struct_dict_unique_key(self):
"""Tests if dict gets properly converted to NaElements."""
root = netapp_api.NaElement('root')
child = {'e1': 'v1', 'e2': 'v2', 'e3': 'v3'}
root.translate_struct(child)
self.assertEqual(3, len(root.get_children()))
self.assertEqual('v1', root.get_child_content('e1'))
self.assertEqual('v2', root.get_child_content('e2'))
self.assertEqual('v3', root.get_child_content('e3'))
def test_translate_struct_dict_nonunique_key(self):
"""Tests if list/dict gets properly converted to NaElements."""
root = netapp_api.NaElement('root')
child = [{'e1': 'v1', 'e2': 'v2'}, {'e1': 'v3'}]
root.translate_struct(child)
self.assertEqual(3, len(root.get_children()))
children = root.get_children()
for c in children:
if c.get_name() == 'e1':
self.assertIn(c.get_content(), ['v1', 'v3'])
else:
self.assertEqual('v2', c.get_content())
def test_translate_struct_list(self):
"""Tests if list gets properly converted to NaElements."""
root = netapp_api.NaElement('root')
child = ['e1', 'e2']
root.translate_struct(child)
self.assertEqual(2, len(root.get_children()))
self.assertIsNone(root.get_child_content('e1'))
self.assertIsNone(root.get_child_content('e2'))
def test_translate_struct_tuple(self):
"""Tests if tuple gets properly converted to NaElements."""
root = netapp_api.NaElement('root')
child = ('e1', 'e2')
root.translate_struct(child)
self.assertEqual(2, len(root.get_children()))
self.assertIsNone(root.get_child_content('e1'))
self.assertIsNone(root.get_child_content('e2'))
def test_translate_invalid_struct(self):
"""Tests if invalid data structure raises exception."""
root = netapp_api.NaElement('root')
child = 'random child element'
self.assertRaises(ValueError, root.translate_struct, child)
def test_setter_builtin_types(self):
"""Tests str, int, float get converted to NaElement."""
root = netapp_api.NaElement('root')
root['e1'] = 'v1'
root['e2'] = 1
root['e3'] = 2.0
root['e4'] = 8
self.assertEqual(4, len(root.get_children()))
self.assertEqual('v1', root.get_child_content('e1'))
self.assertEqual('1', root.get_child_content('e2'))
self.assertEqual('2.0', root.get_child_content('e3'))
self.assertEqual('8', root.get_child_content('e4'))
def test_setter_na_element(self):
"""Tests na_element gets appended as child."""
root = netapp_api.NaElement('root')
root['e1'] = netapp_api.NaElement('nested')
self.assertEqual(1, len(root.get_children()))
e1 = root.get_child_by_name('e1')
self.assertIsInstance(e1, netapp_api.NaElement)
self.assertIsInstance(e1.get_child_by_name('nested'),
netapp_api.NaElement)
def test_setter_child_dict(self):
"""Tests dict is appended as child to root."""
root = netapp_api.NaElement('root')
root['d'] = {'e1': 'v1', 'e2': 'v2'}
e1 = root.get_child_by_name('d')
self.assertIsInstance(e1, netapp_api.NaElement)
sub_ch = e1.get_children()
self.assertEqual(2, len(sub_ch))
for c in sub_ch:
self.assertIn(c.get_name(), ['e1', 'e2'])
if c.get_name() == 'e1':
self.assertEqual('v1', c.get_content())
else:
self.assertEqual('v2', c.get_content())
def test_setter_child_list_tuple(self):
"""Tests list/tuple are appended as child to root."""
root = netapp_api.NaElement('root')
root['l'] = ['l1', 'l2']
root['t'] = ('t1', 't2')<|fim▁hole|> t = root.get_child_by_name('t')
self.assertIsInstance(t, netapp_api.NaElement)
for le in l.get_children():
self.assertIn(le.get_name(), ['l1', 'l2'])
for te in t.get_children():
self.assertIn(te.get_name(), ['t1', 't2'])
def test_setter_no_value(self):
"""Tests key with None value."""
root = netapp_api.NaElement('root')
root['k'] = None
self.assertIsNone(root.get_child_content('k'))
def test_setter_invalid_value(self):
"""Tests invalid value raises exception."""
root = netapp_api.NaElement('root')
try:
root['k'] = netapp_api.NaServer('localhost')
except Exception as e:
if not isinstance(e, TypeError):
self.fail(_('Error not a TypeError.'))
def test_setter_invalid_key(self):
"""Tests invalid value raises exception."""
root = netapp_api.NaElement('root')
try:
root[None] = 'value'
except Exception as e:
if not isinstance(e, KeyError):
self.fail(_('Error not a KeyError.'))
def test_getter_key_error(self):
"""Tests invalid key raises exception"""
root = netapp_api.NaElement('root')
self.mock_object(root, 'get_child_by_name', return_value=None)
self.mock_object(root, 'has_attr', return_value=None)
self.assertRaises(KeyError,
netapp_api.NaElement.__getitem__,
root, '123')
def test_getter_na_element_list(self):
"""Tests returning NaElement list"""
root = netapp_api.NaElement('root')
root['key'] = ['val1', 'val2']
self.assertEqual(root.get_child_by_name('key').get_name(),
root.__getitem__('key').get_name())
def test_getter_child_text(self):
"""Tests NaElement having no children"""
root = netapp_api.NaElement('root')
root.set_content('FAKE_CONTENT')
self.mock_object(root, 'get_child_by_name', return_value=root)
self.assertEqual('FAKE_CONTENT',
root.__getitem__('root'))
def test_getter_child_attr(self):
"""Tests invalid key raises exception"""
root = netapp_api.NaElement('root')
root.add_attr('val', 'FAKE_VALUE')
self.assertEqual('FAKE_VALUE',
root.__getitem__('val'))
def test_add_node_with_children(self):
"""Tests adding a child node with its own children"""
root = netapp_api.NaElement('root')
self.mock_object(netapp_api.NaElement,
'create_node_with_children',
return_value=zapi_fakes.FAKE_INVOKE_DATA)
mock_invoke = self.mock_object(root, 'add_child_elem')
root.add_node_with_children('options')
mock_invoke.assert_called_with(zapi_fakes.FAKE_INVOKE_DATA)
def test_create_node_with_children(self):
"""Tests adding a child node with its own children"""
root = netapp_api.NaElement('root')
self.mock_object(root, 'add_new_child', return_value='abc')
result_xml = str(root.create_node_with_children(
'options', test1=zapi_fakes.FAKE_XML_STR,
test2=zapi_fakes.FAKE_XML_STR))
# No ordering is guaranteed for elements in this XML.
self.assertTrue(result_xml.startswith("<options>"), result_xml)
self.assertTrue("<test1>abc</test1>" in result_xml, result_xml)
self.assertTrue("<test2>abc</test2>" in result_xml, result_xml)
self.assertTrue(result_xml.rstrip().endswith("</options>"), result_xml)
def test_add_new_child(self):
"""Tests adding a child node with its own children"""
root = netapp_api.NaElement('root')
self.mock_object(netapp_api.NaElement,
'_convert_entity_refs',
return_value=zapi_fakes.FAKE_INVOKE_DATA)
root.add_new_child('options', zapi_fakes.FAKE_INVOKE_DATA)
self.assertEqual(zapi_fakes.FAKE_XML2, root.to_string())
def test_get_attr_names_empty_attr(self):
"""Tests _elements.attrib being empty"""
root = netapp_api.NaElement('root')
self.assertEqual([], root.get_attr_names())
def test_get_attr_names(self):
"""Tests _elements.attrib being non-empty"""
root = netapp_api.NaElement('root')
root.add_attr('attr1', 'a1')
root.add_attr('attr2', 'a2')
self.assertEqual(['attr1', 'attr2'], root.get_attr_names())
@ddt.ddt
class SSHUtilTests(test.TestCase):
"""Test Cases for SSH API invocation."""
def setUp(self):
super(SSHUtilTests, self).setUp()
self.mock_object(netapp_api.SSHUtil, '_init_ssh_pool')
self.sshutil = netapp_api.SSHUtil('127.0.0.1',
'fake_user',
'fake_password')
def test_execute_command(self):
ssh = mock.Mock(paramiko.SSHClient)
stdin, stdout, stderr = self._mock_ssh_channel_files(
paramiko.ChannelFile)
self.mock_object(ssh, 'exec_command',
return_value=(stdin, stdout, stderr))
wait_on_stdout = self.mock_object(self.sshutil, '_wait_on_stdout')
stdout_read = self.mock_object(stdout, 'read', return_value='')
self.sshutil.execute_command(ssh, 'ls')
wait_on_stdout.assert_called_once_with(stdout,
netapp_api.SSHUtil.RECV_TIMEOUT)
stdout_read.assert_called_once_with()
def test_execute_read_exception(self):
ssh = mock.Mock(paramiko.SSHClient)
exec_command = self.mock_object(ssh, 'exec_command')
exec_command.side_effect = paramiko.SSHException('Failure')
wait_on_stdout = self.mock_object(self.sshutil, '_wait_on_stdout')
self.assertRaises(paramiko.SSHException,
self.sshutil.execute_command, ssh, 'ls')
wait_on_stdout.assert_not_called()
@ddt.data('Password:',
'Password: ',
'Password: \n\n')
def test_execute_command_with_prompt(self, response):
ssh = mock.Mock(paramiko.SSHClient)
stdin, stdout, stderr = self._mock_ssh_channel_files(paramiko.Channel)
stdout_read = self.mock_object(stdout.channel, 'recv',
return_value=response)
stdin_write = self.mock_object(stdin, 'write')
self.mock_object(ssh, 'exec_command',
return_value=(stdin, stdout, stderr))
wait_on_stdout = self.mock_object(self.sshutil, '_wait_on_stdout')
self.sshutil.execute_command_with_prompt(ssh, 'sudo ls',
'Password:', 'easypass')
wait_on_stdout.assert_called_once_with(stdout,
netapp_api.SSHUtil.RECV_TIMEOUT)
stdout_read.assert_called_once_with(999)
stdin_write.assert_called_once_with('easypass' + '\n')
def test_execute_command_unexpected_response(self):
ssh = mock.Mock(paramiko.SSHClient)
stdin, stdout, stderr = self._mock_ssh_channel_files(paramiko.Channel)
stdout_read = self.mock_object(stdout.channel, 'recv',
return_value='bad response')
self.mock_object(ssh, 'exec_command',
return_value=(stdin, stdout, stderr))
wait_on_stdout = self.mock_object(self.sshutil, '_wait_on_stdout')
self.assertRaises(exception.VolumeBackendAPIException,
self.sshutil.execute_command_with_prompt,
ssh, 'sudo ls', 'Password:', 'easypass')
wait_on_stdout.assert_called_once_with(stdout,
netapp_api.SSHUtil.RECV_TIMEOUT)
stdout_read.assert_called_once_with(999)
def test_wait_on_stdout(self):
stdout = mock.Mock()
stdout.channel = mock.Mock(paramiko.Channel)
exit_status = self.mock_object(stdout.channel, 'exit_status_ready',
return_value=False)
self.sshutil._wait_on_stdout(stdout, 1)
exit_status.assert_any_call()
self.assertGreater(exit_status.call_count, 2)
def _mock_ssh_channel_files(self, channel):
stdin = mock.Mock()
stdin.channel = mock.Mock(channel)
stdout = mock.Mock()
stdout.channel = mock.Mock(channel)
stderr = mock.Mock()
stderr.channel = mock.Mock(channel)
return stdin, stdout, stderr<|fim▁end|>
|
l = root.get_child_by_name('l')
self.assertIsInstance(l, netapp_api.NaElement)
|
<|file_name|>first_run.js<|end_file_name|><|fim▁begin|>/**
* @fileOverview first_run.js shows the necessary navigation and
* design elements to be integrated into the privly-applications
* bundle.
*/
/**
* Initialize the applications by showing and hiding the proper
* elements.
*/
function init() {
// Set the nav bar to the proper domain
privlyNetworkService.initializeNavigation();
privlyNetworkService.initPrivlyService(
privlyNetworkService.contentServerDomain(),
privlyNetworkService.showLoggedInNav,
privlyNetworkService.showLoggedOutNav
);
$("#messages").hide();
$("#form").show();
// Show a preview of the tooltip to the user
$("#tooltip").append(Privly.glyph.getGlyphDOM())
.show()
.append("<br/><br/><p>This is your Privly Glyph</p>");
}
// Initialize the application<|fim▁hole|><|fim▁end|>
|
document.addEventListener('DOMContentLoaded', init);
|
<|file_name|>profile.js<|end_file_name|><|fim▁begin|>angular.module('gitphaser').controller('ProfileController', ProfileCtrl);
/**
* @ngdoc object
* @module gitphaser
* @name gitphaser.object:ProfileCtrl
* @description Exposes GitHub.me profile object or account object to the profile template.
* Governs the `/tab/profile` and `others/:username` routes.
*/
function ProfileCtrl ($scope, $stateParams, $state, $cordovaInAppBrowser, GitHub, account) {
var self = this;
self.browser = $cordovaInAppBrowser;
/**
* @ngdoc object
* @propertyOf gitphaser.object:ProfileCtrl
* @name gitphaser..object:ProfileCtrl.modalOpen
* @description `Boolean`: Triggers appearance changes in the template when
* a contact modal opens. See 'contact' directive.
*/
self.modalOpen = false;
<|fim▁hole|> if (account) {
self.user = account.info;
self.repos = account.repos;
self.events = account.events;
self.viewTitle = account.info.login;
self.state = $state;
self.nav = true;
self.canFollow = GitHub.canFollow(account.info.login);
// The user's own profile
} else {
self.user = GitHub.me;
self.repos = GitHub.repos;
self.events = GitHub.events;
self.viewTitle = GitHub.me.login;
self.canFollow = false;
self.nav = false;
}
// Info logic: There are four optional profile fields
// and two spaces to show them in. In order of importance:
// 1. Company, 2. Blog, 3. Email, 4. Location
self.company = self.user.company;
self.email = self.user.email;
self.blog = self.user.blog;
self.location = self.user.location;
// Case: both exist - no space
if (self.company && self.email) {
self.blog = false;
self.location = false;
// Case: One exists - one space, pick blog, or location
} else if ((!self.company && self.email) || (self.company && !self.email)) {
(self.blog) ? self.location = false : true;
}
/**
* @ngdoc method
* @methodOf gitphaser.object:ProfileCtrl
* @name gitphaser.object:ProfileCtrl.back
* @description Navigates back to `$stateParams.origin`. For nav back arrow visible in the `others`
* route.
*/
self.back = function () {
if ($stateParams.origin === 'nearby') $state.go('tab.nearby');
if ($stateParams.origin === 'notifications') $state.go('tab.notifications');
};
/**
* @ngdoc method
* @methodOf gitphaser.object:ProfileCtrl
* @name gitphaser.object:ProfileCtrl.follow
* @description Wraps `GitHub.follow` and hides the follow button when clicked.
*/
self.follow = function () {
self.canFollow = false;
GitHub.follow(self.user);
};
}<|fim▁end|>
|
// Arbitrary profile
|
<|file_name|>0base.js<|end_file_name|><|fim▁begin|>checkRolesInFunction = function (doRole, userId) {
if (!Meteor.userId() || ENUM.getUserById(userId))
throw ENUM.ERROR(403);
};
getSelector = function (selector) {
var baseSelector = {
delete_flg: {$ne: 1}
};
return _.extend(baseSelector, selector);
};
detectEnv = function(){
var appFolder = process.env.PWD;
var lastEnv = "";<|fim▁hole|> if (appFolder === addr){
return env;
}
if (addr === "default"){
lastEnv = env;
}
}
return lastEnv;
};
getSettings = function(){
var env = detectEnv();
return Meteor.settings[env];
}<|fim▁end|>
|
for (let env in Meteor.settings.env_address){
var addr = Meteor.settings.env_address[env]
|
<|file_name|>http.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""PySide port of the network/http example from Qt v4.x"""
import sys
from PySide import QtCore, QtGui, QtNetwork
class HttpWindow(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, parent)
self.urlLineEdit = QtGui.QLineEdit("http://www.ietf.org/iesg/1rfc_index.txt")
self.urlLabel = QtGui.QLabel(self.tr("&URL:"))
self.urlLabel.setBuddy(self.urlLineEdit)
self.statusLabel = QtGui.QLabel(self.tr("Please enter the URL of a file "
"you want to download."))
self.quitButton = QtGui.QPushButton(self.tr("Quit"))
self.downloadButton = QtGui.QPushButton(self.tr("Download"))
self.downloadButton.setDefault(True)
self.progressDialog = QtGui.QProgressDialog(self)
self.http = QtNetwork.QHttp(self)
self.outFile = None
self.httpGetId = 0
self.httpRequestAborted = False
self.connect(self.urlLineEdit, QtCore.SIGNAL("textChanged(QString &)"),
self.enableDownloadButton)
self.connect(self.http, QtCore.SIGNAL("requestFinished(int, bool)"),
self.httpRequestFinished)
self.connect(self.http, QtCore.SIGNAL("dataReadProgress(int, int)"),
self.updateDataReadProgress)
self.connect(self.http, QtCore.SIGNAL("responseHeaderReceived(QHttpResponseHeader &)"),
self.readResponseHeader)
self.connect(self.progressDialog, QtCore.SIGNAL("canceled()"),
self.cancelDownload)
self.connect(self.downloadButton, QtCore.SIGNAL("clicked()"),
self.downloadFile)
self.connect(self.quitButton, QtCore.SIGNAL("clicked()"),
self, QtCore.SLOT("close()"))
topLayout = QtGui.QHBoxLayout()
topLayout.addWidget(self.urlLabel)
topLayout.addWidget(self.urlLineEdit)
buttonLayout = QtGui.QHBoxLayout()
buttonLayout.addStretch(1)
buttonLayout.addWidget(self.downloadButton)
buttonLayout.addWidget(self.quitButton)
mainLayout = QtGui.QVBoxLayout()
mainLayout.addLayout(topLayout)
mainLayout.addWidget(self.statusLabel)
mainLayout.addLayout(buttonLayout)
self.setLayout(mainLayout)
self.setWindowTitle(self.tr("HTTP"))
self.urlLineEdit.setFocus()
def downloadFile(self):
url = QtCore.QUrl(self.urlLineEdit.text())
fileInfo = QtCore.QFileInfo(url.path())
fileName = fileInfo.fileName()
if QtCore.QFile.exists(fileName):
QtGui.QMessageBox.information(self, self.tr("HTTP"), self.tr(
"There already exists a file called %s "
"in the current directory.") % (fileName))
return
self.outFile = QtCore.QFile(fileName)
if not self.outFile.open(QtCore.QIODevice.WriteOnly):
QtGui.QMessageBox.information(self, self.tr("HTTP"),
self.tr("Unable to save the file %(name)s: %(error)s.")
% {'name': fileName,
'error': self.outFile.errorString()})
self.outFile = None
return
<|fim▁hole|> else:
self.http.setHost(url.host(), 80)
if url.userName():
self.http.setUser(url.userName(), url.password())
self.httpRequestAborted = False
self.httpGetId = self.http.get(url.path(), self.outFile)
self.progressDialog.setWindowTitle(self.tr("HTTP"))
self.progressDialog.setLabelText(self.tr("Downloading %s.") % (fileName))
self.downloadButton.setEnabled(False)
def cancelDownload(self):
self.statusLabel.setText(self.tr("Download canceled."))
self.httpRequestAborted = True
self.http.abort()
self.downloadButton.setEnabled(True)
def httpRequestFinished(self, requestId, error):
if self.httpRequestAborted:
if self.outFile is not None:
self.outFile.close()
self.outFile.remove()
self.outFile = None
self.progressDialog.hide()
return
if requestId != self.httpGetId:
return
self.progressDialog.hide()
self.outFile.close()
if error:
self.outFile.remove()
QtGui.QMessageBox.information(self, self.tr("HTTP"),
self.tr("Download failed: %s.")
% (self.http.errorString()))
else:
fileName = QtCore.QFileInfo(QtCore.QUrl(self.urlLineEdit.text()).path()).fileName()
self.statusLabel.setText(self.tr("Downloaded %s to current directory.") % (fileName))
self.downloadButton.setEnabled(True)
self.outFile = None
def readResponseHeader(self, responseHeader):
if responseHeader.statusCode() != 200:
QtGui.QMessageBox.information(self, self.tr("HTTP"),
self.tr("Download failed: %s.")
% (responseHeader.reasonPhrase()))
self.httpRequestAborted = True
self.progressDialog.hide()
self.http.abort()
return
def updateDataReadProgress(self, bytesRead, totalBytes):
if self.httpRequestAborted:
return
self.progressDialog.setMaximum(totalBytes)
self.progressDialog.setValue(bytesRead)
def enableDownloadButton(self):
self.downloadButton.setEnabled(not self.urlLineEdit.text())
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
httpWin = HttpWindow()
sys.exit(httpWin.exec_())<|fim▁end|>
|
if url.port() != -1:
self.http.setHost(url.host(), url.port())
|
<|file_name|>factories.py<|end_file_name|><|fim▁begin|>import factory
from .models import User
USER_PASSWORD = "2fast2furious"<|fim▁hole|> name = "John Doe"
email = factory.Sequence(lambda n: "john{}@example.com".format(n))
password = factory.PostGenerationMethodCall('set_password', USER_PASSWORD)
gender = "male"
class Meta:
model = User<|fim▁end|>
|
class UserFactory(factory.DjangoModelFactory):
|
<|file_name|>saddle.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
import petsc4py
import sys
petsc4py.init(sys.argv)
from petsc4py import PETSc
Print = PETSc.Sys.Print
# from MatrixOperations import *
from dolfin import *
import numpy as np
import matplotlib.pylab as plt
import scipy.sparse as sps
import scipy.sparse.linalg as slinalg
import os
import scipy.io
import PETScIO as IO
import MatrixOperations as MO
def StoreMatrix(A,name):
test ="".join([name,".mat"])
scipy.io.savemat( test, {name: A},oned_as='row')
parameters['num_threads'] = 10
m = 6
errL2b =np.zeros((m-1,1))
errCurlb =np.zeros((m-1,1))
errL2r =np.zeros((m-1,1))
errH1r =np.zeros((m-1,1))
l2border = np.zeros((m-1,1))
Curlborder =np.zeros((m-1,1))
# set_log_level(DEBUG)
NN = np.zeros((m-1,1))
DoF = np.zeros((m-1,1))
Vdim = np.zeros((m-1,1))
Qdim = np.zeros((m-1,1))
Wdim = np.zeros((m-1,1))
iterations = np.zeros((m-1,1))
SolTime = np.zeros((m-1,1))
udiv = np.zeros((m-1,1))
MU = np.zeros((m-1,1))
nn = 2
dim = 2
Solving = 'Direct'
ShowResultPlots = 'yes'
ShowErrorPlots = 'no'
EigenProblem = 'no'
SavePrecond = 'no'
CheckMu = 'no'
case = 4
parameters['linear_algebra_backend'] = 'uBLAS'
MU[0]= 1e0
for xx in xrange(1,m):
print xx
nn = 2**(xx)/2
if (CheckMu == 'yes'):
if (xx != 1):
MU[xx-1] = MU[xx-2]/10
else:
if (xx != 1):
MU[xx-1] = MU[xx-2]
# Create mesh and define function space
nn = int(nn)
NN[xx-1] = nn
parameters["form_compiler"]["quadrature_degree"] = 3
parameters["form_compiler"]["optimize"] = True
parameters["form_compiler"]["representation"] = 'quadrature'
# mesh = BoxMesh(-1,-1,-1,1, 1, 1, nn, nn, nn)
mesh = UnitCubeMesh(nn,nn,nn)
parameters['reorder_dofs_serial'] = False
V = FunctionSpace(mesh, "N1curl",2)
Q = FunctionSpace(mesh, "CG",2)
Vdim[xx-1] = V.dim()
print "\n\n\n V-dim", V.dim()
def boundary(x, on_boundary):
return on_boundary
if case == 1:
u0 = Expression(("x[1]*x[1]*(x[1]-1)","x[0]*x[0]*(x[0]-1)","0"))
elif case == 2:
u0 = Expression(("sin(2*pi*x[1])*cos(2*pi*x[0])","-sin(2*pi*x[0])*cos(2*pi*x[1])"))
elif case == 3:
u0 = Expression(("x[0]*x[0]*(x[0]-1)","x[1]*x[1]*(x[1]-1)","0"))
elif case == 4:
u0 = Expression(("x[0]*x[1]*x[2]*(x[0]-1)","x[0]*x[1]*x[2]*(x[1]-1)","x[0]*x[1]*x[2]*(x[2]-1)"))
bcs = DirichletBC(V,u0, boundary)
# (u1) = TrialFunctions(V)
# (v1) = TestFunctions(V)
c = .5
if case == 1:
# f= Expression(("(8*pow(pi,2)-C)*sin(2*pi*x[1])*cos(2*pi*x[0])","-(8*pow(pi,2)-C)*sin(2*pi*x[0])*cos(2*pi*x[1])"),C = c)
f = Expression(("-6*x[1]+2","-6*x[0]+2"))+c*u0
elif case == 2:
f = 8*pow(pi,2)*u0+c*u0
elif case == 3:
f = Expression(("0","0","0"),C = c)
f = c*u0
elif case == 4:
f = Expression(("x[2]*(2*x[1]-1)+x[1]*(2*x[2]-1)","x[0]*(2*x[2]-1)+x[2]*(2*x[0]-1)","x[1]*(2*x[0]-1)+x[0]*(2*x[1]-1)"))+c*u0
(u) = TrialFunction(V)
(v) = TestFunction(V)
a = dot(curl(u),curl(v))*dx+c*inner(u, v)*dx
L1 = inner(v, f)*dx
tic()
AA, bb = assemble_system(a, L1, bcs)
As = AA.sparray()
StoreMatrix(As,'A')
A = PETSc.Mat().createAIJ(size=As.shape,csr=(As.indptr, As.indices, As.data))
# exit
# A = as_backend_type(AA).mat()
print toc()
b = bb.array()
zeros = 0*b
x = IO.arrayToVec(zeros)
bb = IO.arrayToVec(b)
if (Solving == 'Direct'):
ksp = PETSc.KSP().create()
ksp.setOperators(A)
ksp.setFromOptions()
ksp.setType(ksp.Type.PREONLY)
ksp.pc.setType(ksp.pc.Type.LU)
# print 'Solving with:', ksp.getType()
# Solve!
tic()
ksp.solve(bb, x)
SolTime[xx-1] = toc()
print "time to solve: ",SolTime[xx-1]
del AA
if (Solving == 'Iterative' or Solving == 'Direct'):
if case == 1:
ue = Expression(("x[1]*x[1]*(x[1]-1)","x[0]*x[0]*(x[0]-1)"))
elif case == 2:
ue = Expression(("sin(2*pi*x[1])*cos(2*pi*x[0])","-sin(2*pi*x[0])*cos(2*pi*x[1])"))
elif case == 3:
ue=u0
elif case == 4:
ue=u0
Ve = FunctionSpace(mesh, "N1curl",4)
u = interpolate(ue,Ve)
Nv = u.vector().array().shape
X = IO.vecToArray(x)
x = X[0:Nv[0]]
ua = Function(V)
ua.vector()[:] = x
parameters["form_compiler"]["quadrature_degree"] = 4
parameters["form_compiler"]["optimize"] = True
ErrorB = Function(V)
ErrorB.vector()[:] = interpolate(ue,V).vector().array()-ua.vector().array()
errL2b[xx-1] = sqrt(assemble(inner(ErrorB, ErrorB)*dx))
errCurlb[xx-1] = sqrt(assemble(inner(curl(ErrorB), curl(ErrorB))*dx))
if xx == 1:
a = 1
else:
l2border[xx-1] = np.abs(np.log2(errL2b[xx-2]/errL2b[xx-1]))
Curlborder[xx-1] = np.abs(np.log2(errCurlb[xx-2]/errCurlb[xx-1]))
print errL2b[xx-1]
print errCurlb[xx-1]
import pandas as pd
print "\n\n Magnetic convergence"
MagneticTitles = ["Total DoF","Soln Time","B-L2","B-order","B-Curl","Curl-order"]
MagneticValues = np.concatenate((Vdim,SolTime,errL2b,l2border,errCurlb,Curlborder),axis=1)
MagneticTable= pd.DataFrame(MagneticValues, columns = MagneticTitles)
pd.set_option('precision',3)
MagneticTable = MO.PandasFormat(MagneticTable,"B-Curl","%2.4e")
MagneticTable = MO.PandasFormat(MagneticTable,'B-L2',"%2.4e")
print MagneticTable
<|fim▁hole|>
if (SavePrecond == 'yes'):
scipy.io.savemat('eigenvalues/Wdim.mat', {'Wdim':Wdim-1},oned_as = 'row')
if (ShowResultPlots == 'yes'):
plot(ua)
plot(interpolate(ue,V))
interactive()<|fim▁end|>
| |
<|file_name|>round.js<|end_file_name|><|fim▁begin|>/*jslint browser: true, devel: true, node: true, ass: true, nomen: true, unparam: true, indent: 4 */
/**
* @license
* Copyright (c) 2015 The ExpandJS authors. All rights reserved.
* This code may only be used under the BSD style license found at https://expandjs.github.io/LICENSE.txt
* The complete set of authors may be found at https://expandjs.github.io/AUTHORS.txt
* The complete set of contributors may be found at https://expandjs.github.io/CONTRIBUTORS.txt
*/
(function () {
"use strict";
var assertArgument = require('../assert/assertArgument'),
isVoid = require('../tester/isVoid'),
isFinite = require('../tester/isFinite'),
isIndex = require('../tester/isIndex');
/**
* Rounds up a number to the nearest integet. If a second parameter is
* specified the number can be rounded using digits after the decimal point.
*
* ```js
* XP.round(1.2)
* // => 1
*
* XP.round(1.5)
* // => 2
*
* XP.fixed(1.49, 1)
* // => 1.5
*
* XP.round(1.492, 2)
* // => 1.49
*
* XP.round(1.499, 2)<|fim▁hole|> * // => 1.5
* ```
*
* @function round
* @param {number} number The reference number to format
* @param {number} [precision = 0] The number of digits to be shown after the decimal point
* @returns {number} Returns the number rounded up
*/
module.exports = function round(number, precision) {
assertArgument(isFinite(number), 1, 'number');
assertArgument(isVoid(precision) || isIndex(precision), 2, 'number');
return Math.round(number * (precision = Math.pow(10, precision || 0))) / precision;
};
}());<|fim▁end|>
| |
<|file_name|>test_kubernetes_pod_operator_backcompat.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import json
import sys
import unittest
from unittest import mock
from unittest.mock import patch
import kubernetes.client.models as k8s
import pendulum
import pytest
from kubernetes.client.api_client import ApiClient
from kubernetes.client.rest import ApiException
from airflow.exceptions import AirflowException
from airflow.kubernetes import kube_client
from airflow.kubernetes.pod import Port
from airflow.kubernetes.pod_runtime_info_env import PodRuntimeInfoEnv
from airflow.kubernetes.secret import Secret
from airflow.kubernetes.volume import Volume
from airflow.kubernetes.volume_mount import VolumeMount
from airflow.models import DAG, TaskInstance
from airflow.providers.cncf.kubernetes.operators.kubernetes_pod import KubernetesPodOperator
from airflow.providers.cncf.kubernetes.utils.pod_launcher import PodLauncher
from airflow.providers.cncf.kubernetes.utils.xcom_sidecar import PodDefaults
from airflow.utils import timezone
from airflow.utils.state import State
from airflow.version import version as airflow_version
from kubernetes_tests.test_base import EXECUTOR
# noinspection DuplicatedCode
def create_context(task):
dag = DAG(dag_id="dag")
tzinfo = pendulum.timezone("Europe/Amsterdam")
execution_date = timezone.datetime(2016, 1, 1, 1, 0, 0, tzinfo=tzinfo)
task_instance = TaskInstance(task=task, execution_date=execution_date)
task_instance.xcom_push = mock.Mock()
return {
"dag": dag,
"ts": execution_date.isoformat(),
"task": task,
"ti": task_instance,
"task_instance": task_instance,
}
# noinspection DuplicatedCode,PyUnusedLocal
@pytest.mark.skipif(EXECUTOR != 'KubernetesExecutor', reason="Only runs on KubernetesExecutor")
class TestKubernetesPodOperatorSystem(unittest.TestCase):
def get_current_task_name(self):
# reverse test name to make pod name unique (it has limited length)
return "_" + unittest.TestCase.id(self).replace(".", "_")[::-1]
def setUp(self):
self.maxDiff = None
self.api_client = ApiClient()
self.expected_pod = {
'apiVersion': 'v1',
'kind': 'Pod',
'metadata': {
'namespace': 'default',
'name': mock.ANY,
'annotations': {},
'labels': {
'foo': 'bar',
'kubernetes_pod_operator': 'True',
'airflow_version': airflow_version.replace('+', '-'),
'execution_date': '2016-01-01T0100000100-a2f50a31f',
'dag_id': 'dag',
'task_id': 'task',
'try_number': '1',
},
},
'spec': {
'affinity': {},
'containers': [
{
'image': 'ubuntu:16.04',
'args': ["echo 10"],
'command': ["bash", "-cx"],
'env': [],
'envFrom': [],
'resources': {},
'name': 'base',
'ports': [],
'volumeMounts': [],
}
],
'hostNetwork': False,
'imagePullSecrets': [],
'initContainers': [],
'nodeSelector': {},
'restartPolicy': 'Never',
'securityContext': {},
'tolerations': [],
'volumes': [],
},
}
def tearDown(self):
client = kube_client.get_kube_client(in_cluster=False)
client.delete_collection_namespaced_pod(namespace="default")
@mock.patch("airflow.providers.cncf.kubernetes.utils.pod_launcher.PodLauncher.start_pod")
@mock.patch("airflow.providers.cncf.kubernetes.utils.pod_launcher.PodLauncher.monitor_pod")
@mock.patch("airflow.kubernetes.kube_client.get_kube_client")
def test_image_pull_secrets_correctly_set(self, mock_client, monitor_mock, start_mock):
fake_pull_secrets = "fakeSecret"
k = KubernetesPodOperator(
namespace='default',
image="ubuntu:16.04",
cmds=["bash", "-cx"],
arguments=["echo 10"],
labels={"foo": "bar"},
name="test",
task_id="task",
in_cluster=False,
do_xcom_push=False,
image_pull_secrets=fake_pull_secrets,
cluster_context='default',
)
monitor_mock.return_value = (State.SUCCESS, None, None)
context = create_context(k)
k.execute(context=context)
assert start_mock.call_args[0][0].spec.image_pull_secrets == [
k8s.V1LocalObjectReference(name=fake_pull_secrets)
]
def test_working_pod(self):
k = KubernetesPodOperator(
namespace='default',
image="ubuntu:16.04",
cmds=["bash", "-cx"],
arguments=["echo 10"],
labels={"foo": "bar"},
name="test",
task_id="task",
in_cluster=False,
do_xcom_push=False,
)
context = create_context(k)
k.execute(context)
actual_pod = self.api_client.sanitize_for_serialization(k.pod)
assert self.expected_pod['spec'] == actual_pod['spec']
assert self.expected_pod['metadata']['labels'] == actual_pod['metadata']['labels']
def test_pod_node_selectors(self):
node_selectors = {'beta.kubernetes.io/os': 'linux'}
k = KubernetesPodOperator(
namespace='default',
image="ubuntu:16.04",
cmds=["bash", "-cx"],
arguments=["echo 10"],
labels={"foo": "bar"},
name="test",
task_id="task",
in_cluster=False,
do_xcom_push=False,
node_selectors=node_selectors,
)
context = create_context(k)
k.execute(context)
actual_pod = self.api_client.sanitize_for_serialization(k.pod)
self.expected_pod['spec']['nodeSelector'] = node_selectors
assert self.expected_pod == actual_pod
def test_pod_resources(self):
resources = {
'limit_cpu': 0.25,
'limit_memory': '64Mi',
'limit_ephemeral_storage': '2Gi',
'request_cpu': '250m',
'request_memory': '64Mi',
'request_ephemeral_storage': '1Gi',
}
k = KubernetesPodOperator(
namespace='default',
image="ubuntu:16.04",
cmds=["bash", "-cx"],
arguments=["echo 10"],
labels={"foo": "bar"},
name="test",
task_id="task",
in_cluster=False,
do_xcom_push=False,
resources=resources,
)
context = create_context(k)
k.execute(context)
actual_pod = self.api_client.sanitize_for_serialization(k.pod)
self.expected_pod['spec']['containers'][0]['resources'] = {
'requests': {'memory': '64Mi', 'cpu': '250m', 'ephemeral-storage': '1Gi'},
'limits': {'memory': '64Mi', 'cpu': 0.25, 'ephemeral-storage': '2Gi'},
}
assert self.expected_pod == actual_pod
def test_pod_affinity(self):
affinity = {
'nodeAffinity': {<|fim▁hole|> 'nodeSelectorTerms': [
{
'matchExpressions': [
{'key': 'beta.kubernetes.io/os', 'operator': 'In', 'values': ['linux']}
]
}
]
}
}
}
k = KubernetesPodOperator(
namespace='default',
image="ubuntu:16.04",
cmds=["bash", "-cx"],
arguments=["echo 10"],
labels={"foo": "bar"},
name="test",
task_id="task",
in_cluster=False,
do_xcom_push=False,
affinity=affinity,
)
context = create_context(k)
k.execute(context=context)
actual_pod = self.api_client.sanitize_for_serialization(k.pod)
self.expected_pod['spec']['affinity'] = affinity
assert self.expected_pod == actual_pod
def test_port(self):
port = Port('http', 80)
k = KubernetesPodOperator(
namespace='default',
image="ubuntu:16.04",
cmds=["bash", "-cx"],
arguments=["echo 10"],
labels={"foo": "bar"},
name="test",
task_id="task",
in_cluster=False,
do_xcom_push=False,
ports=[port],
)
context = create_context(k)
k.execute(context=context)
actual_pod = self.api_client.sanitize_for_serialization(k.pod)
self.expected_pod['spec']['containers'][0]['ports'] = [{'name': 'http', 'containerPort': 80}]
assert self.expected_pod == actual_pod
def test_volume_mount(self):
with patch.object(PodLauncher, 'log') as mock_logger:
volume_mount = VolumeMount(
'test-volume', mount_path='/tmp/test_volume', sub_path=None, read_only=False
)
volume_config = {'persistentVolumeClaim': {'claimName': 'test-volume'}}
volume = Volume(name='test-volume', configs=volume_config)
args = [
"echo \"retrieved from mount\" > /tmp/test_volume/test.txt "
"&& cat /tmp/test_volume/test.txt"
]
k = KubernetesPodOperator(
namespace='default',
image="ubuntu:16.04",
cmds=["bash", "-cx"],
arguments=args,
labels={"foo": "bar"},
volume_mounts=[volume_mount],
volumes=[volume],
is_delete_operator_pod=False,
name="test",
task_id="task",
in_cluster=False,
do_xcom_push=False,
)
context = create_context(k)
k.execute(context=context)
mock_logger.info.assert_any_call('retrieved from mount')
actual_pod = self.api_client.sanitize_for_serialization(k.pod)
self.expected_pod['spec']['containers'][0]['args'] = args
self.expected_pod['spec']['containers'][0]['volumeMounts'] = [
{'name': 'test-volume', 'mountPath': '/tmp/test_volume', 'readOnly': False}
]
self.expected_pod['spec']['volumes'] = [
{'name': 'test-volume', 'persistentVolumeClaim': {'claimName': 'test-volume'}}
]
assert self.expected_pod == actual_pod
def test_run_as_user_root(self):
security_context = {
'securityContext': {
'runAsUser': 0,
}
}
k = KubernetesPodOperator(
namespace='default',
image="ubuntu:16.04",
cmds=["bash", "-cx"],
arguments=["echo 10"],
labels={"foo": "bar"},
name="test",
task_id="task",
in_cluster=False,
do_xcom_push=False,
security_context=security_context,
)
context = create_context(k)
k.execute(context)
actual_pod = self.api_client.sanitize_for_serialization(k.pod)
self.expected_pod['spec']['securityContext'] = security_context
assert self.expected_pod == actual_pod
def test_run_as_user_non_root(self):
security_context = {
'securityContext': {
'runAsUser': 1000,
}
}
k = KubernetesPodOperator(
namespace='default',
image="ubuntu:16.04",
cmds=["bash", "-cx"],
arguments=["echo 10"],
labels={"foo": "bar"},
name="test",
task_id="task",
in_cluster=False,
do_xcom_push=False,
security_context=security_context,
)
context = create_context(k)
k.execute(context)
actual_pod = self.api_client.sanitize_for_serialization(k.pod)
self.expected_pod['spec']['securityContext'] = security_context
assert self.expected_pod == actual_pod
def test_fs_group(self):
security_context = {
'securityContext': {
'fsGroup': 1000,
}
}
k = KubernetesPodOperator(
namespace='default',
image="ubuntu:16.04",
cmds=["bash", "-cx"],
arguments=["echo 10"],
labels={"foo": "bar"},
name="test",
task_id="task",
in_cluster=False,
do_xcom_push=False,
security_context=security_context,
)
context = create_context(k)
k.execute(context)
actual_pod = self.api_client.sanitize_for_serialization(k.pod)
self.expected_pod['spec']['securityContext'] = security_context
assert self.expected_pod == actual_pod
def test_faulty_service_account(self):
bad_service_account_name = "foobar"
k = KubernetesPodOperator(
namespace='default',
image="ubuntu:16.04",
cmds=["bash", "-cx"],
arguments=["echo 10"],
labels={"foo": "bar"},
name="test",
task_id="task",
in_cluster=False,
do_xcom_push=False,
startup_timeout_seconds=5,
service_account_name=bad_service_account_name,
)
with pytest.raises(ApiException):
context = create_context(k)
k.execute(context)
actual_pod = self.api_client.sanitize_for_serialization(k.pod)
self.expected_pod['spec']['serviceAccountName'] = bad_service_account_name
assert self.expected_pod == actual_pod
def test_pod_failure(self):
"""
Tests that the task fails when a pod reports a failure
"""
bad_internal_command = ["foobar 10 "]
k = KubernetesPodOperator(
namespace='default',
image="ubuntu:16.04",
cmds=["bash", "-cx"],
arguments=bad_internal_command,
labels={"foo": "bar"},
name="test",
task_id="task",
in_cluster=False,
do_xcom_push=False,
)
with pytest.raises(AirflowException):
context = create_context(k)
k.execute(context)
actual_pod = self.api_client.sanitize_for_serialization(k.pod)
self.expected_pod['spec']['containers'][0]['args'] = bad_internal_command
assert self.expected_pod == actual_pod
def test_xcom_push(self):
return_value = '{"foo": "bar"\n, "buzz": 2}'
args = [f'echo \'{return_value}\' > /airflow/xcom/return.json']
k = KubernetesPodOperator(
namespace='default',
image="ubuntu:16.04",
cmds=["bash", "-cx"],
arguments=args,
labels={"foo": "bar"},
name="test",
task_id="task",
in_cluster=False,
do_xcom_push=True,
)
context = create_context(k)
assert k.execute(context) == json.loads(return_value)
actual_pod = self.api_client.sanitize_for_serialization(k.pod)
volume = self.api_client.sanitize_for_serialization(PodDefaults.VOLUME)
volume_mount = self.api_client.sanitize_for_serialization(PodDefaults.VOLUME_MOUNT)
container = self.api_client.sanitize_for_serialization(PodDefaults.SIDECAR_CONTAINER)
self.expected_pod['spec']['containers'][0]['args'] = args
self.expected_pod['spec']['containers'][0]['volumeMounts'].insert(0, volume_mount)
self.expected_pod['spec']['volumes'].insert(0, volume)
self.expected_pod['spec']['containers'].append(container)
assert self.expected_pod == actual_pod
@mock.patch("airflow.providers.cncf.kubernetes.utils.pod_launcher.PodLauncher.start_pod")
@mock.patch("airflow.providers.cncf.kubernetes.utils.pod_launcher.PodLauncher.monitor_pod")
@mock.patch("airflow.kubernetes.kube_client.get_kube_client")
def test_envs_from_configmaps(self, mock_client, mock_monitor, mock_start):
# GIVEN
configmap = 'test-configmap'
# WHEN
k = KubernetesPodOperator(
namespace='default',
image="ubuntu:16.04",
cmds=["bash", "-cx"],
arguments=["echo 10"],
labels={"foo": "bar"},
name="test",
task_id="task",
in_cluster=False,
do_xcom_push=False,
configmaps=[configmap],
)
# THEN
mock_monitor.return_value = (State.SUCCESS, None, None)
context = create_context(k)
k.execute(context)
assert mock_start.call_args[0][0].spec.containers[0].env_from == [
k8s.V1EnvFromSource(config_map_ref=k8s.V1ConfigMapEnvSource(name=configmap))
]
@mock.patch("airflow.providers.cncf.kubernetes.utils.pod_launcher.PodLauncher.start_pod")
@mock.patch("airflow.providers.cncf.kubernetes.utils.pod_launcher.PodLauncher.monitor_pod")
@mock.patch("airflow.kubernetes.kube_client.get_kube_client")
def test_envs_from_secrets(self, mock_client, monitor_mock, start_mock):
# GIVEN
secret_ref = 'secret_name'
secrets = [Secret('env', None, secret_ref)]
# WHEN
k = KubernetesPodOperator(
namespace='default',
image="ubuntu:16.04",
cmds=["bash", "-cx"],
arguments=["echo 10"],
secrets=secrets,
labels={"foo": "bar"},
name="test",
task_id="task",
in_cluster=False,
do_xcom_push=False,
)
# THEN
monitor_mock.return_value = (State.SUCCESS, None, None)
context = create_context(k)
k.execute(context)
assert start_mock.call_args[0][0].spec.containers[0].env_from == [
k8s.V1EnvFromSource(secret_ref=k8s.V1SecretEnvSource(name=secret_ref))
]
def test_env_vars(self):
# WHEN
k = KubernetesPodOperator(
namespace='default',
image="ubuntu:16.04",
cmds=["bash", "-cx"],
arguments=["echo 10"],
env_vars={
"ENV1": "val1",
"ENV2": "val2",
},
pod_runtime_info_envs=[PodRuntimeInfoEnv("ENV3", "status.podIP")],
labels={"foo": "bar"},
name="test",
task_id="task",
in_cluster=False,
do_xcom_push=False,
)
context = create_context(k)
k.execute(context)
# THEN
actual_pod = self.api_client.sanitize_for_serialization(k.pod)
self.expected_pod['spec']['containers'][0]['env'] = [
{'name': 'ENV1', 'value': 'val1'},
{'name': 'ENV2', 'value': 'val2'},
{'name': 'ENV3', 'valueFrom': {'fieldRef': {'fieldPath': 'status.podIP'}}},
]
assert self.expected_pod == actual_pod
def test_pod_template_file_with_overrides_system(self):
fixture = sys.path[0] + '/tests/kubernetes/basic_pod.yaml'
k = KubernetesPodOperator(
task_id="task" + self.get_current_task_name(),
labels={"foo": "bar", "fizz": "buzz"},
env_vars={"env_name": "value"},
in_cluster=False,
pod_template_file=fixture,
do_xcom_push=True,
)
context = create_context(k)
result = k.execute(context)
assert result is not None
assert k.pod.metadata.labels == {
'fizz': 'buzz',
'foo': 'bar',
'airflow_version': mock.ANY,
'dag_id': 'dag',
'execution_date': mock.ANY,
'kubernetes_pod_operator': 'True',
'task_id': mock.ANY,
'try_number': '1',
}
assert k.pod.spec.containers[0].env == [k8s.V1EnvVar(name="env_name", value="value")]
assert result == {"hello": "world"}
def test_init_container(self):
# GIVEN
volume_mounts = [
k8s.V1VolumeMount(mount_path='/etc/foo', name='test-volume', sub_path=None, read_only=True)
]
init_environments = [
k8s.V1EnvVar(name='key1', value='value1'),
k8s.V1EnvVar(name='key2', value='value2'),
]
init_container = k8s.V1Container(
name="init-container",
image="ubuntu:16.04",
env=init_environments,
volume_mounts=volume_mounts,
command=["bash", "-cx"],
args=["echo 10"],
)
volume_config = {'persistentVolumeClaim': {'claimName': 'test-volume'}}
volume = Volume(name='test-volume', configs=volume_config)
expected_init_container = {
'name': 'init-container',
'image': 'ubuntu:16.04',
'command': ['bash', '-cx'],
'args': ['echo 10'],
'env': [{'name': 'key1', 'value': 'value1'}, {'name': 'key2', 'value': 'value2'}],
'volumeMounts': [{'mountPath': '/etc/foo', 'name': 'test-volume', 'readOnly': True}],
}
k = KubernetesPodOperator(
namespace='default',
image="ubuntu:16.04",
cmds=["bash", "-cx"],
arguments=["echo 10"],
labels={"foo": "bar"},
name="test",
task_id="task",
volumes=[volume],
init_containers=[init_container],
in_cluster=False,
do_xcom_push=False,
)
context = create_context(k)
k.execute(context)
actual_pod = self.api_client.sanitize_for_serialization(k.pod)
self.expected_pod['spec']['initContainers'] = [expected_init_container]
self.expected_pod['spec']['volumes'] = [
{'name': 'test-volume', 'persistentVolumeClaim': {'claimName': 'test-volume'}}
]
assert self.expected_pod == actual_pod<|fim▁end|>
|
'requiredDuringSchedulingIgnoredDuringExecution': {
|
<|file_name|>flag.go<|end_file_name|><|fim▁begin|>package cli
import (
"flag"
"fmt"
"os"
"strconv"
"strings"
"time"
)
// This flag enables bash-completion for all commands and subcommands
var BashCompletionFlag = BoolFlag{
Name: "generate-bash-completion",
Hide: true,
}
// This flag prints the version for the application
var VersionFlag = BoolFlag{
Name: "version, v",
Usage: "print the version",
}
// This flag prints the help for all commands and subcommands
// Set to the zero value (BoolFlag{}) to disable flag -- keeps subcommand
// unless HideHelp is set to true)
var HelpFlag = BoolFlag{
Name: "help, h",
Usage: "show help",
Hide: true,
}
// Flag is a common interface related to parsing flags in cli.
// For more advanced flag parsing techniques, it is recomended that
// this interface be implemented.
type Flag interface {
fmt.Stringer
// Apply Flag settings to the given flag set
Apply(*flag.FlagSet)
getName() string
isNotHidden() bool
}
func flagSet(name string, flags []Flag) *flag.FlagSet {
set := flag.NewFlagSet(name, flag.ContinueOnError)
for _, f := range flags {
f.Apply(set)
}
return set
}
func eachName(longName string, fn func(string)) {
parts := strings.Split(longName, ",")
for _, name := range parts {
name = strings.Trim(name, " ")
fn(name)
}
}
// Generic is a generic parseable type identified by a specific flag
type Generic interface {
Set(value string) error
String() string
}
// GenericFlag is the flag type for types implementing Generic
type GenericFlag struct {
Name string
Value Generic
Usage string
EnvVar string
Hide bool
}
// String returns the string representation of the generic flag to display the
// help text to the user (uses the String() method of the generic flag to show
// the value)
func (f GenericFlag) String() string {
return withEnvHint(f.EnvVar, fmt.Sprintf("%s%s \"%v\"\t%v", prefixFor(f.Name), f.Name, f.Value, f.Usage))
}
// Apply takes the flagset and calls Set on the generic flag with the value
// provided by the user for parsing by the flag
func (f GenericFlag) Apply(set *flag.FlagSet) {
val := f.Value
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal := os.Getenv(envVar); envVal != "" {
val.Set(envVal)
break
}
}
}
eachName(f.Name, func(name string) {
set.Var(f.Value, name, f.Usage)
})
}
func (f GenericFlag) getName() string {
return f.Name
}
func (f GenericFlag) isNotHidden() bool {
return !f.Hide
}
type StringSlice []string
func (f *StringSlice) Set(value string) error {
*f = append(*f, value)
return nil
}
func (f *StringSlice) String() string {
return fmt.Sprintf("%s", *f)
}
func (f *StringSlice) Value() []string {
return *f
}
type StringSliceFlag struct {
Name string
Value *StringSlice
Usage string
EnvVar string
Hide bool
}
func (f StringSliceFlag) String() string {
firstName := strings.Trim(strings.Split(f.Name, ",")[0], " ")
pref := prefixFor(firstName)
return withEnvHint(f.EnvVar, fmt.Sprintf("%s [%v]\t%v", prefixedNames(f.Name), pref+firstName+" option "+pref+firstName+" option", f.Usage))
}
func (f StringSliceFlag) Apply(set *flag.FlagSet) {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal := os.Getenv(envVar); envVal != "" {
newVal := &StringSlice{}
for _, s := range strings.Split(envVal, ",") {
s = strings.TrimSpace(s)
newVal.Set(s)
}
f.Value = newVal
break
}
}
}
eachName(f.Name, func(name string) {
set.Var(f.Value, name, f.Usage)
})
}
func (f StringSliceFlag) getName() string {
return f.Name
}
func (f StringSliceFlag) isNotHidden() bool {
return !f.Hide
}
type IntSlice []int
func (f *IntSlice) Set(value string) error {
tmp, err := strconv.Atoi(value)
if err != nil {
return err
} else {
*f = append(*f, tmp)
}
return nil
}
func (f *IntSlice) String() string {
return fmt.Sprintf("%d", *f)
}
func (f *IntSlice) Value() []int {
return *f
}
type IntSliceFlag struct {
Name string
Value *IntSlice
Usage string
EnvVar string
Hide bool
}
func (f IntSliceFlag) String() string {
firstName := strings.Trim(strings.Split(f.Name, ",")[0], " ")
pref := prefixFor(firstName)
return withEnvHint(f.EnvVar, fmt.Sprintf("%s [%v]\t%v", prefixedNames(f.Name), pref+firstName+" option "+pref+firstName+" option", f.Usage))
}
func (f IntSliceFlag) Apply(set *flag.FlagSet) {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal := os.Getenv(envVar); envVal != "" {
newVal := &IntSlice{}
for _, s := range strings.Split(envVal, ",") {
s = strings.TrimSpace(s)
err := newVal.Set(s)
if err != nil {
fmt.Fprintf(os.Stderr, err.Error())
}
}
f.Value = newVal
break
}
}
}
eachName(f.Name, func(name string) {
set.Var(f.Value, name, f.Usage)
})
}
func (f IntSliceFlag) getName() string {
return f.Name
}
func (f IntSliceFlag) isNotHidden() bool {
return !f.Hide
}
type BoolFlag struct {
Name string
Usage string
EnvVar string
Hide bool
}
func (f BoolFlag) String() string {
return withEnvHint(f.EnvVar, fmt.Sprintf("%s\t%v", prefixedNames(f.Name), f.Usage))
}
func (f BoolFlag) Apply(set *flag.FlagSet) {
val := false
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal := os.Getenv(envVar); envVal != "" {
envValBool, err := strconv.ParseBool(envVal)
if err == nil {
val = envValBool
}
break
}
}
}
eachName(f.Name, func(name string) {
set.Bool(name, val, f.Usage)
})
}
func (f BoolFlag) getName() string {
return f.Name
}
func (f BoolFlag) isNotHidden() bool {
return !f.Hide
}
type BoolTFlag struct {
Name string
Usage string
EnvVar string
Hide bool
}
func (f BoolTFlag) String() string {
return withEnvHint(f.EnvVar, fmt.Sprintf("%s\t%v", prefixedNames(f.Name), f.Usage))
}
func (f BoolTFlag) Apply(set *flag.FlagSet) {
val := true
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal := os.Getenv(envVar); envVal != "" {
envValBool, err := strconv.ParseBool(envVal)
if err == nil {
val = envValBool
break
}
}
}
}
eachName(f.Name, func(name string) {
set.Bool(name, val, f.Usage)
})
}
func (f BoolTFlag) getName() string {
return f.Name
}
func (f BoolTFlag) isNotHidden() bool {
return !f.Hide
}
type StringFlag struct {
Name string
Value string
Usage string
EnvVar string
Hide bool
}
func (f StringFlag) String() string {
var fmtString string
fmtString = "%s %v\t%v"
if len(f.Value) > 0 {
fmtString = "%s \"%v\"\t%v"
} else {
fmtString = "%s %v\t%v"
}
return withEnvHint(f.EnvVar, fmt.Sprintf(fmtString, prefixedNames(f.Name), f.Value, f.Usage))
}
func (f StringFlag) Apply(set *flag.FlagSet) {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal := os.Getenv(envVar); envVal != "" {
f.Value = envVal
break
}
}
}
eachName(f.Name, func(name string) {
set.String(name, f.Value, f.Usage)
})
}
func (f StringFlag) getName() string {
return f.Name
}
func (f StringFlag) isNotHidden() bool {
return !f.Hide
}
type IntFlag struct {
Name string
Value int
Usage string
EnvVar string
Hide bool
}
func (f IntFlag) String() string {
return withEnvHint(f.EnvVar, fmt.Sprintf("%s \"%v\"\t%v", prefixedNames(f.Name), f.Value, f.Usage))
}
func (f IntFlag) Apply(set *flag.FlagSet) {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal := os.Getenv(envVar); envVal != "" {
envValInt, err := strconv.ParseInt(envVal, 0, 64)<|fim▁hole|> if err == nil {
f.Value = int(envValInt)
break
}
}
}
}
eachName(f.Name, func(name string) {
set.Int(name, f.Value, f.Usage)
})
}
func (f IntFlag) getName() string {
return f.Name
}
func (f IntFlag) isNotHidden() bool {
return !f.Hide
}
type DurationFlag struct {
Name string
Value time.Duration
Usage string
EnvVar string
Hide bool
}
func (f DurationFlag) String() string {
return withEnvHint(f.EnvVar, fmt.Sprintf("%s \"%v\"\t%v", prefixedNames(f.Name), f.Value, f.Usage))
}
func (f DurationFlag) Apply(set *flag.FlagSet) {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal := os.Getenv(envVar); envVal != "" {
envValDuration, err := time.ParseDuration(envVal)
if err == nil {
f.Value = envValDuration
break
}
}
}
}
eachName(f.Name, func(name string) {
set.Duration(name, f.Value, f.Usage)
})
}
func (f DurationFlag) getName() string {
return f.Name
}
func (f DurationFlag) isNotHidden() bool {
return !f.Hide
}
type Float64Flag struct {
Name string
Value float64
Usage string
EnvVar string
Hide bool
}
func (f Float64Flag) String() string {
return withEnvHint(f.EnvVar, fmt.Sprintf("%s \"%v\"\t%v", prefixedNames(f.Name), f.Value, f.Usage))
}
func (f Float64Flag) Apply(set *flag.FlagSet) {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal := os.Getenv(envVar); envVal != "" {
envValFloat, err := strconv.ParseFloat(envVal, 10)
if err == nil {
f.Value = float64(envValFloat)
}
}
}
}
eachName(f.Name, func(name string) {
set.Float64(name, f.Value, f.Usage)
})
}
func (f Float64Flag) getName() string {
return f.Name
}
func (f Float64Flag) isNotHidden() bool {
return !f.Hide
}
func prefixFor(name string) (prefix string) {
if len(name) == 1 {
prefix = "-"
} else {
prefix = "--"
}
return
}
func prefixedNames(fullName string) (prefixed string) {
parts := strings.Split(fullName, ",")
for i, name := range parts {
name = strings.Trim(name, " ")
prefixed += prefixFor(name) + name
if i < len(parts)-1 {
prefixed += ", "
}
}
return
}
func withEnvHint(envVar, str string) string {
envText := ""
if envVar != "" {
envText = fmt.Sprintf(" [$%s]", strings.Join(strings.Split(envVar, ","), ", $"))
}
return str + envText
}<|fim▁end|>
| |
<|file_name|>die-macro.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Just testing that fail!() type checks in statement or expr
#![allow(unreachable_code)]
fn f() {
fail!();<|fim▁hole|> let _x: int = fail!();
}
pub fn main() {
}<|fim▁end|>
| |
<|file_name|>play.js<|end_file_name|><|fim▁begin|>// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
(function() {
"use strict";
var runFunc;
var count = 0;
function getId() {
return "code" + (count++);
}
function text(node) {
var s = "";
for (var i = 0; i < node.childNodes.length; i++) {
var n = node.childNodes[i];
if (n.nodeType === 1 && n.tagName === "SPAN" && n.className != "number") {
var innerText = n.innerText === undefined ? "textContent" : "innerText";
s += n[innerText] + "\n";
continue;
}
if (n.nodeType === 1 && n.tagName !== "BUTTON") {
s += text(n);
}
}
return s;
}
function init(code) {
var id = getId();
var output = document.createElement('div');
var outpre = document.createElement('pre');
var stopFunc;
function onKill() {
if (stopFunc) {
stopFunc();
}
}
function onRun(e) {
onKill();
outpre.innerHTML = "";
output.style.display = "block";
run.style.display = "none";
var options = {Race: e.shiftKey};
stopFunc = runFunc(text(code), outpre, options);
}
function onClose() {
onKill();
output.style.display = "none";
run.style.display = "inline-block";
}
var run = document.createElement('button');
run.innerHTML = 'Run';
run.className = 'run';
run.addEventListener("click", onRun, false);
var run2 = document.createElement('button');
run2.className = 'run';
run2.innerHTML = 'Run';
run2.addEventListener("click", onRun, false);
var kill = document.createElement('button');
kill.className = 'kill';
kill.innerHTML = 'Kill';
kill.addEventListener("click", onKill, false);
var close = document.createElement('button');
close.className = 'close';
close.innerHTML = 'Close';
close.addEventListener("click", onClose, false);
var button = document.createElement('div');
button.classList.add('buttons');
button.appendChild(run);
// Hack to simulate insertAfter
code.parentNode.insertBefore(button, code.nextSibling);
var buttons = document.createElement('div');
buttons.classList.add('buttons');
buttons.appendChild(run2);
buttons.appendChild(kill);<|fim▁hole|> buttons.appendChild(close);
output.classList.add('output');
output.appendChild(buttons);
output.appendChild(outpre);
output.style.display = "none";
code.parentNode.insertBefore(output, button.nextSibling);
}
var play = document.querySelectorAll('div.playground');
for (var i = 0; i < play.length; i++) {
init(play[i]);
}
if (play.length > 0) {
if (window.connectPlayground) {
runFunc = window.connectPlayground("ws://" + window.location.host + "/socket");
} else {
// If this message is logged,
// we have neglected to include socket.js or playground.js.
console.log("No playground transport available.");
}
}
})();<|fim▁end|>
| |
<|file_name|>extent.rs<|end_file_name|><|fim▁begin|>//
// Copyright 2016 Andrew Hunter
//
// 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.
//
use super::address::*;
///
/// An extent represents a series of nodes starting at a specified node
///
#[derive(Clone, Copy, PartialEq)]
pub enum TreeExtent {
/// Just the initial node
ThisNode,
/// The children of this node<|fim▁hole|> /// This does not extend beyond the immediate children of the current node.
Children,
/// The entire subtree (all children, and their children, and so on)
///
/// Unlike Children, this covers the current node and its entire subtree
SubTree
}
impl TreeExtent {
///
/// Returns true if this extent will cover the specified address, which is relative to where the extent starts
///
pub fn covers(&self, address: &TreeAddress) -> bool {
match *self {
TreeExtent::ThisNode => {
match *address {
TreeAddress::Here => true,
_ => false
}
},
TreeExtent::Children => {
match *address {
TreeAddress::ChildAtIndex(_, ref child_address) => TreeExtent::ThisNode.covers(child_address),
TreeAddress::ChildWithTag(_, ref child_address) => TreeExtent::ThisNode.covers(child_address),
_ => false
}
},
TreeExtent::SubTree => true
}
}
}
#[cfg(test)]
mod extent_tests {
use super::super::super::tree::*;
#[test]
fn thisnode_covers_only_here() {
assert!(TreeExtent::ThisNode.covers(&TreeAddress::Here));
assert!(!TreeExtent::ThisNode.covers(&(1.to_tree_address())));
}
#[test]
fn children_covers_only_immediate_children() {
assert!(TreeExtent::Children.covers(&(1.to_tree_address())));
assert!(TreeExtent::Children.covers(&("tag".to_tree_address())));
assert!(!TreeExtent::Children.covers(&((1, 2).to_tree_address())));
assert!(!TreeExtent::Children.covers(&(("tag", "othertag").to_tree_address())));
assert!(!TreeExtent::Children.covers(&TreeAddress::Here));
}
#[test]
fn subtree_covers_everything() {
assert!(TreeExtent::SubTree.covers(&(1.to_tree_address())));
assert!(TreeExtent::SubTree.covers(&("tag".to_tree_address())));
assert!(TreeExtent::SubTree.covers(&((1, 2).to_tree_address())));
assert!(TreeExtent::SubTree.covers(&(("tag", "othertag").to_tree_address())));
assert!(TreeExtent::SubTree.covers(&TreeAddress::Here));
}
}<|fim▁end|>
|
///
|
<|file_name|>FacebookConnect.spec.ts<|end_file_name|><|fim▁begin|>import {addProviders} from '@angular/core/testing'
import {testBootstrap, injectAsync, defaultProviders} from '../../../testing/Utils'
import {FacebookConnect} from './FacebookConnect'
import {Facebook} from 'ionic-native'
let testProviders: Array<any> = [
//custom providers
];
describe('FacebookConnect component', () => {
let facebookButton: HTMLElement;
beforeEach(() => addProviders(defaultProviders.concat(testProviders)));
beforeEach(injectAsync(testBootstrap(FacebookConnect, this, true, () => {
facebookButton = this.element.querySelector('button.facebook-connect');
/**
* we need to call expect() after a next tick because all the spies return promises
*/
this.clickButton = (): Promise<HTMLElement> => {
facebookButton.click()
return new Promise((accept) => {
process.nextTick(() => {
accept(facebookButton)
})
})
}
})));
it('should contain a button', () => {
expect(facebookButton.innerText.trim()).toBe('Continue with Facebook')
})
it('should call the facebook plugin on click', (done) => {
spyOn(this.instance, 'fbConnect').and.callThrough()
this.clickButton().then(() => {
expect(this.instance.fbConnect).toHaveBeenCalled()
done()
})
})
it('should return a promise resolving a user object when user is already connected', (done) => {
spyOn(this.instance, 'onFacebookOk').and.callThrough()
spyOn(Facebook, 'getLoginStatus').and.returnValue(Promise.resolve({ test: 'hello', status: 'connected' }))
this.instance.onConnect.subscribe((ev) => {
expect(this.instance.onFacebookOk).toHaveBeenCalledWith({ test: 'hello', status: 'connected' })
expect(ev.status).toBe('connected')
done()
})
this.clickButton()
})
<|fim▁hole|> spyOn(this.instance, 'onFacebookOk')
spyOn(Facebook, 'getLoginStatus').and.returnValue(Promise.resolve({ test: 'hello', status: 'not-connected' }))
spyOn(Facebook, 'login').and.returnValue(Promise.resolve({ test: 'hello', status: 'connected' }))
this.clickButton().then(() => {
expect(this.instance.fbLogin).toHaveBeenCalledTimes(1)
expect(Facebook.login).toHaveBeenCalledWith(['friend_list', 'email'])
expect(this.instance.onFacebookOk).toHaveBeenCalledTimes(1)
done()
})
})
it('should call error method in case getLoginStatus() fails', (done) => {
spyOn(this.instance, 'onFacebookError').and.callThrough()
spyOn(Facebook, 'getLoginStatus').and.returnValue(Promise.reject('this is terrible'))
this.instance.onError.subscribe((ev) => {
expect(this.instance.onFacebookError).toHaveBeenCalledTimes(1)
done()
})
this.clickButton()
})
it('should call error method in case login() fails', (done) => {
spyOn(this.instance, 'onFacebookCancel').and.callThrough()
spyOn(Facebook, 'getLoginStatus').and.returnValue(Promise.resolve({ test: 'hello', status: 'not-connected' }))
spyOn(Facebook, 'login').and.returnValue(Promise.reject('ups!'))
this.instance.onError.subscribe((ev) => {
expect(Facebook.login).toHaveBeenCalledTimes(1)
expect(this.instance.onFacebookCancel).toHaveBeenCalledTimes(1)
done()
})
this.clickButton()
})
})<|fim▁end|>
|
it('should login when user is not yet connected', (done) => {
spyOn(this.instance, 'fbLogin').and.callThrough()
|
<|file_name|>cvscontrol.cpp<|end_file_name|><|fim▁begin|>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "cvscontrol.h"
#include "cvsplugin.h"<|fim▁hole|>#include <vcsbase/vcsbaseconstants.h>
#include <QtCore/QFileInfo>
using namespace CVS;
using namespace CVS::Internal;
CVSControl::CVSControl(CVSPlugin *plugin) :
m_plugin(plugin)
{
}
QString CVSControl::displayName() const
{
return QLatin1String("cvs");
}
QString CVSControl::id() const
{
return QLatin1String(VCSBase::Constants::VCS_ID_CVS);
}
bool CVSControl::isConfigured() const
{
const QString binary = m_plugin->settings().cvsCommand;
if (binary.isEmpty())
return false;
QFileInfo fi(binary);
return fi.exists() && fi.isFile() && fi.isExecutable();
}
bool CVSControl::supportsOperation(Operation operation) const
{
bool rc = isConfigured();
switch (operation) {
case AddOperation:
case DeleteOperation:
case AnnotateOperation:
case OpenOperation:
break;
case MoveOperation:
case CreateRepositoryOperation:
case SnapshotOperations:
case CheckoutOperation:
case GetRepositoryRootOperation:
rc = false;
break;
}
return rc;
}
bool CVSControl::vcsOpen(const QString &fileName)
{
const QFileInfo fi(fileName);
return m_plugin->edit(fi.absolutePath(), QStringList(fi.fileName()));
}
bool CVSControl::vcsAdd(const QString &fileName)
{
const QFileInfo fi(fileName);
return m_plugin->vcsAdd(fi.absolutePath(), fi.fileName());
}
bool CVSControl::vcsDelete(const QString &fileName)
{
const QFileInfo fi(fileName);
return m_plugin->vcsDelete(fi.absolutePath(), fi.fileName());
}
bool CVSControl::vcsMove(const QString &from, const QString &to)
{
Q_UNUSED(from);
Q_UNUSED(to);
return false;
}
bool CVSControl::vcsCreateRepository(const QString &)
{
return false;
}
QString CVSControl::vcsGetRepositoryURL(const QString &)
{
return QString();
}
bool CVSControl::vcsCheckout(const QString &, const QByteArray &)
{
return false;
}
QString CVSControl::vcsCreateSnapshot(const QString &)
{
return QString();
}
QStringList CVSControl::vcsSnapshots(const QString &)
{
return QStringList();
}
bool CVSControl::vcsRestoreSnapshot(const QString &, const QString &)
{
return false;
}
bool CVSControl::vcsRemoveSnapshot(const QString &, const QString &)
{
return false;
}
bool CVSControl::vcsAnnotate(const QString &file, int line)
{
m_plugin->vcsAnnotate(file, QString(), line);
return true;
}
bool CVSControl::managesDirectory(const QString &directory, QString *topLevel) const
{
return m_plugin->managesDirectory(directory, topLevel);
}
void CVSControl::emitRepositoryChanged(const QString &s)
{
emit repositoryChanged(s);
}
void CVSControl::emitFilesChanged(const QStringList &l)
{
emit filesChanged(l);
}
void CVSControl::emitConfigurationChanged()
{
emit configurationChanged();
}<|fim▁end|>
|
#include "cvssettings.h"
|
<|file_name|>durand.py<|end_file_name|><|fim▁begin|>"""
Implementation of the paper,
Durand and Dorsey SIGGGRAPH 2002,
"Fast Bilateral Fitering for the display of high-dynamic range images"
"""
import numpy as np
import hydra.io
import hydra.filters
def bilateral_separation(img, sigma_s=0.02, sigma_r=0.4):
r, c = img.shape
sigma_s = max(r, c) * sigma_s
img_log = np.log10(img + 1.0e-6)
img_fil = hydra.filters.bilateral(img_log, sigma_s, sigma_r)
base = 10.0 ** (img_fil) - 1.0e-6
base[base <= 0.0] = 0.0
base = base.reshape((r, c))
detail = hydra.core.remove_specials(img / base)
return base, detail
def durand(img, target_contrast=5.0):
L = hydra.core.lum(img)
tmp = np.zeros(img.shape)
for c in range(3):
tmp[:,:,c] = hydra.core.remove_specials(img[:,:,c] / L)
Lbase, Ldetail = bilateral_separation(L)<|fim▁hole|>
max_log_base = np.max(log_base)
log_detail = np.log10(Ldetail)
compression_factor = np.log(target_contrast) / (max_log_base - np.min(log_base))
log_absolute = compression_factor * max_log_base
log_compressed = log_base * compression_factor + log_detail - log_absolute
output = np.power(10.0, log_compressed)
ret = np.zeros(img.shape)
for c in range(3):
ret[:,:,c] = tmp[:,:,c] * output
ret = np.maximum(ret, 0.0)
ret = np.minimum(ret, 1.0)
return ret<|fim▁end|>
|
log_base = np.log10(Lbase)
|
<|file_name|>ssm.rs<|end_file_name|><|fim▁begin|>//! Amazon EC2 Simple Systems Manager
//!
//! If you're using the service, you're probably looking for [SsmClient](struct.SsmClient.html).
<|fim▁hole|><|fim▁end|>
|
include!(concat!(env!("OUT_DIR"), "/ssm.rs"));
|
<|file_name|>htmltablerowelement.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/. */
use dom::bindings::utils::{DOMString, ErrorResult};
use dom::htmlelement::HTMLElement;
pub struct HTMLTableRowElement {
htmlelement: HTMLElement,
}
impl HTMLTableRowElement {
pub fn RowIndex(&self) -> i32 {
0
}
<|fim▁hole|> }
pub fn SectionRowIndex(&self) -> i32 {
0
}
pub fn GetSectionRowIndex(&self) -> i32 {
0
}
pub fn DeleteCell(&mut self, _index: i32) -> ErrorResult {
Ok(())
}
pub fn Align(&self) -> DOMString {
None
}
pub fn SetAlign(&self, _align: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Ch(&self) -> DOMString {
None
}
pub fn SetCh(&self, _ch: &DOMString) -> ErrorResult {
Ok(())
}
pub fn ChOff(&self) -> DOMString {
None
}
pub fn SetChOff(&self, _ch_off: &DOMString) -> ErrorResult {
Ok(())
}
pub fn VAlign(&self) -> DOMString {
None
}
pub fn SetVAlign(&self, _v_align: &DOMString) -> ErrorResult {
Ok(())
}
pub fn BgColor(&self) -> DOMString {
None
}
pub fn SetBgColor(&self, _bg_color: &DOMString) -> ErrorResult {
Ok(())
}
}<|fim▁end|>
|
pub fn GetRowIndex(&self) -> i32 {
0
|
<|file_name|>testPlugin2.cpp<|end_file_name|><|fim▁begin|>/**
*
* This file is part of Tulip (www.tulip-software.org)
*
* Authors: David Auber and the Tulip development Team
* from LaBRI, University of Bordeaux
*
* Tulip is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License<|fim▁hole|> * Tulip 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.
*
*/
#include <stdio.h>
#include <string>
#include <iostream>
#include <cppunit/TestCase.h>
#include <tulip/TulipPluginHeaders.h>
using namespace std;
class Test2 : public tlp::BooleanAlgorithm {
public:
PLUGININFORMATION("Test2","Jezequel","03/11/2004","0","1.0", "")
Test2(tlp::PluginContext* context) : tlp::BooleanAlgorithm(context) {}
~Test2() {}
bool run() {
return true;
}
};
PLUGIN(Test2)<|fim▁end|>
|
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
|
<|file_name|>AnalogArrowIndicator.js<|end_file_name|><|fim▁begin|>define(["dojo/_base/declare","./AnalogIndicatorBase"],
function(declare, AnalogIndicatorBase) {
return declare("dojox.gauges.AnalogArrowIndicator", [AnalogIndicatorBase],{<|fim▁hole|> // to the value of the indicator.
_getShapes: function(group){
// summary:
// Override of dojox.gauges.AnalogLineIndicator._getShapes
if(!this._gauge){
return null;
}
var color = this.color ? this.color : 'black';
var strokeColor = this.strokeColor ? this.strokeColor : color;
var stroke = { color: strokeColor, width: 1};
if (this.color.type && !this.strokeColor){
stroke.color = this.color.colors[0].color;
}
var x = Math.floor(this.width/2);
var head = this.width * 5;
var odd = (this.width & 1);
var shapes = [];
var points = [{x:-x, y:0},
{x:-x, y:-this.length+head},
{x:-2*x, y:-this.length+head},
{x:0, y:-this.length},
{x:2*x+odd,y:-this.length+head},
{x:x+odd, y:-this.length+head},
{x:x+odd, y:0},
{x:-x, y:0}];
shapes[0] = group.createPolyline(points)
.setStroke(stroke)
.setFill(color);
shapes[1] = group.createLine({ x1:-x, y1: 0, x2: -x, y2:-this.length+head })
.setStroke({color: this.highlight});
shapes[2] = group.createLine({ x1:-x-3, y1: -this.length+head, x2: 0, y2:-this.length })
.setStroke({color: this.highlight});
shapes[3] = group.createCircle({cx: 0, cy: 0, r: this.width})
.setStroke(stroke)
.setFill(color);
return shapes;
}
});
});<|fim▁end|>
|
// summary:
// An indicator for the AnalogGauge that draws an arrow. The arrow is drawn on the angle that corresponds
|
<|file_name|>84.py<|end_file_name|><|fim▁begin|>from qgl2.qgl2 import qgl2decl, qgl2main, qreg
from qgl2.qgl2 import QRegister
from qgl2.qgl1 import X, Y, Z, Id, Utheta
from itertools import product
@qgl2decl
def cond_helper(q: qreg, cond):
if cond:
X(q)
@qgl2decl
def t1():
"""
Correct result is [ X(q1) ]
"""
q1 = QRegister('q1')
cond_helper(q1, False)
X(q1)<|fim▁hole|>def t2():
"""
Correct result is [ X(q1) ]
"""
q1 = QRegister('q1')
q2 = QRegister('q2')
# We're not going to reference q2 anywhere,
# just to make sure that the compiler doesn't
# freak out
X(q1)
@qgl2decl
def t3():
"""
Like t2, but with a function call
"""
q1 = QRegister('q1')
q2 = QRegister('q2')
cond_helper(q1, True)
@qgl2decl
def t4():
"""
Like t3, but the function call does nothing
"""
q1 = QRegister('q1')
q2 = QRegister('q2')
cond_helper(q1, False)
X(q1) # need to do something
@qgl2decl
def t5():
"""
Like t3, but the function call does nothing
"""
q1 = QRegister('q1')
q2 = QRegister('q2')
# don't do anything at all<|fim▁end|>
|
@qgl2decl
|
<|file_name|>hero-detail.service.ts<|end_file_name|><|fim▁begin|>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Hero } from '../model/hero';
import { HeroService } from '../model/hero.service';
// #docregion prototype<|fim▁hole|>@Injectable()
export class HeroDetailService {
constructor(private heroService: HeroService) { }
// #enddocregion prototype
// Returns a clone which caller may modify safely
getHero(id: number | string): Observable<Hero> {
if (typeof id === 'string') {
id = parseInt(id, 10);
}
return this.heroService.getHero(id).pipe(
map(hero => {
return hero ? Object.assign({}, hero) : null; // clone or null
})
);
}
saveHero(hero: Hero) {
return this.heroService.updateHero(hero);
}
// #docregion prototype
}
// #enddocregion prototype<|fim▁end|>
| |
<|file_name|>plot_gpr_prior_posterior.py<|end_file_name|><|fim▁begin|>"""
==========================================================================
Illustration of prior and posterior Gaussian process for different kernels
==========================================================================
This example illustrates the prior and posterior of a
:class:`~sklearn.gaussian_process.GaussianProcessRegressor` with different
kernels. Mean, standard deviation, and 5 samples are shown for both prior
and posterior distributions.
Here, we only give some illustration. To know more about kernels' formulation,
refer to the :ref:`User Guide <gp_kernels>`.
"""
print(__doc__)
# Authors: Jan Hendrik Metzen <[email protected]>
# Guillaume Lemaitre <[email protected]>
# License: BSD 3 clause
# %%
# Helper function
# ---------------
#
# Before presenting each individual kernel available for Gaussian processes,
# we will define an helper function allowing us plotting samples drawn from
# the Gaussian process.
#
# This function will take a
# :class:`~sklearn.gaussian_process.GaussianProcessRegressor` model and will
# drawn sample from the Gaussian process. If the model was not fit, the samples
# are drawn from the prior distribution while after model fitting, the samples are
# drawn from the posterior distribution.
import matplotlib.pyplot as plt
import numpy as np
def plot_gpr_samples(gpr_model, n_samples, ax):
"""Plot samples drawn from the Gaussian process model.
If the Gaussian process model is not trained then the drawn samples are
drawn from the prior distribution. Otherwise, the samples are drawn from
the posterior distribution. Be aware that a sample here corresponds to a
function.
Parameters
----------
gpr_model : `GaussianProcessRegressor`
A :class:`~sklearn.gaussian_process.GaussianProcessRegressor` model.
n_samples : int
The number of samples to draw from the Gaussian process distribution.
ax : matplotlib axis
The matplotlib axis where to plot the samples.
"""
x = np.linspace(0, 5, 100)
X = x.reshape(-1, 1)
y_mean, y_std = gpr_model.predict(X, return_std=True)
y_samples = gpr_model.sample_y(X, n_samples)
y_mean, y_std = gpr_model.predict(X, return_std=True)
y_samples = gpr_model.sample_y(X, n_samples)
for idx, single_prior in enumerate(y_samples.T):
ax.plot(
x,
single_prior,
linestyle="--",
alpha=0.7,
label=f"Sampled function #{idx + 1}",
)
ax.plot(x, y_mean, color="black", label="Mean")
ax.fill_between(
x,
y_mean - y_std,
y_mean + y_std,<|fim▁hole|> ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_ylim([-3, 3])
# %%
# Dataset and Gaussian process generation
# ---------------------------------------
# We will create a training dataset that we will use in the different sections.
rng = np.random.RandomState(4)
X_train = rng.uniform(0, 5, 10).reshape(-1, 1)
y_train = np.sin((X_train[:, 0] - 2.5) ** 2)
n_samples = 5
# %%
# Kernel cookbook
# ---------------
#
# In this section, we illustrate some samples drawn from the prior and posterior
# distributions of the Gaussian process with different kernels.
#
# Radial Basis Function kernel
# ............................
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF
kernel = 1.0 * RBF(length_scale=1.0, length_scale_bounds=(1e-1, 10.0))
gpr = GaussianProcessRegressor(kernel=kernel, random_state=0)
fig, axs = plt.subplots(nrows=2, sharex=True, sharey=True, figsize=(10, 8))
# plot prior
plot_gpr_samples(gpr, n_samples=n_samples, ax=axs[0])
axs[0].set_title("Samples from prior distribution")
# plot posterior
gpr.fit(X_train, y_train)
plot_gpr_samples(gpr, n_samples=n_samples, ax=axs[1])
axs[1].scatter(X_train[:, 0], y_train, color="red", zorder=10, label="Observations")
axs[1].legend(bbox_to_anchor=(1.05, 1.5), loc="upper left")
axs[1].set_title("Samples from posterior distribution")
fig.suptitle("Radial Basis Function kernel", fontsize=18)
plt.tight_layout()
# %%
print(f"Kernel parameters before fit:\n{kernel})")
print(
f"Kernel parameters after fit: \n{gpr.kernel_} \n"
f"Log-likelihood: {gpr.log_marginal_likelihood(gpr.kernel_.theta):.3f}"
)
# %%
# Rational Quadradtic kernel
# ..........................
from sklearn.gaussian_process.kernels import RationalQuadratic
kernel = 1.0 * RationalQuadratic(length_scale=1.0, alpha=0.1, alpha_bounds=(1e-5, 1e15))
gpr = GaussianProcessRegressor(kernel=kernel, random_state=0)
fig, axs = plt.subplots(nrows=2, sharex=True, sharey=True, figsize=(10, 8))
# plot prior
plot_gpr_samples(gpr, n_samples=n_samples, ax=axs[0])
axs[0].set_title("Samples from prior distribution")
# plot posterior
gpr.fit(X_train, y_train)
plot_gpr_samples(gpr, n_samples=n_samples, ax=axs[1])
axs[1].scatter(X_train[:, 0], y_train, color="red", zorder=10, label="Observations")
axs[1].legend(bbox_to_anchor=(1.05, 1.5), loc="upper left")
axs[1].set_title("Samples from posterior distribution")
fig.suptitle("Rational Quadratic kernel", fontsize=18)
plt.tight_layout()
# %%
print(f"Kernel parameters before fit:\n{kernel})")
print(
f"Kernel parameters after fit: \n{gpr.kernel_} \n"
f"Log-likelihood: {gpr.log_marginal_likelihood(gpr.kernel_.theta):.3f}"
)
# %%
# Periodic kernel
# ...............
from sklearn.gaussian_process.kernels import ExpSineSquared
kernel = 1.0 * ExpSineSquared(
length_scale=1.0,
periodicity=3.0,
length_scale_bounds=(0.1, 10.0),
periodicity_bounds=(1.0, 10.0),
)
gpr = GaussianProcessRegressor(kernel=kernel, random_state=0)
fig, axs = plt.subplots(nrows=2, sharex=True, sharey=True, figsize=(10, 8))
# plot prior
plot_gpr_samples(gpr, n_samples=n_samples, ax=axs[0])
axs[0].set_title("Samples from prior distribution")
# plot posterior
gpr.fit(X_train, y_train)
plot_gpr_samples(gpr, n_samples=n_samples, ax=axs[1])
axs[1].scatter(X_train[:, 0], y_train, color="red", zorder=10, label="Observations")
axs[1].legend(bbox_to_anchor=(1.05, 1.5), loc="upper left")
axs[1].set_title("Samples from posterior distribution")
fig.suptitle("Periodic kernel", fontsize=18)
plt.tight_layout()
# %%
print(f"Kernel parameters before fit:\n{kernel})")
print(
f"Kernel parameters after fit: \n{gpr.kernel_} \n"
f"Log-likelihood: {gpr.log_marginal_likelihood(gpr.kernel_.theta):.3f}"
)
# %%
# Dot product kernel
# ..................
from sklearn.gaussian_process.kernels import ConstantKernel, DotProduct
kernel = ConstantKernel(0.1, (0.01, 10.0)) * (
DotProduct(sigma_0=1.0, sigma_0_bounds=(0.1, 10.0)) ** 2
)
gpr = GaussianProcessRegressor(kernel=kernel, random_state=0)
fig, axs = plt.subplots(nrows=2, sharex=True, sharey=True, figsize=(10, 8))
# plot prior
plot_gpr_samples(gpr, n_samples=n_samples, ax=axs[0])
axs[0].set_title("Samples from prior distribution")
# plot posterior
gpr.fit(X_train, y_train)
plot_gpr_samples(gpr, n_samples=n_samples, ax=axs[1])
axs[1].scatter(X_train[:, 0], y_train, color="red", zorder=10, label="Observations")
axs[1].legend(bbox_to_anchor=(1.05, 1.5), loc="upper left")
axs[1].set_title("Samples from posterior distribution")
fig.suptitle("Dot product kernel", fontsize=18)
plt.tight_layout()
# %%
print(f"Kernel parameters before fit:\n{kernel})")
print(
f"Kernel parameters after fit: \n{gpr.kernel_} \n"
f"Log-likelihood: {gpr.log_marginal_likelihood(gpr.kernel_.theta):.3f}"
)
# %%
# Mattern kernel
# ..............
from sklearn.gaussian_process.kernels import Matern
kernel = 1.0 * Matern(length_scale=1.0, length_scale_bounds=(1e-1, 10.0), nu=1.5)
gpr = GaussianProcessRegressor(kernel=kernel, random_state=0)
fig, axs = plt.subplots(nrows=2, sharex=True, sharey=True, figsize=(10, 8))
# plot prior
plot_gpr_samples(gpr, n_samples=n_samples, ax=axs[0])
axs[0].set_title("Samples from prior distribution")
# plot posterior
gpr.fit(X_train, y_train)
plot_gpr_samples(gpr, n_samples=n_samples, ax=axs[1])
axs[1].scatter(X_train[:, 0], y_train, color="red", zorder=10, label="Observations")
axs[1].legend(bbox_to_anchor=(1.05, 1.5), loc="upper left")
axs[1].set_title("Samples from posterior distribution")
fig.suptitle("Mattern kernel", fontsize=18)
plt.tight_layout()
# %%
print(f"Kernel parameters before fit:\n{kernel})")
print(
f"Kernel parameters after fit: \n{gpr.kernel_} \n"
f"Log-likelihood: {gpr.log_marginal_likelihood(gpr.kernel_.theta):.3f}"
)<|fim▁end|>
|
alpha=0.1,
color="black",
label=r"$\pm$ 1 std. dev.",
)
|
<|file_name|>example.rs<|end_file_name|><|fim▁begin|>static ABC: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
pub fn get_diamond(diamond_char: char) -> Vec<String> {
let mut result: Vec<String> = Vec::new();
let diamond_char = diamond_char.to_ascii_uppercase();
if ABC.find(diamond_char).is_none() {
return result;
}
if diamond_char == 'A' {
return vec![String::from("A")];
}
//build first half
for char_in_abc in ABC.chars() {
result.push(get_line(char_in_abc, diamond_char).clone());
if char_in_abc == diamond_char {
break;
}
}
//build second half
let mut rev = result.clone();
rev.pop(); //remove middle piece to avoid duplicates
for line in rev.drain(..).rev() {
result.push(line);
}
result
}
fn get_line(char_in_abc: char, diamond_char: char) -> String {
let mut r = String::new();
let letter_e = get_letter_line(char_in_abc);
let letter_c = get_letter_line(diamond_char);
let ws = letter_c.len() - letter_e.len(); //number of whitespaces
//left
for _ in 0..ws / 2 {
r.push(' ');
}<|fim▁hole|> //right
for _ in 0..ws / 2 {
r.push(' ');
}
r
}
fn get_letter_line(char_in_abc: char) -> String {
let mut r = String::new();
let odd = (0..)
.filter(|x| x % 2 != 0)
.nth(ABC.find(char_in_abc).unwrap())
.unwrap();
for i in 0..odd {
if i == 0 || i == odd - 1 {
r.push(char_in_abc);
} else {
r.push(' ');
}
}
r
}<|fim▁end|>
|
//letter line
for i in letter_e.chars() {
r.push(i)
}
|
<|file_name|>ipspace_modify_parameters.go<|end_file_name|><|fim▁begin|>// Code generated by go-swagger; DO NOT EDIT.
package networking
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"time"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
cr "github.com/go-openapi/runtime/client"
"github.com/go-openapi/strfmt"
"github.com/netapp/trident/storage_drivers/ontap/api/rest/models"
)
// NewIpspaceModifyParams creates a new IpspaceModifyParams object,
// with the default timeout for this client.
//
// Default values are not hydrated, since defaults are normally applied by the API server side.
//
// To enforce default values in parameter, use SetDefaults or WithDefaults.
func NewIpspaceModifyParams() *IpspaceModifyParams {
return &IpspaceModifyParams{
timeout: cr.DefaultTimeout,
}
}
// NewIpspaceModifyParamsWithTimeout creates a new IpspaceModifyParams object
// with the ability to set a timeout on a request.
func NewIpspaceModifyParamsWithTimeout(timeout time.Duration) *IpspaceModifyParams {
return &IpspaceModifyParams{
timeout: timeout,
}
}
// NewIpspaceModifyParamsWithContext creates a new IpspaceModifyParams object
// with the ability to set a context for a request.
func NewIpspaceModifyParamsWithContext(ctx context.Context) *IpspaceModifyParams {
return &IpspaceModifyParams{
Context: ctx,
}
}
// NewIpspaceModifyParamsWithHTTPClient creates a new IpspaceModifyParams object
// with the ability to set a custom HTTPClient for a request.
func NewIpspaceModifyParamsWithHTTPClient(client *http.Client) *IpspaceModifyParams {
return &IpspaceModifyParams{
HTTPClient: client,
}
}
/* IpspaceModifyParams contains all the parameters to send to the API endpoint
for the ipspace modify operation.
Typically these are written to a http.Request.
*/
type IpspaceModifyParams struct {
// Info.
Info *models.Ipspace
/* UUID.
IPspace UUID
*/
UUIDPathParameter string
timeout time.Duration
Context context.Context
HTTPClient *http.Client
}
// WithDefaults hydrates default values in the ipspace modify params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *IpspaceModifyParams) WithDefaults() *IpspaceModifyParams {
o.SetDefaults()
return o
}
// SetDefaults hydrates default values in the ipspace modify params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *IpspaceModifyParams) SetDefaults() {
// no default values defined for this parameter
}
// WithTimeout adds the timeout to the ipspace modify params
func (o *IpspaceModifyParams) WithTimeout(timeout time.Duration) *IpspaceModifyParams {
o.SetTimeout(timeout)
return o
}
// SetTimeout adds the timeout to the ipspace modify params
func (o *IpspaceModifyParams) SetTimeout(timeout time.Duration) {
o.timeout = timeout
}
// WithContext adds the context to the ipspace modify params
func (o *IpspaceModifyParams) WithContext(ctx context.Context) *IpspaceModifyParams {
o.SetContext(ctx)
return o
}
// SetContext adds the context to the ipspace modify params
func (o *IpspaceModifyParams) SetContext(ctx context.Context) {
o.Context = ctx
}
// WithHTTPClient adds the HTTPClient to the ipspace modify params
func (o *IpspaceModifyParams) WithHTTPClient(client *http.Client) *IpspaceModifyParams {
o.SetHTTPClient(client)
return o<|fim▁hole|>func (o *IpspaceModifyParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithInfo adds the info to the ipspace modify params
func (o *IpspaceModifyParams) WithInfo(info *models.Ipspace) *IpspaceModifyParams {
o.SetInfo(info)
return o
}
// SetInfo adds the info to the ipspace modify params
func (o *IpspaceModifyParams) SetInfo(info *models.Ipspace) {
o.Info = info
}
// WithUUIDPathParameter adds the uuid to the ipspace modify params
func (o *IpspaceModifyParams) WithUUIDPathParameter(uuid string) *IpspaceModifyParams {
o.SetUUIDPathParameter(uuid)
return o
}
// SetUUIDPathParameter adds the uuid to the ipspace modify params
func (o *IpspaceModifyParams) SetUUIDPathParameter(uuid string) {
o.UUIDPathParameter = uuid
}
// WriteToRequest writes these params to a swagger request
func (o *IpspaceModifyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {
if err := r.SetTimeout(o.timeout); err != nil {
return err
}
var res []error
if o.Info != nil {
if err := r.SetBodyParam(o.Info); err != nil {
return err
}
}
// path param uuid
if err := r.SetPathParam("uuid", o.UUIDPathParameter); err != nil {
return err
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}<|fim▁end|>
|
}
// SetHTTPClient adds the HTTPClient to the ipspace modify params
|
<|file_name|>hash.rs<|end_file_name|><|fim▁begin|>// Copyright 2015-2017 Parity Technologies
//
// 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.
//! General hash types, a fixed-size raw-data type used as the output of hash functions.
use std::{ops, fmt, cmp};
use std::cmp::{min, Ordering};
use std::ops::{Deref, DerefMut, BitXor, BitAnd, BitOr, IndexMut, Index};
use std::hash::{Hash, Hasher, BuildHasherDefault};
use std::collections::{HashMap, HashSet};
use std::str::FromStr;
use rand::Rng;
use rand::os::OsRng;
use rustc_serialize::hex::{FromHex, FromHexError};
use bigint::U256;
use libc::{c_void, memcmp};
/// Return `s` without the `0x` at the beginning of it, if any.
pub fn clean_0x(s: &str) -> &str {
if s.starts_with("0x") {
&s[2..]
} else {
s
}
}
macro_rules! impl_hash {
($from: ident, $size: expr) => {
#[repr(C)]
/// Unformatted binary data of fixed length.
pub struct $from (pub [u8; $size]);
impl From<[u8; $size]> for $from {
fn from(bytes: [u8; $size]) -> Self {
$from(bytes)
}
}
impl From<$from> for [u8; $size] {
fn from(s: $from) -> Self {
s.0
}
}
impl Deref for $from {
type Target = [u8];
#[inline]
fn deref(&self) -> &[u8] {
&self.0
}
}
impl AsRef<[u8]> for $from {
#[inline]
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl DerefMut for $from {
#[inline]
fn deref_mut(&mut self) -> &mut [u8] {
&mut self.0
}
}
impl $from {
/// Create a new, zero-initialised, instance.
pub fn new() -> $from {
$from([0; $size])
}
/// Synonym for `new()`. Prefer to new as it's more readable.
pub fn zero() -> $from {
$from([0; $size])
}
/// Create a new, cryptographically random, instance.
pub fn random() -> $from {
let mut hash = $from::new();
hash.randomize();
hash
}
/// Assign self have a cryptographically random value.
pub fn randomize(&mut self) {
let mut rng = OsRng::new().unwrap();
rng.fill_bytes(&mut self.0);
}
/// Get the size of this object in bytes.
pub fn len() -> usize {
$size
}
#[inline]
/// Assign self to be of the same value as a slice of bytes of length `len()`.
pub fn clone_from_slice(&mut self, src: &[u8]) -> usize {
let min = cmp::min($size, src.len());
self.0[..min].copy_from_slice(&src[..min]);
min
}
/// Convert a slice of bytes of length `len()` to an instance of this type.
pub fn from_slice(src: &[u8]) -> Self {
let mut r = Self::new();
r.clone_from_slice(src);
r
}
/// Copy the data of this object into some mutable slice of length `len()`.
pub fn copy_to(&self, dest: &mut[u8]) {
let min = cmp::min($size, dest.len());
dest[..min].copy_from_slice(&self.0[..min]);
}
/// Returns `true` if all bits set in `b` are also set in `self`.
pub fn contains<'a>(&'a self, b: &'a Self) -> bool {
&(b & self) == b
}
/// Returns `true` if no bits are set.
pub fn is_zero(&self) -> bool {
self.eq(&Self::new())
}
/// Returns the lowest 8 bytes interpreted as a BigEndian integer.
pub fn low_u64(&self) -> u64 {
let mut ret = 0u64;
for i in 0..min($size, 8) {
ret |= (self.0[$size - 1 - i] as u64) << (i * 8);
}
ret
}
}
impl FromStr for $from {
type Err = FromHexError;
fn from_str(s: &str) -> Result<$from, FromHexError> {
let a = s.from_hex()?;
if a.len() != $size {
return Err(FromHexError::InvalidHexLength);
}
let mut ret = [0;$size];
ret.copy_from_slice(&a);
Ok($from(ret))
}
}
impl fmt::Debug for $from {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for i in &self.0[..] {
write!(f, "{:02x}", i)?;
}
Ok(())
}
}
impl fmt::Display for $from {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for i in &self.0[0..2] {
write!(f, "{:02x}", i)?;
}
write!(f, "…")?;
for i in &self.0[$size - 2..$size] {
write!(f, "{:02x}", i)?;
}
Ok(())
}
}
impl Copy for $from {}
#[cfg_attr(feature="dev", allow(expl_impl_clone_on_copy))]
impl Clone for $from {
fn clone(&self) -> $from {
let mut ret = $from::new();
ret.0.copy_from_slice(&self.0);
ret
}
}
impl Eq for $from {}
impl PartialEq for $from {
fn eq(&self, other: &Self) -> bool {
unsafe { memcmp(self.0.as_ptr() as *const c_void, other.0.as_ptr() as *const c_void, $size) == 0 }
}
}
impl Ord for $from {
fn cmp(&self, other: &Self) -> Ordering {
let r = unsafe { memcmp(self.0.as_ptr() as *const c_void, other.0.as_ptr() as *const c_void, $size) };
if r < 0 { return Ordering::Less }
if r > 0 { return Ordering::Greater }
return Ordering::Equal;
}
}
impl PartialOrd for $from {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Hash for $from {
fn hash<H>(&self, state: &mut H) where H: Hasher {
state.write(&self.0);
state.finish();
}
}
impl Index<usize> for $from {
type Output = u8;
fn index(&self, index: usize) -> &u8 {
&self.0[index]
}
}
impl IndexMut<usize> for $from {
fn index_mut(&mut self, index: usize) -> &mut u8 {
&mut self.0[index]
}
}
impl Index<ops::Range<usize>> for $from {
type Output = [u8];
fn index(&self, index: ops::Range<usize>) -> &[u8] {
&self.0[index]
}
}
impl IndexMut<ops::Range<usize>> for $from {
fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [u8] {
&mut self.0[index]
}
}
impl Index<ops::RangeFull> for $from {
type Output = [u8];
fn index(&self, _index: ops::RangeFull) -> &[u8] {
&self.0
}
}
impl IndexMut<ops::RangeFull> for $from {
fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [u8] {
&mut self.0
}
}
/// `BitOr` on references
impl<'a> BitOr for &'a $from {
type Output = $from;
fn bitor(self, rhs: Self) -> Self::Output {
let mut ret: $from = $from::default();
for i in 0..$size {
ret.0[i] = self.0[i] | rhs.0[i];
}
ret
}
}
/// Moving `BitOr`
impl BitOr for $from {
type Output = $from;
fn bitor(self, rhs: Self) -> Self::Output {
&self | &rhs
}
}
/// `BitAnd` on references
impl <'a> BitAnd for &'a $from {
type Output = $from;
fn bitand(self, rhs: Self) -> Self::Output {
let mut ret: $from = $from::default();
for i in 0..$size {
ret.0[i] = self.0[i] & rhs.0[i];
}
ret
}
}
/// Moving `BitAnd`
impl BitAnd for $from {
type Output = $from;
fn bitand(self, rhs: Self) -> Self::Output {
&self & &rhs
}
}
/// `BitXor` on references
impl <'a> BitXor for &'a $from {
type Output = $from;
fn bitxor(self, rhs: Self) -> Self::Output {
let mut ret: $from = $from::default();
for i in 0..$size {
ret.0[i] = self.0[i] ^ rhs.0[i];
}
ret
}
}
/// Moving `BitXor`
impl BitXor for $from {
type Output = $from;
fn bitxor(self, rhs: Self) -> Self::Output {
&self ^ &rhs
}
}
impl $from {
/// Get a hex representation.
pub fn hex(&self) -> String {
format!("{:?}", self)
}
}
impl Default for $from {
fn default() -> Self { $from::new() }
}
impl From<u64> for $from {
fn from(mut value: u64) -> $from {
let mut ret = $from::new();
for i in 0..8 {
if i < $size {
ret.0[$size - i - 1] = (value & 0xff) as u8;
value >>= 8;
}
}
ret
}
}
impl From<&'static str> for $from {
fn from(s: &'static str) -> $from {
let s = clean_0x(s);
if s.len() % 2 == 1 {
$from::from_str(&("0".to_owned() + s)).unwrap()
} else {
$from::from_str(s).unwrap()
}
}
}
impl<'a> From<&'a [u8]> for $from {
fn from(s: &'a [u8]) -> $from {
$from::from_slice(s)
}
}
}
}
impl From<U256> for H256 {
fn from(value: U256) -> H256 {
let mut ret = H256::new();
value.to_big_endian(&mut ret);
ret
}
}
impl<'a> From<&'a U256> for H256 {
fn from(value: &'a U256) -> H256 {
let mut ret: H256 = H256::new();
value.to_big_endian(&mut ret);
ret
}
}
impl From<H256> for U256 {
fn from(value: H256) -> U256 {
U256::from(&value)
}
}
impl<'a> From<&'a H256> for U256 {
fn from(value: &'a H256) -> U256 {
U256::from(value.as_ref() as &[u8])
}
}
impl From<H256> for H160 {
fn from(value: H256) -> H160 {
let mut ret = H160::new();
ret.0.copy_from_slice(&value[12..32]);
ret
}
}
impl From<H256> for H64 {
fn from(value: H256) -> H64 {
let mut ret = H64::new();
ret.0.copy_from_slice(&value[20..28]);
ret
}
}
impl From<H160> for H256 {
fn from(value: H160) -> H256 {
let mut ret = H256::new();
ret.0[12..32].copy_from_slice(&value);
ret
}
}
impl<'a> From<&'a H160> for H256 {
fn from(value: &'a H160) -> H256 {
let mut ret = H256::new();
ret.0[12..32].copy_from_slice(value);
ret
}
}
impl_hash!(H32, 4);
impl_hash!(H64, 8);
impl_hash!(H128, 16);
impl_hash!(H160, 20);
impl_hash!(H256, 32);
impl_hash!(H264, 33);
impl_hash!(H512, 64);
impl_hash!(H520, 65);
impl_hash!(H1024, 128);
impl_hash!(H2048, 256);
known_heap_size!(0, H32, H64, H128, H160, H256, H264, H512, H520, H1024, H2048);
// Specialized HashMap and HashSet
/// Hasher that just takes 8 bytes of the provided value.
/// May only be used for keys which are 32 bytes.
pub struct PlainHasher {
prefix: [u8; 8],
_marker: [u64; 0], // for alignment
}
impl Default for PlainHasher {
#[inline]
fn default() -> PlainHasher {
PlainHasher {
prefix: [0; 8],
_marker: [0; 0],
}<|fim▁hole|> #[inline]
fn finish(&self) -> u64 {
unsafe { ::std::mem::transmute(self.prefix) }
}
#[inline]
fn write(&mut self, bytes: &[u8]) {
debug_assert!(bytes.len() == 32);
for quarter in bytes.chunks(8) {
for (x, y) in self.prefix.iter_mut().zip(quarter) {
*x ^= *y
}
}
}
}
/// Specialized version of `HashMap` with H256 keys and fast hashing function.
pub type H256FastMap<T> = HashMap<H256, T, BuildHasherDefault<PlainHasher>>;
/// Specialized version of `HashSet` with H256 keys and fast hashing function.
pub type H256FastSet = HashSet<H256, BuildHasherDefault<PlainHasher>>;
#[cfg(test)]
mod tests {
use hash::*;
use std::str::FromStr;
#[test]
fn hasher_alignment() {
use std::mem::align_of;
assert_eq!(align_of::<u64>(), align_of::<PlainHasher>());
}
#[test]
#[cfg_attr(feature="dev", allow(eq_op))]
fn hash() {
let h = H64([0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]);
assert_eq!(H64::from_str("0123456789abcdef").unwrap(), h);
assert_eq!(format!("{}", h), "0123…cdef");
assert_eq!(format!("{:?}", h), "0123456789abcdef");
assert_eq!(h.hex(), "0123456789abcdef");
assert!(h == h);
assert!(h != H64([0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xee]));
assert!(h != H64([0; 8]));
}
#[test]
fn hash_bitor() {
let a = H64([1; 8]);
let b = H64([2; 8]);
let c = H64([3; 8]);
// borrow
assert_eq!(&a | &b, c);
// move
assert_eq!(a | b, c);
}
#[test]
fn from_and_to_address() {
let address: H160 = "ef2d6d194084c2de36e0dabfce45d046b37d1106".into();
let h = H256::from(address.clone());
let a = H160::from(h);
assert_eq!(address, a);
}
#[test]
fn from_u64() {
assert_eq!(H128::from(0x1234567890abcdef), H128::from_str("00000000000000001234567890abcdef").unwrap());
assert_eq!(H64::from(0x1234567890abcdef), H64::from_str("1234567890abcdef").unwrap());
assert_eq!(H32::from(0x1234567890abcdef), H32::from_str("90abcdef").unwrap());
}
#[test]
fn from_str() {
assert_eq!(H64::from(0x1234567890abcdef), H64::from("0x1234567890abcdef"));
assert_eq!(H64::from(0x1234567890abcdef), H64::from("1234567890abcdef"));
assert_eq!(H64::from(0x234567890abcdef), H64::from("0x234567890abcdef"));
}
#[test]
fn from_and_to_u256() {
let u: U256 = 0x123456789abcdef0u64.into();
let h = H256::from(u);
assert_eq!(H256::from(u), H256::from("000000000000000000000000000000000000000000000000123456789abcdef0"));
let h_ref = H256::from(&u);
assert_eq!(h, h_ref);
let r_ref: U256 = From::from(&h);
assert_eq!(r_ref, u);
let r: U256 = From::from(h);
assert_eq!(r, u);
}
}<|fim▁end|>
|
}
}
impl Hasher for PlainHasher {
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
Cairo test suite.
"""
import imp
import os
import cairosvg
reference_cairosvg = imp.load_source(
'cairosvg_reference', pathname=os.path.join(
os.path.dirname(__file__), 'cairosvg_reference', 'cairosvg',
'__init__.py'))<|fim▁hole|>cairosvg.features.LOCALE = reference_cairosvg.features.LOCALE = 'en_US'
TEST_FOLDER = os.path.join(os.path.dirname(__file__), 'svg')
os.chdir(TEST_FOLDER) # relative image urls
if os.environ.get('CAIROSVG_TEST_FILES'): # pragma: no cover
ALL_FILES = os.environ['CAIROSVG_TEST_FILES'].split(',')
else:
ALL_FILES = os.listdir(TEST_FOLDER)
ALL_FILES.sort(key=lambda name: name.lower())
FILES = [
os.path.join(
os.path.dirname(TEST_FOLDER) if name.startswith('fail')
else TEST_FOLDER, name)
for name in ALL_FILES]<|fim▁end|>
| |
<|file_name|>optionsF.cc<|end_file_name|><|fim▁begin|>/***
* * WHAT
* * FILE
* * $Source: /home/vdmtools/cvsroot/toolbox/code/qtgui/optionsF.cc,v $
* * VERSION
* * $Revision: 1.29 $
* * DATE
* * $Date: 2006/02/07 01:52:03 $
* * AUTHOR
* * $Author: vdmtools $
* * COPYRIGHT
* * (C) Kyushu University
***/
#include "optionsF.h"
#include "mainF.h"
#include "interface2TB.h"
#include "interfacesF.h"
#include "qtport.h"
#if QT_VERSION < 0x040000
#include <qfile.h>
#endif // QT_VERSION < 0x040000
/*
* Constructs a optionsW which is a child of 'parent', with the
* name 'name' and widget flags set to 'f'
*
* The dialog will by default be modeless, unless you set 'modal' to
* TRUE to construct a modal dialog.
*/
optionsW::optionsW( QWidget* parent, const char* name, bool modal, WFlags fl )
#if QT_VERSION >= 0x040000
: QDialog( parent, fl )
#else
: QDialog( parent, name, modal, fl )
#endif // QT_VERSION >= 0x040000
{
this->mainw = (mainW*)parent;
this->setWindowName( (name == NULL) ? "optionsW" : name );
#if QT_VERSION >= 0x040000
this->setModal(modal);
this->setWindowTitle( tr( "Project Options" ) );
#else
if ( !name ) {
this->setName( "optionsW" );
}
this->setCaption( tr( "Project Options" ) );
#endif // QT_VERSION >= 0x040000
this->setSizeGripEnabled( true );
QVBoxLayout* layout = this->createVBoxLayout( this );
layout->setMargin( 11 );
layout->addWidget( this->createTabPart( this ) );
layout->addLayout( this->createButtonPart( this ) );
#ifdef VICE
#ifdef _MSC_VER
this->resize( this->sizeHint().width() + 40, this->sizeHint().height());
#else
this->resize( this->sizeHint() );
#endif // _MSC_VER
#else
this->resize( this->sizeHint() );
#endif // VICE
this->setOptions();
}
QWidget* optionsW::createTabPart( QWidget* parent )
{
#if QT_VERSION >= 0x040000
QTabWidget* tabWidget = new QTabWidget( this );
tabWidget->setTabPosition( QTabWidget::North );
#else
QTabWidget* tabWidget = new QTabWidget( this );
tabWidget->setTabPosition( QTabWidget::Top );
#endif // QT_VERSION >= 0x040000
tabWidget->setTabShape( QTabWidget::Rounded );
#if QT_VERSION >= 0x040000
tabWidget->addTab( this->createInterpreterTab( tabWidget ), tr( "Interpreter" ) );
#else
tabWidget->insertTab( this->createInterpreterTab( tabWidget ), tr( "Interpreter" ) );
#endif // QT_VERSION >= 0x040000
#ifdef VDMPP
#ifdef VICE
#if QT_VERSION >= 0x040000
tabWidget->addTab( this->createVICETab( tabWidget ), tr( "VICE" ) );
#else
tabWidget->insertTab( this->createVICETab( tabWidget ), tr( "VICE" ) );
#endif // QT_VERSION >= 0x040000
#endif // VICE
#endif // VDMPP
#if QT_VERSION >= 0x040000
tabWidget->addTab( this->createTypeCheckerTab( tabWidget ), tr( "Type checker" ) );
tabWidget->addTab( this->createPrettyPrinterTab( tabWidget ), tr( "Pretty printer" ) );
tabWidget->addTab( this->createCppCodeGeneratorTab( tabWidget ), tr( "C++ code generator" ) );
#ifdef VDMPP
tabWidget->addTab( this->createJavaCodeGeneratorTab( tabWidget ), tr( "Java code generator" ) );
tabWidget->addTab( this->createJ2VTab( tabWidget ), tr( "Java to VDM++" ) );
#endif // VDMPP
#else
tabWidget->insertTab( this->createTypeCheckerTab( tabWidget ), tr( "Type checker" ) );
tabWidget->insertTab( this->createPrettyPrinterTab( tabWidget ), tr( "Pretty printer" ) );
tabWidget->insertTab( this->createCppCodeGeneratorTab( tabWidget ), tr( "C++ code generator" ) );
#ifdef VDMPP
tabWidget->insertTab( this->createJavaCodeGeneratorTab( tabWidget ), tr( "Java code generator" ) );
tabWidget->insertTab( this->createJ2VTab( tabWidget ), tr( "Java to VDM++" ) );
#endif // VDMPP
#endif // QT_VERSION >= 0x040000
this->maintab = tabWidget;
return tabWidget;
}
QSpacerItem * optionsW::createSpacer()
{
return new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding );
}
QFrame * optionsW::createFrame( QWidget* parent )
{
QFrame* frame = new QFrame( parent );
frame->setFrameShape( QFrame::StyledPanel );
frame->setFrameShadow( QFrame::Raised );
return frame;
}
QGroupBox * optionsW::createVGroupBox( QWidget* parent )
{
#if QT_VERSION >= 0x040000
QGroupBox* gbox = new QGroupBox( parent );
QVBoxLayout* layout = this->createVBoxLayout( NULL );
gbox->setLayout(layout);
#else
QGroupBox* gbox = new QGroupBox( parent );
gbox->setOrientation( Qt::Vertical );
QLayout* layout = gbox->layout();
layout->setSpacing(6);
layout->setMargin(11);
#endif // QT_VERSION >= 0x040000
return gbox;
}
QVBoxLayout* optionsW::createVBoxLayout( QWidget* parent )
{
QVBoxLayout* layout = new QVBoxLayout( parent );
layout->setSpacing( 6 );
layout->setAlignment( Qt::AlignTop );
return layout;
}
QHBoxLayout* optionsW::createHBoxLayout( QWidget* parent )
{
QHBoxLayout* layout = new QHBoxLayout( parent );
layout->setSpacing( 6 );
return layout;
}
QVBoxLayout* optionsW::createVBoxFrameLayout( QFrame* frame )
{
QVBoxLayout* layout = this->createVBoxLayout( frame );
#if QT_VERSION >= 0x040000
#else
layout->setMargin( 6 );
#endif // QT_VERSION >= 0x040000
layout->setAlignment( Qt::AlignTop );
return layout;
}
QSpinBox* optionsW::createSpinBox( QWidget* parent, int min, int max, int value )
{
QSpinBox * sbox = new QSpinBox( parent );
#if QT_VERSION >= 0x040000
sbox->setMaximum( max );
sbox->setMinimum( min );
#else
sbox->setMaxValue( max );
sbox->setMinValue( min );
#endif // QT_VERSION >= 0x040000
sbox->setValue( value );
return sbox;
}
QComboBox* optionsW::createComboBox( QWidget* parent )
{
QComboBox * cbox = new QComboBox( parent );
#if QT_VERSION >= 0x040000
cbox->setMaxVisibleItems( 5 );
#else
cbox->setSizeLimit( 5 );
#endif // QT_VERSION >= 0x040000
// cbox->setMaxCount( 5 );
cbox->setAutoCompletion( true );
cbox->setDuplicatesEnabled( false );
return cbox;
}
QWidget* optionsW::createInterpreterTab( QWidget* parent )
{
QWidget* tab = new QWidget( parent );
QVBoxLayout* layout = this->createVBoxLayout( tab );
layout->addWidget( this->createInterpreterFrame( tab ) );
return tab;
}
QWidget* optionsW::createInterpreterFrame( QWidget* parent )
{
QFrame* frame = this->createFrame( parent );
QVBoxLayout* layout = this->createVBoxFrameLayout( frame );
QHBoxLayout* hlayout = this->createHBoxLayout( NULL );
hlayout->addItem( this->createInterpreterLayout1( frame ) );
hlayout->addItem( this->createInterpreterLayout2( frame ) );
layout->addItem(hlayout);
layout->addItem(this->createExpressionLayout( frame ));
return frame;
}
QLayout* optionsW::createInterpreterLayout1( QWidget* parent )
{
QVBoxLayout* layout = this->createVBoxLayout( NULL );
layout->addWidget( this->createRuntimeCheckingGroupBox( parent ));
this->ip_ppValues = new QCheckBox( parent );
this->ip_ppValues->setText( mainW::mf(tr( "Pretty printing of &values" )) );
layout->addWidget( this->ip_ppValues );
this->ip_exception = new QCheckBox( parent );
this->ip_exception->setText( mainW::mf(tr( "Catch RunTime Error as &exception" )) );
layout->addWidget( this->ip_exception );
this->ip_oldreverse = new QCheckBox( parent );
this->ip_oldreverse->setText( mainW::mf( tr( "Old reverse in Sequence Loop Stmt" )) );
layout->addWidget( this->ip_oldreverse );
#ifdef VDMPP
layout->addItem( this->createSpacer() );
#endif //VDMPP
QObject::connect( this->ip_dynInvCheck, SIGNAL(clicked()), this, SLOT(invClicked()));
return layout;
}
QWidget* optionsW::createRuntimeCheckingGroupBox( QWidget * parent )
{
QGroupBox* gbox = this->createVGroupBox( parent );
gbox->setTitle( tr("Runtime checking") );
QLayout* layout = gbox->layout();
this->ip_dynTypeCheck = new QCheckBox( parent );
this->ip_dynTypeCheck->setText( mainW::mf(tr( "&Dynamic type check" )) );
#if QT_VERSION >= 0x040000
layout->addWidget( this->ip_dynTypeCheck );
#else
layout->add( this->ip_dynTypeCheck );
#endif // QT_VERSION >= 0x040000
this->ip_dynInvCheck = new QCheckBox( parent );
this->ip_dynInvCheck->setText( mainW::mf(tr( "Dynamic checks of &invariants" )) );
#if QT_VERSION >= 0x040000
layout->addWidget( this->ip_dynInvCheck );
#else
layout->add( this->ip_dynInvCheck );
#endif // QT_VERSION >= 0x040000
this->ip_preCheck = new QCheckBox( parent );
this->ip_preCheck->setText( mainW::mf(tr( "Check of &pre-conditions" )) );
#if QT_VERSION >= 0x040000
layout->addWidget( this->ip_preCheck );
#else
layout->add( this->ip_preCheck );
#endif // QT_VERSION >= 0x040000
this->ip_postCheck = new QCheckBox( parent );
this->ip_postCheck->setText( mainW::mf(tr( "Check of p&ost-conditions" )) );
#if QT_VERSION >= 0x040000
layout->addWidget( this->ip_postCheck );
#else
layout->add( this->ip_postCheck );
#endif // QT_VERSION >= 0x040000
this->ip_measureCheck = new QCheckBox( parent );
this->ip_measureCheck->setText( mainW::mf(tr( "Check of &measures" )) );
#if QT_VERSION >= 0x040000
layout->addWidget( this->ip_measureCheck );
#else
layout->add( this->ip_measureCheck );
#endif // QT_VERSION >= 0x040000
return gbox;
}
QLayout* optionsW::createInterpreterLayout2( QWidget* parent )
{
QVBoxLayout* layout = this->createVBoxLayout( NULL );
layout->addWidget( this->createRandomGeneratorGroupBox(parent) );
#ifdef VDMPP
layout->addWidget( this->createMultiThreadGroupBox( parent ) );
#endif // VDMPP
#ifdef VDMSL
layout->addItem( this->createSpacer() );
#endif // VDMSL
return layout;
}
QLayout* optionsW::createExpressionLayout( QWidget* parent )
{
QVBoxLayout* layout = this->createVBoxLayout( NULL );
QHBoxLayout* hlayout = new QHBoxLayout();
QLabel* label = new QLabel( parent );
label->setText( tr( "Expression: " ) );
hlayout->addWidget( label );
QLineEdit * edit = new QLineEdit( parent );
hlayout->addWidget( edit );
this->ip_expression = edit;
layout->addItem(hlayout);
return layout;
}
QWidget* optionsW::createRandomGeneratorGroupBox( QWidget * parent )
{
QGroupBox* gbox = this->createVGroupBox( parent );
gbox->setTitle( tr("Nondeterministic") );
QLayout* layout = gbox->layout();
layout->addItem( this->createRandomGeneratorSeedLayout( gbox ) );
layout->addItem( this->createRandomGeneratorMessageLayout( gbox ) );
return gbox;
}
QLayout* optionsW::createRandomGeneratorSeedLayout( QWidget * parent )
{
QHBoxLayout* layout = new QHBoxLayout();
QLabel* label = new QLabel( parent );
label->setText( tr( "Initialize random generator with:" ) );
layout->addWidget( label );
QSpinBox * sbox = this->createSpinBox( parent, -1, 999999, -1 );
layout->addWidget( sbox );
this->ip_rndGen = sbox;
return layout;
}
QLayout* optionsW::createRandomGeneratorMessageLayout( QWidget * parent )
{
QHBoxLayout* layout = new QHBoxLayout();
layout->addItem( new QSpacerItem( 20, 20, QSizePolicy::Minimum) );
QLabel* label = new QLabel( parent );
label->setText( tr( "(-1 non random)" ) );
layout->addWidget( label );
return layout;
}
#ifdef VDMPP
QWidget* optionsW::createMultiThreadGroupBox( QWidget * parent )
{
QGroupBox* gbox = this->createVGroupBox( parent );
gbox->setTitle( tr("Multi Thread") );
QLayout* layout = gbox->layout();
ip_prioritySchd = new QCheckBox( gbox );
ip_prioritySchd->setText( mainW::mf(tr( "Enable priority-based &scheduling" )) );
#if QT_VERSION >= 0x040000
layout->addWidget( ip_prioritySchd );
#else
layout->add( ip_prioritySchd );
#endif // QT_VERSION >= 0x040000
layout->addItem( this->createPrimarySchdAlgorithmLayout( gbox ) );
layout->addItem( this->createMaxInstrLayout( gbox ) );
#ifdef VICE
layout->addItem( this->createMaxTimeLayout( gbox ) );
#endif // VICE
return gbox;
}
QLayout* optionsW::createMaxInstrLayout( QWidget * parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
QLabel* label = new QLabel( parent );
label->setText( tr( "Maximum instructions per slice:" ) );
layout->addWidget( label );
this->ip_maxInstrLabel = label;
QSpinBox * sbox = this->createSpinBox( parent, 1, 999999, 1000 );
layout->addWidget( sbox );
this->ip_maxInstr = sbox;
return layout;
}
#ifdef VICE
QLayout* optionsW::createMaxTimeLayout( QWidget * parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
QLabel* label = new QLabel( parent );
label->setText( tr( "Maximum time per slice:" ) );
layout->addWidget( label );
this->ip_maxTimeLabel = label;
QSpinBox * sbox = this->createSpinBox( parent, 1, 999999, 1000 );
layout->addWidget( sbox );
this->ip_maxTime = sbox;
return layout;
}
#endif // VICE
QLayout* optionsW::createPrimarySchdAlgorithmLayout( QWidget * parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
QLabel* label = new QLabel( parent );
label->setText( tr( "Primary Scheduling Algorithm" ) );
layout->addWidget( label );
QComboBox * cbox = this->createComboBox( parent );
#if QT_VERSION >= 0x040000
cbox->addItem(tr("pure_cooperative"));
#ifdef VICE
cbox->addItem(tr("timeslice"));
#endif // VISE
cbox->addItem(tr("instruction_number_slice"));
#else
cbox->insertItem(tr("pure_cooperative"));
#ifdef VICE
cbox->insertItem(tr("timeslice"));
#endif // VISE
cbox->insertItem(tr("instruction_number_slice"));
#endif // QT_VERSION >= 0x040000
layout->addWidget( cbox );
QObject::connect(cbox, SIGNAL(activated(int)), this, SLOT(algorithmChanged(int)));
this->ip_primaryAlg = cbox;
return layout;
}
#ifdef VICE
QLayout* optionsW::createStepSizeLayout( QWidget * parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
QLabel* label = new QLabel( parent );
label->setText( tr( "Step Size:" ) );
layout->addWidget( label );
QSpinBox * sbox = this->createSpinBox( parent, 0, 999999, 100 );
layout->addWidget( sbox );
this->ip_stepSize = sbox;
return layout;
}
QWidget* optionsW::createVirtualCPUCapacityGroupBox( QWidget * parent )
{
QGroupBox* gbox = this->createVGroupBox( parent );
gbox->setTitle( tr("Virtual CPU") );
QLayout* layout = gbox->layout();
QCheckBox* checkbox = new QCheckBox( gbox );
checkbox->setText( tr( "Specify Virtual CPU Capacity" ) );
#if QT_VERSION >= 0x040000
layout->addWidget( checkbox );
#else
layout->add( checkbox );
#endif // QT_VERSION >= 0x040000
this->ip_vcpuCapacitycb = checkbox;
QLabel* label2 = new QLabel( gbox );
label2->setText( tr( "(Unchecking means INFINITE)" ) );
#if QT_VERSION >= 0x040000
layout->addWidget( label2 );
#else
layout->add( label2 );
#endif // QT_VERSION >= 0x040000
QLabel* label = new QLabel( gbox );
label->setText( tr( "Virtual CPU Capacity:" ) );
#if QT_VERSION >= 0x040000
layout->addWidget( label );
#else
layout->add( label );
#endif // QT_VERSION >= 0x040000
this->ip_vcpuCapacityLabel = label;
QSpinBox * sbox = this->createSpinBox( gbox, 1, 99999999, 1000000 );
#if QT_VERSION >= 0x040000
layout->addWidget( sbox );
#else
layout->add( sbox );
#endif // QT_VERSION >= 0x040000
this->ip_vcpuCapacity = sbox;
QObject::connect(this->ip_vcpuCapacitycb, SIGNAL(clicked()), this, SLOT(vcpuCapacityEnabled()));
return gbox;
}
QLayout* optionsW::createDefaultCapacityLayout( QWidget * parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
QLabel* label = new QLabel( parent );
label->setText( tr( "Default CPU Capacity:" ) );
layout->addWidget( label );
QSpinBox * sbox = this->createSpinBox( parent, 1, 99999999, 1000000 );
layout->addWidget( sbox );
this->ip_cpuCapacity = sbox;
return layout;
}
QLayout* optionsW::createJitterModeLayout( QWidget * parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
QLabel* label = new QLabel( parent );
label->setText( tr( "Jitter Mode:" ) );
layout->addWidget( label );
QComboBox * cbox = this->createComboBox( parent );
#if QT_VERSION >= 0x040000
cbox->addItem(tr("Early"));
cbox->addItem(tr("Random"));
cbox->addItem(tr("Late"));
#else
cbox->insertItem(tr("Early"));
cbox->insertItem(tr("Random"));
cbox->insertItem(tr("Late"));
#endif // QT_VERSION >= 0x040000
layout->addWidget( cbox );
this->ip_jitterMode = cbox;
return layout;
}
QWidget* optionsW::createTraceLogGroupBox( QWidget* parent )
{
QGroupBox* gbox = this->createVGroupBox( parent );
gbox->setTitle( tr("Trace Logging") );
QLayout* layout = gbox->layout();
QCheckBox * cbox = new QCheckBox( gbox );
cbox->setText( tr( "Log All Operation's Arguments" ) );
#if QT_VERSION >= 0x040000
layout->addWidget( cbox );
#else
layout->add( cbox );
#endif // QT_VERSION >= 0x040000
this->ip_logArgsAllCheck = cbox;
QObject::connect(cbox, SIGNAL(clicked()), this, SLOT(logArgsAllEnabled()));
// QPushButton* button = new QPushButton( gbox, "OpSelectButton" );
// button->setText( tr( "Select operations" ) );
// layout->add( button );
// this->ip_opsSelectButton = button;
// QObject::connect(button,SIGNAL(clicked()),this,SLOT(interfaces()));
#if QT_VERSION >= 0x040000
QListWidget * lbox = new QListWidget( gbox );
layout->addWidget( lbox );
#else
QListBox * lbox = new QListBox( gbox );
layout->add( lbox );
#endif // QT_VERSION >= 0x040000
this->ip_selectedOpsList = lbox;
layout->addItem( this->createClassInputLayout( gbox ) );
layout->addItem( this->createOpInputLayout( gbox ) );
layout->addItem( this->createAddDelButtonLayout( gbox ) );
return gbox;
}
QLayout* optionsW::createClassInputLayout( QWidget * parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
QLabel* label = new QLabel( parent );
label->setText( tr( "Class Name:" ) );
layout->addWidget( label );
this->ip_classNameLabel = label;
QComboBox * cbox = this->createComboBox( parent );
QObject::connect(cbox, SIGNAL(activated(int)), this, SLOT(classChanged(int)));
layout->addWidget( cbox );
this->ip_className = cbox;
return layout;
}
QLayout* optionsW::createOpInputLayout( QWidget * parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
QLabel* label = new QLabel( parent );
label->setText( tr( "Operation Name:" ) );
layout->addWidget( label );
this->ip_opNameLabel = label;
QComboBox * cbox = this->createComboBox( parent );
layout->addWidget( cbox );
this->ip_opName = cbox;
return layout;
}
QLayout* optionsW::createAddDelButtonLayout( QWidget * parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
layout->addWidget( this->createAddButton( parent ) );
layout->addWidget( this->createDeleteButton( parent ) );
return layout;
}
QPushButton * optionsW::createAddButton( QWidget * parent )
{
QPushButton* button = new QPushButton( parent );
button->setText( tr( "Add Operation" ) );
this->ip_opAddButton = button;
QObject::connect(button,SIGNAL(clicked()),this,SLOT(addOperation()));
return button;
}
QPushButton * optionsW::createDeleteButton( QWidget * parent )
{
QPushButton* button = new QPushButton( parent );
button->setText( tr( "Remove Operation" ) );
this->ip_opDelButton = button;
QObject::connect(button,SIGNAL(clicked()),this,SLOT(delOperation()));
return button;
}
#endif // VICE
#endif // VDMPP
QWidget* optionsW::createTypeCheckerTab( QWidget* parent )
{
QWidget* tab = new QWidget( parent );
QVBoxLayout* layout = this->createVBoxLayout( tab );
layout->addWidget( this->createTypeCheckerFrame( tab ) );
return tab;
}
QWidget* optionsW::createTypeCheckerFrame( QWidget* parent )
{
QFrame* frame = this->createFrame( parent );
QVBoxLayout* layout = this->createVBoxFrameLayout( frame );
layout->addWidget(this->createTypeCheckerButtonGroup( frame ));
layout->addWidget( this->createTypeCheckerExtCheckBox( frame ) );
layout->addWidget( this->createTypeCheckerMsgSepCheckBox( frame ) );
#ifdef VDMSL
layout->addWidget( this->createStandardVDMSLCheckBox( frame ) );
#endif // VDMSL
layout->addWidget( this->createVDM10CheckBox( frame ) );
layout->addItem( this->createSpacer() );
return frame;
}
QWidget* optionsW::createTypeCheckerButtonGroup( QWidget* parent )
{
#if QT_VERSION >= 0x040000
QGroupBox * bg = new QGroupBox( tr("Type Check Mode"), parent );
QRadioButton* radio1 = new QRadioButton( tr( "\"pos\" type check" ) );
this->tc_posTc = radio1;
QRadioButton* radio2 = new QRadioButton( tr( "\"def\" type check" ) );
this->tc_defTc = radio2;
QVBoxLayout * layout = new QVBoxLayout();
layout->addWidget(radio1);
layout->addWidget(radio2);
bg->setLayout(layout);
#else
QVButtonGroup* bg = new QVButtonGroup(tr("Type Check Mode"), parent, "tcButtons");
QRadioButton* radio1 = new QRadioButton(bg, "tcPos");
radio1->setText( tr( "\"pos\" type check" ) );
this->tc_posTc = radio1;
QRadioButton* radio2 = new QRadioButton(bg, "tcDef");
radio2->setText( tr( "\"def\" type check" ) );
this->tc_defTc = radio2;
#endif // QT_VERSION >= 0x040000
return bg;
}
QCheckBox* optionsW::createTypeCheckerExtCheckBox( QWidget* parent )
{
QCheckBox * cbox = new QCheckBox( parent );
cbox->setText( tr( "Extended type check" ) );
this->tc_extTc = cbox;
return cbox;
}
QCheckBox* optionsW::createTypeCheckerMsgSepCheckBox( QWidget* parent )
{
QCheckBox * cbox = new QCheckBox( parent );
cbox->setText( tr( "Warning/error message separation" ) );
this->tc_msgSeparation = cbox;
return cbox;
}
QCheckBox* optionsW::createStandardVDMSLCheckBox( QWidget* parent )
{
QCheckBox * cbox = new QCheckBox( parent );
cbox->setText( tr( "Standard VDMSL" ) );
this->tc_standardVDMSL = cbox;
return cbox;
}
QCheckBox* optionsW::createVDM10CheckBox( QWidget* parent )
{
QCheckBox * cbox = new QCheckBox( parent );
cbox->setText( tr( "VDM10 Compatible" ) );
this->tc_vdm10 = cbox;
return cbox;
}
QWidget* optionsW::createPrettyPrinterTab( QWidget* parent )
{
QWidget* tab = new QWidget( parent );
QVBoxLayout* layout = this->createVBoxLayout( tab );
layout->addWidget( this->createPrettyPrinterFrame( tab ) );
return tab;
}
QWidget* optionsW::createPrettyPrinterFrame( QWidget* parent )
{
QFrame* frame = this->createFrame( parent );
QVBoxLayout* layout = this->createVBoxFrameLayout( frame );
layout->addWidget( this->createPrettyPrinterIndex( frame ) );
layout->addWidget( this->createPrettyPrinterCloring( frame ) );
layout->addItem( this->createSpacer() );
return frame;
}
QWidget* optionsW::createPrettyPrinterIndex( QWidget* parent )
{
#if QT_VERSION >= 0x040000
QGroupBox * bg = new QGroupBox( tr("Output index"), parent );
QRadioButton* radio1 = new QRadioButton( tr( "No output index" ) );
this->pp_noIndex = radio1;
QRadioButton* radio2 = new QRadioButton( tr( "Output index of definitions" ) );
this->pp_defIndex = radio2;
QRadioButton* radio3 = new QRadioButton( tr( "Output index of definitions and uses" ) );
this->pp_useIndex = radio3;
QVBoxLayout * layout = new QVBoxLayout();
layout->addWidget(radio1);
layout->addWidget(radio2);
layout->addWidget(radio3);
bg->setLayout(layout);
#else
QVButtonGroup* bg = new QVButtonGroup(tr("Output index"), parent, "ppButtons");
QRadioButton* radio1 = new QRadioButton(bg, "pp_noIndex");
radio1->setText( tr( "No output index" ) );
this->pp_noIndex = radio1;
QRadioButton* radio2 = new QRadioButton(bg, "pp_defIndex");
radio2->setText( tr( "Output index of definitions" ) );
this->pp_defIndex = radio2;
QRadioButton* radio3 = new QRadioButton(bg, "pp_useIndex");
radio3->setText( tr( "Output index of definitions and uses" ) );
this->pp_useIndex = radio3;
#endif // QT_VERSION >= 0x040000
return bg;
}
QCheckBox* optionsW::createPrettyPrinterCloring( QWidget* parent )
{
QCheckBox * cbox = new QCheckBox( parent );
cbox->setText( tr( "Test coverage coloring" ) );
this->pp_tcovCol = cbox;
return cbox;
}
QWidget* optionsW::createCppCodeGeneratorTab( QWidget* parent )
{
QWidget* widget = new QWidget( parent );
QVBoxLayout* layout = this->createVBoxLayout( widget );
layout->addWidget( this->createCppCodeGeneratorFrame( widget ) );
return widget;
}
QWidget* optionsW::createCppCodeGeneratorFrame( QWidget* parent )
{
QFrame* frame = this->createFrame( parent );
QVBoxLayout* layout = this->createVBoxFrameLayout( frame );
layout->addWidget( this->createCppCodeGenPosInfCheckBox( frame ) );
#ifdef VDMPP
layout->addWidget( this->createCppCodeGenCheckCondsCheckBox( frame ) );
#endif // VDMPP
layout->addItem( this->createSpacer() );
return frame;
}
QCheckBox* optionsW::createCppCodeGenPosInfCheckBox( QWidget* parent )
{
QCheckBox * cbox = new QCheckBox( parent );
cbox->setText( tr( "Output position information" ) );
this->cpp_posInfo = cbox;
return cbox;
}
QCheckBox* optionsW::createCppCodeGenCheckCondsCheckBox( QWidget* parent )
{
QCheckBox * cbox = new QCheckBox( parent );
cbox->setText( tr( "Check pre and post conditions" ) );
this->cpp_checkConds = cbox;
return cbox;
}
#ifdef VDMPP
QWidget* optionsW::createJavaCodeGeneratorTab( QWidget* parent )
{
QWidget* tab = new QWidget( parent );
QVBoxLayout* layout = this->createVBoxLayout( tab );
layout->addWidget( this->createJavaCodeGeneratorFrame( tab ) );
return tab;
}
QWidget* optionsW::createJavaInterfacesButton( QWidget* parent )
{
QPushButton* button = new QPushButton( parent );
button->setText( tr( "Select interfaces" ) );
QObject::connect(button,SIGNAL(clicked()),this,SLOT(interfaces()));
return button;
}
QLayout* optionsW::createJavaPackageLayout( QWidget* parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
QLabel* label = new QLabel( parent );
label->setText( tr( "Package:" ) );
layout->addWidget( label );
QLineEdit * edit = new QLineEdit( parent );
layout->addWidget( edit );
this->jcg_packageName = edit;
return layout;
}
QLayout* optionsW::createOutputDirCheckBox( QWidget* parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
QCheckBox* checkbox = new QCheckBox( parent );
checkbox->setText( tr( "Specify Code Output Directory" ) );
this->jcg_useOutputDir = checkbox;
layout->addWidget( checkbox );
QPushButton* button = new QPushButton( parent );
button->setText( tr( "Select Code Output Directory" ) );
connect( button, SIGNAL(clicked()), this, SLOT(selectJCGDir()));
this->jcg_selectDir = button;
layout->addWidget( button );
return layout;
}
QLayout* optionsW::createOutputDirNamePart( QWidget* parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
QLabel* label = new QLabel( parent );
label->setText( tr( "Output Directroy:" ) );
layout->addWidget( label );
this->jcg_outputDirLabel = label;
QLineEdit* le = new QLineEdit( parent );
layout->addWidget( le );
this->jcg_outputDirName = le;
return layout;
}
QWidget* optionsW::createJavaCodeGeneratorFrame( QWidget* parent )
{
QFrame* frame = this->createFrame( parent );
QVBoxLayout* layout = this->createVBoxFrameLayout( frame );
QHBoxLayout* hlayout = this->createHBoxLayout( NULL );
QVBoxLayout* vlayout1 = this->createVBoxLayout( NULL );
QVBoxLayout* vlayout2 = this->createVBoxLayout( NULL );
this->jcg_skeletonsOnly = new QCheckBox( frame );
this->jcg_skeletonsOnly->setText( tr( "Generate only skeletons, except for types" ) );
vlayout1->addWidget( this->jcg_skeletonsOnly );
this->jcg_typesOnly = new QCheckBox( frame );
this->jcg_typesOnly->setText( tr( "Generate only types" ) );
vlayout1->addWidget( this->jcg_typesOnly );
this->jcg_useLongs = new QCheckBox( frame );
this->jcg_useLongs->setText( tr( "Generate integers as longs" ) );
vlayout1->addWidget( this->jcg_useLongs );
this->jcg_genConc = new QCheckBox( frame );
this->jcg_genConc->setText( tr( "Generate code with concurrency constructs" ) );
vlayout1->addWidget( this->jcg_genConc );
this->jcg_genConds = new QCheckBox( frame );
this->jcg_genConds->setText( tr( "Generate pre and post functions/operations" ) );
vlayout2->addWidget( this->jcg_genConds );
this->jcg_checkConds = new QCheckBox( frame );
this->jcg_checkConds->setText( tr( "Check pre and post conditions" ) );
vlayout2->addWidget( this->jcg_checkConds );
this->jcg_vdmPrefix = new QCheckBox( frame );
this->jcg_vdmPrefix->setText( tr( "Disable generate \"vdm_\" prefix" ) );
vlayout2->addWidget( this->jcg_vdmPrefix);
this->jcg_needBackup = new QCheckBox( frame );
this->jcg_needBackup->setText( tr( "Create backup file (*.bak)" ) );
vlayout2->addWidget( this->jcg_needBackup);
hlayout->addLayout(vlayout1);
hlayout->addLayout(vlayout2);
layout->addLayout(hlayout);
layout->addWidget( this->createJavaInterfacesButton( frame ) );
layout->addLayout( this->createJavaPackageLayout( frame ) );
layout->addItem( this->createOutputDirCheckBox( frame ) );
layout->addItem( this->createOutputDirNamePart( frame ) );
return frame;
}
QWidget* optionsW::createJ2VTab( QWidget* parent )
{
QWidget* tab = new QWidget( parent );
QVBoxLayout* layout = this->createVBoxLayout( tab );
layout->addWidget( this->createJ2VFrame( tab ) );
return tab;
}
QWidget* optionsW::createJ2VFrame( QWidget* parent )
{
QFrame* frame = this->createFrame( parent );
QVBoxLayout* layout = this->createVBoxFrameLayout( frame );
j2v_stubsOnly = new QCheckBox( frame );
j2v_stubsOnly->setText( mainW::mf(tr( "Generate &stubs only" )) );
layout->addWidget( j2v_stubsOnly );
// j2v_autoRenaming = new QCheckBox( frame );
// j2v_autoRenaming->setText( tr( "Automatic &renaming" ) );
// layout->addWidget( j2v_autoRenaming );
// j2v_genAccessors = new QCheckBox( frame );
// j2v_genAccessors->setText( tr( "&Generate acessor functions" ) );
// layout->addWidget( j2v_genAccessors );
j2v_transforms = new QCheckBox( frame );
j2v_transforms->setText( mainW::mf(tr( "Apply VDM++ &transformations" )) );
layout->addWidget( j2v_transforms );
layout->addItem( this->createSpacer() );
return frame;
}
#ifdef VICE
QWidget* optionsW::createVICETab( QWidget* parent )
{
QWidget* widget = new QWidget( parent );
QHBoxLayout* layout = this->createHBoxLayout( widget );
layout->addItem( this->createVICELayout1( widget ) );
layout->addItem( this->createVICELayout2( widget ) );
return widget;
}
QLayout* optionsW::createVICELayout1( QWidget* parent )
{
QVBoxLayout* layout = this->createVBoxLayout( NULL );
layout->addLayout( this->createStepSizeLayout(parent) );
layout->addLayout( this->createJitterModeLayout(parent) );
layout->addLayout( this->createDefaultCapacityLayout(parent) );
layout->addWidget( this->createVirtualCPUCapacityGroupBox(parent) );
layout->addItem( this->createSpacer() );
return layout;
}
QLayout* optionsW::createVICELayout2( QWidget* parent )
{
QVBoxLayout* layout = this->createVBoxLayout( NULL );
layout->addWidget( this->createTraceLogGroupBox( parent ) );
return layout;
}
#endif // VICE
#endif // VDMPP
QLayout* optionsW::createButtonPart( QWidget* parent )
{
QHBoxLayout* layout = this->createHBoxLayout( NULL );
layout->addWidget( this->createSaveOptionsCheckbox( parent ) );
layout->addItem( this->createSpacer() );
layout->addWidget( this->createCancelButton( parent ) );
layout->addWidget( this->createApplyButton( parent ) );
layout->addWidget( this->createOkButton( parent ) );
return layout;
}
QWidget* optionsW::createHelpButton( QWidget* parent )
{
QPushButton* button = new QPushButton( parent );
button->setText( mainW::mf(tr( "&Help" )) );
button->setAutoDefault( true );
return button;
}
QWidget* optionsW::createSaveOptionsCheckbox( QWidget* parent )
{
QCheckBox* checkbox = new QCheckBox( parent );
checkbox->setText( tr( "Save Options" ) );
checkbox->setChecked(true);
this->saveOptionsFlag = checkbox;
return checkbox;
}
QWidget* optionsW::createOkButton( QWidget* parent )
{
QPushButton* button = new QPushButton( parent );
button->setText( mainW::mf(tr( "&OK" )) );
button->setAutoDefault( true );
button->setDefault( true );
connect( button, SIGNAL( clicked() ), this, SLOT( okPressed() ) );
return button;
}
QWidget* optionsW::createCancelButton( QWidget* parent )
{
QPushButton* button = new QPushButton( parent );
button->setText( mainW::mf(tr( "&Cancel" )) );
button->setAutoDefault( true );
connect( button, SIGNAL( clicked() ), this, SLOT( reject() ) );
return button;
}
QWidget* optionsW::createApplyButton( QWidget* parent )
{
QPushButton* button = new QPushButton( parent );
button->setText( mainW::mf(tr( "&Apply" )) );
button->setAutoDefault( true );
connect( button, SIGNAL( clicked() ), this, SLOT( putOptions() ));
return button;
}
/*
* Destroys the object and frees any allocated resources
*/
optionsW::~optionsW()
{
// no need to delete child widgets, Qt does it all for us
}
void optionsW::interfaces()
{
interfacesW * interfacesF = new interfacesW(this, "", true, 0);
#if QT_VERSION >= 0x040000
interfacesF->setWindowIcon(windowIcon());
#else
interfacesF->setIcon(*icon());
#endif // QT_VERSION >= 0x040000
interfacesF->show();
interfacesF->exec();
if (interfacesF->result() == QDialog::Accepted)
{
QStringList interfaces (interfacesF->getInterfaces());
Qt2TB::setSelectedInterfacesI(interfaces);
}
}
void optionsW::show()
{
// this->loadOptions();
this->setOptions();
QDialog::show();
}
void optionsW::okPressed()
{
this->putOptions();
accept();
this->saveOptions();
}
void optionsW::setOptions()
{
QMap<QString, QString> optionMap (Qt2TB::GetOptions());
this->ip_dynTypeCheck->setChecked(String2Bool(optionMap[ "DTC" ]));
this->ip_dynInvCheck->setChecked(String2Bool(optionMap[ "INV" ]));
this->ip_preCheck->setChecked(String2Bool(optionMap[ "PRE" ]));
this->ip_postCheck->setChecked(String2Bool(optionMap[ "POST" ]));
this->ip_measureCheck->setChecked(String2Bool(optionMap[ "MEASURE" ]));
#ifdef VDMPP
this->ip_prioritySchd->setChecked(String2Bool(optionMap[ "PRIORITY" ]));
QString alg (optionMap[ "PRIMARYALGORITHM" ]);
for(int i = 0; i < this->ip_primaryAlg->count(); i++) {
#if QT_VERSION >= 0x040000
this->ip_primaryAlg->setCurrentIndex(i);
#else
this->ip_primaryAlg->setCurrentItem(i);
#endif // QT_VERSION >= 0x040000
if(alg == this->ip_primaryAlg->currentText()) {
this->algorithmChanged(i);
break;
}
}
this->ip_maxInstr->setValue(optionMap[ "MAXINSTR" ].toInt());
#ifdef VICE
this->ip_maxTime->setValue(optionMap[ "MAXTIME" ].toInt());
this->ip_stepSize->setValue(optionMap[ "STEPSIZE" ].toInt());
this->ip_cpuCapacity->setValue(optionMap[ "DEFAULTCPUCAPACITY" ].toInt());
if(optionMap[ "DEFAULTVCPUCAPACITY" ] == "<INFINITE>") {
this->ip_vcpuCapacitycb->setChecked(false);
}
else {
this->ip_vcpuCapacitycb->setChecked(true);
this->ip_vcpuCapacity->setValue(optionMap[ "DEFAULTVCPUCAPACITY" ].toInt());
}
this->vcpuCapacityEnabled();
QString jmode (optionMap[ "JITTERMODE" ]);
for(int j = 0; j < this->ip_jitterMode->count(); j++) {
#if QT_VERSION >= 0x040000
this->ip_jitterMode->setCurrentIndex(j);
#else
this->ip_jitterMode->setCurrentItem(j);
#endif // QT_VERSION >= 0x040000
if(jmode == this->ip_jitterMode->currentText()) {
break;
}
}
this->ip_selectedOpsList->clear();
QString logargs (optionMap[ "LOGARGS" ]);
if (logargs == "<ALL>") {<|fim▁hole|> this->ip_logArgsAllCheck->setChecked(true);
}
else {
this->ip_logArgsAllCheck->setChecked(false);
#if QT_VERSION >= 0x040000
QStringList list (logargs.split( ',' ));
#else
QStringList list (QStringList::split( ',', logargs ));
#endif // QT_VERSION >= 0x040000
for( QStringList::const_iterator it = list.begin(); it != list.end(); ++it ) {
#if QT_VERSION >= 0x040000
this->ip_selectedOpsList->addItem(*it);
#else
this->ip_selectedOpsList->insertItem(*it);
#endif // QT_VERSION >= 0x040000
}
}
this->loadClassName();
#endif // VICE
#endif //VDMPP
this->ip_ppValues->setChecked(String2Bool(optionMap[ "PRINT_FORMAT" ]));
this->ip_exception->setChecked(String2Bool(optionMap[ "RTERR_EXCEPTION" ]));
this->ip_rndGen->setValue(optionMap[ "Seed_nondetstmt" ].toInt());
this->ip_expression->setText(optionMap[ "EXPRESSION" ]);
this->ip_oldreverse->setChecked(String2Bool(optionMap[ "OLD_REVERSE" ]));
// Type checker options
this->tc_posTc->setChecked(optionMap[ "DEF" ] != "def");
this->tc_defTc->setChecked(optionMap[ "DEF" ] == "def");
this->tc_extTc->setChecked(String2Bool(optionMap[ "errlevel" ]));
this->tc_msgSeparation->setChecked(String2Bool(optionMap[ "SEP" ]));
#ifdef VDMSL
this->tc_standardVDMSL->setChecked(String2Bool(optionMap[ "VDMSLMOD" ]));
#endif // VDMSL
this->tc_vdm10->setChecked(String2Bool(optionMap[ "VDM10" ]));
// Pretty printer options
int index = optionMap[ "INDEX" ].toInt();
this->pp_noIndex->setChecked(index == 0);
this->pp_defIndex->setChecked(index == 1);
this->pp_useIndex->setChecked(index == 2);
this->pp_tcovCol->setChecked(String2Bool(optionMap[ "PrettyPrint_RTI" ]));
// C++ Code generator options
this->cpp_posInfo->setChecked(String2Bool(optionMap[ "CG_RTI" ]));
#ifdef VDMPP
this->cpp_checkConds->setChecked(String2Bool(optionMap[ "CG_CHECKPREPOST" ]));
#endif // VDMPP
#ifdef VDMPP
// Java code generator options
this->jcg_skeletonsOnly->setChecked(String2Bool(optionMap[ "JCG_SKEL" ]));
this->jcg_typesOnly->setChecked(String2Bool(optionMap[ "JCG_TYPES" ]));
this->jcg_useLongs->setChecked(String2Bool(optionMap[ "JCG_LONGS" ]));
this->jcg_genConc->setChecked(String2Bool(optionMap[ "JCG_CONCUR" ]));
this->jcg_genConds->setChecked(String2Bool(optionMap[ "JCG_GENPREPOST" ]));
this->jcg_checkConds->setChecked(String2Bool(optionMap[ "JCG_CHECKPREPOST" ]));
this->jcg_packageName->setText(optionMap[ "JCG_PACKAGE" ]);
this->jcg_vdmPrefix->setChecked(!String2Bool(optionMap[ "JCG_VDMPREFIX" ]));
this->jcg_useOutputDir->setChecked(String2Bool(optionMap[ "JCG_USEDIRNAME" ]));
this->jcg_outputDirName->setText(optionMap[ "JCG_DIRNAME" ]);
this->jcg_needBackup->setChecked(String2Bool(optionMap[ "JCG_NEEDBACKUP" ]));
if (this->jcg_useOutputDir->isChecked()) {
QDir dir (this->jcg_outputDirName->text());
if (!dir.exists()) {
this->jcg_useOutputDir->setChecked(false);
this->jcg_outputDirName->setText("");
}
}
#endif //VDMPP
// Java2VDM options
// j2v_stubsOnly->setChecked();
// j2v_autoRenaming->setChecked();
// j2v_genAccessors->setChecked();
this->invClicked();
}
void optionsW::putOptions()
{
QMap<QString, QString> optionMap;
optionMap[ "DTC" ] = (this->ip_dynTypeCheck->isChecked() ? "1" : "0");
optionMap[ "INV" ] = (this->ip_dynInvCheck->isChecked() ? "1" : "0");
optionMap[ "PRE" ] = (this->ip_preCheck->isChecked() ? "1" : "0");
optionMap[ "POST" ] = (this->ip_postCheck->isChecked() ? "1" : "0");
optionMap[ "MEASURE" ] = (this->ip_measureCheck->isChecked() ? "1" : "0");
#ifdef VDMPP
optionMap[ "PRIORITY" ] = (this->ip_prioritySchd->isChecked() ? "1" : "0");
optionMap[ "PRIMARYALGORITHM" ] = this->ip_primaryAlg->currentText();
optionMap[ "MAXINSTR" ] = QString::number(this->ip_maxInstr->value());
#ifdef VICE
optionMap[ "MAXTIME" ] = QString::number(this->ip_maxTime->value());
optionMap[ "STEPSIZE" ] = QString::number(this->ip_stepSize->value());
optionMap[ "DEFAULTCPUCAPACITY" ] = QString::number(this->ip_cpuCapacity->value());
if( this->ip_vcpuCapacitycb->isChecked() ) {
optionMap[ "DEFAULTVCPUCAPACITY" ] = QString::number(this->ip_vcpuCapacity->value());
}
else {
optionMap[ "DEFAULTVCPUCAPACITY" ] = "<INFINITE>";
}
optionMap[ "JITTERMODE" ] = this->ip_jitterMode->currentText();
if( this->ip_logArgsAllCheck->isChecked() ) {
optionMap[ "LOGARGS" ] = "<ALL>";
}
else {
int len = this->ip_selectedOpsList->count();
QString str;
for(int i = 0; i < len; i++) {
if( i > 0 ) str += ",";
#if QT_VERSION >= 0x040000
QListWidgetItem * item = this->ip_selectedOpsList->item(i);
str += item->text();
#else
str += this->ip_selectedOpsList->text(i);
#endif // QT_VERSION >= 0x040000
}
optionMap[ "LOGARGS" ] = str;
}
#endif // VICE
#endif //VDMPP
optionMap[ "PRINT_FORMAT" ] = (this->ip_ppValues->isChecked() ? "1" : "0");
optionMap[ "RTERR_EXCEPTION" ] = (this->ip_exception->isChecked() ? "1" : "0");
optionMap[ "EXPRESSION" ] = this->ip_expression->text();
optionMap[ "Seed_nondetstmt" ] = QString::number(this->ip_rndGen->value());
optionMap[ "OLD_REVERSE" ] = (this->ip_oldreverse->isChecked() ? "1" : "0");
optionMap[ "DEF" ] = (this->tc_defTc->isChecked() ? "def" : "pos");
optionMap[ "errlevel" ] = (this->tc_extTc->isChecked() ? "1" : "0");
optionMap[ "SEP" ] = (this->tc_msgSeparation->isChecked() ? "1" : "0");
#ifdef VDMSL
optionMap[ "VDMSLMOD" ] = (this->tc_standardVDMSL->isChecked() ? "1" : "0");
#endif // VDMSL
optionMap[ "VDM10" ] = (this->tc_vdm10->isChecked() ? "1" : "0");
// Pretty printer options
if (this->pp_useIndex->isChecked()) {
optionMap[ "INDEX" ] = "2";
}
else if (this->pp_defIndex->isChecked()) {
optionMap[ "INDEX" ] = "1";
}
else {
optionMap[ "INDEX" ] = "0";
}
optionMap[ "PrettyPrint_RTI" ] = (this->pp_tcovCol->isChecked() ? "1" : "0");
// C++ Code generator options
optionMap[ "CG_RTI" ] = (this->cpp_posInfo->isChecked() ? "1" : "0");
#ifdef VDMPP
optionMap[ "CG_CHECKPREPOST" ] = (this->cpp_checkConds->isChecked() ? "1" : "0");
#endif // VDMPP
#ifdef VDMPP
// Java code generator options
optionMap[ "JCG_SKEL" ] = (this->jcg_skeletonsOnly->isChecked() ? "1" : "0");
optionMap[ "JCG_TYPES" ] = (this->jcg_typesOnly->isChecked() ? "1" : "0");
optionMap[ "JCG_LONGS" ] = (this->jcg_useLongs->isChecked() ? "1" : "0");
optionMap[ "JCG_CONCUR" ] = (this->jcg_genConc->isChecked() ? "1" : "0");
optionMap[ "JCG_GENPREPOST" ] = (this->jcg_genConds->isChecked() ? "1" : "0");
optionMap[ "JCG_CHECKPREPOST" ] = (this->jcg_checkConds->isChecked() ? "1" : "0");
optionMap[ "JCG_PACKAGE" ] = this->jcg_packageName->text();
optionMap[ "JCG_VDMPREFIX" ] = (!this->jcg_vdmPrefix->isChecked() ? "1" : "0");
optionMap[ "JCG_USEDIRNAME" ] = (this->jcg_useOutputDir->isChecked() ? "1" : "0");
optionMap[ "JCG_DIRNAME" ] = this->jcg_outputDirName->text();
optionMap[ "JCG_NEEDBACKUP" ] = (this->jcg_needBackup->isChecked() ? "1" : "0");
#endif //VDMPP
Qt2TB::SetOptions(optionMap);
// Java2VDM options
// j2v_stubsOnly->setChecked();
// j2v_autoRenaming->setChecked();
// j2v_genAccessors->setChecked();
}
#ifdef VDMPP
bool optionsW::get_j2v_stubsOnly()
{
return j2v_stubsOnly->isChecked();
}
/*
bool optionsW::get_j2v_autoRenaming()
{
return j2v_autoRenaming->isChecked();
}
*/
bool optionsW::get_j2v_transforms()
{
return j2v_transforms->isChecked();
}
void optionsW::clearJ2VOptions()
{
this->j2v_stubsOnly->setChecked(false);
this->j2v_transforms->setChecked(false);
}
#endif //VDMPP
QString optionsW::getOptionFileName(const QString & prj)
{
QString nm = prj;
if (nm.right(4) != ".prj") return QString();
nm.replace( ".prj", ".opt" );
return nm;
}
void optionsW::loadOptions()
{
#ifdef VDMPP
this->clearJ2VOptions();
#endif // VDMPP
QString filenm( getOptionFileName(Qt2TB::getProjectNameI()) );
if( !filenm.isEmpty() ) {
this->mainw->logWrite(QString("loadOptions for ") + filenm);
QFile optionFile( filenm );
#if QT_VERSION >= 0x040000
if( optionFile.open(QIODevice::ReadOnly) ) {
#else
if( optionFile.open(IO_ReadOnly) ) {
#endif // QT_VERSION >= 0x040000
QTextStream optionStream(&optionFile);
QString version = optionStream.readLine();
optionFile.close();
if( version == "FormatVersion:2" ) {
this->loadOptionsV2();
}
else {
this->loadOptionsV1();
}
#if QT_VERSION >= 0x040000
this->maintab->setCurrentIndex(0);
#else
this->maintab->setCurrentPage(0);
#endif // QT_VERSION >= 0x040000
return;
}
}
Qt2TB::InitOptions();
}
bool optionsW::String2Bool(const QString & str)
{
if( str == "0" || str == "false" || str == "off" ) {
return false;
}
else if( str == "1" || str == "true" || str == "on" ) {
return true;
}
return false;
}
bool optionsW::optionFileExists()
{
QString filenm( getOptionFileName(Qt2TB::getProjectNameI()) );
if( !filenm.isEmpty() ) {
QFile optionFile( filenm );
#if QT_VERSION >= 0x040000
if( optionFile.open(QIODevice::ReadOnly) ) {
#else
if( optionFile.open(IO_ReadOnly) ) {
#endif // QT_VERSION >= 0x040000
optionFile.close();
return true;
}
}
return false;
}
void optionsW::loadOptionsV1()
{
QString filenm( getOptionFileName(Qt2TB::getProjectNameI()) );
if( !filenm.isEmpty() ) {
QFile optionFile( filenm );
#if QT_VERSION >= 0x040000
if( optionFile.open(QIODevice::ReadOnly) ) {
#else
if( optionFile.open(IO_ReadOnly) ) {
#endif // QT_VERSION >= 0x040000
QTextStream optionStream(&optionFile);
QMap<QString, QString> optionMap;
optionMap[ "DTC" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "PRE" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "POST" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "INV" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "SEP" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "CONTEXT" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
#ifdef VDMPP
optionMap[ "MAXINSTR" ] = (optionStream.readLine());
optionMap[ "PRIORITY" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
#ifdef VICE
optionMap[ "PRIMARYALGORITHM" ] = (optionStream.readLine());
optionMap[ "TASKSWITCH" ] = (optionStream.readLine());
optionMap[ "MAXTIME" ] = (optionStream.readLine());
optionMap[ "TIMEFACTOR" ] = (optionStream.readLine());
#endif //VICE
#endif //VDMPP
optionMap[ "VDMSLMODE" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "errlevel" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "PRINT_FORMAT" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "RTERR_EXCEPTION" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "CG_RTI" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "CG_CHECKPREPOST" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
QString tmp;
tmp = optionStream.readLine();
optionMap[ "DEF" ] = ((tmp == "1" || tmp == "def") ? "def" : "pos");
optionMap[ "INDEX" ] = (optionStream.readLine());
optionMap[ "PrettyPrint_RTI" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "C_flag" ] = (optionStream.readLine());
optionMap[ "JCG_SKEL" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "JCG_GENPREPOST" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "JCG_TYPES" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "JCG_SMALLTYPES" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "JCG_LONGS" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "JCG_PACKAGE" ] = (optionStream.readLine());
optionMap[ "JCG_CONCUR" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "JCG_CHECKPREPOST" ] = (String2Bool(optionStream.readLine()) ? "1" : "0");
optionMap[ "JCG_INTERFACES" ] = (optionStream.readLine());
optionMap[ "Seed_nondetstmt" ] = (optionStream.readLine());
Qt2TB::SetOptions(optionMap);
#ifdef VDMPP
j2v_stubsOnly->setChecked(String2Bool(optionStream.readLine()));
j2v_transforms->setChecked(String2Bool(optionStream.readLine()));
#endif // VDMPP
optionFile.close();
}
}
}
void optionsW::loadOptionsV2()
{
QString filenm( getOptionFileName(Qt2TB::getProjectNameI()) );
if( !filenm.isEmpty() ) {
QMap<QString, QString> optionMap (readOption2(filenm));;
#if QT_VERSION >= 0x040000
if (!optionMap.empty()) {
#else
if (!optionMap.isEmpty()) {
#endif // QT_VERSION >= 0x040000
#ifdef VDMPP
if( optionMap.contains( "FVStatic" ) && !optionMap.contains( "VDM10" ) ) {
optionMap["VDM10"] == optionMap["FVStatic"];
}
#endif // VDMPP
Qt2TB::SetOptions(optionMap);
#ifdef VDMPP
if( optionMap.contains( "j2v_stubsOnly" ) ) {
j2v_stubsOnly->setChecked(optionMap["j2v_stubsOnly"] == "1");
}
if( optionMap.contains( "j2v_transforms" ) ) {
j2v_transforms->setChecked(optionMap["j2v_transforms"] == "1");
}
#endif // VDMPP
}
}
}
QMap<QString, QString> optionsW::readOption2(const QString & filename)
{
QMap<QString, QString> optionMap;
QFile optionFile( filename );
#if QT_VERSION >= 0x040000
if( optionFile.open(QIODevice::ReadOnly) ) {
#else
if( optionFile.open(IO_ReadOnly) ) {
#endif // QT_VERSION >= 0x040000
QTextStream optionStream(&optionFile);
while( !optionStream.atEnd() ) {
QString tmp = optionStream.readLine();
if( !tmp.isEmpty() ) {
#if QT_VERSION >= 0x040000
int index = tmp.indexOf( ':' );
if( index != -1 ) {
QString key = tmp.left( index ).simplified();
QString value = tmp.right( tmp.length() - index - 1 ).simplified();
optionMap[ key ] = value;
}
#else
int index = tmp.find( ':' );
if( index != -1 ) {
QString key = tmp.left( index ).stripWhiteSpace();
QString value = tmp.right( tmp.length() - index - 1 ).stripWhiteSpace();
optionMap[ key ] = value;
}
#endif // QT_VERSION >= 0x040000
}
}
optionFile.close();
}
return optionMap;
}
void optionsW::saveOptions()
{
if( this->saveOptionsFlag->isChecked() ) {
QString filenm( getOptionFileName(Qt2TB::getProjectNameI()) );
if( !filenm.isEmpty() ) {
QFile optionFile( filenm );
#if QT_VERSION >= 0x040000
if( optionFile.open(QIODevice::WriteOnly) ) {
#else
if( optionFile.open(IO_WriteOnly) ) {
#endif // QT_VERSION >= 0x040000
QTextStream optionStream(&optionFile);
optionStream << "FormatVersion:2" << endl;
QMap<QString, QString> optionMap (Qt2TB::GetOptions());
#if QT_VERSION >= 0x040000
QList<QString> keys (optionMap.keys());
for (QList<QString>::const_iterator it = keys.begin();it != keys.end();++it) {
#else
QValueList<QString> keys (optionMap.keys());
for (QValueList<QString>::const_iterator it = keys.begin();it != keys.end();++it) {
#endif // QT_VERSION >= 0x040000
optionStream << *it << ":" << optionMap[*it] << endl;
}
#ifdef VDMPP
optionStream << "j2v_stubsOnly:" << ( j2v_stubsOnly->isChecked() ? "1" : "0" ) << endl;
optionStream << "j2v_transforms:" << ( j2v_transforms->isChecked() ? "1" : "0" ) << endl;
#endif // VDMPP
optionStream << "TextCodecName:" << this->currentCodecName << endl;
optionFile.close();
}
}
}
}
void optionsW::algorithmChanged(int)
{
#ifdef VDMPP
QString alg (this->ip_primaryAlg->currentText());
if( alg == "instruction_number_slice" ) {
this->ip_maxInstr->setEnabled(true);
this->ip_maxInstrLabel->setEnabled(true);
#ifdef VICE
this->ip_maxTime->setEnabled(false);
this->ip_maxTimeLabel->setEnabled(false);
#endif // VICE
}
#ifdef VICE
else if( alg == "timeslice" ) {
this->ip_maxInstr->setEnabled(false);
this->ip_maxInstrLabel->setEnabled(false);
this->ip_maxTime->setEnabled(true);
this->ip_maxTimeLabel->setEnabled(true);
}
#endif // VICE
else {
this->ip_maxInstr->setEnabled(false);
this->ip_maxInstrLabel->setEnabled(false);
#ifdef VICE
this->ip_maxTime->setEnabled(false);
this->ip_maxTimeLabel->setEnabled(false);
#endif // VICE
}
#endif // VDMPP
}
void optionsW::vcpuCapacityEnabled()
{
#ifdef VICE
if (this->ip_vcpuCapacitycb->isChecked()) {
this->ip_vcpuCapacityLabel->setEnabled(true);
this->ip_vcpuCapacity->setEnabled(true);
}
else {
this->ip_vcpuCapacityLabel->setEnabled(false);
this->ip_vcpuCapacity->setEnabled(false);
}
#endif // VICE
}
#ifdef VICE
void optionsW::loadClassName()
{
QStringList clist (Qt2TB::getModulesI());
this->ip_className->clear();
for (QStringList::const_iterator it= clist.begin();it != clist.end();++it) {
#if QT_VERSION >= 0x040000
this->ip_className->addItem(*it);
#else
this->ip_className->insertItem(*it);
#endif // QT_VERSION >= 0x040000
}
#if QT_VERSION >= 0x040000
this->ip_className->setCurrentIndex(0);
#else
this->ip_className->setCurrentItem(0);
#endif // QT_VERSION >= 0x040000
this->classChanged(0);
}
#endif // VICE
void optionsW::logArgsAllEnabled()
{
#ifdef VICE
if(this->ip_logArgsAllCheck->isChecked()) {
this->ip_selectedOpsList->setEnabled(false);
this->ip_classNameLabel->setEnabled(false);
this->ip_className->setEnabled(false);
this->ip_opNameLabel->setEnabled(false);
this->ip_opName->setEnabled(false);
this->ip_opAddButton->setEnabled(false);
this->ip_opDelButton->setEnabled(false);
}
else {
this->ip_selectedOpsList->setEnabled(true);
this->ip_classNameLabel->setEnabled(true);
this->ip_className->setEnabled(true);
this->ip_opNameLabel->setEnabled(true);
this->ip_opName->setEnabled(true);
this->ip_opAddButton->setEnabled(true);
this->ip_opDelButton->setEnabled(true);
}
#endif // VICE
}
void optionsW::classChanged(int i)
{
#ifdef VICE
this->ip_opName->clear();
QString clsnm (this->ip_className->currentText());
if( !clsnm.isEmpty() ) {
QStringList oplist;
Qt2TB::setBlock(false);
int res = Qt2TB::getOperationsI(clsnm, oplist);
Qt2TB::setBlock(true);
if( res == INT_OK ) {
for (QStringList::const_iterator it= oplist.begin();it != oplist.end();++it) {
#if QT_VERSION >= 0x040000
this->ip_opName->addItem(*it);
#else
this->ip_opName->insertItem(*it);
#endif // QT_VERSION >= 0x040000
}
#if QT_VERSION >= 0x040000
this->ip_opName->setCurrentIndex(0);
#else
this->ip_opName->setCurrentItem(0);
#endif// QT_VERSION >= 0x040000
}
else {
this->mainw->logWrite("Specification is not initialized.");
}
}
#endif // VICE
}
void optionsW::addOperation()
{
#ifdef VICE
QString clsnm (this->ip_className->currentText());
QString opnm (this->ip_opName->currentText());
if( !clsnm.isEmpty() && !opnm.isEmpty() ) {
QString fullnm (clsnm + "`" + opnm);
#if QT_VERSION >= 0x040000
if( (this->ip_selectedOpsList->findItems(fullnm, 0)).empty() ) {
this->ip_selectedOpsList->addItem(fullnm);
}
#else
if( this->ip_selectedOpsList->findItem(fullnm) == 0 ) {
this->ip_selectedOpsList->insertItem(fullnm);
}
#endif // QT_VERSION >= 0x040000
}
#endif // VICE
}
void optionsW::delOperation()
{
#ifdef VICE
#if QT_VERSION >= 0x040000
int ci = this->ip_selectedOpsList->currentRow();
QListWidgetItem * item = this->ip_selectedOpsList->item(ci);
if( item->isSelected() ) {
this->ip_selectedOpsList->removeItemWidget(item);
}
#else
int ci = this->ip_selectedOpsList->currentItem();
if( this->ip_selectedOpsList->isSelected( ci ) ) {
this->ip_selectedOpsList->removeItem(ci);
}
#endif // QT_VERSION >= 0x040000
#endif // VICE
}
void optionsW::invClicked()
{
if(this->ip_dynInvCheck->isChecked()) {
this->ip_dynTypeCheck->setChecked(true);
this->ip_dynTypeCheck->setEnabled(false);
}
else {
this->ip_dynTypeCheck->setEnabled(true);
}
}
void optionsW::selectJCGDir()
{
#ifdef VDMPP
QString res (QtPort::QtGetExistingDirectory( this, tr("Choose a java code directory"), QString()));
if( !res.isNull() ) {
this->jcg_outputDirName->setText(res);
}
#endif // VDMPP
}
void optionsW::initTab()
{
#if QT_VERSION >= 0x040000
this->maintab->setCurrentIndex(0);
#else
this->maintab->setCurrentPage(0);
#endif // QT_VERSION >= 0x040000
}
QString optionsW::getCodecName(const QString & prj)
{
QString ofn (getOptionFileName(prj));
QMap<QString, QString> optionMap (readOption2(ofn));
if( optionMap.contains( "TextCodecName" ) ) {
return optionMap["TextCodecName"];
}
else {
return QString("");
}
}
QString optionsW::getExpression()
{
QString filenm( getOptionFileName(Qt2TB::getProjectNameI()) );
if( !filenm.isEmpty() ) {
QMap<QString, QString> optionMap (readOption2(filenm));;
if( optionMap.contains( "EXPRESSION" ) ) {
return optionMap["EXPRESSION"];
}
}
return QString("");
}<|fim▁end|>
| |
<|file_name|>0009_auto_20180524_2221.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2018-05-25 02:21
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('itemreg', '0008_auto_20160828_2058'),
]
operations = [
migrations.AlterField(
model_name='calculatorregistration',
name='user',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(<|fim▁hole|> migrations.AlterField(
model_name='phoneregistration',
name='user',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]<|fim▁end|>
|
model_name='computerregistration',
name='user',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
|
<|file_name|>cimgvolumereader.cpp<|end_file_name|><|fim▁begin|>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop<|fim▁hole|> *
* Copyright (c) 2015-2021 Inviwo Foundation
* 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.
*
* 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.
*
*********************************************************************************/
#include <modules/cimg/cimgvolumereader.h>
#include <modules/cimg/cimgutils.h>
#include <inviwo/core/datastructures/volume/volumeramprecision.h>
#include <inviwo/core/datastructures/volume/volumedisk.h>
#include <inviwo/core/util/formatdispatching.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/io/datareaderexception.h>
namespace inviwo {
CImgVolumeReader::CImgVolumeReader() : DataReaderType<Volume>() {
addExtension(FileExtension("hdr", "Analyze 7.5"));
}
CImgVolumeReader* CImgVolumeReader::clone() const { return new CImgVolumeReader(*this); }
std::shared_ptr<Volume> CImgVolumeReader::readData(std::string_view filePath) {
if (!filesystem::fileExists(filePath)) {
throw DataReaderException(IVW_CONTEXT, "Error could not find input file: {}", filePath);
}
auto volumeDisk = std::make_shared<VolumeDisk>(filePath);
volumeDisk->setLoader(new CImgVolumeRAMLoader(filePath));
return std::make_shared<Volume>(volumeDisk);
}
void CImgVolumeReader::printMetaInfo(const MetaDataOwner& metaDataOwner,
std::string_view key) const {
if (auto metaData = metaDataOwner.getMetaData<StringMetaData>(key)) {
std::string metaStr = metaData->get();
replaceInString(metaStr, "\n", ", ");
LogInfo(key << ": " << metaStr);
}
}
CImgVolumeRAMLoader::CImgVolumeRAMLoader(std::string_view sourceFile) : sourceFile_{sourceFile} {}
CImgVolumeRAMLoader* CImgVolumeRAMLoader::clone() const { return new CImgVolumeRAMLoader(*this); }
std::shared_ptr<VolumeRepresentation> CImgVolumeRAMLoader::createRepresentation(
const VolumeRepresentation& src) const {
size3_t dimensions = src.getDimensions();
DataFormatId formatId = DataFormatId::NotSpecialized;
std::string fileName = sourceFile_;
if (!filesystem::fileExists(fileName)) {
const auto newPath = filesystem::addBasePath(fileName);
if (filesystem::fileExists(newPath)) {
fileName = newPath;
} else {
throw DataReaderException("Error could not find input file: " + fileName, IVW_CONTEXT);
}
}
void* data = cimgutil::loadVolumeData(nullptr, fileName, dimensions, formatId);
auto volumeRAM =
createVolumeRAM(dimensions, DataFormatBase::get(formatId), data, src.getSwizzleMask(),
src.getInterpolation(), src.getWrapping());
return volumeRAM;
}
void CImgVolumeRAMLoader::updateRepresentation(std::shared_ptr<VolumeRepresentation> dest,
const VolumeRepresentation& src) const {
auto volumeDst = std::static_pointer_cast<VolumeRAM>(dest);
size3_t dimensions = src.getDimensions();
DataFormatId formatId = DataFormatId::NotSpecialized;
std::string fileName = sourceFile_;
if (!filesystem::fileExists(fileName)) {
const auto newPath = filesystem::addBasePath(fileName);
if (filesystem::fileExists(newPath)) {
fileName = newPath;
} else {
throw DataReaderException("Error could not find input file: " + fileName, IVW_CONTEXT);
}
}
cimgutil::loadVolumeData(volumeDst->getData(), fileName, dimensions, formatId);
}
} // namespace inviwo<|fim▁end|>
| |
<|file_name|>0019_auto_20150903_0458.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
<|fim▁hole|> ]
operations = [
migrations.AlterUniqueTogether(
name='friend_relationship',
unique_together=None,
),
migrations.RemoveField(
model_name='friend_relationship',
name='from_user',
),
migrations.RemoveField(
model_name='friend_relationship',
name='to_user',
),
migrations.RemoveField(
model_name='nice_user',
name='friends',
),
migrations.DeleteModel(
name='Friend_Relationship',
),
]<|fim▁end|>
|
dependencies = [
('course_selection', '0018_auto_20150830_0319'),
|
<|file_name|>codedarticle.py<|end_file_name|><|fim▁begin|>###########################################################################
# (C) Vrije Universiteit, Amsterdam (the Netherlands) #
# #
# This file is part of AmCAT - The Amsterdam Content Analysis Toolkit #
# #
# AmCAT is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Affero General Public License as published by the #
# Free Software Foundation, either version 3 of the License, or (at your #<|fim▁hole|># FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public #
# License for more details. #
# #
# You should have received a copy of the GNU Affero General Public #
# License along with AmCAT. If not, see <http://www.gnu.org/licenses/>. #
###########################################################################
import collections
from functools import partial
from django.db import models, transaction, connection, IntegrityError
import logging
from django.db.models import sql
import itertools
from amcat.models.coding.codingschemafield import CodingSchemaField
from amcat.models.coding.coding import CodingValue, Coding
from amcat.tools.model import AmcatModel
log = logging.getLogger(__name__)
STATUS_NOTSTARTED, STATUS_INPROGRESS, STATUS_COMPLETE, STATUS_IRRELEVANT = 0, 1, 2, 9
class CodedArticleStatus(AmcatModel):
id = models.IntegerField(primary_key=True, db_column='status_id')
label = models.CharField(max_length=50)
class Meta():
db_table = 'coded_article_status'
app_label = 'amcat'
def _to_coding(coded_article, coding):
"""
Takes a dictionary with keys 'sentence_id', 'start', 'end', and creates
an (unsaved) Coding object.
@type codingjob: CodingJob
@type article: Article
@type coding: dict
"""
return Coding(
coded_article=coded_article, sentence_id=coding.get("sentence_id"),
start=coding.get("start"), end=coding.get("end")
)
def _to_codingvalue(coding, codingvalue):
"""
Takes a dictionary with keys 'codingschemafield_id', 'intval', 'strval' and creates
an (unsaved) CodingValue object.
@type coding: Coding
@type codingvalue: dict
"""
return CodingValue(
field_id=codingvalue.get("codingschemafield_id"),
intval=codingvalue.get("intval"),
strval=codingvalue.get("strval"),
coding=coding
)
def _to_codingvalues(coding, values):
"""
Takes an iterator with codingvalue dictionaries (see _to_coding) and a coding,
and returns an iterator with CodingValue's.
"""
return map(partial(_to_codingvalue, coding), values)
class CodedArticle(models.Model):
"""
A CodedArticle is an article in a context of two other objects: a codingjob and an
article. It exist for every (codingjob, article) in {codingjobs} X {codingjobarticles}
and is created when creating a codingjob (see `create_coded_articles` in codingjob.py).
Each coded article contains codings (1:N) and each coding contains codingvalues (1:N).
"""
comments = models.TextField(blank=True, null=True)
status = models.ForeignKey(CodedArticleStatus, default=STATUS_NOTSTARTED)
article = models.ForeignKey("amcat.Article", related_name="coded_articles")
codingjob = models.ForeignKey("amcat.CodingJob", related_name="coded_articles")
def __unicode__(self):
return "Article: {self.article}, Codingjob: {self.codingjob}".format(**locals())
def set_status(self, status):
"""Set the status of this coding, deserialising status as needed"""
if type(status) == int:
status = CodedArticleStatus.objects.get(pk=status)
self.status = status
self.save()
def get_codings(self):
"""Returns a generator yielding tuples (coding, [codingvalues])"""
codings = Coding.objects.filter(coded_article=self)
values = CodingValue.objects.filter(coding__in=codings)
values_dict = collections.defaultdict(list)
for value in values:
values_dict[value.coding_id].append(value)
for coding in codings:
yield (coding, values_dict[coding.id])
def _replace_codings(self, new_codings):
# Updating tactic: delete all existing codings and codingvalues, then insert
# the new ones. This prevents calculating a delta, and confronting the
# database with (potentially) many update queries.
CodingValue.objects.filter(coding__coded_article=self).delete()
Coding.objects.filter(coded_article=self).delete()
new_coding_objects = map(partial(_to_coding, self), new_codings)
# Saving each coding is pretty inefficient, but Django doesn't allow retrieving
# id's when using bulk_create. See Django ticket #19527.
if connection.vendor == "postgresql":
query = sql.InsertQuery(Coding)
query.insert_values(Coding._meta.fields[1:], new_coding_objects)
raw_sql, params = query.sql_with_params()[0]
new_coding_objects = Coding.objects.raw("%s %s" % (raw_sql, "RETURNING coding_id"), params)
else:
# Do naive O(n) approach
for coding in new_coding_objects:
coding.save()
coding_values = itertools.chain.from_iterable(
_to_codingvalues(co, c["values"]) for c, co in itertools.izip(new_codings, new_coding_objects)
)
return (new_coding_objects, CodingValue.objects.bulk_create(coding_values))
def replace_codings(self, coding_dicts):
"""
Creates codings and replace currently existing ones. It takes one parameter
which has to be an iterator of dictionaries with each dictionary following
a specific format:
{
"sentence_id" : int,
"start" : int,
"end" : int,
"values" : [CodingDict]
}
with CodingDict being:
{
"codingschemafield_id" : int,
"intval" : int / NoneType,
"strval" : str / NoneType
}
@raises IntegrityError: codingschemafield_id is None
@raises ValueError: intval == strval == None
@raises ValueError: intval != None and strval != None
@returns: ([Coding], [CodingValue])
"""
coding_dicts = tuple(coding_dicts)
values = tuple(itertools.chain.from_iterable(cd["values"] for cd in coding_dicts))
if any(v.get("intval") == v.get("strval") == None for v in values):
raise ValueError("intval and strval cannot both be None")
if any(v.get("intval") is not None and v.get("strval") is not None for v in values):
raise ValueError("intval and strval cannot both be not None")
schemas = (self.codingjob.unitschema_id, self.codingjob.articleschema_id)
fields = CodingSchemaField.objects.filter(codingschema__id__in=schemas)
field_ids = set(fields.values_list("id", flat=True)) | {None}
if any(v.get("codingschemafield_id") not in field_ids for v in values):
raise ValueError("codingschemafield_id must be in codingjob")
with transaction.atomic():
return self._replace_codings(coding_dicts)
class Meta():
db_table = 'coded_articles'
app_label = 'amcat'
unique_together = ("codingjob", "article")
###########################################################################
# U N I T T E S T S #
###########################################################################
from amcat.tools import amcattest
class TestCodedArticle(amcattest.AmCATTestCase):
def test_comments(self):
"""Can we set and read comments?"""
from amcat.models import CodedArticle
ca = amcattest.create_test_coded_article()
self.assertIsNone(ca.comments)
for offset in range(4563, 20000, 1000):
s = "".join(unichr(offset + c) for c in range(12, 1000, 100))
ca.comments = s
ca.save()
ca = CodedArticle.objects.get(pk=ca.id)
self.assertEqual(ca.comments, s)
def _get_coding_dict(self, sentence_id=None, field_id=None, intval=None, strval=None, start=None, end=None):
return {
"sentence_id" : sentence_id,
"start" : start,
"end" : end,
"values" : [{
"codingschemafield_id" : field_id,
"intval" : intval,
"strval" : strval
}]
}
def test_replace_codings(self):
schema, codebook, strf, intf, codef = amcattest.create_test_schema_with_fields(isarticleschema=True)
schema2, codebook2, strf2, intf2, codef2 = amcattest.create_test_schema_with_fields(isarticleschema=True)
codingjob = amcattest.create_test_job(articleschema=schema, narticles=10)
coded_article = CodedArticle.objects.get(article=codingjob.articleset.articles.all()[0], codingjob=codingjob)
coded_article.replace_codings([self._get_coding_dict(intval=10, field_id=codef.id)])
self.assertEqual(1, coded_article.codings.all().count())
self.assertEqual(1, coded_article.codings.all()[0].values.all().count())
coding = coded_article.codings.all()[0]
value = coding.values.all()[0]
self.assertEqual(coding.sentence, None)
self.assertEqual(value.strval, None)
self.assertEqual(value.intval, 10)
self.assertEqual(value.field, codef)
# Overwrite previous coding
coded_article.replace_codings([self._get_coding_dict(intval=11, field_id=intf.id)])
self.assertEqual(1, coded_article.codings.all().count())
self.assertEqual(1, coded_article.codings.all()[0].values.all().count())
coding = coded_article.codings.all()[0]
value = coding.values.all()[0]
self.assertEqual(coding.sentence, None)
self.assertEqual(value.strval, None)
self.assertEqual(value.intval, 11)
self.assertEqual(value.field, intf)
# Try to insert illigal values
illval1 = self._get_coding_dict(intval=1, strval="a", field_id=intf.id)
illval2 = self._get_coding_dict(field_id=intf.id)
illval3 = self._get_coding_dict(intval=1)
illval4 = self._get_coding_dict(intval=1, field_id=strf2.id)
self.assertRaises(ValueError, coded_article.replace_codings, [illval1])
self.assertRaises(ValueError, coded_article.replace_codings, [illval2])
self.assertRaises(IntegrityError, coded_article.replace_codings, [illval3])
self.assertRaises(ValueError, coded_article.replace_codings, [illval4])
# Unspecified values default to None
val = self._get_coding_dict(intval=1, field_id=intf.id)
del val["values"][0]["strval"]
coded_article.replace_codings([val])
value = coded_article.codings.all()[0].values.all()[0]
self.assertEqual(value.strval, None)
self.assertEqual(value.intval, 1)
val = self._get_coding_dict(strval="a", field_id=intf.id)
del val["values"][0]["intval"]
coded_article.replace_codings([val])
value = coded_article.codings.all()[0].values.all()[0]
self.assertEqual(value.strval, "a")
self.assertEqual(value.intval, None)
class TestCodedArticleStatus(amcattest.AmCATTestCase):
def test_status(self):
"""Is initial status 0? Can we set it?"""
ca = amcattest.create_test_coded_article()
self.assertEqual(ca.status.id, 0)
self.assertEqual(ca.status, CodedArticleStatus.objects.get(pk=STATUS_NOTSTARTED))
ca.set_status(STATUS_INPROGRESS)
self.assertEqual(ca.status, CodedArticleStatus.objects.get(pk=1))
ca.set_status(STATUS_COMPLETE)
self.assertEqual(ca.status, CodedArticleStatus.objects.get(pk=2))
ca.set_status(STATUS_IRRELEVANT)
self.assertEqual(ca.status, CodedArticleStatus.objects.get(pk=9))
ca.set_status(STATUS_NOTSTARTED)
self.assertEqual(ca.status, CodedArticleStatus.objects.get(pk=0))<|fim▁end|>
|
# option) any later version. #
# #
# AmCAT is distributed in the hope that it will be useful, but WITHOUT #
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or #
|
<|file_name|>development.js<|end_file_name|><|fim▁begin|>'use strict';
module.exports = {
db: 'mongodb://localhost/qaapp-dev',<|fim▁hole|> //db: 'mongodb://nodejitsu:[email protected]:10001/nodejitsudb3924701379',
mongoose: {
debug: true
},
app: {
name: 'AskOn'
},
facebook: {
clientID: 'DEFAULT_APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/facebook/callback'
},
twitter: {
clientID: 'DEFAULT_CONSUMER_KEY',
clientSecret: 'CONSUMER_SECRET',
callbackURL: 'http://localhost:3000/auth/twitter/callback'
},
github: {
clientID: 'DEFAULT_APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/github/callback'
},
google: {
clientID: 'DEFAULT_APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/google/callback'
},
linkedin: {
clientID: 'DEFAULT_API_KEY',
clientSecret: 'SECRET_KEY',
callbackURL: 'http://localhost:3000/auth/linkedin/callback'
},
emailFrom: 'SENDER EMAIL ADDRESS', // sender address like ABC <[email protected]>
mailer: {
service: 'SERVICE_PROVIDER', // Gmail, SMTP
auth: {
user: 'EMAIL_ID',
pass: 'PASSWORD'
}
}
};<|fim▁end|>
| |
<|file_name|>inputs-outputs.component.ts<|end_file_name|><|fim▁begin|>import {Component} from '@angular/core';
import {SourceCodeViewComponent} from '../../components/source-code-view/source-code-view.component';
import {RunExampleComponent} from '../../components/run-example/run-example';
@Component({<|fim▁hole|> directives: [SourceCodeViewComponent, RunExampleComponent]
})
export class InputsOutputsComponent {
public thisModuleId: string = module.id;
}<|fim▁end|>
|
moduleId: module.id,
selector: 'inputs-outputs',
styleUrls: ['inputs-outputs.component.css'],
templateUrl: 'inputs-outputs.component.html',
|
<|file_name|>first-8.ts<|end_file_name|><|fim▁begin|>import { helper as buildHelper } from '@ember/component/helper';
<|fim▁hole|> return params[0].substring(0, 8);
}
export default buildHelper(first8);<|fim▁end|>
|
export function first8(params: any[] /*, hash*/) {
|
<|file_name|>imgui_widgets.cpp<|end_file_name|><|fim▁begin|>// dear imgui, v1.69
// (widgets code)
/*
Index of this file:
// [SECTION] Forward Declarations
// [SECTION] Widgets: Text, etc.
// [SECTION] Widgets: Main (Button, Image, Checkbox, RadioButton, ProgressBar, Bullet, etc.)
// [SECTION] Widgets: Low-level Layout helpers (Spacing, Dummy, NewLine, Separator, etc.)
// [SECTION] Widgets: ComboBox
// [SECTION] Data Type and Data Formatting Helpers
// [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc.
// [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc.
// [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc.
// [SECTION] Widgets: InputText, InputTextMultiline
// [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc.
// [SECTION] Widgets: TreeNode, CollapsingHeader, etc.
// [SECTION] Widgets: Selectable
// [SECTION] Widgets: ListBox
// [SECTION] Widgets: PlotLines, PlotHistogram
// [SECTION] Widgets: Value helpers
// [SECTION] Widgets: MenuItem, BeginMenu, EndMenu, etc.
// [SECTION] Widgets: BeginTabBar, EndTabBar, etc.
// [SECTION] Widgets: BeginTabItem, EndTabItem, etc.
*/
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "imgui.h"
#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif
#include "imgui_internal.h"
#include <ctype.h> // toupper, isprint
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include <stddef.h> // intptr_t
#else
#include <stdint.h> // intptr_t
#endif
// Visual Studio warnings
#ifdef _MSC_VER
#pragma warning (disable: 4127) // condition expression is constant
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
#endif
// Clang/GCC warnings with -Weverything
#ifdef __clang__
#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
#pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness //
#if __has_warning("-Wzero-as-null-pointer-constant")
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning : zero as null pointer constant // some standard header variations use #define NULL 0
#endif
#if __has_warning("-Wdouble-promotion")
#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
#endif
#elif defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
#if __GNUC__ >= 8
#pragma GCC diagnostic ignored "-Wclass-memaccess" // warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
#endif
#endif
//-------------------------------------------------------------------------
// Data
//-------------------------------------------------------------------------
// Those MIN/MAX values are not define because we need to point to them
static const signed char IM_S8_MIN = -128;
static const signed char IM_S8_MAX = 127;
static const unsigned char IM_U8_MIN = 0;
static const unsigned char IM_U8_MAX = 0xFF;
static const signed short IM_S16_MIN = -32768;
static const signed short IM_S16_MAX = 32767;
static const unsigned short IM_U16_MIN = 0;
static const unsigned short IM_U16_MAX = 0xFFFF;
static const ImS32 IM_S32_MIN = INT_MIN; // (-2147483647 - 1), (0x80000000);
static const ImS32 IM_S32_MAX = INT_MAX; // (2147483647), (0x7FFFFFFF)
static const ImU32 IM_U32_MIN = 0;
static const ImU32 IM_U32_MAX = UINT_MAX; // (0xFFFFFFFF)
#ifdef LLONG_MIN
static const ImS64 IM_S64_MIN = LLONG_MIN; // (-9223372036854775807ll - 1ll);
static const ImS64 IM_S64_MAX = LLONG_MAX; // (9223372036854775807ll);
#else
static const ImS64 IM_S64_MIN = -9223372036854775807LL - 1;
static const ImS64 IM_S64_MAX = 9223372036854775807LL;
#endif
static const ImU64 IM_U64_MIN = 0;
#ifdef ULLONG_MAX
static const ImU64 IM_U64_MAX = ULLONG_MAX; // (0xFFFFFFFFFFFFFFFFull);
#else
static const ImU64 IM_U64_MAX = (2ULL * 9223372036854775807LL + 1);
#endif
//-------------------------------------------------------------------------
// [SECTION] Forward Declarations
//-------------------------------------------------------------------------
// Data Type helpers
static inline int DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* data_ptr, const char* format);
static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg_1, const void* arg_2);
static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* format);
// For InputTextEx()
static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data);
static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end);
static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining = NULL, ImVec2* out_offset = NULL, bool stop_on_new_line = false);
//-------------------------------------------------------------------------
// [SECTION] Widgets: Text, etc.
//-------------------------------------------------------------------------
// - TextUnformatted()
// - Text()
// - TextV()
// - TextColored()
// - TextColoredV()
// - TextDisabled()
// - TextDisabledV()
// - TextWrapped()
// - TextWrappedV()
// - LabelText()
// - LabelTextV()
// - BulletText()
// - BulletTextV()
//-------------------------------------------------------------------------
void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
IM_ASSERT(text != NULL);
const char* text_begin = text;
if (text_end == NULL)
text_end = text + strlen(text); // FIXME-OPT
const ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrentLineTextBaseOffset);
const float wrap_pos_x = window->DC.TextWrapPos;
const bool wrap_enabled = (wrap_pos_x >= 0.0f);
if (text_end - text > 2000 && !wrap_enabled)
{
// Long text!
// Perform manual coarse clipping to optimize for long multi-line text
// - From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled.
// - We also don't vertically center the text within the line full height, which is unlikely to matter because we are likely the biggest and only item on the line.
// - We use memchr(), pay attention that well optimized versions of those str/mem functions are much faster than a casually written loop.
const char* line = text;
const float line_height = GetTextLineHeight();
ImVec2 text_size(0,0);
// Lines to skip (can't skip when logging text)
ImVec2 pos = text_pos;
if (!g.LogEnabled)
{
int lines_skippable = (int)((window->ClipRect.Min.y - text_pos.y) / line_height);
if (lines_skippable > 0)
{
int lines_skipped = 0;
while (line < text_end && lines_skipped < lines_skippable)
{
const char* line_end = (const char*)memchr(line, '\n', text_end - line);
if (!line_end)
line_end = text_end;
if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0)
text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x);
line = line_end + 1;
lines_skipped++;
}
pos.y += lines_skipped * line_height;
}
}
// Lines to render
if (line < text_end)
{
ImRect line_rect(pos, pos + ImVec2(FLT_MAX, line_height));
while (line < text_end)
{
if (IsClippedEx(line_rect, 0, false))
break;
const char* line_end = (const char*)memchr(line, '\n', text_end - line);
if (!line_end)
line_end = text_end;
text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x);
RenderText(pos, line, line_end, false);
line = line_end + 1;
line_rect.Min.y += line_height;
line_rect.Max.y += line_height;
pos.y += line_height;
}
// Count remaining lines
int lines_skipped = 0;
while (line < text_end)
{
const char* line_end = (const char*)memchr(line, '\n', text_end - line);
if (!line_end)
line_end = text_end;
if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0)
text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x);
line = line_end + 1;
lines_skipped++;
}
pos.y += lines_skipped * line_height;
}
text_size.y = (pos - text_pos).y;
ImRect bb(text_pos, text_pos + text_size);
ItemSize(text_size);
ItemAdd(bb, 0);
}
else
{
const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f;
const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width);
ImRect bb(text_pos, text_pos + text_size);
ItemSize(text_size);
if (!ItemAdd(bb, 0))
return;
// Render (we don't hide text after ## in this end-user function)
RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width);
}
}
void ImGui::TextUnformatted(const char* text, const char* text_end)
{
TextEx(text, text_end, ImGuiTextFlags_NoWidthForLargeClippedText);
}
void ImGui::Text(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
TextV(fmt, args);
va_end(args);
}
void ImGui::TextV(const char* fmt, va_list args)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const char* text_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
TextEx(g.TempBuffer, text_end, ImGuiTextFlags_NoWidthForLargeClippedText);
}
void ImGui::TextColored(const ImVec4& col, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
TextColoredV(col, fmt, args);
va_end(args);
}
void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args)
{
PushStyleColor(ImGuiCol_Text, col);
TextV(fmt, args);
PopStyleColor();
}
void ImGui::TextDisabled(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
TextDisabledV(fmt, args);
va_end(args);
}
void ImGui::TextDisabledV(const char* fmt, va_list args)
{
PushStyleColor(ImGuiCol_Text, GImGui->Style.Colors[ImGuiCol_TextDisabled]);
TextV(fmt, args);
PopStyleColor();
}
void ImGui::TextWrapped(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
TextWrappedV(fmt, args);
va_end(args);
}
void ImGui::TextWrappedV(const char* fmt, va_list args)
{
bool need_backup = (GImGui->CurrentWindow->DC.TextWrapPos < 0.0f); // Keep existing wrap position if one is already set
if (need_backup)
PushTextWrapPos(0.0f);
TextV(fmt, args);
if (need_backup)
PopTextWrapPos();
}
void ImGui::LabelText(const char* label, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
LabelTextV(label, fmt, args);
va_end(args);
}
// Add a label+text combo aligned to other label+value widgets
void ImGui::LabelTextV(const char* label, const char* fmt, va_list args)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const float w = CalcItemWidth();
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2));
const ImRect total_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x : 0.0f), style.FramePadding.y*2) + label_size);
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, 0))
return;
// Render
const char* value_text_begin = &g.TempBuffer[0];
const char* value_text_end = value_text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
RenderTextClipped(value_bb.Min, value_bb.Max, value_text_begin, value_text_end, NULL, ImVec2(0.0f,0.5f));
if (label_size.x > 0.0f)
RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label);
}
void ImGui::BulletText(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
BulletTextV(fmt, args);
va_end(args);
}
// Text with a little bullet aligned to the typical tree node.
void ImGui::BulletTextV(const char* fmt, va_list args)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const char* text_begin = g.TempBuffer;
const char* text_end = text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
const ImVec2 label_size = CalcTextSize(text_begin, text_end, false);
const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it
const float line_height = ImMax(ImMin(window->DC.CurrentLineSize.y, g.FontSize + g.Style.FramePadding.y*2), g.FontSize);
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize + (label_size.x > 0.0f ? (label_size.x + style.FramePadding.x*2) : 0.0f), ImMax(line_height, label_size.y))); // Empty text doesn't add padding
ItemSize(bb);
if (!ItemAdd(bb, 0))
return;
// Render
RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f));
RenderText(bb.Min+ImVec2(g.FontSize + style.FramePadding.x*2, text_base_offset_y), text_begin, text_end, false);
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: Main
//-------------------------------------------------------------------------
// - ButtonBehavior() [Internal]
// - Button()
// - SmallButton()
// - InvisibleButton()
// - ArrowButton()
// - CloseButton() [Internal]
// - CollapseButton() [Internal]
// - Scrollbar() [Internal]
// - Image()
// - ImageButton()
// - Checkbox()
// - CheckboxFlags()
// - RadioButton()
// - ProgressBar()
// - Bullet()
//-------------------------------------------------------------------------
bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
if (flags & ImGuiButtonFlags_Disabled)
{
if (out_hovered) *out_hovered = false;
if (out_held) *out_held = false;
if (g.ActiveId == id) ClearActiveID();
return false;
}
// Default behavior requires click+release on same spot
if ((flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick)) == 0)
flags |= ImGuiButtonFlags_PressedOnClickRelease;
ImGuiWindow* backup_hovered_window = g.HoveredWindow;
if ((flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredRootWindow == window)
g.HoveredWindow = window;
#ifdef IMGUI_ENABLE_TEST_ENGINE
if (id != 0 && window->DC.LastItemId != id)
ImGuiTestEngineHook_ItemAdd(&g, bb, id);
#endif
bool pressed = false;
bool hovered = ItemHoverable(bb, id);
// Drag source doesn't report as hovered
if (hovered && g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))
hovered = false;
// Special mode for Drag and Drop where holding button pressed for a long time while dragging another item triggers the button
if (g.DragDropActive && (flags & ImGuiButtonFlags_PressedOnDragDropHold) && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoHoldToOpenOthers))
if (IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
{
hovered = true;
SetHoveredID(id);
if (CalcTypematicPressedRepeatAmount(g.HoveredIdTimer + 0.0001f, g.HoveredIdTimer + 0.0001f - g.IO.DeltaTime, 0.01f, 0.70f)) // FIXME: Our formula for CalcTypematicPressedRepeatAmount() is fishy
{
pressed = true;
FocusWindow(window);
}
}
if ((flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredRootWindow == window)
g.HoveredWindow = backup_hovered_window;
// AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match. This allows using patterns where a later submitted widget overlaps a previous one.
if (hovered && (flags & ImGuiButtonFlags_AllowItemOverlap) && (g.HoveredIdPreviousFrame != id && g.HoveredIdPreviousFrame != 0))
hovered = false;
// Mouse
if (hovered)
{
if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt))
{
// | CLICKING | HOLDING with ImGuiButtonFlags_Repeat
// PressedOnClickRelease | <on release>* | <on repeat> <on repeat> .. (NOT on release) <-- MOST COMMON! (*) only if both click/release were over bounds
// PressedOnClick | <on click> | <on click> <on repeat> <on repeat> ..
// PressedOnRelease | <on release> | <on repeat> <on repeat> .. (NOT on release)
// PressedOnDoubleClick | <on dclick> | <on dclick> <on repeat> <on repeat> ..
// FIXME-NAV: We don't honor those different behaviors.
if ((flags & ImGuiButtonFlags_PressedOnClickRelease) && g.IO.MouseClicked[0])
{
SetActiveID(id, window);
if (!(flags & ImGuiButtonFlags_NoNavFocus))
SetFocusID(id, window);
FocusWindow(window);
}
if (((flags & ImGuiButtonFlags_PressedOnClick) && g.IO.MouseClicked[0]) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDoubleClicked[0]))
{
pressed = true;
if (flags & ImGuiButtonFlags_NoHoldingActiveID)
ClearActiveID();
else
SetActiveID(id, window); // Hold on ID
FocusWindow(window);
}
if ((flags & ImGuiButtonFlags_PressedOnRelease) && g.IO.MouseReleased[0])
{
if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release>
pressed = true;
ClearActiveID();
}
// 'Repeat' mode acts when held regardless of _PressedOn flags (see table above).
// Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings.
if ((flags & ImGuiButtonFlags_Repeat) && g.ActiveId == id && g.IO.MouseDownDuration[0] > 0.0f && IsMouseClicked(0, true))
pressed = true;
}
if (pressed)
g.NavDisableHighlight = true;
}
// Gamepad/Keyboard navigation
// We report navigated item as hovered but we don't set g.HoveredId to not interfere with mouse.
if (g.NavId == id && !g.NavDisableHighlight && g.NavDisableMouseHover && (g.ActiveId == 0 || g.ActiveId == id || g.ActiveId == window->MoveId))
hovered = true;
if (g.NavActivateDownId == id)
{
bool nav_activated_by_code = (g.NavActivateId == id);
bool nav_activated_by_inputs = IsNavInputPressed(ImGuiNavInput_Activate, (flags & ImGuiButtonFlags_Repeat) ? ImGuiInputReadMode_Repeat : ImGuiInputReadMode_Pressed);
if (nav_activated_by_code || nav_activated_by_inputs)
pressed = true;
if (nav_activated_by_code || nav_activated_by_inputs || g.ActiveId == id)
{
// Set active id so it can be queried by user via IsItemActive(), equivalent of holding the mouse button.
g.NavActivateId = id; // This is so SetActiveId assign a Nav source
SetActiveID(id, window);
if ((nav_activated_by_code || nav_activated_by_inputs) && !(flags & ImGuiButtonFlags_NoNavFocus))
SetFocusID(id, window);
g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right) | (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
}
}
bool held = false;
if (g.ActiveId == id)
{
if (pressed)
g.ActiveIdHasBeenPressed = true;
if (g.ActiveIdSource == ImGuiInputSource_Mouse)
{
if (g.ActiveIdIsJustActivated)
g.ActiveIdClickOffset = g.IO.MousePos - bb.Min;
if (g.IO.MouseDown[0])
{
held = true;
}
else
{
if (hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease))
if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release>
if (!g.DragDropActive)
pressed = true;
ClearActiveID();
}
if (!(flags & ImGuiButtonFlags_NoNavFocus))
g.NavDisableHighlight = true;
}
else if (g.ActiveIdSource == ImGuiInputSource_Nav)
{
if (g.NavActivateDownId != id)
ClearActiveID();
}
}
if (out_hovered) *out_hovered = hovered;
if (out_held) *out_held = held;
return pressed;
}
bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
ImVec2 pos = window->DC.CursorPos;
if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrentLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag)
pos.y += window->DC.CurrentLineTextBaseOffset - style.FramePadding.y;
ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f);
const ImRect bb(pos, pos + size);
ItemSize(size, style.FramePadding.y);
if (!ItemAdd(bb, id))
return false;
if (window->DC.ItemFlags & ImGuiItemFlags_ButtonRepeat)
flags |= ImGuiButtonFlags_Repeat;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
if (pressed)
MarkItemEdited(id);
// Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
RenderNavHighlight(bb, id);
RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb);
// Automatically close popups
//if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
// CloseCurrentPopup();
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags);
return pressed;
}
bool ImGui::Button(const char* label, const ImVec2& size_arg)
{
return ButtonEx(label, size_arg, 0);
}
// Small buttons fits within text without additional vertical spacing.
bool ImGui::SmallButton(const char* label)
{
ImGuiContext& g = *GImGui;
float backup_padding_y = g.Style.FramePadding.y;
g.Style.FramePadding.y = 0.0f;
bool pressed = ButtonEx(label, ImVec2(0, 0), ImGuiButtonFlags_AlignTextBaseLine);
g.Style.FramePadding.y = backup_padding_y;
return pressed;
}
// Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack.
// Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id)
bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
// Cannot use zero-size for InvisibleButton(). Unlike Button() there is not way to fallback using the label size.
IM_ASSERT(size_arg.x != 0.0f && size_arg.y != 0.0f);
const ImGuiID id = window->GetID(str_id);
ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f);
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
ItemSize(size);
if (!ItemAdd(bb, id))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
return pressed;
}
bool ImGui::ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size, ImGuiButtonFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiID id = window->GetID(str_id);
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
const float default_size = GetFrameHeight();
ItemSize(bb, (size.y >= default_size) ? g.Style.FramePadding.y : 0.0f);
if (!ItemAdd(bb, id))
return false;
if (window->DC.ItemFlags & ImGuiItemFlags_ButtonRepeat)
flags |= ImGuiButtonFlags_Repeat;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
// Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
RenderNavHighlight(bb, id);
RenderFrame(bb.Min, bb.Max, col, true, g.Style.FrameRounding);
RenderArrow(bb.Min + ImVec2(ImMax(0.0f, (size.x - g.FontSize) * 0.5f), ImMax(0.0f, (size.y - g.FontSize) * 0.5f)), dir);
return pressed;
}
bool ImGui::ArrowButton(const char* str_id, ImGuiDir dir)
{
float sz = GetFrameHeight();
return ArrowButtonEx(str_id, dir, ImVec2(sz, sz), 0);
}
// Button to close a window
bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos, float radius)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
// We intentionally allow interaction when clipped so that a mechanical Alt,Right,Validate sequence close a window.
// (this isn't the regular behavior of buttons, but it doesn't affect the user much because navigation tends to keep items visible).
const ImRect bb(pos - ImVec2(radius,radius), pos + ImVec2(radius,radius));
bool is_clipped = !ItemAdd(bb, id);
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
if (is_clipped)
return pressed;
// Render
ImVec2 center = bb.GetCenter();
if (hovered)
window->DrawList->AddCircleFilled(center, ImMax(2.0f, radius), GetColorU32(held ? ImGuiCol_ButtonActive : ImGuiCol_ButtonHovered), 9);
float cross_extent = (radius * 0.7071f) - 1.0f;
ImU32 cross_col = GetColorU32(ImGuiCol_Text);
center -= ImVec2(0.5f, 0.5f);
window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), cross_col, 1.0f);
window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), cross_col, 1.0f);
return pressed;
}
bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImRect bb(pos, pos + ImVec2(g.FontSize, g.FontSize) + g.Style.FramePadding * 2.0f);
ItemAdd(bb, id);
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_None);
ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
if (hovered || held)
window->DrawList->AddCircleFilled(bb.GetCenter() + ImVec2(0.0f, -0.5f), g.FontSize * 0.5f + 1.0f, col, 9);
RenderArrow(bb.Min + g.Style.FramePadding, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f);
// Switch to moving the window after mouse is moved beyond the initial drag threshold
if (IsItemActive() && IsMouseDragging())
StartMouseMovingWindow(window);
return pressed;
}
ImGuiID ImGui::GetScrollbarID(ImGuiWindow* window, ImGuiAxis axis)
{
return window->GetIDNoKeepAlive(axis == ImGuiAxis_X ? "#SCROLLX" : "#SCROLLY");
}
// Vertical/Horizontal scrollbar
// The entire piece of code below is rather confusing because:
// - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab)
// - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar
// - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal.
void ImGui::Scrollbar(ImGuiAxis axis)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const bool horizontal = (axis == ImGuiAxis_X);
const ImGuiStyle& style = g.Style;
const ImGuiID id = GetScrollbarID(window, axis);
KeepAliveID(id);
// Render background
bool other_scrollbar = (horizontal ? window->ScrollbarY : window->ScrollbarX);
float other_scrollbar_size_w = other_scrollbar ? style.ScrollbarSize : 0.0f;
const ImRect window_rect = window->Rect();
const float border_size = window->WindowBorderSize;
ImRect bb = horizontal
? ImRect(window->Pos.x + border_size, window_rect.Max.y - style.ScrollbarSize, window_rect.Max.x - other_scrollbar_size_w - border_size, window_rect.Max.y - border_size)
: ImRect(window_rect.Max.x - style.ScrollbarSize, window->Pos.y + border_size, window_rect.Max.x - border_size, window_rect.Max.y - other_scrollbar_size_w - border_size);
if (!horizontal)
bb.Min.y += window->TitleBarHeight() + ((window->Flags & ImGuiWindowFlags_MenuBar) ? window->MenuBarHeight() : 0.0f);
const float bb_height = bb.GetHeight();
if (bb.GetWidth() <= 0.0f || bb_height <= 0.0f)
return;
// When we are too small, start hiding and disabling the grab (this reduce visual noise on very small window and facilitate using the resize grab)
float alpha = 1.0f;
if ((axis == ImGuiAxis_Y) && bb_height < g.FontSize + g.Style.FramePadding.y * 2.0f)
{
alpha = ImSaturate((bb_height - g.FontSize) / (g.Style.FramePadding.y * 2.0f));
if (alpha <= 0.0f)
return;
}
const bool allow_interaction = (alpha >= 1.0f);
int window_rounding_corners;
if (horizontal)
window_rounding_corners = ImDrawCornerFlags_BotLeft | (other_scrollbar ? 0 : ImDrawCornerFlags_BotRight);
else
window_rounding_corners = (((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImDrawCornerFlags_TopRight : 0) | (other_scrollbar ? 0 : ImDrawCornerFlags_BotRight);
window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_ScrollbarBg), window->WindowRounding, window_rounding_corners);
bb.Expand(ImVec2(-ImClamp((float)(int)((bb.Max.x - bb.Min.x - 2.0f) * 0.5f), 0.0f, 3.0f), -ImClamp((float)(int)((bb.Max.y - bb.Min.y - 2.0f) * 0.5f), 0.0f, 3.0f)));
// V denote the main, longer axis of the scrollbar (= height for a vertical scrollbar)
float scrollbar_size_v = horizontal ? bb.GetWidth() : bb.GetHeight();
float scroll_v = horizontal ? window->Scroll.x : window->Scroll.y;
float win_size_avail_v = (horizontal ? window->SizeFull.x : window->SizeFull.y) - other_scrollbar_size_w;
float win_size_contents_v = horizontal ? window->SizeContents.x : window->SizeContents.y;
// Calculate the height of our grabbable box. It generally represent the amount visible (vs the total scrollable amount)
// But we maintain a minimum size in pixel to allow for the user to still aim inside.
IM_ASSERT(ImMax(win_size_contents_v, win_size_avail_v) > 0.0f); // Adding this assert to check if the ImMax(XXX,1.0f) is still needed. PLEASE CONTACT ME if this triggers.
const float win_size_v = ImMax(ImMax(win_size_contents_v, win_size_avail_v), 1.0f);
const float grab_h_pixels = ImClamp(scrollbar_size_v * (win_size_avail_v / win_size_v), style.GrabMinSize, scrollbar_size_v);
const float grab_h_norm = grab_h_pixels / scrollbar_size_v;
// Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar().
bool held = false;
bool hovered = false;
const bool previously_held = (g.ActiveId == id);
ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_NoNavFocus);
float scroll_max = ImMax(1.0f, win_size_contents_v - win_size_avail_v);
float scroll_ratio = ImSaturate(scroll_v / scroll_max);
float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v;
if (held && allow_interaction && grab_h_norm < 1.0f)
{
float scrollbar_pos_v = horizontal ? bb.Min.x : bb.Min.y;
float mouse_pos_v = horizontal ? g.IO.MousePos.x : g.IO.MousePos.y;
float* click_delta_to_grab_center_v = horizontal ? &g.ScrollbarClickDeltaToGrabCenter.x : &g.ScrollbarClickDeltaToGrabCenter.y;
// Click position in scrollbar normalized space (0.0f->1.0f)
const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v);
SetHoveredID(id);
bool seek_absolute = false;
if (!previously_held)
{
// On initial click calculate the distance between mouse and the center of the grab
if (clicked_v_norm >= grab_v_norm && clicked_v_norm <= grab_v_norm + grab_h_norm)
{
*click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f;
}
else
{
seek_absolute = true;
*click_delta_to_grab_center_v = 0.0f;
}
}
// Apply scroll
// It is ok to modify Scroll here because we are being called in Begin() after the calculation of SizeContents and before setting up our starting position
const float scroll_v_norm = ImSaturate((clicked_v_norm - *click_delta_to_grab_center_v - grab_h_norm*0.5f) / (1.0f - grab_h_norm));
scroll_v = (float)(int)(0.5f + scroll_v_norm * scroll_max);//(win_size_contents_v - win_size_v));
if (horizontal)
window->Scroll.x = scroll_v;
else
window->Scroll.y = scroll_v;
// Update values for rendering
scroll_ratio = ImSaturate(scroll_v / scroll_max);
grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v;
// Update distance to grab now that we have seeked and saturated
if (seek_absolute)
*click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f;
}
// Render grab
const ImU32 grab_col = GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab, alpha);
ImRect grab_rect;
if (horizontal)
grab_rect = ImRect(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y, ImMin(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, window_rect.Max.x), bb.Max.y);
else
grab_rect = ImRect(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm), bb.Max.x, ImMin(ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels, window_rect.Max.y));
window->DrawList->AddRectFilled(grab_rect.Min, grab_rect.Max, grab_col, style.ScrollbarRounding);
}
void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
if (border_col.w > 0.0f)
bb.Max += ImVec2(2, 2);
ItemSize(bb);
if (!ItemAdd(bb, 0))
return;
if (border_col.w > 0.0f)
{
window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(border_col), 0.0f);
window->DrawList->AddImage(user_texture_id, bb.Min + ImVec2(1, 1), bb.Max - ImVec2(1, 1), uv0, uv1, GetColorU32(tint_col));
}
else
{
window->DrawList->AddImage(user_texture_id, bb.Min, bb.Max, uv0, uv1, GetColorU32(tint_col));
}
}
// frame_padding < 0: uses FramePadding from style (default)
// frame_padding = 0: no framing
// frame_padding > 0: set framing size
// The color used are the button colors.
bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
// Default to using texture ID as ID. User can still push string/integer prefixes.
// We could hash the size/uv to create a unique ID but that would prevent the user from animating UV.
PushID((void*)(intptr_t)user_texture_id);
const ImGuiID id = window->GetID("#image");
PopID();
const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : style.FramePadding;
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size + padding * 2);
const ImRect image_bb(window->DC.CursorPos + padding, window->DC.CursorPos + padding + size);
ItemSize(bb);
if (!ItemAdd(bb, id))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
// Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
RenderNavHighlight(bb, id);
RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, style.FrameRounding));
if (bg_col.w > 0.0f)
window->DrawList->AddRectFilled(image_bb.Min, image_bb.Max, GetColorU32(bg_col));
window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, GetColorU32(tint_col));
return pressed;
}
bool ImGui::Checkbox(const char* label, bool* v)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const float square_sz = GetFrameHeight();
const ImVec2 pos = window->DC.CursorPos;
const ImRect total_bb(pos, pos + ImVec2(square_sz + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), label_size.y + style.FramePadding.y * 2.0f));
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, id))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
if (pressed)
{
*v = !(*v);
MarkItemEdited(id);
}
const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz));
RenderNavHighlight(total_bb, id);
RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding);
if (*v)
{
const float pad = ImMax(1.0f, (float)(int)(square_sz / 6.0f));
RenderCheckMark(check_bb.Min + ImVec2(pad, pad), GetColorU32(ImGuiCol_CheckMark), square_sz - pad*2.0f);
}
if (g.LogEnabled)
LogRenderedText(&total_bb.Min, *v ? "[x]" : "[ ]");
if (label_size.x > 0.0f)
RenderText(ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y), label);
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0));
return pressed;
}
bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value)
{
bool v = ((*flags & flags_value) == flags_value);
bool pressed = Checkbox(label, &v);
if (pressed)
{
if (v)
*flags |= flags_value;
else
*flags &= ~flags_value;
}
return pressed;
}
bool ImGui::RadioButton(const char* label, bool active)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const float square_sz = GetFrameHeight();
const ImVec2 pos = window->DC.CursorPos;
const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz));
const ImRect total_bb(pos, pos + ImVec2(square_sz + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), label_size.y + style.FramePadding.y * 2.0f));
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, id))
return false;
ImVec2 center = check_bb.GetCenter();
center.x = (float)(int)center.x + 0.5f;
center.y = (float)(int)center.y + 0.5f;
const float radius = (square_sz - 1.0f) * 0.5f;
bool hovered, held;
bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
if (pressed)
MarkItemEdited(id);
RenderNavHighlight(total_bb, id);
window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16);
if (active)
{
const float pad = ImMax(1.0f, (float)(int)(square_sz / 6.0f));
window->DrawList->AddCircleFilled(center, radius - pad, GetColorU32(ImGuiCol_CheckMark), 16);
}
if (style.FrameBorderSize > 0.0f)
{
window->DrawList->AddCircle(center + ImVec2(1,1), radius, GetColorU32(ImGuiCol_BorderShadow), 16, style.FrameBorderSize);
window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16, style.FrameBorderSize);
}
if (g.LogEnabled)
LogRenderedText(&total_bb.Min, active ? "(x)" : "( )");
if (label_size.x > 0.0f)
RenderText(ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y), label);
return pressed;
}
bool ImGui::RadioButton(const char* label, int* v, int v_button)
{
const bool pressed = RadioButton(label, *v == v_button);
if (pressed)
*v = v_button;
return pressed;
}
// size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size
void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
ImVec2 pos = window->DC.CursorPos;
ImRect bb(pos, pos + CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f));
ItemSize(bb, style.FramePadding.y);
if (!ItemAdd(bb, 0))
return;
// Render
fraction = ImSaturate(fraction);
RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
bb.Expand(ImVec2(-style.FrameBorderSize, -style.FrameBorderSize));
const ImVec2 fill_br = ImVec2(ImLerp(bb.Min.x, bb.Max.x, fraction), bb.Max.y);
RenderRectFilledRangeH(window->DrawList, bb, GetColorU32(ImGuiCol_PlotHistogram), 0.0f, fraction, style.FrameRounding);
// Default displaying the fraction as percentage string, but user can override it
char overlay_buf[32];
if (!overlay)
{
ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction*100+0.01f);
overlay = overlay_buf;
}
ImVec2 overlay_size = CalcTextSize(overlay, NULL);
if (overlay_size.x > 0.0f)
RenderTextClipped(ImVec2(ImClamp(fill_br.x + style.ItemSpacing.x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImVec2(0.0f,0.5f), &bb);
}
void ImGui::Bullet()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const float line_height = ImMax(ImMin(window->DC.CurrentLineSize.y, g.FontSize + g.Style.FramePadding.y*2), g.FontSize);
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height));
ItemSize(bb);
if (!ItemAdd(bb, 0))
{
SameLine(0, style.FramePadding.x*2);
return;
}
// Render and stay on same line
RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f));
SameLine(0, style.FramePadding.x*2);
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: Low-level Layout helpers
//-------------------------------------------------------------------------
// - Spacing()
// - Dummy()
// - NewLine()
// - AlignTextToFramePadding()
// - Separator()
// - VerticalSeparator() [Internal]
// - SplitterBehavior() [Internal]
//-------------------------------------------------------------------------
void ImGui::Spacing()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ItemSize(ImVec2(0,0));
}
void ImGui::Dummy(const ImVec2& size)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
ItemSize(bb);
ItemAdd(bb, 0);
}
void ImGui::NewLine()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const ImGuiLayoutType backup_layout_type = window->DC.LayoutType;
window->DC.LayoutType = ImGuiLayoutType_Vertical;
if (window->DC.CurrentLineSize.y > 0.0f) // In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height.
ItemSize(ImVec2(0,0));
else
ItemSize(ImVec2(0.0f, g.FontSize));
window->DC.LayoutType = backup_layout_type;
}
void ImGui::AlignTextToFramePadding()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
window->DC.CurrentLineSize.y = ImMax(window->DC.CurrentLineSize.y, g.FontSize + g.Style.FramePadding.y * 2);
window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y);
}
// Horizontal/vertical separating line
void ImGui::Separator()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
// Those flags should eventually be overridable by the user
ImGuiSeparatorFlags flags = (window->DC.LayoutType == ImGuiLayoutType_Horizontal) ? ImGuiSeparatorFlags_Vertical : ImGuiSeparatorFlags_Horizontal;
IM_ASSERT(ImIsPowerOfTwo(flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical))); // Check that only 1 option is selected
if (flags & ImGuiSeparatorFlags_Vertical)
{
VerticalSeparator();
return;
}
// Horizontal Separator
if (window->DC.ColumnsSet)
PopClipRect();
float x1 = window->Pos.x;
float x2 = window->Pos.x + window->Size.x;
if (!window->DC.GroupStack.empty())
x1 += window->DC.Indent.x;
const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y+1.0f));
ItemSize(ImVec2(0.0f, 0.0f)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit, we don't provide height to not alter layout.
if (!ItemAdd(bb, 0))
{
if (window->DC.ColumnsSet)
PushColumnClipRect();
return;
}
window->DrawList->AddLine(bb.Min, ImVec2(bb.Max.x,bb.Min.y), GetColorU32(ImGuiCol_Separator));
if (g.LogEnabled)
LogRenderedText(&bb.Min, "--------------------------------");
if (window->DC.ColumnsSet)
{
PushColumnClipRect();
window->DC.ColumnsSet->LineMinY = window->DC.CursorPos.y;
}
}
void ImGui::VerticalSeparator()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
float y1 = window->DC.CursorPos.y;
float y2 = window->DC.CursorPos.y + window->DC.CurrentLineSize.y;
const ImRect bb(ImVec2(window->DC.CursorPos.x, y1), ImVec2(window->DC.CursorPos.x + 1.0f, y2));
ItemSize(ImVec2(bb.GetWidth(), 0.0f));
if (!ItemAdd(bb, 0))
return;
window->DrawList->AddLine(ImVec2(bb.Min.x, bb.Min.y), ImVec2(bb.Min.x, bb.Max.y), GetColorU32(ImGuiCol_Separator));
if (g.LogEnabled)
LogText(" |");
}
// Using 'hover_visibility_delay' allows us to hide the highlight and mouse cursor for a short time, which can be convenient to reduce visual noise.
bool ImGui::SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend, float hover_visibility_delay)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags;
window->DC.ItemFlags |= ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus;
bool item_add = ItemAdd(bb, id);
window->DC.ItemFlags = item_flags_backup;
if (!item_add)
return false;
bool hovered, held;
ImRect bb_interact = bb;
bb_interact.Expand(axis == ImGuiAxis_Y ? ImVec2(0.0f, hover_extend) : ImVec2(hover_extend, 0.0f));
ButtonBehavior(bb_interact, id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_AllowItemOverlap);
if (g.ActiveId != id)
SetItemAllowOverlap();
if (held || (g.HoveredId == id && g.HoveredIdPreviousFrame == id && g.HoveredIdTimer >= hover_visibility_delay))
SetMouseCursor(axis == ImGuiAxis_Y ? ImGuiMouseCursor_ResizeNS : ImGuiMouseCursor_ResizeEW);
ImRect bb_render = bb;
if (held)
{
ImVec2 mouse_delta_2d = g.IO.MousePos - g.ActiveIdClickOffset - bb_interact.Min;
float mouse_delta = (axis == ImGuiAxis_Y) ? mouse_delta_2d.y : mouse_delta_2d.x;
// Minimum pane size
float size_1_maximum_delta = ImMax(0.0f, *size1 - min_size1);
float size_2_maximum_delta = ImMax(0.0f, *size2 - min_size2);
if (mouse_delta < -size_1_maximum_delta)
mouse_delta = -size_1_maximum_delta;
if (mouse_delta > size_2_maximum_delta)
mouse_delta = size_2_maximum_delta;
// Apply resize
if (mouse_delta != 0.0f)
{
if (mouse_delta < 0.0f)
IM_ASSERT(*size1 + mouse_delta >= min_size1);
if (mouse_delta > 0.0f)
IM_ASSERT(*size2 - mouse_delta >= min_size2);
*size1 += mouse_delta;
*size2 -= mouse_delta;
bb_render.Translate((axis == ImGuiAxis_X) ? ImVec2(mouse_delta, 0.0f) : ImVec2(0.0f, mouse_delta));
MarkItemEdited(id);
}
}
// Render
const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : (hovered && g.HoveredIdTimer >= hover_visibility_delay) ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
window->DrawList->AddRectFilled(bb_render.Min, bb_render.Max, col, g.Style.FrameRounding);
return held;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: ComboBox
//-------------------------------------------------------------------------
// - BeginCombo()
// - EndCombo()
// - Combo()
//-------------------------------------------------------------------------
static float CalcMaxPopupHeightFromItemCount(int items_count)
{
ImGuiContext& g = *GImGui;
if (items_count <= 0)
return FLT_MAX;
return (g.FontSize + g.Style.ItemSpacing.y) * items_count - g.Style.ItemSpacing.y + (g.Style.WindowPadding.y * 2);
}
bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags)
{
// Always consume the SetNextWindowSizeConstraint() call in our early return paths
ImGuiContext& g = *GImGui;
ImGuiCond backup_next_window_size_constraint = g.NextWindowData.SizeConstraintCond;
g.NextWindowData.SizeConstraintCond = 0;
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
IM_ASSERT((flags & (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)) != (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)); // Can't use both flags together
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const float arrow_size = (flags & ImGuiComboFlags_NoArrowButton) ? 0.0f : GetFrameHeight();
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const float w = (flags & ImGuiComboFlags_NoPreview) ? arrow_size : CalcItemWidth();
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, id, &frame_bb))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(frame_bb, id, &hovered, &held);
bool popup_open = IsPopupOpen(id);
const ImRect value_bb(frame_bb.Min, frame_bb.Max - ImVec2(arrow_size, 0.0f));
const ImU32 frame_col = GetColorU32(hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
RenderNavHighlight(frame_bb, id);
if (!(flags & ImGuiComboFlags_NoPreview))
window->DrawList->AddRectFilled(frame_bb.Min, ImVec2(frame_bb.Max.x - arrow_size, frame_bb.Max.y), frame_col, style.FrameRounding, ImDrawCornerFlags_Left);
if (!(flags & ImGuiComboFlags_NoArrowButton))
{
window->DrawList->AddRectFilled(ImVec2(frame_bb.Max.x - arrow_size, frame_bb.Min.y), frame_bb.Max, GetColorU32((popup_open || hovered) ? ImGuiCol_ButtonHovered : ImGuiCol_Button), style.FrameRounding, (w <= arrow_size) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Right);
RenderArrow(ImVec2(frame_bb.Max.x - arrow_size + style.FramePadding.y, frame_bb.Min.y + style.FramePadding.y), ImGuiDir_Down);
}
RenderFrameBorder(frame_bb.Min, frame_bb.Max, style.FrameRounding);
if (preview_value != NULL && !(flags & ImGuiComboFlags_NoPreview))
RenderTextClipped(frame_bb.Min + style.FramePadding, value_bb.Max, preview_value, NULL, NULL, ImVec2(0.0f,0.0f));
if (label_size.x > 0)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
if ((pressed || g.NavActivateId == id) && !popup_open)
{
if (window->DC.NavLayerCurrent == 0)
window->NavLastIds[0] = id;
OpenPopupEx(id);
popup_open = true;
}
if (!popup_open)
return false;
if (backup_next_window_size_constraint)
{
g.NextWindowData.SizeConstraintCond = backup_next_window_size_constraint;
g.NextWindowData.SizeConstraintRect.Min.x = ImMax(g.NextWindowData.SizeConstraintRect.Min.x, w);
}
else
{
if ((flags & ImGuiComboFlags_HeightMask_) == 0)
flags |= ImGuiComboFlags_HeightRegular;
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiComboFlags_HeightMask_)); // Only one
int popup_max_height_in_items = -1;
if (flags & ImGuiComboFlags_HeightRegular) popup_max_height_in_items = 8;
else if (flags & ImGuiComboFlags_HeightSmall) popup_max_height_in_items = 4;
else if (flags & ImGuiComboFlags_HeightLarge) popup_max_height_in_items = 20;
SetNextWindowSizeConstraints(ImVec2(w, 0.0f), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items)));
}
char name[16];
ImFormatString(name, IM_ARRAYSIZE(name), "##Combo_%02d", g.BeginPopupStack.Size); // Recycle windows based on depth
// Peak into expected window size so we can position it
if (ImGuiWindow* popup_window = FindWindowByName(name))
if (popup_window->WasActive)
{
ImVec2 size_expected = CalcWindowExpectedSize(popup_window);
if (flags & ImGuiComboFlags_PopupAlignLeft)
popup_window->AutoPosLastDirection = ImGuiDir_Left;
ImRect r_outer = GetWindowAllowedExtentRect(popup_window);
ImVec2 pos = FindBestWindowPosForPopupEx(frame_bb.GetBL(), size_expected, &popup_window->AutoPosLastDirection, r_outer, frame_bb, ImGuiPopupPositionPolicy_ComboBox);
SetNextWindowPos(pos);
}
// Horizontally align ourselves with the framed text
ImGuiWindowFlags window_flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(style.FramePadding.x, style.WindowPadding.y));
bool ret = Begin(name, NULL, window_flags);
PopStyleVar();
if (!ret)
{
EndPopup();
IM_ASSERT(0); // This should never happen as we tested for IsPopupOpen() above
return false;
}
return true;
}
void ImGui::EndCombo()
{
EndPopup();
}
// Getter for the old Combo() API: const char*[]
static bool Items_ArrayGetter(void* data, int idx, const char** out_text)
{
const char* const* items = (const char* const*)data;
if (out_text)
*out_text = items[idx];
return true;
}
// Getter for the old Combo() API: "item1\0item2\0item3\0"
static bool Items_SingleStringGetter(void* data, int idx, const char** out_text)
{
// FIXME-OPT: we could pre-compute the indices to fasten this. But only 1 active combo means the waste is limited.
const char* items_separated_by_zeros = (const char*)data;
int items_count = 0;
const char* p = items_separated_by_zeros;
while (*p)
{
if (idx == items_count)
break;
p += strlen(p) + 1;
items_count++;
}
if (!*p)
return false;
if (out_text)
*out_text = p;
return true;
}
// Old API, prefer using BeginCombo() nowadays if you can.
bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int popup_max_height_in_items)
{
ImGuiContext& g = *GImGui;
// Call the getter to obtain the preview string which is a parameter to BeginCombo()
const char* preview_value = NULL;
if (*current_item >= 0 && *current_item < items_count)
items_getter(data, *current_item, &preview_value);
// The old Combo() API exposed "popup_max_height_in_items". The new more general BeginCombo() API doesn't have/need it, but we emulate it here.
if (popup_max_height_in_items != -1 && !g.NextWindowData.SizeConstraintCond)
SetNextWindowSizeConstraints(ImVec2(0,0), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items)));
if (!BeginCombo(label, preview_value, ImGuiComboFlags_None))
return false;
// Display items
// FIXME-OPT: Use clipper (but we need to disable it on the appearing frame to make sure our call to SetItemDefaultFocus() is processed)
bool value_changed = false;
for (int i = 0; i < items_count; i++)
{
PushID((void*)(intptr_t)i);
const bool item_selected = (i == *current_item);
const char* item_text;
if (!items_getter(data, i, &item_text))
item_text = "*Unknown item*";
if (Selectable(item_text, item_selected))
{
value_changed = true;
*current_item = i;
}
if (item_selected)
SetItemDefaultFocus();
PopID();
}
EndCombo();
return value_changed;
}
// Combo box helper allowing to pass an array of strings.
bool ImGui::Combo(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items)
{
const bool value_changed = Combo(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_in_items);
return value_changed;
}
// Combo box helper allowing to pass all items in a single string literal holding multiple zero-terminated items "item1\0item2\0"
bool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items)
{
int items_count = 0;
const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open
while (*p)
{
p += strlen(p) + 1;
items_count++;
}
bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items);
return value_changed;
}
//-------------------------------------------------------------------------
// [SECTION] Data Type and Data Formatting Helpers [Internal]
//-------------------------------------------------------------------------
// - PatchFormatStringFloatToInt()
// - DataTypeFormatString()
// - DataTypeApplyOp()
// - DataTypeApplyOpFromText()
// - GetMinimumStepAtDecimalPrecision
// - RoundScalarWithFormat<>()
//-------------------------------------------------------------------------
struct ImGuiDataTypeInfo
{
size_t Size;
const char* PrintFmt; // Unused
const char* ScanFmt;
};
static const ImGuiDataTypeInfo GDataTypeInfo[] =
{
{ sizeof(char), "%d", "%d" }, // ImGuiDataType_S8
{ sizeof(unsigned char), "%u", "%u" },
{ sizeof(short), "%d", "%d" }, // ImGuiDataType_S16
{ sizeof(unsigned short), "%u", "%u" },
{ sizeof(int), "%d", "%d" }, // ImGuiDataType_S32
{ sizeof(unsigned int), "%u", "%u" },
#ifdef _MSC_VER
{ sizeof(ImS64), "%I64d","%I64d" }, // ImGuiDataType_S64
{ sizeof(ImU64), "%I64u","%I64u" },
#else
{ sizeof(ImS64), "%lld", "%lld" }, // ImGuiDataType_S64
{ sizeof(ImU64), "%llu", "%llu" },
#endif
{ sizeof(float), "%f", "%f" }, // ImGuiDataType_Float (float are promoted to double in va_arg)
{ sizeof(double), "%f", "%lf" }, // ImGuiDataType_Double
};
IM_STATIC_ASSERT(IM_ARRAYSIZE(GDataTypeInfo) == ImGuiDataType_COUNT);
// FIXME-LEGACY: Prior to 1.61 our DragInt() function internally used floats and because of this the compile-time default value for format was "%.0f".
// Even though we changed the compile-time default, we expect users to have carried %f around, which would break the display of DragInt() calls.
// To honor backward compatibility we are rewriting the format string, unless IMGUI_DISABLE_OBSOLETE_FUNCTIONS is enabled. What could possibly go wrong?!
static const char* PatchFormatStringFloatToInt(const char* fmt)
{
if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '0' && fmt[3] == 'f' && fmt[4] == 0) // Fast legacy path for "%.0f" which is expected to be the most common case.
return "%d";
const char* fmt_start = ImParseFormatFindStart(fmt); // Find % (if any, and ignore %%)
const char* fmt_end = ImParseFormatFindEnd(fmt_start); // Find end of format specifier, which itself is an exercise of confidence/recklessness (because snprintf is dependent on libc or user).
if (fmt_end > fmt_start && fmt_end[-1] == 'f')
{
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
if (fmt_start == fmt && fmt_end[0] == 0)
return "%d";
ImGuiContext& g = *GImGui;
ImFormatString(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), "%.*s%%d%s", (int)(fmt_start - fmt), fmt, fmt_end); // Honor leading and trailing decorations, but lose alignment/precision.
return g.TempBuffer;
#else
IM_ASSERT(0 && "DragInt(): Invalid format string!"); // Old versions used a default parameter of "%.0f", please replace with e.g. "%d"
#endif
}
return fmt;
}
static inline int DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* data_ptr, const char* format)
{
// Signedness doesn't matter when pushing integer arguments
if (data_type == ImGuiDataType_S32 || data_type == ImGuiDataType_U32)
return ImFormatString(buf, buf_size, format, *(const ImU32*)data_ptr);
if (data_type == ImGuiDataType_S64 || data_type == ImGuiDataType_U64)
return ImFormatString(buf, buf_size, format, *(const ImU64*)data_ptr);
if (data_type == ImGuiDataType_Float)
return ImFormatString(buf, buf_size, format, *(const float*)data_ptr);
if (data_type == ImGuiDataType_Double)
return ImFormatString(buf, buf_size, format, *(const double*)data_ptr);
if (data_type == ImGuiDataType_S8)
return ImFormatString(buf, buf_size, format, *(const ImS8*)data_ptr);
if (data_type == ImGuiDataType_U8)
return ImFormatString(buf, buf_size, format, *(const ImU8*)data_ptr);
if (data_type == ImGuiDataType_S16)
return ImFormatString(buf, buf_size, format, *(const ImS16*)data_ptr);
if (data_type == ImGuiDataType_U16)
return ImFormatString(buf, buf_size, format, *(const ImU16*)data_ptr);
IM_ASSERT(0);
return 0;
}
static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg1, const void* arg2)
{
IM_ASSERT(op == '+' || op == '-');
switch (data_type)
{
case ImGuiDataType_S8:
if (op == '+') { *(ImS8*)output = ImAddClampOverflow(*(const ImS8*)arg1, *(const ImS8*)arg2, IM_S8_MIN, IM_S8_MAX); }
if (op == '-') { *(ImS8*)output = ImSubClampOverflow(*(const ImS8*)arg1, *(const ImS8*)arg2, IM_S8_MIN, IM_S8_MAX); }
return;
case ImGuiDataType_U8:
if (op == '+') { *(ImU8*)output = ImAddClampOverflow(*(const ImU8*)arg1, *(const ImU8*)arg2, IM_U8_MIN, IM_U8_MAX); }
if (op == '-') { *(ImU8*)output = ImSubClampOverflow(*(const ImU8*)arg1, *(const ImU8*)arg2, IM_U8_MIN, IM_U8_MAX); }
return;
case ImGuiDataType_S16:
if (op == '+') { *(ImS16*)output = ImAddClampOverflow(*(const ImS16*)arg1, *(const ImS16*)arg2, IM_S16_MIN, IM_S16_MAX); }
if (op == '-') { *(ImS16*)output = ImSubClampOverflow(*(const ImS16*)arg1, *(const ImS16*)arg2, IM_S16_MIN, IM_S16_MAX); }
return;
case ImGuiDataType_U16:
if (op == '+') { *(ImU16*)output = ImAddClampOverflow(*(const ImU16*)arg1, *(const ImU16*)arg2, IM_U16_MIN, IM_U16_MAX); }
if (op == '-') { *(ImU16*)output = ImSubClampOverflow(*(const ImU16*)arg1, *(const ImU16*)arg2, IM_U16_MIN, IM_U16_MAX); }
return;
case ImGuiDataType_S32:
if (op == '+') { *(ImS32*)output = ImAddClampOverflow(*(const ImS32*)arg1, *(const ImS32*)arg2, IM_S32_MIN, IM_S32_MAX); }
if (op == '-') { *(ImS32*)output = ImSubClampOverflow(*(const ImS32*)arg1, *(const ImS32*)arg2, IM_S32_MIN, IM_S32_MAX); }
return;
case ImGuiDataType_U32:
if (op == '+') { *(ImU32*)output = ImAddClampOverflow(*(const ImU32*)arg1, *(const ImU32*)arg2, IM_U32_MIN, IM_U32_MAX); }
if (op == '-') { *(ImU32*)output = ImSubClampOverflow(*(const ImU32*)arg1, *(const ImU32*)arg2, IM_U32_MIN, IM_U32_MAX); }
return;
case ImGuiDataType_S64:
if (op == '+') { *(ImS64*)output = ImAddClampOverflow(*(const ImS64*)arg1, *(const ImS64*)arg2, IM_S64_MIN, IM_S64_MAX); }
if (op == '-') { *(ImS64*)output = ImSubClampOverflow(*(const ImS64*)arg1, *(const ImS64*)arg2, IM_S64_MIN, IM_S64_MAX); }
return;
case ImGuiDataType_U64:
if (op == '+') { *(ImU64*)output = ImAddClampOverflow(*(const ImU64*)arg1, *(const ImU64*)arg2, IM_U64_MIN, IM_U64_MAX); }
if (op == '-') { *(ImU64*)output = ImSubClampOverflow(*(const ImU64*)arg1, *(const ImU64*)arg2, IM_U64_MIN, IM_U64_MAX); }
return;
case ImGuiDataType_Float:
if (op == '+') { *(float*)output = *(const float*)arg1 + *(const float*)arg2; }
if (op == '-') { *(float*)output = *(const float*)arg1 - *(const float*)arg2; }
return;
case ImGuiDataType_Double:
if (op == '+') { *(double*)output = *(const double*)arg1 + *(const double*)arg2; }
if (op == '-') { *(double*)output = *(const double*)arg1 - *(const double*)arg2; }
return;
case ImGuiDataType_COUNT: break;
}
IM_ASSERT(0);
}
// User can input math operators (e.g. +100) to edit a numerical values.
// NB: This is _not_ a full expression evaluator. We should probably add one and replace this dumb mess..
static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* format)
{
while (ImCharIsBlankA(*buf))
buf++;
// We don't support '-' op because it would conflict with inputing negative value.
// Instead you can use +-100 to subtract from an existing value
char op = buf[0];
if (op == '+' || op == '*' || op == '/')
{
buf++;
while (ImCharIsBlankA(*buf))
buf++;
}
else
{
op = 0;
}
if (!buf[0])
return false;
// Copy the value in an opaque buffer so we can compare at the end of the function if it changed at all.
IM_ASSERT(data_type < ImGuiDataType_COUNT);
int data_backup[2];
IM_ASSERT(GDataTypeInfo[data_type].Size <= sizeof(data_backup));
memcpy(data_backup, data_ptr, GDataTypeInfo[data_type].Size);
if (format == NULL)
format = GDataTypeInfo[data_type].ScanFmt;
// FIXME-LEGACY: The aim is to remove those operators and write a proper expression evaluator at some point..
int arg1i = 0;
if (data_type == ImGuiDataType_S32)
{
int* v = (int*)data_ptr;
int arg0i = *v;
float arg1f = 0.0f;
if (op && sscanf(initial_value_buf, format, &arg0i) < 1)
return false;
// Store operand in a float so we can use fractional value for multipliers (*1.1), but constant always parsed as integer so we can fit big integers (e.g. 2000000003) past float precision
if (op == '+') { if (sscanf(buf, "%d", &arg1i)) *v = (int)(arg0i + arg1i); } // Add (use "+-" to subtract)
else if (op == '*') { if (sscanf(buf, "%f", &arg1f)) *v = (int)(arg0i * arg1f); } // Multiply
else if (op == '/') { if (sscanf(buf, "%f", &arg1f) && arg1f != 0.0f) *v = (int)(arg0i / arg1f); } // Divide
else { if (sscanf(buf, format, &arg1i) == 1) *v = arg1i; } // Assign constant
}
else if (data_type == ImGuiDataType_Float)
{
// For floats we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in
format = "%f";
float* v = (float*)data_ptr;
float arg0f = *v, arg1f = 0.0f;
if (op && sscanf(initial_value_buf, format, &arg0f) < 1)
return false;
if (sscanf(buf, format, &arg1f) < 1)
return false;
if (op == '+') { *v = arg0f + arg1f; } // Add (use "+-" to subtract)
else if (op == '*') { *v = arg0f * arg1f; } // Multiply
else if (op == '/') { if (arg1f != 0.0f) *v = arg0f / arg1f; } // Divide
else { *v = arg1f; } // Assign constant
}
else if (data_type == ImGuiDataType_Double)
{
format = "%lf"; // scanf differentiate float/double unlike printf which forces everything to double because of ellipsis
double* v = (double*)data_ptr;
double arg0f = *v, arg1f = 0.0;
if (op && sscanf(initial_value_buf, format, &arg0f) < 1)
return false;
if (sscanf(buf, format, &arg1f) < 1)
return false;
if (op == '+') { *v = arg0f + arg1f; } // Add (use "+-" to subtract)
else if (op == '*') { *v = arg0f * arg1f; } // Multiply
else if (op == '/') { if (arg1f != 0.0f) *v = arg0f / arg1f; } // Divide
else { *v = arg1f; } // Assign constant
}
else if (data_type == ImGuiDataType_U32 || data_type == ImGuiDataType_S64 || data_type == ImGuiDataType_U64)
{
// All other types assign constant
// We don't bother handling support for legacy operators since they are a little too crappy. Instead we will later implement a proper expression evaluator in the future.
sscanf(buf, format, data_ptr);
}
else
{
// Small types need a 32-bit buffer to receive the result from scanf()
int v32;
sscanf(buf, format, &v32);
if (data_type == ImGuiDataType_S8)
*(ImS8*)data_ptr = (ImS8)ImClamp(v32, (int)IM_S8_MIN, (int)IM_S8_MAX);
else if (data_type == ImGuiDataType_U8)
*(ImU8*)data_ptr = (ImU8)ImClamp(v32, (int)IM_U8_MIN, (int)IM_U8_MAX);
else if (data_type == ImGuiDataType_S16)
*(ImS16*)data_ptr = (ImS16)ImClamp(v32, (int)IM_S16_MIN, (int)IM_S16_MAX);
else if (data_type == ImGuiDataType_U16)
*(ImU16*)data_ptr = (ImU16)ImClamp(v32, (int)IM_U16_MIN, (int)IM_U16_MAX);
else
IM_ASSERT(0);
}
return memcmp(data_backup, data_ptr, GDataTypeInfo[data_type].Size) != 0;
}
static float GetMinimumStepAtDecimalPrecision(int decimal_precision)
{
static const float min_steps[10] = { 1.0f, 0.1f, 0.01f, 0.001f, 0.0001f, 0.00001f, 0.000001f, 0.0000001f, 0.00000001f, 0.000000001f };
if (decimal_precision < 0)
return FLT_MIN;
return (decimal_precision < IM_ARRAYSIZE(min_steps)) ? min_steps[decimal_precision] : ImPow(10.0f, (float)-decimal_precision);
}
template<typename TYPE>
static const char* ImAtoi(const char* src, TYPE* output)
{
int negative = 0;
if (*src == '-') { negative = 1; src++; }
if (*src == '+') { src++; }
TYPE v = 0;
while (*src >= '0' && *src <= '9')
v = (v * 10) + (*src++ - '0');
*output = negative ? -v : v;
return src;
}
template<typename TYPE, typename SIGNEDTYPE>
TYPE ImGui::RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, TYPE v)
{
const char* fmt_start = ImParseFormatFindStart(format);
if (fmt_start[0] != '%' || fmt_start[1] == '%') // Don't apply if the value is not visible in the format string
return v;
char v_str[64];
ImFormatString(v_str, IM_ARRAYSIZE(v_str), fmt_start, v);
const char* p = v_str;
while (*p == ' ')
p++;
if (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double)
v = (TYPE)ImAtof(p);
else
ImAtoi(p, (SIGNEDTYPE*)&v);
return v;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc.
//-------------------------------------------------------------------------
// - DragBehaviorT<>() [Internal]
// - DragBehavior() [Internal]
// - DragScalar()
// - DragScalarN()
// - DragFloat()
// - DragFloat2()
// - DragFloat3()
// - DragFloat4()
// - DragFloatRange2()
// - DragInt()
// - DragInt2()
// - DragInt3()
// - DragInt4()
// - DragIntRange2()
//-------------------------------------------------------------------------
// This is called by DragBehavior() when the widget is active (held by mouse or being manipulated with Nav controls)
template<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE>
bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiDragFlags flags)
{
ImGuiContext& g = *GImGui;
const ImGuiAxis axis = (flags & ImGuiDragFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X;
const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double);
const bool has_min_max = (v_min != v_max);
const bool is_power = (power != 1.0f && is_decimal && has_min_max && (v_max - v_min < FLT_MAX));
// Default tweak speed
if (v_speed == 0.0f && has_min_max && (v_max - v_min < FLT_MAX))
v_speed = (float)((v_max - v_min) * g.DragSpeedDefaultRatio);
// Inputs accumulates into g.DragCurrentAccum, which is flushed into the current value as soon as it makes a difference with our precision settings
float adjust_delta = 0.0f;
if (g.ActiveIdSource == ImGuiInputSource_Mouse && IsMousePosValid() && g.IO.MouseDragMaxDistanceSqr[0] > 1.0f*1.0f)
{
adjust_delta = g.IO.MouseDelta[axis];
if (g.IO.KeyAlt)
adjust_delta *= 1.0f / 100.0f;
if (g.IO.KeyShift)
adjust_delta *= 10.0f;
}
else if (g.ActiveIdSource == ImGuiInputSource_Nav)
{
int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 0;
adjust_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard | ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 1.0f / 10.0f, 10.0f)[axis];
v_speed = ImMax(v_speed, GetMinimumStepAtDecimalPrecision(decimal_precision));
}
adjust_delta *= v_speed;
// For vertical drag we currently assume that Up=higher value (like we do with vertical sliders). This may become a parameter.
if (axis == ImGuiAxis_Y)
adjust_delta = -adjust_delta;
// Clear current value on activation
// Avoid altering values and clamping when we are _already_ past the limits and heading in the same direction, so e.g. if range is 0..255, current value is 300 and we are pushing to the right side, keep the 300.
bool is_just_activated = g.ActiveIdIsJustActivated;
bool is_already_past_limits_and_pushing_outward = has_min_max && ((*v >= v_max && adjust_delta > 0.0f) || (*v <= v_min && adjust_delta < 0.0f));
bool is_drag_direction_change_with_power = is_power && ((adjust_delta < 0 && g.DragCurrentAccum > 0) || (adjust_delta > 0 && g.DragCurrentAccum < 0));
if (is_just_activated || is_already_past_limits_and_pushing_outward || is_drag_direction_change_with_power)
{
g.DragCurrentAccum = 0.0f;
g.DragCurrentAccumDirty = false;
}
else if (adjust_delta != 0.0f)
{
g.DragCurrentAccum += adjust_delta;
g.DragCurrentAccumDirty = true;
}
if (!g.DragCurrentAccumDirty)
return false;
TYPE v_cur = *v;
FLOATTYPE v_old_ref_for_accum_remainder = (FLOATTYPE)0.0f;
if (is_power)
{
// Offset + round to user desired precision, with a curve on the v_min..v_max range to get more precision on one side of the range
FLOATTYPE v_old_norm_curved = ImPow((FLOATTYPE)(v_cur - v_min) / (FLOATTYPE)(v_max - v_min), (FLOATTYPE)1.0f / power);
FLOATTYPE v_new_norm_curved = v_old_norm_curved + (g.DragCurrentAccum / (v_max - v_min));
v_cur = v_min + (TYPE)ImPow(ImSaturate((float)v_new_norm_curved), power) * (v_max - v_min);
v_old_ref_for_accum_remainder = v_old_norm_curved;
}
else
{
v_cur += (TYPE)g.DragCurrentAccum;
}
// Round to user desired precision based on format string
v_cur = RoundScalarWithFormatT<TYPE, SIGNEDTYPE>(format, data_type, v_cur);
// Preserve remainder after rounding has been applied. This also allow slow tweaking of values.
g.DragCurrentAccumDirty = false;
if (is_power)
{
FLOATTYPE v_cur_norm_curved = ImPow((FLOATTYPE)(v_cur - v_min) / (FLOATTYPE)(v_max - v_min), (FLOATTYPE)1.0f / power);
g.DragCurrentAccum -= (float)(v_cur_norm_curved - v_old_ref_for_accum_remainder);
}
else
{
g.DragCurrentAccum -= (float)((SIGNEDTYPE)v_cur - (SIGNEDTYPE)*v);
}
// Lose zero sign for float/double
if (v_cur == (TYPE)-0)
v_cur = (TYPE)0;
// Clamp values (+ handle overflow/wrap-around for integer types)
if (*v != v_cur && has_min_max)
{
if (v_cur < v_min || (v_cur > *v && adjust_delta < 0.0f && !is_decimal))
v_cur = v_min;
if (v_cur > v_max || (v_cur < *v && adjust_delta > 0.0f && !is_decimal))
v_cur = v_max;
}
// Apply result
if (*v == v_cur)
return false;
*v = v_cur;
return true;
}
bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* v, float v_speed, const void* v_min, const void* v_max, const char* format, float power, ImGuiDragFlags flags)
{
ImGuiContext& g = *GImGui;
if (g.ActiveId == id)
{
if (g.ActiveIdSource == ImGuiInputSource_Mouse && !g.IO.MouseDown[0])
ClearActiveID();
else if (g.ActiveIdSource == ImGuiInputSource_Nav && g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated)
ClearActiveID();
}
if (g.ActiveId != id)
return false;
switch (data_type)
{
case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)v; bool r = DragBehaviorT<ImS32, ImS32, float >(ImGuiDataType_S32, &v32, v_speed, v_min ? *(const ImS8*) v_min : IM_S8_MIN, v_max ? *(const ImS8*)v_max : IM_S8_MAX, format, power, flags); if (r) *(ImS8*)v = (ImS8)v32; return r; }
case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)v; bool r = DragBehaviorT<ImU32, ImS32, float >(ImGuiDataType_U32, &v32, v_speed, v_min ? *(const ImU8*) v_min : IM_U8_MIN, v_max ? *(const ImU8*)v_max : IM_U8_MAX, format, power, flags); if (r) *(ImU8*)v = (ImU8)v32; return r; }
case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)v; bool r = DragBehaviorT<ImS32, ImS32, float >(ImGuiDataType_S32, &v32, v_speed, v_min ? *(const ImS16*)v_min : IM_S16_MIN, v_max ? *(const ImS16*)v_max : IM_S16_MAX, format, power, flags); if (r) *(ImS16*)v = (ImS16)v32; return r; }
case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)v; bool r = DragBehaviorT<ImU32, ImS32, float >(ImGuiDataType_U32, &v32, v_speed, v_min ? *(const ImU16*)v_min : IM_U16_MIN, v_max ? *(const ImU16*)v_max : IM_U16_MAX, format, power, flags); if (r) *(ImU16*)v = (ImU16)v32; return r; }
case ImGuiDataType_S32: return DragBehaviorT<ImS32, ImS32, float >(data_type, (ImS32*)v, v_speed, v_min ? *(const ImS32* )v_min : IM_S32_MIN, v_max ? *(const ImS32* )v_max : IM_S32_MAX, format, power, flags);
case ImGuiDataType_U32: return DragBehaviorT<ImU32, ImS32, float >(data_type, (ImU32*)v, v_speed, v_min ? *(const ImU32* )v_min : IM_U32_MIN, v_max ? *(const ImU32* )v_max : IM_U32_MAX, format, power, flags);
case ImGuiDataType_S64: return DragBehaviorT<ImS64, ImS64, double>(data_type, (ImS64*)v, v_speed, v_min ? *(const ImS64* )v_min : IM_S64_MIN, v_max ? *(const ImS64* )v_max : IM_S64_MAX, format, power, flags);
case ImGuiDataType_U64: return DragBehaviorT<ImU64, ImS64, double>(data_type, (ImU64*)v, v_speed, v_min ? *(const ImU64* )v_min : IM_U64_MIN, v_max ? *(const ImU64* )v_max : IM_U64_MAX, format, power, flags);
case ImGuiDataType_Float: return DragBehaviorT<float, float, float >(data_type, (float*)v, v_speed, v_min ? *(const float* )v_min : -FLT_MAX, v_max ? *(const float* )v_max : FLT_MAX, format, power, flags);
case ImGuiDataType_Double: return DragBehaviorT<double,double,double>(data_type, (double*)v, v_speed, v_min ? *(const double*)v_min : -DBL_MAX, v_max ? *(const double*)v_max : DBL_MAX, format, power, flags);
case ImGuiDataType_COUNT: break;
}
IM_ASSERT(0);
return false;
}
bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* v, float v_speed, const void* v_min, const void* v_max, const char* format, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
if (power != 1.0f)
IM_ASSERT(v_min != NULL && v_max != NULL); // When using a power curve the drag needs to have known bounds
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const float w = CalcItemWidth();
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, id, &frame_bb))
return false;
const bool hovered = ItemHoverable(frame_bb, id);
// Default format string when passing NULL
// Patch old "%.0f" format string to use "%d", read function comments for more details.
IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT);
if (format == NULL)
format = GDataTypeInfo[data_type].PrintFmt;
else if (data_type == ImGuiDataType_S32 && strcmp(format, "%d") != 0)
format = PatchFormatStringFloatToInt(format);
// Tabbing or CTRL-clicking on Drag turns it into an input box
bool start_text_input = false;
const bool focus_requested = FocusableItemRegister(window, id);
if (focus_requested || (hovered && (g.IO.MouseClicked[0] || g.IO.MouseDoubleClicked[0])) || g.NavActivateId == id || (g.NavInputId == id && g.ScalarAsInputTextId != id))
{
SetActiveID(id, window);
SetFocusID(id, window);
FocusWindow(window);
g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
if (focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0] || g.NavInputId == id)
{
start_text_input = true;
g.ScalarAsInputTextId = 0;
}
}
if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id))
{
window->DC.CursorPos = frame_bb.Min;
FocusableItemUnregister(window);
return InputScalarAsWidgetReplacement(frame_bb, id, label, data_type, v, format);
}
// Actual drag behavior
const bool value_changed = DragBehavior(id, data_type, v, v_speed, v_min, v_max, format, power, ImGuiDragFlags_None);
if (value_changed)
MarkItemEdited(id);
// Draw frame
const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
RenderNavHighlight(frame_bb, id);
RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding);
// Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
char value_buf[64];
const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, v, format);
RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f));
if (label_size.x > 0.0f)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags);
return value_changed;
}
bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* v, int components, float v_speed, const void* v_min, const void* v_max, const char* format, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
BeginGroup();
PushID(label);
PushMultiItemsWidths(components);
size_t type_size = GDataTypeInfo[data_type].Size;
for (int i = 0; i < components; i++)
{
PushID(i);
value_changed |= DragScalar("", data_type, v, v_speed, v_min, v_max, format, power);
SameLine(0, g.Style.ItemInnerSpacing.x);
PopID();
PopItemWidth();
v = (void*)((char*)v + type_size);
}
PopID();
TextEx(label, FindRenderedTextEnd(label));
EndGroup();
return value_changed;
}
bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power)
{
return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, power);
}
bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power)
{
return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, power);
}
bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power)
{
return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, power);
}
bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power)
{
return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, power);
}
bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
PushID(label);
BeginGroup();
PushMultiItemsWidths(2);
bool value_changed = DragFloat("##min", v_current_min, v_speed, (v_min >= v_max) ? -FLT_MAX : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), format, power);
PopItemWidth();
SameLine(0, g.Style.ItemInnerSpacing.x);
value_changed |= DragFloat("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? FLT_MAX : v_max, format_max ? format_max : format, power);
PopItemWidth();
SameLine(0, g.Style.ItemInnerSpacing.x);
TextEx(label, FindRenderedTextEnd(label));
EndGroup();
PopID();
return value_changed;
}
// NB: v_speed is float to allow adjusting the drag speed with more precision
bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format)
{
return DragScalar(label, ImGuiDataType_S32, v, v_speed, &v_min, &v_max, format);
}
bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format)
{
return DragScalarN(label, ImGuiDataType_S32, v, 2, v_speed, &v_min, &v_max, format);
}
bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format)
{
return DragScalarN(label, ImGuiDataType_S32, v, 3, v_speed, &v_min, &v_max, format);
}
bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format)
{
return DragScalarN(label, ImGuiDataType_S32, v, 4, v_speed, &v_min, &v_max, format);
}
bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
PushID(label);
BeginGroup();
PushMultiItemsWidths(2);
bool value_changed = DragInt("##min", v_current_min, v_speed, (v_min >= v_max) ? INT_MIN : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), format);
PopItemWidth();
SameLine(0, g.Style.ItemInnerSpacing.x);
value_changed |= DragInt("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? INT_MAX : v_max, format_max ? format_max : format);
PopItemWidth();
SameLine(0, g.Style.ItemInnerSpacing.x);
TextEx(label, FindRenderedTextEnd(label));
EndGroup();
PopID();
return value_changed;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc.
//-------------------------------------------------------------------------
// - SliderBehaviorT<>() [Internal]
// - SliderBehavior() [Internal]
// - SliderScalar()
// - SliderScalarN()
// - SliderFloat()
// - SliderFloat2()
// - SliderFloat3()
// - SliderFloat4()
// - SliderAngle()
// - SliderInt()
// - SliderInt2()
// - SliderInt3()
// - SliderInt4()
// - VSliderScalar()
// - VSliderFloat()
// - VSliderInt()
//-------------------------------------------------------------------------
template<typename TYPE, typename FLOATTYPE>
float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float power, float linear_zero_pos)
{
if (v_min == v_max)
return 0.0f;
const bool is_power = (power != 1.0f) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double);
const TYPE v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min);
if (is_power)
{
if (v_clamped < 0.0f)
{
const float f = 1.0f - (float)((v_clamped - v_min) / (ImMin((TYPE)0, v_max) - v_min));
return (1.0f - ImPow(f, 1.0f/power)) * linear_zero_pos;
}
else
{
const float f = (float)((v_clamped - ImMax((TYPE)0, v_min)) / (v_max - ImMax((TYPE)0, v_min)));
return linear_zero_pos + ImPow(f, 1.0f/power) * (1.0f - linear_zero_pos);
}
}
// Linear slider
return (float)((FLOATTYPE)(v_clamped - v_min) / (FLOATTYPE)(v_max - v_min));
}
// FIXME: Move some of the code into SliderBehavior(). Current responsability is larger than what the equivalent DragBehaviorT<> does, we also do some rendering, etc.
template<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE>
bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, TYPE* v, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb)
{
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X;
const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double);
const bool is_power = (power != 1.0f) && is_decimal;
const float grab_padding = 2.0f;
const float slider_sz = (bb.Max[axis] - bb.Min[axis]) - grab_padding * 2.0f;
float grab_sz = style.GrabMinSize;
SIGNEDTYPE v_range = (v_min < v_max ? v_max - v_min : v_min - v_max);
if (!is_decimal && v_range >= 0) // v_range < 0 may happen on integer overflows
grab_sz = ImMax((float)(slider_sz / (v_range + 1)), style.GrabMinSize); // For integer sliders: if possible have the grab size represent 1 unit
grab_sz = ImMin(grab_sz, slider_sz);
const float slider_usable_sz = slider_sz - grab_sz;
const float slider_usable_pos_min = bb.Min[axis] + grab_padding + grab_sz*0.5f;
const float slider_usable_pos_max = bb.Max[axis] - grab_padding - grab_sz*0.5f;
// For power curve sliders that cross over sign boundary we want the curve to be symmetric around 0.0f
float linear_zero_pos; // 0.0->1.0f
if (is_power && v_min * v_max < 0.0f)
{
// Different sign
const FLOATTYPE linear_dist_min_to_0 = ImPow(v_min >= 0 ? (FLOATTYPE)v_min : -(FLOATTYPE)v_min, (FLOATTYPE)1.0f/power);
const FLOATTYPE linear_dist_max_to_0 = ImPow(v_max >= 0 ? (FLOATTYPE)v_max : -(FLOATTYPE)v_max, (FLOATTYPE)1.0f/power);
linear_zero_pos = (float)(linear_dist_min_to_0 / (linear_dist_min_to_0 + linear_dist_max_to_0));
}
else
{
// Same sign
linear_zero_pos = v_min < 0.0f ? 1.0f : 0.0f;
}
// Process interacting with the slider
bool value_changed = false;
if (g.ActiveId == id)
{
bool set_new_value = false;
float clicked_t = 0.0f;
if (g.ActiveIdSource == ImGuiInputSource_Mouse)
{
if (!g.IO.MouseDown[0])
{
ClearActiveID();
}
else
{
const float mouse_abs_pos = g.IO.MousePos[axis];
clicked_t = (slider_usable_sz > 0.0f) ? ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f) : 0.0f;
if (axis == ImGuiAxis_Y)
clicked_t = 1.0f - clicked_t;
set_new_value = true;
}
}
else if (g.ActiveIdSource == ImGuiInputSource_Nav)
{
const ImVec2 delta2 = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard | ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 0.0f, 0.0f);
float delta = (axis == ImGuiAxis_X) ? delta2.x : -delta2.y;
if (g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated)
{
ClearActiveID();
}
else if (delta != 0.0f)
{
clicked_t = SliderCalcRatioFromValueT<TYPE,FLOATTYPE>(data_type, *v, v_min, v_max, power, linear_zero_pos);
const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 0;
if ((decimal_precision > 0) || is_power)
{
delta /= 100.0f; // Gamepad/keyboard tweak speeds in % of slider bounds
if (IsNavInputDown(ImGuiNavInput_TweakSlow))
delta /= 10.0f;
}
else
{
if ((v_range >= -100.0f && v_range <= 100.0f) || IsNavInputDown(ImGuiNavInput_TweakSlow))
delta = ((delta < 0.0f) ? -1.0f : +1.0f) / (float)v_range; // Gamepad/keyboard tweak speeds in integer steps
else
delta /= 100.0f;
}
if (IsNavInputDown(ImGuiNavInput_TweakFast))
delta *= 10.0f;
set_new_value = true;
if ((clicked_t >= 1.0f && delta > 0.0f) || (clicked_t <= 0.0f && delta < 0.0f)) // This is to avoid applying the saturation when already past the limits
set_new_value = false;
else
clicked_t = ImSaturate(clicked_t + delta);
}
}
if (set_new_value)
{
TYPE v_new;
if (is_power)
{
// Account for power curve scale on both sides of the zero
if (clicked_t < linear_zero_pos)
{
// Negative: rescale to the negative range before powering
float a = 1.0f - (clicked_t / linear_zero_pos);
a = ImPow(a, power);
v_new = ImLerp(ImMin(v_max, (TYPE)0), v_min, a);
}
else
{
// Positive: rescale to the positive range before powering
float a;
if (ImFabs(linear_zero_pos - 1.0f) > 1.e-6f)
a = (clicked_t - linear_zero_pos) / (1.0f - linear_zero_pos);
else
a = clicked_t;
a = ImPow(a, power);
v_new = ImLerp(ImMax(v_min, (TYPE)0), v_max, a);
}
}
else
{
// Linear slider
if (is_decimal)
{
v_new = ImLerp(v_min, v_max, clicked_t);
}
else
{
// For integer values we want the clicking position to match the grab box so we round above
// This code is carefully tuned to work with large values (e.g. high ranges of U64) while preserving this property..
FLOATTYPE v_new_off_f = (v_max - v_min) * clicked_t;
TYPE v_new_off_floor = (TYPE)(v_new_off_f);
TYPE v_new_off_round = (TYPE)(v_new_off_f + (FLOATTYPE)0.5);
if (!is_decimal && v_new_off_floor < v_new_off_round)
v_new = v_min + v_new_off_round;
else
v_new = v_min + v_new_off_floor;
}
}
// Round to user desired precision based on format string
v_new = RoundScalarWithFormatT<TYPE,SIGNEDTYPE>(format, data_type, v_new);
// Apply result
if (*v != v_new)
{
*v = v_new;
value_changed = true;
}
}
}
// Output grab position so it can be displayed by the caller
float grab_t = SliderCalcRatioFromValueT<TYPE,FLOATTYPE>(data_type, *v, v_min, v_max, power, linear_zero_pos);
if (axis == ImGuiAxis_Y)
grab_t = 1.0f - grab_t;
const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t);
if (axis == ImGuiAxis_X)
*out_grab_bb = ImRect(grab_pos - grab_sz*0.5f, bb.Min.y + grab_padding, grab_pos + grab_sz*0.5f, bb.Max.y - grab_padding);
else
*out_grab_bb = ImRect(bb.Min.x + grab_padding, grab_pos - grab_sz*0.5f, bb.Max.x - grab_padding, grab_pos + grab_sz*0.5f);
return value_changed;
}
// For 32-bits and larger types, slider bounds are limited to half the natural type range.
// So e.g. an integer Slider between INT_MAX-10 and INT_MAX will fail, but an integer Slider between INT_MAX/2-10 and INT_MAX/2 will be ok.
// It would be possible to lift that limitation with some work but it doesn't seem to be worth it for sliders.
bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* v, const void* v_min, const void* v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb)
{
switch (data_type)
{
case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)v; bool r = SliderBehaviorT<ImS32, ImS32, float >(bb, id, ImGuiDataType_S32, &v32, *(const ImS8*)v_min, *(const ImS8*)v_max, format, power, flags, out_grab_bb); if (r) *(ImS8*)v = (ImS8)v32; return r; }
case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)v; bool r = SliderBehaviorT<ImU32, ImS32, float >(bb, id, ImGuiDataType_U32, &v32, *(const ImU8*)v_min, *(const ImU8*)v_max, format, power, flags, out_grab_bb); if (r) *(ImU8*)v = (ImU8)v32; return r; }
case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)v; bool r = SliderBehaviorT<ImS32, ImS32, float >(bb, id, ImGuiDataType_S32, &v32, *(const ImS16*)v_min, *(const ImS16*)v_max, format, power, flags, out_grab_bb); if (r) *(ImS16*)v = (ImS16)v32; return r; }
case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)v; bool r = SliderBehaviorT<ImU32, ImS32, float >(bb, id, ImGuiDataType_U32, &v32, *(const ImU16*)v_min, *(const ImU16*)v_max, format, power, flags, out_grab_bb); if (r) *(ImU16*)v = (ImU16)v32; return r; }
case ImGuiDataType_S32:
IM_ASSERT(*(const ImS32*)v_min >= IM_S32_MIN/2 && *(const ImS32*)v_max <= IM_S32_MAX/2);
return SliderBehaviorT<ImS32, ImS32, float >(bb, id, data_type, (ImS32*)v, *(const ImS32*)v_min, *(const ImS32*)v_max, format, power, flags, out_grab_bb);
case ImGuiDataType_U32:
IM_ASSERT(*(const ImU32*)v_min <= IM_U32_MAX/2);
return SliderBehaviorT<ImU32, ImS32, float >(bb, id, data_type, (ImU32*)v, *(const ImU32*)v_min, *(const ImU32*)v_max, format, power, flags, out_grab_bb);
case ImGuiDataType_S64:
IM_ASSERT(*(const ImS64*)v_min >= IM_S64_MIN/2 && *(const ImS64*)v_max <= IM_S64_MAX/2);
return SliderBehaviorT<ImS64, ImS64, double>(bb, id, data_type, (ImS64*)v, *(const ImS64*)v_min, *(const ImS64*)v_max, format, power, flags, out_grab_bb);
case ImGuiDataType_U64:
IM_ASSERT(*(const ImU64*)v_min <= IM_U64_MAX/2);
return SliderBehaviorT<ImU64, ImS64, double>(bb, id, data_type, (ImU64*)v, *(const ImU64*)v_min, *(const ImU64*)v_max, format, power, flags, out_grab_bb);
case ImGuiDataType_Float:
IM_ASSERT(*(const float*)v_min >= -FLT_MAX/2.0f && *(const float*)v_max <= FLT_MAX/2.0f);
return SliderBehaviorT<float, float, float >(bb, id, data_type, (float*)v, *(const float*)v_min, *(const float*)v_max, format, power, flags, out_grab_bb);
case ImGuiDataType_Double:
IM_ASSERT(*(const double*)v_min >= -DBL_MAX/2.0f && *(const double*)v_max <= DBL_MAX/2.0f);
return SliderBehaviorT<double,double,double>(bb, id, data_type, (double*)v, *(const double*)v_min, *(const double*)v_max, format, power, flags, out_grab_bb);
case ImGuiDataType_COUNT: break;
}
IM_ASSERT(0);
return false;
}
bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* v, const void* v_min, const void* v_max, const char* format, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const float w = CalcItemWidth();
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, id, &frame_bb))
return false;
// Default format string when passing NULL
// Patch old "%.0f" format string to use "%d", read function comments for more details.
IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT);
if (format == NULL)
format = GDataTypeInfo[data_type].PrintFmt;
else if (data_type == ImGuiDataType_S32 && strcmp(format, "%d") != 0)
format = PatchFormatStringFloatToInt(format);
// Tabbing or CTRL-clicking on Slider turns it into an input box
bool start_text_input = false;
const bool focus_requested = FocusableItemRegister(window, id);
const bool hovered = ItemHoverable(frame_bb, id);
if (focus_requested || (hovered && g.IO.MouseClicked[0]) || g.NavActivateId == id || (g.NavInputId == id && g.ScalarAsInputTextId != id))
{
SetActiveID(id, window);
SetFocusID(id, window);
FocusWindow(window);
g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
if (focus_requested || g.IO.KeyCtrl || g.NavInputId == id)
{
start_text_input = true;
g.ScalarAsInputTextId = 0;
}
}
if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id))
{
window->DC.CursorPos = frame_bb.Min;
FocusableItemUnregister(window);
return InputScalarAsWidgetReplacement(frame_bb, id, label, data_type, v, format);
}
// Draw frame
const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
RenderNavHighlight(frame_bb, id);
RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding);
// Slider behavior
ImRect grab_bb;
const bool value_changed = SliderBehavior(frame_bb, id, data_type, v, v_min, v_max, format, power, ImGuiSliderFlags_None, &grab_bb);
if (value_changed)
MarkItemEdited(id);
// Render grab
window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding);
// Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
char value_buf[64];
const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, v, format);
RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.5f));
if (label_size.x > 0.0f)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags);
return value_changed;
}
// Add multiple sliders on 1 line for compact edition of multiple components
bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
BeginGroup();
PushID(label);
PushMultiItemsWidths(components);
size_t type_size = GDataTypeInfo[data_type].Size;
for (int i = 0; i < components; i++)
{
PushID(i);
value_changed |= SliderScalar("", data_type, v, v_min, v_max, format, power);
SameLine(0, g.Style.ItemInnerSpacing.x);
PopID();
PopItemWidth();
v = (void*)((char*)v + type_size);
}
PopID();
TextEx(label, FindRenderedTextEnd(label));
EndGroup();
return value_changed;
}
bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power)
{
return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, power);
}
bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power)
{
return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, power);
}
bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power)
{
return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, power);
}
bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power)
{
return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, power);
}
bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max, const char* format)
{
if (format == NULL)
format = "%.0f deg";
float v_deg = (*v_rad) * 360.0f / (2*IM_PI);
bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, format, 1.0f);
*v_rad = v_deg * (2*IM_PI) / 360.0f;
return value_changed;
}
bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* format)
{
return SliderScalar(label, ImGuiDataType_S32, v, &v_min, &v_max, format);
}
bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format)
{
return SliderScalarN(label, ImGuiDataType_S32, v, 2, &v_min, &v_max, format);
}
bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format)
{
return SliderScalarN(label, ImGuiDataType_S32, v, 3, &v_min, &v_max, format);
}
bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format)
{
return SliderScalarN(label, ImGuiDataType_S32, v, 4, &v_min, &v_max, format);
}
bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* v, const void* v_min, const void* v_max, const char* format, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size);
const ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
ItemSize(bb, style.FramePadding.y);
if (!ItemAdd(frame_bb, id))
return false;
// Default format string when passing NULL
// Patch old "%.0f" format string to use "%d", read function comments for more details.
IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT);
if (format == NULL)
format = GDataTypeInfo[data_type].PrintFmt;
else if (data_type == ImGuiDataType_S32 && strcmp(format, "%d") != 0)
format = PatchFormatStringFloatToInt(format);
const bool hovered = ItemHoverable(frame_bb, id);
if ((hovered && g.IO.MouseClicked[0]) || g.NavActivateId == id || g.NavInputId == id)
{
SetActiveID(id, window);
SetFocusID(id, window);
FocusWindow(window);
g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right);
}
// Draw frame
const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
RenderNavHighlight(frame_bb, id);
RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding);
// Slider behavior
ImRect grab_bb;
const bool value_changed = SliderBehavior(frame_bb, id, data_type, v, v_min, v_max, format, power, ImGuiSliderFlags_Vertical, &grab_bb);
if (value_changed)
MarkItemEdited(id);
// Render grab
window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding);
// Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
// For the vertical slider we allow centered text to overlap the frame padding
char value_buf[64];
const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, v, format);
RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.0f));
if (label_size.x > 0.0f)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
return value_changed;
}
bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, float power)
{
return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, power);
}
bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format)
{
return VSliderScalar(label, size, ImGuiDataType_S32, v, &v_min, &v_max, format);
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc.
//-------------------------------------------------------------------------
// - ImParseFormatFindStart() [Internal]
// - ImParseFormatFindEnd() [Internal]
// - ImParseFormatTrimDecorations() [Internal]
// - ImParseFormatPrecision() [Internal]
// - InputScalarAsWidgetReplacement() [Internal]
// - InputScalar()
// - InputScalarN()
// - InputFloat()
// - InputFloat2()
// - InputFloat3()
// - InputFloat4()
// - InputInt()
// - InputInt2()
// - InputInt3()
// - InputInt4()
// - InputDouble()
//-------------------------------------------------------------------------
// We don't use strchr() because our strings are usually very short and often start with '%'
const char* ImParseFormatFindStart(const char* fmt)
{
while (char c = fmt[0])
{
if (c == '%' && fmt[1] != '%')
return fmt;
else if (c == '%')
fmt++;
fmt++;
}
return fmt;
}
const char* ImParseFormatFindEnd(const char* fmt)
{
// Printf/scanf types modifiers: I/L/h/j/l/t/w/z. Other uppercase letters qualify as types aka end of the format.
if (fmt[0] != '%')
return fmt;
const unsigned int ignored_uppercase_mask = (1 << ('I'-'A')) | (1 << ('L'-'A'));
const unsigned int ignored_lowercase_mask = (1 << ('h'-'a')) | (1 << ('j'-'a')) | (1 << ('l'-'a')) | (1 << ('t'-'a')) | (1 << ('w'-'a')) | (1 << ('z'-'a'));
for (char c; (c = *fmt) != 0; fmt++)
{
if (c >= 'A' && c <= 'Z' && ((1 << (c - 'A')) & ignored_uppercase_mask) == 0)
return fmt + 1;
if (c >= 'a' && c <= 'z' && ((1 << (c - 'a')) & ignored_lowercase_mask) == 0)
return fmt + 1;
}
return fmt;
}
// Extract the format out of a format string with leading or trailing decorations
// fmt = "blah blah" -> return fmt
// fmt = "%.3f" -> return fmt
// fmt = "hello %.3f" -> return fmt + 6
// fmt = "%.3f hello" -> return buf written with "%.3f"
const char* ImParseFormatTrimDecorations(const char* fmt, char* buf, size_t buf_size)
{
const char* fmt_start = ImParseFormatFindStart(fmt);
if (fmt_start[0] != '%')
return fmt;
const char* fmt_end = ImParseFormatFindEnd(fmt_start);
if (fmt_end[0] == 0) // If we only have leading decoration, we don't need to copy the data.
return fmt_start;
ImStrncpy(buf, fmt_start, ImMin((size_t)(fmt_end - fmt_start) + 1, buf_size));
return buf;
}
// Parse display precision back from the display format string
// FIXME: This is still used by some navigation code path to infer a minimum tweak step, but we should aim to rework widgets so it isn't needed.
int ImParseFormatPrecision(const char* fmt, int default_precision)
{
fmt = ImParseFormatFindStart(fmt);
if (fmt[0] != '%')
return default_precision;
fmt++;
while (*fmt >= '0' && *fmt <= '9')
fmt++;
int precision = INT_MAX;
if (*fmt == '.')
{
fmt = ImAtoi<int>(fmt + 1, &precision);
if (precision < 0 || precision > 99)
precision = default_precision;
}
if (*fmt == 'e' || *fmt == 'E') // Maximum precision with scientific notation
precision = -1;
if ((*fmt == 'g' || *fmt == 'G') && precision == INT_MAX)
precision = -1;
return (precision == INT_MAX) ? default_precision : precision;
}
// Create text input in place of an active drag/slider (used when doing a CTRL+Click on drag/slider widgets)
// FIXME: Facilitate using this in variety of other situations.
bool ImGui::InputScalarAsWidgetReplacement(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* data_ptr, const char* format)
{
IM_UNUSED(id);
ImGuiContext& g = *GImGui;
// On the first frame, g.ScalarAsInputTextId == 0, then on subsequent frames it becomes == id.
// We clear ActiveID on the first frame to allow the InputText() taking it back.
if (g.ScalarAsInputTextId == 0)
ClearActiveID();
char fmt_buf[32];
char data_buf[32];
format = ImParseFormatTrimDecorations(format, fmt_buf, IM_ARRAYSIZE(fmt_buf));
DataTypeFormatString(data_buf, IM_ARRAYSIZE(data_buf), data_type, data_ptr, format);
ImStrTrimBlanks(data_buf);
ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | ((data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) ? ImGuiInputTextFlags_CharsScientific : ImGuiInputTextFlags_CharsDecimal);
bool value_changed = InputTextEx(label, NULL, data_buf, IM_ARRAYSIZE(data_buf), bb.GetSize(), flags);
if (g.ScalarAsInputTextId == 0)
{
// First frame we started displaying the InputText widget, we expect it to take the active id.
IM_ASSERT(g.ActiveId == id);
g.ScalarAsInputTextId = g.ActiveId;
}
if (value_changed)
return DataTypeApplyOpFromText(data_buf, g.InputTextState.InitialTextA.Data, data_type, data_ptr, NULL);
return false;
}
bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* data_ptr, const void* step, const void* step_fast, const char* format, ImGuiInputTextFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT);
if (format == NULL)
format = GDataTypeInfo[data_type].PrintFmt;
char buf[64];
DataTypeFormatString(buf, IM_ARRAYSIZE(buf), data_type, data_ptr, format);
bool value_changed = false;
if ((flags & (ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsScientific)) == 0)
flags |= ImGuiInputTextFlags_CharsDecimal;
flags |= ImGuiInputTextFlags_AutoSelectAll;
if (step != NULL)
{
const float button_size = GetFrameHeight();
BeginGroup(); // The only purpose of the group here is to allow the caller to query item data e.g. IsItemActive()
PushID(label);
PushItemWidth(ImMax(1.0f, CalcItemWidth() - (button_size + style.ItemInnerSpacing.x) * 2));
if (InputText("", buf, IM_ARRAYSIZE(buf), flags)) // PushId(label) + "" gives us the expected ID from outside point of view
value_changed = DataTypeApplyOpFromText(buf, g.InputTextState.InitialTextA.Data, data_type, data_ptr, format);
PopItemWidth();
// Step buttons
const ImVec2 backup_frame_padding = style.FramePadding;
style.FramePadding.x = style.FramePadding.y;
ImGuiButtonFlags button_flags = ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups;
if (flags & ImGuiInputTextFlags_ReadOnly)
button_flags |= ImGuiButtonFlags_Disabled;
SameLine(0, style.ItemInnerSpacing.x);
if (ButtonEx("-", ImVec2(button_size, button_size), button_flags))
{
DataTypeApplyOp(data_type, '-', data_ptr, data_ptr, g.IO.KeyCtrl && step_fast ? step_fast : step);
value_changed = true;
}
SameLine(0, style.ItemInnerSpacing.x);
if (ButtonEx("+", ImVec2(button_size, button_size), button_flags))
{
DataTypeApplyOp(data_type, '+', data_ptr, data_ptr, g.IO.KeyCtrl && step_fast ? step_fast : step);
value_changed = true;
}
SameLine(0, style.ItemInnerSpacing.x);
TextEx(label, FindRenderedTextEnd(label));
style.FramePadding = backup_frame_padding;
PopID();
EndGroup();
}
else
{
if (InputText(label, buf, IM_ARRAYSIZE(buf), flags))
value_changed = DataTypeApplyOpFromText(buf, g.InputTextState.InitialTextA.Data, data_type, data_ptr, format);
}
return value_changed;
}
bool ImGui::InputScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* step, const void* step_fast, const char* format, ImGuiInputTextFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
BeginGroup();
PushID(label);
PushMultiItemsWidths(components);
size_t type_size = GDataTypeInfo[data_type].Size;
for (int i = 0; i < components; i++)
{
PushID(i);
value_changed |= InputScalar("", data_type, v, step, step_fast, format, flags);
SameLine(0, g.Style.ItemInnerSpacing.x);
PopID();
PopItemWidth();
v = (void*)((char*)v + type_size);
}
PopID();
TextEx(label, FindRenderedTextEnd(label));
EndGroup();
return value_changed;
}
bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, const char* format, ImGuiInputTextFlags flags)
{
flags |= ImGuiInputTextFlags_CharsScientific;
return InputScalar(label, ImGuiDataType_Float, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), format, flags);
}
bool ImGui::InputFloat2(const char* label, float v[2], const char* format, ImGuiInputTextFlags flags)
{
return InputScalarN(label, ImGuiDataType_Float, v, 2, NULL, NULL, format, flags);
}
bool ImGui::InputFloat3(const char* label, float v[3], const char* format, ImGuiInputTextFlags flags)
{
return InputScalarN(label, ImGuiDataType_Float, v, 3, NULL, NULL, format, flags);
}
bool ImGui::InputFloat4(const char* label, float v[4], const char* format, ImGuiInputTextFlags flags)
{
return InputScalarN(label, ImGuiDataType_Float, v, 4, NULL, NULL, format, flags);
}
// Prefer using "const char* format" directly, which is more flexible and consistent with other API.
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags flags)
{
char format[16] = "%f";
if (decimal_precision >= 0)
ImFormatString(format, IM_ARRAYSIZE(format), "%%.%df", decimal_precision);
return InputFloat(label, v, step, step_fast, format, flags);
}
bool ImGui::InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags flags)
{
char format[16] = "%f";
if (decimal_precision >= 0)
ImFormatString(format, IM_ARRAYSIZE(format), "%%.%df", decimal_precision);
return InputScalarN(label, ImGuiDataType_Float, v, 2, NULL, NULL, format, flags);
}
bool ImGui::InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags flags)
{
char format[16] = "%f";
if (decimal_precision >= 0)
ImFormatString(format, IM_ARRAYSIZE(format), "%%.%df", decimal_precision);
return InputScalarN(label, ImGuiDataType_Float, v, 3, NULL, NULL, format, flags);
}
bool ImGui::InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags flags)
{
char format[16] = "%f";
if (decimal_precision >= 0)
ImFormatString(format, IM_ARRAYSIZE(format), "%%.%df", decimal_precision);
return InputScalarN(label, ImGuiDataType_Float, v, 4, NULL, NULL, format, flags);
}
#endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS
bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags flags)
{
// Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes.
const char* format = (flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d";
return InputScalar(label, ImGuiDataType_S32, (void*)v, (void*)(step>0 ? &step : NULL), (void*)(step_fast>0 ? &step_fast : NULL), format, flags);
}
bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags flags)
{
return InputScalarN(label, ImGuiDataType_S32, v, 2, NULL, NULL, "%d", flags);
}
bool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags flags)
{
return InputScalarN(label, ImGuiDataType_S32, v, 3, NULL, NULL, "%d", flags);
}
bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags flags)
{
return InputScalarN(label, ImGuiDataType_S32, v, 4, NULL, NULL, "%d", flags);
}
bool ImGui::InputDouble(const char* label, double* v, double step, double step_fast, const char* format, ImGuiInputTextFlags flags)
{
flags |= ImGuiInputTextFlags_CharsScientific;
return InputScalar(label, ImGuiDataType_Double, (void*)v, (void*)(step>0.0 ? &step : NULL), (void*)(step_fast>0.0 ? &step_fast : NULL), format, flags);
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: InputText, InputTextMultiline, InputTextWithHint
//-------------------------------------------------------------------------
// - InputText()
// - InputTextWithHint()
// - InputTextMultiline()
// - InputTextEx() [Internal]
//-------------------------------------------------------------------------
bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)
{
IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline()
return InputTextEx(label, NULL, buf, (int)buf_size, ImVec2(0,0), flags, callback, user_data);
}
bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)
{
return InputTextEx(label, NULL, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data);
}
bool ImGui::InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)
{
IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline()
return InputTextEx(label, hint, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data);
}
static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end)
{
int line_count = 0;
const char* s = text_begin;
while (char c = *s++) // We are only matching for \n so we can ignore UTF-8 decoding
if (c == '\n')
line_count++;
s--;
if (s[0] != '\n' && s[0] != '\r')
line_count++;
*out_text_end = s;
return line_count;
}
static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining, ImVec2* out_offset, bool stop_on_new_line)
{
ImGuiContext& g = *GImGui;
ImFont* font = g.Font;
const float line_height = g.FontSize;
const float scale = line_height / font->FontSize;
ImVec2 text_size = ImVec2(0,0);
float line_width = 0.0f;
const ImWchar* s = text_begin;
while (s < text_end)
{
unsigned int c = (unsigned int)(*s++);
if (c == '\n')
{
text_size.x = ImMax(text_size.x, line_width);
text_size.y += line_height;
line_width = 0.0f;
if (stop_on_new_line)
break;
continue;
}
if (c == '\r')
continue;
const float char_width = font->GetCharAdvance((ImWchar)c) * scale;
line_width += char_width;
}
if (text_size.x < line_width)
text_size.x = line_width;
if (out_offset)
*out_offset = ImVec2(line_width, text_size.y + line_height); // offset allow for the possibility of sitting after a trailing \n
if (line_width > 0 || text_size.y == 0.0f) // whereas size.y will ignore the trailing \n
text_size.y += line_height;
if (remaining)
*remaining = s;
return text_size;
}
// Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar)
namespace ImStb
{
static int STB_TEXTEDIT_STRINGLEN(const STB_TEXTEDIT_STRING* obj) { return obj->CurLenW; }
static ImWchar STB_TEXTEDIT_GETCHAR(const STB_TEXTEDIT_STRING* obj, int idx) { return obj->TextW[idx]; }
static float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { ImWchar c = obj->TextW[line_start_idx+char_idx]; if (c == '\n') return STB_TEXTEDIT_GETWIDTH_NEWLINE; return GImGui->Font->GetCharAdvance(c) * (GImGui->FontSize / GImGui->Font->FontSize); }
static int STB_TEXTEDIT_KEYTOTEXT(int key) { return key >= 0x10000 ? 0 : key; }
static ImWchar STB_TEXTEDIT_NEWLINE = '\n';
static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, STB_TEXTEDIT_STRING* obj, int line_start_idx)
{
const ImWchar* text = obj->TextW.Data;
const ImWchar* text_remaining = NULL;
const ImVec2 size = InputTextCalcTextSizeW(text + line_start_idx, text + obj->CurLenW, &text_remaining, NULL, true);
r->x0 = 0.0f;
r->x1 = size.x;
r->baseline_y_delta = size.y;
r->ymin = 0.0f;
r->ymax = size.y;
r->num_chars = (int)(text_remaining - (text + line_start_idx));
}
static bool is_separator(unsigned int c) { return ImCharIsBlankW(c) || c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|'; }
static int is_word_boundary_from_right(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (is_separator( obj->TextW[idx-1] ) && !is_separator( obj->TextW[idx] ) ) : 1; }
static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx--; while (idx >= 0 && !is_word_boundary_from_right(obj, idx)) idx--; return idx < 0 ? 0 : idx; }
#ifdef __APPLE__ // FIXME: Move setting to IO structure
static int is_word_boundary_from_left(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (!is_separator( obj->TextW[idx-1] ) && is_separator( obj->TextW[idx] ) ) : 1; }
static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_left(obj, idx)) idx++; return idx > len ? len : idx; }
#else
static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_right(obj, idx)) idx++; return idx > len ? len : idx; }
#endif
#define STB_TEXTEDIT_MOVEWORDLEFT STB_TEXTEDIT_MOVEWORDLEFT_IMPL // They need to be #define for stb_textedit.h
#define STB_TEXTEDIT_MOVEWORDRIGHT STB_TEXTEDIT_MOVEWORDRIGHT_IMPL
static void STB_TEXTEDIT_DELETECHARS(STB_TEXTEDIT_STRING* obj, int pos, int n)
{
ImWchar* dst = obj->TextW.Data + pos;
// We maintain our buffer length in both UTF-8 and wchar formats
obj->CurLenA -= ImTextCountUtf8BytesFromStr(dst, dst + n);
obj->CurLenW -= n;
// Offset remaining text (FIXME-OPT: Use memmove)
const ImWchar* src = obj->TextW.Data + pos + n;
while (ImWchar c = *src++)
*dst++ = c;
*dst = '\0';
}
static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const ImWchar* new_text, int new_text_len)
{
const bool is_resizable = (obj->UserFlags & ImGuiInputTextFlags_CallbackResize) != 0;
const int text_len = obj->CurLenW;
IM_ASSERT(pos <= text_len);
const int new_text_len_utf8 = ImTextCountUtf8BytesFromStr(new_text, new_text + new_text_len);
if (!is_resizable && (new_text_len_utf8 + obj->CurLenA + 1 > obj->BufCapacityA))
return false;
// Grow internal buffer if needed
if (new_text_len + text_len + 1 > obj->TextW.Size)
{
if (!is_resizable)
return false;
IM_ASSERT(text_len < obj->TextW.Size);
obj->TextW.resize(text_len + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1);
}
ImWchar* text = obj->TextW.Data;
if (pos != text_len)
memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos) * sizeof(ImWchar));
memcpy(text + pos, new_text, (size_t)new_text_len * sizeof(ImWchar));
obj->CurLenW += new_text_len;
obj->CurLenA += new_text_len_utf8;
obj->TextW[obj->CurLenW] = '\0';
return true;
}
// We don't use an enum so we can build even with conflicting symbols (if another user of stb_textedit.h leak their STB_TEXTEDIT_K_* symbols)
#define STB_TEXTEDIT_K_LEFT 0x10000 // keyboard input to move cursor left
#define STB_TEXTEDIT_K_RIGHT 0x10001 // keyboard input to move cursor right
#define STB_TEXTEDIT_K_UP 0x10002 // keyboard input to move cursor up
#define STB_TEXTEDIT_K_DOWN 0x10003 // keyboard input to move cursor down
#define STB_TEXTEDIT_K_LINESTART 0x10004 // keyboard input to move cursor to start of line
#define STB_TEXTEDIT_K_LINEEND 0x10005 // keyboard input to move cursor to end of line
#define STB_TEXTEDIT_K_TEXTSTART 0x10006 // keyboard input to move cursor to start of text
#define STB_TEXTEDIT_K_TEXTEND 0x10007 // keyboard input to move cursor to end of text
#define STB_TEXTEDIT_K_DELETE 0x10008 // keyboard input to delete selection or character under cursor
#define STB_TEXTEDIT_K_BACKSPACE 0x10009 // keyboard input to delete selection or character left of cursor
#define STB_TEXTEDIT_K_UNDO 0x1000A // keyboard input to perform undo
#define STB_TEXTEDIT_K_REDO 0x1000B // keyboard input to perform redo
#define STB_TEXTEDIT_K_WORDLEFT 0x1000C // keyboard input to move cursor left one word
#define STB_TEXTEDIT_K_WORDRIGHT 0x1000D // keyboard input to move cursor right one word
#define STB_TEXTEDIT_K_SHIFT 0x20000
#define STB_TEXTEDIT_IMPLEMENTATION
#include "imstb_textedit.h"
}
void ImGuiInputTextState::OnKeyPressed(int key)
{
stb_textedit_key(this, &Stb, key);
CursorFollow = true;
CursorAnimReset();
}
ImGuiInputTextCallbackData::ImGuiInputTextCallbackData()
{
memset(this, 0, sizeof(*this));
}
// Public API to manipulate UTF-8 text
// We expose UTF-8 to the user (unlike the STB_TEXTEDIT_* functions which are manipulating wchar)
// FIXME: The existence of this rarely exercised code path is a bit of a nuisance.
void ImGuiInputTextCallbackData::DeleteChars(int pos, int bytes_count)
{
IM_ASSERT(pos + bytes_count <= BufTextLen);
char* dst = Buf + pos;
const char* src = Buf + pos + bytes_count;
while (char c = *src++)
*dst++ = c;
*dst = '\0';
if (CursorPos + bytes_count >= pos)
CursorPos -= bytes_count;
else if (CursorPos >= pos)
CursorPos = pos;
SelectionStart = SelectionEnd = CursorPos;
BufDirty = true;
BufTextLen -= bytes_count;
}
void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end)
{
const bool is_resizable = (Flags & ImGuiInputTextFlags_CallbackResize) != 0;
const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text);
if (new_text_len + BufTextLen >= BufSize)
{
if (!is_resizable)
return;
// Contrary to STB_TEXTEDIT_INSERTCHARS() this is working in the UTF8 buffer, hence the midly similar code (until we remove the U16 buffer alltogether!)
ImGuiContext& g = *GImGui;
ImGuiInputTextState* edit_state = &g.InputTextState;
IM_ASSERT(edit_state->ID != 0 && g.ActiveId == edit_state->ID);
IM_ASSERT(Buf == edit_state->TextA.Data);
int new_buf_size = BufTextLen + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1;
edit_state->TextA.reserve(new_buf_size + 1);
Buf = edit_state->TextA.Data;
BufSize = edit_state->BufCapacityA = new_buf_size;
}
if (BufTextLen != pos)
memmove(Buf + pos + new_text_len, Buf + pos, (size_t)(BufTextLen - pos));
memcpy(Buf + pos, new_text, (size_t)new_text_len * sizeof(char));
Buf[BufTextLen + new_text_len] = '\0';
if (CursorPos >= pos)
CursorPos += new_text_len;
SelectionStart = SelectionEnd = CursorPos;
BufDirty = true;
BufTextLen += new_text_len;
}
// Return false to discard a character.
static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)
{
unsigned int c = *p_char;
if (c < 128 && c != ' ' && !isprint((int)(c & 0xFF)))
{
bool pass = false;
pass |= (c == '\n' && (flags & ImGuiInputTextFlags_Multiline));
pass |= (c == '\t' && (flags & ImGuiInputTextFlags_AllowTabInput));
if (!pass)
return false;
}
if (c >= 0xE000 && c <= 0xF8FF) // Filter private Unicode range. I don't imagine anybody would want to input them. GLFW on OSX seems to send private characters for special keys like arrow keys.
return false;
if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_CharsScientific))
{
if (flags & ImGuiInputTextFlags_CharsDecimal)
if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/'))
return false;
if (flags & ImGuiInputTextFlags_CharsScientific)
if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/') && (c != 'e') && (c != 'E'))
return false;
if (flags & ImGuiInputTextFlags_CharsHexadecimal)
if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F'))
return false;
if (flags & ImGuiInputTextFlags_CharsUppercase)
if (c >= 'a' && c <= 'z')
*p_char = (c += (unsigned int)('A'-'a'));
if (flags & ImGuiInputTextFlags_CharsNoBlank)
if (ImCharIsBlankW(c))
return false;
}
if (flags & ImGuiInputTextFlags_CallbackCharFilter)
{
ImGuiInputTextCallbackData callback_data;
memset(&callback_data, 0, sizeof(ImGuiInputTextCallbackData));
callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter;
callback_data.EventChar = (ImWchar)c;
callback_data.Flags = flags;
callback_data.UserData = user_data;
if (callback(&callback_data) != 0)
return false;
*p_char = callback_data.EventChar;
if (!callback_data.EventChar)
return false;
}
return true;
}
// Edit a string of text
// - buf_size account for the zero-terminator, so a buf_size of 6 can hold "Hello" but not "Hello!".
// This is so we can easily call InputText() on static arrays using ARRAYSIZE() and to match
// Note that in std::string world, capacity() would omit 1 byte used by the zero-terminator.
// - When active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while the InputText is active has no effect.
// - If you want to use ImGui::InputText() with std::string, see misc/cpp/imgui_stdlib.h
// (FIXME: Rather confusing and messy function, among the worse part of our codebase, expecting to rewrite a V2 at some point.. Partly because we are
// doing UTF8 > U16 > UTF8 conversions on the go to easily interface with stb_textedit. Ideally should stay in UTF-8 all the time. See https://github.com/nothings/stb/issues/188)
bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* callback_user_data)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys)
IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key)
ImGuiContext& g = *GImGui;
ImGuiIO& io = g.IO;
const ImGuiStyle& style = g.Style;
const bool RENDER_SELECTION_WHEN_INACTIVE = false;
const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0;
const bool is_readonly = (flags & ImGuiInputTextFlags_ReadOnly) != 0;
const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0;
const bool is_undoable = (flags & ImGuiInputTextFlags_NoUndoRedo) == 0;
const bool is_resizable = (flags & ImGuiInputTextFlags_CallbackResize) != 0;
if (is_resizable)
IM_ASSERT(callback != NULL); // Must provide a callback if you set the ImGuiInputTextFlags_CallbackResize flag!
if (is_multiline) // Open group before calling GetID() because groups tracks id created within their scope,
BeginGroup();
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? GetTextLineHeight() * 8.0f : label_size.y) + style.FramePadding.y*2.0f); // Arbitrary default of 8 lines high for multi-line
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size);
const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? (style.ItemInnerSpacing.x + label_size.x) : 0.0f, 0.0f));
ImGuiWindow* draw_window = window;
if (is_multiline)
{
if (!ItemAdd(total_bb, id, &frame_bb))
{
ItemSize(total_bb, style.FramePadding.y);
EndGroup();
return false;
}
if (!BeginChildFrame(id, frame_bb.GetSize()))
{
EndChildFrame();
EndGroup();
return false;
}
draw_window = GetCurrentWindow();
draw_window->DC.NavLayerActiveMaskNext |= draw_window->DC.NavLayerCurrentMask; // This is to ensure that EndChild() will display a navigation highlight
size.x -= draw_window->ScrollbarSizes.x;
}
else
{
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, id, &frame_bb))
return false;
}
const bool hovered = ItemHoverable(frame_bb, id);
if (hovered)
g.MouseCursor = ImGuiMouseCursor_TextInput;
// NB: we are only allowed to access 'edit_state' if we are the active widget.
ImGuiInputTextState* state = NULL;
if (g.InputTextState.ID == id)
state = &g.InputTextState;
const bool focus_requested = FocusableItemRegister(window, id);
const bool focus_requested_by_code = focus_requested && (g.FocusRequestCurrWindow == window && g.FocusRequestCurrCounterAll == window->DC.FocusCounterAll);
const bool focus_requested_by_tab = focus_requested && !focus_requested_by_code;
const bool user_clicked = hovered && io.MouseClicked[0];
const bool user_nav_input_start = (g.ActiveId != id) && ((g.NavInputId == id) || (g.NavActivateId == id && g.NavInputSource == ImGuiInputSource_NavKeyboard));
const bool user_scroll_finish = is_multiline && state != NULL && g.ActiveId == 0 && g.ActiveIdPreviousFrame == GetScrollbarID(draw_window, ImGuiAxis_Y);
const bool user_scroll_active = is_multiline && state != NULL && g.ActiveId == GetScrollbarID(draw_window, ImGuiAxis_Y);
bool clear_active_id = false;
bool select_all = (g.ActiveId != id) && ((flags & ImGuiInputTextFlags_AutoSelectAll) != 0 || user_nav_input_start) && (!is_multiline);
const bool init_make_active = (focus_requested || user_clicked || user_scroll_finish || user_nav_input_start);
const bool init_state = (init_make_active || user_scroll_active);
if (init_state && g.ActiveId != id)
{
// Access state even if we don't own it yet.
state = &g.InputTextState;
state->CursorAnimReset();
// Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar)
// From the moment we focused we are ignoring the content of 'buf' (unless we are in read-only mode)
const int buf_len = (int)strlen(buf);
state->InitialTextA.resize(buf_len + 1); // UTF-8. we use +1 to make sure that .Data is always pointing to at least an empty string.
memcpy(state->InitialTextA.Data, buf, buf_len + 1);
// Start edition
const char* buf_end = NULL;
state->TextW.resize(buf_size + 1); // wchar count <= UTF-8 count. we use +1 to make sure that .Data is always pointing to at least an empty string.
state->TextA.resize(0);
state->TextAIsValid = false; // TextA is not valid yet (we will display buf until then)
state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, buf_size, buf, NULL, &buf_end);
state->CurLenA = (int)(buf_end - buf); // We can't get the result from ImStrncpy() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8.
// Preserve cursor position and undo/redo stack if we come back to same widget
// FIXME: For non-readonly widgets we might be able to require that TextAIsValid && TextA == buf ? (untested) and discard undo stack if user buffer has changed.
const bool recycle_state = (state->ID == id);
if (recycle_state)
{
// Recycle existing cursor/selection/undo stack but clamp position
// Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler.
state->CursorClamp();
}
else
{
state->ID = id;
state->ScrollX = 0.0f;
stb_textedit_initialize_state(&state->Stb, !is_multiline);
if (!is_multiline && focus_requested_by_code)
select_all = true;
}
if (flags & ImGuiInputTextFlags_AlwaysInsertMode)
state->Stb.insert_mode = 1;
if (!is_multiline && (focus_requested_by_tab || (user_clicked && io.KeyCtrl)))
select_all = true;
}
if (g.ActiveId != id && init_make_active)
{
IM_ASSERT(state && state->ID == id);
SetActiveID(id, window);
SetFocusID(id, window);
FocusWindow(window);
IM_ASSERT(ImGuiNavInput_COUNT < 32);
g.ActiveIdBlockNavInputFlags = (1 << ImGuiNavInput_Cancel);
if (flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_AllowTabInput)) // Disable keyboard tabbing out
g.ActiveIdBlockNavInputFlags |= (1 << ImGuiNavInput_KeyTab_);
if (!is_multiline && !(flags & ImGuiInputTextFlags_CallbackHistory))
g.ActiveIdAllowNavDirFlags = ((1 << ImGuiDir_Up) | (1 << ImGuiDir_Down));
}
// We have an edge case if ActiveId was set through another widget (e.g. widget being swapped), clear id immediately (don't wait until the end of the function)
if (g.ActiveId == id && state == NULL)
ClearActiveID();
// Release focus when we click outside
if (g.ActiveId == id && io.MouseClicked[0] && !init_state && !init_make_active) //-V560
clear_active_id = true;
// When read-only we always use the live data passed to the function
// FIXME-OPT: Because our selection/cursor code currently needs the wide text we need to convert it when active, which is not ideal :(
if (is_readonly && state != NULL)
{
const bool will_render_cursor = (g.ActiveId == id) || (user_scroll_active);
const bool will_render_selection = state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || will_render_cursor);
if (will_render_cursor || will_render_selection)
{
const char* buf_end = NULL;
state->TextW.resize(buf_size + 1);
state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, state->TextW.Size, buf, NULL, &buf_end);
state->CurLenA = (int)(buf_end - buf);
state->CursorClamp();
}
}
// Lock the decision of whether we are going to take the path displaying the cursor or selection
const bool render_cursor = (g.ActiveId == id) || (state && user_scroll_active);
const bool render_selection = state && state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor);
bool value_changed = false;
bool enter_pressed = false;
// Select the buffer to render.
const bool buf_display_from_state = (render_cursor || render_selection || g.ActiveId == id) && !is_readonly && state && state->TextAIsValid;
const bool is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0);
// Password pushes a temporary font with only a fallback glyph
if (is_password && !is_displaying_hint)
{
const ImFontGlyph* glyph = g.Font->FindGlyph('*');
ImFont* password_font = &g.InputTextPasswordFont;
password_font->FontSize = g.Font->FontSize;
password_font->Scale = g.Font->Scale;
password_font->DisplayOffset = g.Font->DisplayOffset;
password_font->Ascent = g.Font->Ascent;
password_font->Descent = g.Font->Descent;
password_font->ContainerAtlas = g.Font->ContainerAtlas;
password_font->FallbackGlyph = glyph;
password_font->FallbackAdvanceX = glyph->AdvanceX;
IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexAdvanceX.empty() && password_font->IndexLookup.empty());
PushFont(password_font);
}
// Process mouse inputs and character inputs
int backup_current_text_length = 0;
if (g.ActiveId == id)
{
IM_ASSERT(state != NULL);
backup_current_text_length = state->CurLenA;
state->BufCapacityA = buf_size;
state->UserFlags = flags;
state->UserCallback = callback;
state->UserCallbackData = callback_user_data;
// Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget.
// Down the line we should have a cleaner library-wide concept of Selected vs Active.
g.ActiveIdAllowOverlap = !io.MouseDown[0];
g.WantTextInputNextFrame = 1;
// Edit in progress
const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + state->ScrollX;
const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y - style.FramePadding.y) : (g.FontSize*0.5f));
const bool is_osx = io.ConfigMacOSXBehaviors;
if (select_all || (hovered && !is_osx && io.MouseDoubleClicked[0]))
{
state->SelectAll();
state->SelectedAllMouseLock = true;
}
else if (hovered && is_osx && io.MouseDoubleClicked[0])
{
// Double-click select a word only, OS X style (by simulating keystrokes)
state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT);
state->OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT);
}
else if (io.MouseClicked[0] && !state->SelectedAllMouseLock)
{
if (hovered)
{
stb_textedit_click(state, &state->Stb, mouse_x, mouse_y);
state->CursorAnimReset();
}
}
else if (io.MouseDown[0] && !state->SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f))
{
stb_textedit_drag(state, &state->Stb, mouse_x, mouse_y);
state->CursorAnimReset();
state->CursorFollow = true;
}
if (state->SelectedAllMouseLock && !io.MouseDown[0])
state->SelectedAllMouseLock = false;
if (io.InputQueueCharacters.Size > 0)
{
// Process text input (before we check for Return because using some IME will effectively send a Return?)
// We ignore CTRL inputs, but need to allow ALT+CTRL as some keyboards (e.g. German) use AltGR (which _is_ Alt+Ctrl) to input certain characters.
bool ignore_inputs = (io.KeyCtrl && !io.KeyAlt) || (is_osx && io.KeySuper);
if (!ignore_inputs && !is_readonly && !user_nav_input_start)
for (int n = 0; n < io.InputQueueCharacters.Size; n++)
{
// Insert character if they pass filtering
unsigned int c = (unsigned int)io.InputQueueCharacters[n];
if (InputTextFilterCharacter(&c, flags, callback, callback_user_data))
state->OnKeyPressed((int)c);
}
// Consume characters
io.InputQueueCharacters.resize(0);
}
}
// Process other shortcuts/key-presses
bool cancel_edit = false;
if (g.ActiveId == id && !g.ActiveIdIsJustActivated && !clear_active_id)
{
IM_ASSERT(state != NULL);
const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0);
const bool is_osx = io.ConfigMacOSXBehaviors;
const bool is_shortcut_key = (is_osx ? (io.KeySuper && !io.KeyCtrl) : (io.KeyCtrl && !io.KeySuper)) && !io.KeyAlt && !io.KeyShift; // OS X style: Shortcuts using Cmd/Super instead of Ctrl
const bool is_osx_shift_shortcut = is_osx && io.KeySuper && io.KeyShift && !io.KeyCtrl && !io.KeyAlt;
const bool is_wordmove_key_down = is_osx ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl
const bool is_startend_key_down = is_osx && io.KeySuper && !io.KeyCtrl && !io.KeyAlt; // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End
const bool is_ctrl_key_only = io.KeyCtrl && !io.KeyShift && !io.KeyAlt && !io.KeySuper;
const bool is_shift_key_only = io.KeyShift && !io.KeyCtrl && !io.KeyAlt && !io.KeySuper;
const bool is_cut = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_X)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Delete))) && !is_readonly && !is_password && (!is_multiline || state->HasSelection());
const bool is_copy = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_C)) || (is_ctrl_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && !is_password && (!is_multiline || state->HasSelection());
const bool is_paste = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_V)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && !is_readonly;
const bool is_undo = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_Z)) && !is_readonly && is_undoable);
const bool is_redo = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_Y)) || (is_osx_shift_shortcut && IsKeyPressedMap(ImGuiKey_Z))) && !is_readonly && is_undoable;
if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINESTART : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT : STB_TEXTEDIT_K_LEFT) | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINEEND : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT : STB_TEXTEDIT_K_RIGHT) | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_UpArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMax(draw_window->Scroll.y - g.FontSize, 0.0f)); else state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTSTART : STB_TEXTEDIT_K_UP) | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_DownArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMin(draw_window->Scroll.y + g.FontSize, GetScrollMaxY())); else state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTEND : STB_TEXTEDIT_K_DOWN) | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_Home)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_End)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_Delete) && !is_readonly) { state->OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_Backspace) && !is_readonly)
{
if (!state->HasSelection())
{
if (is_wordmove_key_down)
state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT|STB_TEXTEDIT_K_SHIFT);
else if (is_osx && io.KeySuper && !io.KeyAlt && !io.KeyCtrl)
state->OnKeyPressed(STB_TEXTEDIT_K_LINESTART|STB_TEXTEDIT_K_SHIFT);
}
state->OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask);
}
else if (IsKeyPressedMap(ImGuiKey_Enter))
{
bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0;
if (!is_multiline || (ctrl_enter_for_new_line && !io.KeyCtrl) || (!ctrl_enter_for_new_line && io.KeyCtrl))
{
enter_pressed = clear_active_id = true;
}
else if (!is_readonly)
{
unsigned int c = '\n'; // Insert new line
if (InputTextFilterCharacter(&c, flags, callback, callback_user_data))
state->OnKeyPressed((int)c);
}
}
else if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressedMap(ImGuiKey_Tab) && !io.KeyCtrl && !io.KeyShift && !io.KeyAlt && !is_readonly)
{
unsigned int c = '\t'; // Insert TAB
if (InputTextFilterCharacter(&c, flags, callback, callback_user_data))
state->OnKeyPressed((int)c);
}
else if (IsKeyPressedMap(ImGuiKey_Escape))
{
clear_active_id = cancel_edit = true;
}
else if (is_undo || is_redo)
{
state->OnKeyPressed(is_undo ? STB_TEXTEDIT_K_UNDO : STB_TEXTEDIT_K_REDO);
state->ClearSelection();
}
else if (is_shortcut_key && IsKeyPressedMap(ImGuiKey_A))
{
state->SelectAll();
state->CursorFollow = true;
}
else if (is_cut || is_copy)
{
// Cut, Copy
if (io.SetClipboardTextFn)
{
const int ib = state->HasSelection() ? ImMin(state->Stb.select_start, state->Stb.select_end) : 0;
const int ie = state->HasSelection() ? ImMax(state->Stb.select_start, state->Stb.select_end) : state->CurLenW;
const int clipboard_data_len = ImTextCountUtf8BytesFromStr(state->TextW.Data + ib, state->TextW.Data + ie) + 1;
char* clipboard_data = (char*)MemAlloc(clipboard_data_len * sizeof(char));
ImTextStrToUtf8(clipboard_data, clipboard_data_len, state->TextW.Data + ib, state->TextW.Data + ie);
SetClipboardText(clipboard_data);
MemFree(clipboard_data);
}
if (is_cut)
{
if (!state->HasSelection())
state->SelectAll();
state->CursorFollow = true;
stb_textedit_cut(state, &state->Stb);
}
}
else if (is_paste)
{
if (const char* clipboard = GetClipboardText())
{
// Filter pasted buffer
const int clipboard_len = (int)strlen(clipboard);
ImWchar* clipboard_filtered = (ImWchar*)MemAlloc((clipboard_len+1) * sizeof(ImWchar));
int clipboard_filtered_len = 0;
for (const char* s = clipboard; *s; )
{
unsigned int c;
s += ImTextCharFromUtf8(&c, s, NULL);
if (c == 0)
break;
if (c >= 0x10000 || !InputTextFilterCharacter(&c, flags, callback, callback_user_data))
continue;
clipboard_filtered[clipboard_filtered_len++] = (ImWchar)c;
}
clipboard_filtered[clipboard_filtered_len] = 0;
if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation
{
stb_textedit_paste(state, &state->Stb, clipboard_filtered, clipboard_filtered_len);
state->CursorFollow = true;
}
MemFree(clipboard_filtered);
}
}
}
// Process callbacks and apply result back to user's buffer.
if (g.ActiveId == id)
{
IM_ASSERT(state != NULL);
const char* apply_new_text = NULL;
int apply_new_text_length = 0;
if (cancel_edit)
{
// Restore initial value. Only return true if restoring to the initial value changes the current buffer contents.
if (!is_readonly && strcmp(buf, state->InitialTextA.Data) != 0)
{
apply_new_text = state->InitialTextA.Data;
apply_new_text_length = state->InitialTextA.Size - 1;
}
}
// When using 'ImGuiInputTextFlags_EnterReturnsTrue' as a special case we reapply the live buffer back to the input buffer before clearing ActiveId, even though strictly speaking it wasn't modified on this frame.
// If we didn't do that, code like InputInt() with ImGuiInputTextFlags_EnterReturnsTrue would fail. Also this allows the user to use InputText() with ImGuiInputTextFlags_EnterReturnsTrue without maintaining any user-side storage.
bool apply_edit_back_to_user_buffer = !cancel_edit || (enter_pressed && (flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0);
if (apply_edit_back_to_user_buffer)
{
// Apply new value immediately - copy modified buffer back
// Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer
// FIXME: We actually always render 'buf' when calling DrawList->AddText, making the comment above incorrect.
// FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks.
if (!is_readonly)
{
state->TextAIsValid = true;
state->TextA.resize(state->TextW.Size * 4 + 1);
ImTextStrToUtf8(state->TextA.Data, state->TextA.Size, state->TextW.Data, NULL);
}
// User callback
if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackAlways)) != 0)
{
IM_ASSERT(callback != NULL);
// The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment.
ImGuiInputTextFlags event_flag = 0;
ImGuiKey event_key = ImGuiKey_COUNT;
if ((flags & ImGuiInputTextFlags_CallbackCompletion) != 0 && IsKeyPressedMap(ImGuiKey_Tab))
{
event_flag = ImGuiInputTextFlags_CallbackCompletion;
event_key = ImGuiKey_Tab;
}
else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_UpArrow))
{
event_flag = ImGuiInputTextFlags_CallbackHistory;
event_key = ImGuiKey_UpArrow;
}
else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_DownArrow))
{
event_flag = ImGuiInputTextFlags_CallbackHistory;
event_key = ImGuiKey_DownArrow;
}
else if (flags & ImGuiInputTextFlags_CallbackAlways)
event_flag = ImGuiInputTextFlags_CallbackAlways;
if (event_flag)
{
ImGuiInputTextCallbackData callback_data;
memset(&callback_data, 0, sizeof(ImGuiInputTextCallbackData));
callback_data.EventFlag = event_flag;
callback_data.Flags = flags;
callback_data.UserData = callback_user_data;
callback_data.EventKey = event_key;
callback_data.Buf = state->TextA.Data;
callback_data.BufTextLen = state->CurLenA;
callback_data.BufSize = state->BufCapacityA;
callback_data.BufDirty = false;
// We have to convert from wchar-positions to UTF-8-positions, which can be pretty slow (an incentive to ditch the ImWchar buffer, see https://github.com/nothings/stb/issues/188)
ImWchar* text = state->TextW.Data;
const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + state->Stb.cursor);
const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + state->Stb.select_start);
const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + state->Stb.select_end);
// Call user code
callback(&callback_data);
// Read back what user may have modified
IM_ASSERT(callback_data.Buf == state->TextA.Data); // Invalid to modify those fields
IM_ASSERT(callback_data.BufSize == state->BufCapacityA);
IM_ASSERT(callback_data.Flags == flags);
if (callback_data.CursorPos != utf8_cursor_pos) { state->Stb.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); state->CursorFollow = true; }
if (callback_data.SelectionStart != utf8_selection_start) { state->Stb.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart); }
if (callback_data.SelectionEnd != utf8_selection_end) { state->Stb.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); }
if (callback_data.BufDirty)
{
IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text!
if (callback_data.BufTextLen > backup_current_text_length && is_resizable)
state->TextW.resize(state->TextW.Size + (callback_data.BufTextLen - backup_current_text_length));
state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, state->TextW.Size, callback_data.Buf, NULL);
state->CurLenA = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen()
state->CursorAnimReset();
}
}
}
// Will copy result string if modified
if (!is_readonly && strcmp(state->TextA.Data, buf) != 0)
{
apply_new_text = state->TextA.Data;
apply_new_text_length = state->CurLenA;
}
}
// Copy result to user buffer
if (apply_new_text)
{
IM_ASSERT(apply_new_text_length >= 0);
if (backup_current_text_length != apply_new_text_length && is_resizable)
{
ImGuiInputTextCallbackData callback_data;
callback_data.EventFlag = ImGuiInputTextFlags_CallbackResize;
callback_data.Flags = flags;
callback_data.Buf = buf;
callback_data.BufTextLen = apply_new_text_length;
callback_data.BufSize = ImMax(buf_size, apply_new_text_length + 1);
callback_data.UserData = callback_user_data;
callback(&callback_data);
buf = callback_data.Buf;
buf_size = callback_data.BufSize;
apply_new_text_length = ImMin(callback_data.BufTextLen, buf_size - 1);
IM_ASSERT(apply_new_text_length <= buf_size);
}
// If the underlying buffer resize was denied or not carried to the next frame, apply_new_text_length+1 may be >= buf_size.
ImStrncpy(buf, apply_new_text, ImMin(apply_new_text_length + 1, buf_size));
value_changed = true;
}
// Clear temporary user storage
state->UserFlags = 0;
state->UserCallback = NULL;
state->UserCallbackData = NULL;
}
// Release active ID at the end of the function (so e.g. pressing Return still does a final application of the value)
if (clear_active_id && g.ActiveId == id)
ClearActiveID();
// Render frame
if (!is_multiline)
{
RenderNavHighlight(frame_bb, id);
RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
}
const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + size.x, frame_bb.Min.y + size.y); // Not using frame_bb.Max because we have adjusted size
ImVec2 draw_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding;
ImVec2 text_size(0.0f, 0.0f);
// Set upper limit of single-line InputTextEx() at 2 million characters strings. The current pathological worst case is a long line
// without any carriage return, which would makes ImFont::RenderText() reserve too many vertices and probably crash. Avoid it altogether.
// Note that we only use this limit on single-line InputText(), so a pathologically large line on a InputTextMultiline() would still crash.
const int buf_display_max_length = 2 * 1024 * 1024;
const char* buf_display = buf_display_from_state ? state->TextA.Data : buf; //-V595
const char* buf_display_end = NULL; // We have specialized paths below for setting the length
if (is_displaying_hint)
{
buf_display = hint;
buf_display_end = hint + strlen(hint);
}
// Render text. We currently only render selection when the widget is active or while scrolling.
// FIXME: We could remove the '&& render_cursor' to keep rendering selection when inactive.
if (render_cursor || render_selection)
{
IM_ASSERT(state != NULL);
if (!is_displaying_hint)
buf_display_end = buf_display + state->CurLenA;
// Render text (with cursor and selection)
// This is going to be messy. We need to:
// - Display the text (this alone can be more easily clipped)
// - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation)
// - Measure text height (for scrollbar)
// We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort)
// FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8.
const ImWchar* text_begin = state->TextW.Data;
ImVec2 cursor_offset, select_start_offset;
{
// Find lines numbers straddling 'cursor' (slot 0) and 'select_start' (slot 1) positions.
const ImWchar* searches_input_ptr[2] = { NULL, NULL };
int searches_result_line_no[2] = { -1000, -1000 };
int searches_remaining = 0;
if (render_cursor)
{
searches_input_ptr[0] = text_begin + state->Stb.cursor;
searches_result_line_no[0] = -1;
searches_remaining++;
}
if (render_selection)
{
searches_input_ptr[1] = text_begin + ImMin(state->Stb.select_start, state->Stb.select_end);
searches_result_line_no[1] = -1;
searches_remaining++;
}
// Iterate all lines to find our line numbers
// In multi-line mode, we never exit the loop until all lines are counted, so add one extra to the searches_remaining counter.
searches_remaining += is_multiline ? 1 : 0;
int line_count = 0;
//for (const ImWchar* s = text_begin; (s = (const ImWchar*)wcschr((const wchar_t*)s, (wchar_t)'\n')) != NULL; s++) // FIXME-OPT: Could use this when wchar_t are 16-bits
for (const ImWchar* s = text_begin; *s != 0; s++)
if (*s == '\n')
{
line_count++;
if (searches_result_line_no[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_no[0] = line_count; if (--searches_remaining <= 0) break; }
if (searches_result_line_no[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_no[1] = line_count; if (--searches_remaining <= 0) break; }
}
line_count++;
if (searches_result_line_no[0] == -1)
searches_result_line_no[0] = line_count;
if (searches_result_line_no[1] == -1)
searches_result_line_no[1] = line_count;
// Calculate 2d position by finding the beginning of the line and measuring distance
cursor_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[0], text_begin), searches_input_ptr[0]).x;
cursor_offset.y = searches_result_line_no[0] * g.FontSize;
if (searches_result_line_no[1] >= 0)
{
select_start_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[1], text_begin), searches_input_ptr[1]).x;
select_start_offset.y = searches_result_line_no[1] * g.FontSize;
}
// Store text height (note that we haven't calculated text width at all, see GitHub issues #383, #1224)
if (is_multiline)
text_size = ImVec2(size.x, line_count * g.FontSize);
}
// Scroll
if (render_cursor && state->CursorFollow)
{
// Horizontal scroll in chunks of quarter width
if (!(flags & ImGuiInputTextFlags_NoHorizontalScroll))
{
const float scroll_increment_x = size.x * 0.25f;
if (cursor_offset.x < state->ScrollX)
state->ScrollX = (float)(int)ImMax(0.0f, cursor_offset.x - scroll_increment_x);
else if (cursor_offset.x - size.x >= state->ScrollX)
state->ScrollX = (float)(int)(cursor_offset.x - size.x + scroll_increment_x);
}
else
{
state->ScrollX = 0.0f;
}
// Vertical scroll
if (is_multiline)
{
float scroll_y = draw_window->Scroll.y;
if (cursor_offset.y - g.FontSize < scroll_y)
scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize);
else if (cursor_offset.y - size.y >= scroll_y)
scroll_y = cursor_offset.y - size.y;
draw_window->DC.CursorPos.y += (draw_window->Scroll.y - scroll_y); // Manipulate cursor pos immediately avoid a frame of lag
draw_window->Scroll.y = scroll_y;
draw_pos.y = draw_window->DC.CursorPos.y;
}
state->CursorFollow = false;
}
// Draw selection
const ImVec2 draw_scroll = ImVec2(state->ScrollX, 0.0f);
if (render_selection)
{
const ImWchar* text_selected_begin = text_begin + ImMin(state->Stb.select_start, state->Stb.select_end);
const ImWchar* text_selected_end = text_begin + ImMax(state->Stb.select_start, state->Stb.select_end);
ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg, render_cursor ? 1.0f : 0.6f); // FIXME: current code flow mandate that render_cursor is always true here, we are leaving the transparent one for tests.
float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection.
float bg_offy_dn = is_multiline ? 0.0f : 2.0f;
ImVec2 rect_pos = draw_pos + select_start_offset - draw_scroll;
for (const ImWchar* p = text_selected_begin; p < text_selected_end; )
{
if (rect_pos.y > clip_rect.w + g.FontSize)
break;
if (rect_pos.y < clip_rect.y)
{
//p = (const ImWchar*)wmemchr((const wchar_t*)p, '\n', text_selected_end - p); // FIXME-OPT: Could use this when wchar_t are 16-bits
//p = p ? p + 1 : text_selected_end;
while (p < text_selected_end)
if (*p++ == '\n')
break;
}
else
{
ImVec2 rect_size = InputTextCalcTextSizeW(p, text_selected_end, &p, NULL, true);
if (rect_size.x <= 0.0f) rect_size.x = (float)(int)(g.Font->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines
ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos +ImVec2(rect_size.x, bg_offy_dn));
rect.ClipWith(clip_rect);
if (rect.Overlaps(clip_rect))
draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color);
}
rect_pos.x = draw_pos.x - draw_scroll.x;
rect_pos.y += g.FontSize;
}
}
// We test for 'buf_display_max_length' as a way to avoid some pathological cases (e.g. single-line 1 MB string) which would make ImDrawList crash.
if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length)
{
ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text);
draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect);
}
// Draw blinking cursor
if (render_cursor)
{
state->CursorAnim += io.DeltaTime;
bool cursor_is_visible = (!g.IO.ConfigInputTextCursorBlink) || (state->CursorAnim <= 0.0f) || ImFmod(state->CursorAnim, 1.20f) <= 0.80f;
ImVec2 cursor_screen_pos = draw_pos + cursor_offset - draw_scroll;
ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 0.5f, cursor_screen_pos.x + 1.0f, cursor_screen_pos.y - 1.5f);
if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect))
draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text));
// Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.)
if (!is_readonly)
g.PlatformImePos = ImVec2(cursor_screen_pos.x - 1.0f, cursor_screen_pos.y - g.FontSize);
}
}
else
{
// Render text only (no selection, no cursor)
if (is_multiline)
text_size = ImVec2(size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_display_end) * g.FontSize); // We don't need width
else if (!is_displaying_hint && g.ActiveId == id)
buf_display_end = buf_display + state->CurLenA;
else if (!is_displaying_hint)
buf_display_end = buf_display + strlen(buf_display);
if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length)
{
ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text);
draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect);
}
}
if (is_multiline)
{
Dummy(text_size + ImVec2(0.0f, g.FontSize)); // Always add room to scroll an extra line
EndChildFrame();
EndGroup();
}
if (is_password && !is_displaying_hint)
PopFont();
// Log as text
if (g.LogEnabled && !(is_password && !is_displaying_hint))
LogRenderedText(&draw_pos, buf_display, buf_display_end);
if (label_size.x > 0)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
if (value_changed)
MarkItemEdited(id);
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags);
if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0)
return enter_pressed;
else
return value_changed;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc.
//-------------------------------------------------------------------------
// - ColorEdit3()
// - ColorEdit4()
// - ColorPicker3()
// - RenderColorRectWithAlphaCheckerboard() [Internal]
// - ColorPicker4()
// - ColorButton()
// - SetColorEditOptions()
// - ColorTooltip() [Internal]
// - ColorEditOptionsPopup() [Internal]
// - ColorPickerOptionsPopup() [Internal]
//-------------------------------------------------------------------------
bool ImGui::ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags)
{
return ColorEdit4(label, col, flags | ImGuiColorEditFlags_NoAlpha);
}
// Edit colors components (each component in 0.0f..1.0f range).
// See enum ImGuiColorEditFlags_ for available options. e.g. Only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
// With typical options: Left-click on colored square to open color picker. Right-click to open option menu. CTRL-Click over input fields to edit them and TAB to go to next item.
bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const float square_sz = GetFrameHeight();
const float w_extra = (flags & ImGuiColorEditFlags_NoSmallPreview) ? 0.0f : (square_sz + style.ItemInnerSpacing.x);
const float w_items_all = CalcItemWidth() - w_extra;
const char* label_display_end = FindRenderedTextEnd(label);
BeginGroup();
PushID(label);
// If we're not showing any slider there's no point in doing any HSV conversions
const ImGuiColorEditFlags flags_untouched = flags;
if (flags & ImGuiColorEditFlags_NoInputs)
flags = (flags & (~ImGuiColorEditFlags__DisplayMask)) | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_NoOptions;
// Context menu: display and modify options (before defaults are applied)
if (!(flags & ImGuiColorEditFlags_NoOptions))
ColorEditOptionsPopup(col, flags);
// Read stored options
if (!(flags & ImGuiColorEditFlags__DisplayMask))
flags |= (g.ColorEditOptions & ImGuiColorEditFlags__DisplayMask);
if (!(flags & ImGuiColorEditFlags__DataTypeMask))
flags |= (g.ColorEditOptions & ImGuiColorEditFlags__DataTypeMask);
if (!(flags & ImGuiColorEditFlags__PickerMask))
flags |= (g.ColorEditOptions & ImGuiColorEditFlags__PickerMask);
if (!(flags & ImGuiColorEditFlags__InputMask))
flags |= (g.ColorEditOptions & ImGuiColorEditFlags__InputMask);
flags |= (g.ColorEditOptions & ~(ImGuiColorEditFlags__DisplayMask | ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask | ImGuiColorEditFlags__InputMask));
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__DisplayMask)); // Check that only 1 is selected
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__InputMask)); // Check that only 1 is selected
const bool alpha = (flags & ImGuiColorEditFlags_NoAlpha) == 0;
const bool hdr = (flags & ImGuiColorEditFlags_HDR) != 0;
const int components = alpha ? 4 : 3;
// Convert to the formats we need
float f[4] = { col[0], col[1], col[2], alpha ? col[3] : 1.0f };
if ((flags & ImGuiColorEditFlags_InputHSV) && (flags & ImGuiColorEditFlags_DisplayRGB))
ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]);
else if ((flags & ImGuiColorEditFlags_InputRGB) && (flags & ImGuiColorEditFlags_DisplayHSV))
ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]);
int i[4] = { IM_F32_TO_INT8_UNBOUND(f[0]), IM_F32_TO_INT8_UNBOUND(f[1]), IM_F32_TO_INT8_UNBOUND(f[2]), IM_F32_TO_INT8_UNBOUND(f[3]) };
bool value_changed = false;
bool value_changed_as_float = false;
if ((flags & (ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV)) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0)
{
// RGB/HSV 0..255 Sliders
const float w_item_one = ImMax(1.0f, (float)(int)((w_items_all - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
const float w_item_last = ImMax(1.0f, (float)(int)(w_items_all - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
const bool hide_prefix = (w_item_one <= CalcTextSize((flags & ImGuiColorEditFlags_Float) ? "M:0.000" : "M:000").x);
static const char* ids[4] = { "##X", "##Y", "##Z", "##W" };
static const char* fmt_table_int[3][4] =
{
{ "%3d", "%3d", "%3d", "%3d" }, // Short display
{ "R:%3d", "G:%3d", "B:%3d", "A:%3d" }, // Long display for RGBA
{ "H:%3d", "S:%3d", "V:%3d", "A:%3d" } // Long display for HSVA
};
static const char* fmt_table_float[3][4] =
{
{ "%0.3f", "%0.3f", "%0.3f", "%0.3f" }, // Short display
{ "R:%0.3f", "G:%0.3f", "B:%0.3f", "A:%0.3f" }, // Long display for RGBA
{ "H:%0.3f", "S:%0.3f", "V:%0.3f", "A:%0.3f" } // Long display for HSVA
};
const int fmt_idx = hide_prefix ? 0 : (flags & ImGuiColorEditFlags_DisplayHSV) ? 2 : 1;
PushItemWidth(w_item_one);
for (int n = 0; n < components; n++)
{
if (n > 0)
SameLine(0, style.ItemInnerSpacing.x);
if (n + 1 == components)
PushItemWidth(w_item_last);
if (flags & ImGuiColorEditFlags_Float)
{
value_changed |= DragFloat(ids[n], &f[n], 1.0f/255.0f, 0.0f, hdr ? 0.0f : 1.0f, fmt_table_float[fmt_idx][n]);
value_changed_as_float |= value_changed;
}
else
{
value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, hdr ? 0 : 255, fmt_table_int[fmt_idx][n]);
}
if (!(flags & ImGuiColorEditFlags_NoOptions))
OpenPopupOnItemClick("context");
}
PopItemWidth();
PopItemWidth();
}
else if ((flags & ImGuiColorEditFlags_DisplayHex) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0)
{
// RGB Hexadecimal Input
char buf[64];
if (alpha)
ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", ImClamp(i[0],0,255), ImClamp(i[1],0,255), ImClamp(i[2],0,255), ImClamp(i[3],0,255));
else
ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", ImClamp(i[0],0,255), ImClamp(i[1],0,255), ImClamp(i[2],0,255));
PushItemWidth(w_items_all);
if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase))
{
value_changed = true;
char* p = buf;
while (*p == '#' || ImCharIsBlankA(*p))
p++;
i[0] = i[1] = i[2] = i[3] = 0;
if (alpha)
sscanf(p, "%02X%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2], (unsigned int*)&i[3]); // Treat at unsigned (%X is unsigned)
else
sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]);
}
if (!(flags & ImGuiColorEditFlags_NoOptions))
OpenPopupOnItemClick("context");
PopItemWidth();
}
ImGuiWindow* picker_active_window = NULL;
if (!(flags & ImGuiColorEditFlags_NoSmallPreview))
{
if (!(flags & ImGuiColorEditFlags_NoInputs))
SameLine(0, style.ItemInnerSpacing.x);
const ImVec4 col_v4(col[0], col[1], col[2], alpha ? col[3] : 1.0f);
if (ColorButton("##ColorButton", col_v4, flags))
{
if (!(flags & ImGuiColorEditFlags_NoPicker))
{
// Store current color and open a picker
g.ColorPickerRef = col_v4;
OpenPopup("picker");
SetNextWindowPos(window->DC.LastItemRect.GetBL() + ImVec2(-1,style.ItemSpacing.y));
}
}
if (!(flags & ImGuiColorEditFlags_NoOptions))
OpenPopupOnItemClick("context");
if (BeginPopup("picker"))
{
picker_active_window = g.CurrentWindow;
if (label != label_display_end)
{
TextEx(label, label_display_end);
Spacing();
}
ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask | ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar;
ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf;
PushItemWidth(square_sz * 12.0f); // Use 256 + bar sizes?
value_changed |= ColorPicker4("##picker", col, picker_flags, &g.ColorPickerRef.x);
PopItemWidth();
EndPopup();
}
}
if (label != label_display_end && !(flags & ImGuiColorEditFlags_NoLabel))
{
SameLine(0, style.ItemInnerSpacing.x);
TextEx(label, label_display_end);
}
// Convert back
if (value_changed && picker_active_window == NULL)
{
if (!value_changed_as_float)
for (int n = 0; n < 4; n++)
f[n] = i[n] / 255.0f;
if ((flags & ImGuiColorEditFlags_DisplayHSV) && (flags & ImGuiColorEditFlags_InputRGB))
ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]);
if ((flags & ImGuiColorEditFlags_DisplayRGB) && (flags & ImGuiColorEditFlags_InputHSV))
ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]);
col[0] = f[0];
col[1] = f[1];
col[2] = f[2];
if (alpha)
col[3] = f[3];
}
PopID();
EndGroup();
// Drag and Drop Target
// NB: The flag test is merely an optional micro-optimization, BeginDragDropTarget() does the same test.
if ((window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropTarget())
{
bool accepted_drag_drop = false;
if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F))
{
memcpy((float*)col, payload->Data, sizeof(float) * 3); // Preserve alpha if any //-V512
value_changed = accepted_drag_drop = true;
}
if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F))
{
memcpy((float*)col, payload->Data, sizeof(float) * components);
value_changed = accepted_drag_drop = true;
}
// Drag-drop payloads are always RGB
if (accepted_drag_drop && (flags & ImGuiColorEditFlags_InputHSV))
ColorConvertRGBtoHSV(col[0], col[1], col[2], col[0], col[1], col[2]);
EndDragDropTarget();
}
// When picker is being actively used, use its active id so IsItemActive() will function on ColorEdit4().
if (picker_active_window && g.ActiveId != 0 && g.ActiveIdWindow == picker_active_window)
window->DC.LastItemId = g.ActiveId;
if (value_changed)
MarkItemEdited(window->DC.LastItemId);
return value_changed;
}
bool ImGui::ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags)
{
float col4[4] = { col[0], col[1], col[2], 1.0f };
if (!ColorPicker4(label, col4, flags | ImGuiColorEditFlags_NoAlpha))
return false;
col[0] = col4[0]; col[1] = col4[1]; col[2] = col4[2];
return true;
}
static inline ImU32 ImAlphaBlendColor(ImU32 col_a, ImU32 col_b)
{
float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
return IM_COL32(r, g, b, 0xFF);
}
// Helper for ColorPicker4()
// NB: This is rather brittle and will show artifact when rounding this enabled if rounded corners overlap multiple cells. Caller currently responsible for avoiding that.
// I spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding alltogether.
void ImGui::RenderColorRectWithAlphaCheckerboard(ImVec2 p_min, ImVec2 p_max, ImU32 col, float grid_step, ImVec2 grid_off, float rounding, int rounding_corners_flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (((col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT) < 0xFF)
{
ImU32 col_bg1 = GetColorU32(ImAlphaBlendColor(IM_COL32(204,204,204,255), col));
ImU32 col_bg2 = GetColorU32(ImAlphaBlendColor(IM_COL32(128,128,128,255), col));
window->DrawList->AddRectFilled(p_min, p_max, col_bg1, rounding, rounding_corners_flags);
int yi = 0;
for (float y = p_min.y + grid_off.y; y < p_max.y; y += grid_step, yi++)
{
float y1 = ImClamp(y, p_min.y, p_max.y), y2 = ImMin(y + grid_step, p_max.y);
if (y2 <= y1)
continue;
for (float x = p_min.x + grid_off.x + (yi & 1) * grid_step; x < p_max.x; x += grid_step * 2.0f)
{
float x1 = ImClamp(x, p_min.x, p_max.x), x2 = ImMin(x + grid_step, p_max.x);
if (x2 <= x1)
continue;
int rounding_corners_flags_cell = 0;
if (y1 <= p_min.y) { if (x1 <= p_min.x) rounding_corners_flags_cell |= ImDrawCornerFlags_TopLeft; if (x2 >= p_max.x) rounding_corners_flags_cell |= ImDrawCornerFlags_TopRight; }
if (y2 >= p_max.y) { if (x1 <= p_min.x) rounding_corners_flags_cell |= ImDrawCornerFlags_BotLeft; if (x2 >= p_max.x) rounding_corners_flags_cell |= ImDrawCornerFlags_BotRight; }
rounding_corners_flags_cell &= rounding_corners_flags;
window->DrawList->AddRectFilled(ImVec2(x1,y1), ImVec2(x2,y2), col_bg2, rounding_corners_flags_cell ? rounding : 0.0f, rounding_corners_flags_cell);
}
}
}
else
{
window->DrawList->AddRectFilled(p_min, p_max, col, rounding, rounding_corners_flags);
}
}
// Helper for ColorPicker4()
static void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, float bar_w)
{
ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x + 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Right, IM_COL32_BLACK);
ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x, pos.y), half_sz, ImGuiDir_Right, IM_COL32_WHITE);
ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x - 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Left, IM_COL32_BLACK);
ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x, pos.y), half_sz, ImGuiDir_Left, IM_COL32_WHITE);
}
// Note: ColorPicker4() only accesses 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
// (In C++ the 'float col[4]' notation for a function argument is equivalent to 'float* col', we only specify a size to facilitate understanding of the code.)
// FIXME: we adjust the big color square height based on item width, which may cause a flickering feedback loop (if automatic height makes a vertical scrollbar appears, affecting automatic width..)
bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags, const float* ref_col)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImDrawList* draw_list = window->DrawList;
ImGuiStyle& style = g.Style;
ImGuiIO& io = g.IO;
PushID(label);
BeginGroup();
if (!(flags & ImGuiColorEditFlags_NoSidePreview))
flags |= ImGuiColorEditFlags_NoSmallPreview;
// Context menu: display and store options.
if (!(flags & ImGuiColorEditFlags_NoOptions))
ColorPickerOptionsPopup(col, flags);
// Read stored options
if (!(flags & ImGuiColorEditFlags__PickerMask))
flags |= ((g.ColorEditOptions & ImGuiColorEditFlags__PickerMask) ? g.ColorEditOptions : ImGuiColorEditFlags__OptionsDefault) & ImGuiColorEditFlags__PickerMask;
if (!(flags & ImGuiColorEditFlags__InputMask))
flags |= ((g.ColorEditOptions & ImGuiColorEditFlags__InputMask) ? g.ColorEditOptions : ImGuiColorEditFlags__OptionsDefault) & ImGuiColorEditFlags__InputMask;
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__PickerMask)); // Check that only 1 is selected
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__InputMask)); // Check that only 1 is selected
if (!(flags & ImGuiColorEditFlags_NoOptions))
flags |= (g.ColorEditOptions & ImGuiColorEditFlags_AlphaBar);
// Setup
int components = (flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4;
bool alpha_bar = (flags & ImGuiColorEditFlags_AlphaBar) && !(flags & ImGuiColorEditFlags_NoAlpha);
ImVec2 picker_pos = window->DC.CursorPos;
float square_sz = GetFrameHeight();
float bars_width = square_sz; // Arbitrary smallish width of Hue/Alpha picking bars
float sv_picker_size = ImMax(bars_width * 1, CalcItemWidth() - (alpha_bar ? 2 : 1) * (bars_width + style.ItemInnerSpacing.x)); // Saturation/Value picking box
float bar0_pos_x = picker_pos.x + sv_picker_size + style.ItemInnerSpacing.x;
float bar1_pos_x = bar0_pos_x + bars_width + style.ItemInnerSpacing.x;
float bars_triangles_half_sz = (float)(int)(bars_width * 0.20f);
float backup_initial_col[4];
memcpy(backup_initial_col, col, components * sizeof(float));
float wheel_thickness = sv_picker_size * 0.08f;
float wheel_r_outer = sv_picker_size * 0.50f;
float wheel_r_inner = wheel_r_outer - wheel_thickness;
ImVec2 wheel_center(picker_pos.x + (sv_picker_size + bars_width)*0.5f, picker_pos.y + sv_picker_size*0.5f);
// Note: the triangle is displayed rotated with triangle_pa pointing to Hue, but most coordinates stays unrotated for logic.
float triangle_r = wheel_r_inner - (int)(sv_picker_size * 0.027f);
ImVec2 triangle_pa = ImVec2(triangle_r, 0.0f); // Hue point.
ImVec2 triangle_pb = ImVec2(triangle_r * -0.5f, triangle_r * -0.866025f); // Black point.
ImVec2 triangle_pc = ImVec2(triangle_r * -0.5f, triangle_r * +0.866025f); // White point.
float H = col[0], S = col[1], V = col[2];
float R = col[0], G = col[1], B = col[2];
if (flags & ImGuiColorEditFlags_InputRGB)
ColorConvertRGBtoHSV(R, G, B, H, S, V);
else if (flags & ImGuiColorEditFlags_InputHSV)
ColorConvertHSVtoRGB(H, S, V, R, G, B);
bool value_changed = false, value_changed_h = false, value_changed_sv = false;
PushItemFlag(ImGuiItemFlags_NoNav, true);
if (flags & ImGuiColorEditFlags_PickerHueWheel)
{
// Hue wheel + SV triangle logic
InvisibleButton("hsv", ImVec2(sv_picker_size + style.ItemInnerSpacing.x + bars_width, sv_picker_size));
if (IsItemActive())
{
ImVec2 initial_off = g.IO.MouseClickedPos[0] - wheel_center;
ImVec2 current_off = g.IO.MousePos - wheel_center;
float initial_dist2 = ImLengthSqr(initial_off);
if (initial_dist2 >= (wheel_r_inner-1)*(wheel_r_inner-1) && initial_dist2 <= (wheel_r_outer+1)*(wheel_r_outer+1))
{
// Interactive with Hue wheel
H = ImAtan2(current_off.y, current_off.x) / IM_PI*0.5f;
if (H < 0.0f)
H += 1.0f;
value_changed = value_changed_h = true;
}
float cos_hue_angle = ImCos(-H * 2.0f * IM_PI);
float sin_hue_angle = ImSin(-H * 2.0f * IM_PI);
if (ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, ImRotate(initial_off, cos_hue_angle, sin_hue_angle)))
{
// Interacting with SV triangle
ImVec2 current_off_unrotated = ImRotate(current_off, cos_hue_angle, sin_hue_angle);
if (!ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated))
current_off_unrotated = ImTriangleClosestPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated);
float uu, vv, ww;
ImTriangleBarycentricCoords(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated, uu, vv, ww);
V = ImClamp(1.0f - vv, 0.0001f, 1.0f);
S = ImClamp(uu / V, 0.0001f, 1.0f);
value_changed = value_changed_sv = true;
}
}
if (!(flags & ImGuiColorEditFlags_NoOptions))
OpenPopupOnItemClick("context");
}
else if (flags & ImGuiColorEditFlags_PickerHueBar)
{
// SV rectangle logic
InvisibleButton("sv", ImVec2(sv_picker_size, sv_picker_size));
if (IsItemActive())
{
S = ImSaturate((io.MousePos.x - picker_pos.x) / (sv_picker_size-1));
V = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1));
value_changed = value_changed_sv = true;
}
if (!(flags & ImGuiColorEditFlags_NoOptions))
OpenPopupOnItemClick("context");
// Hue bar logic
SetCursorScreenPos(ImVec2(bar0_pos_x, picker_pos.y));
InvisibleButton("hue", ImVec2(bars_width, sv_picker_size));
if (IsItemActive())
{
H = ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1));
value_changed = value_changed_h = true;
}
}
// Alpha bar logic
if (alpha_bar)
{
SetCursorScreenPos(ImVec2(bar1_pos_x, picker_pos.y));
InvisibleButton("alpha", ImVec2(bars_width, sv_picker_size));
if (IsItemActive())
{
col[3] = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1));
value_changed = true;
}
}
PopItemFlag(); // ImGuiItemFlags_NoNav
if (!(flags & ImGuiColorEditFlags_NoSidePreview))
{
SameLine(0, style.ItemInnerSpacing.x);
BeginGroup();
}
if (!(flags & ImGuiColorEditFlags_NoLabel))
{
const char* label_display_end = FindRenderedTextEnd(label);
if (label != label_display_end)
{
if ((flags & ImGuiColorEditFlags_NoSidePreview))
SameLine(0, style.ItemInnerSpacing.x);
TextEx(label, label_display_end);
}
}
if (!(flags & ImGuiColorEditFlags_NoSidePreview))
{
PushItemFlag(ImGuiItemFlags_NoNavDefaultFocus, true);
ImVec4 col_v4(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
if ((flags & ImGuiColorEditFlags_NoLabel))
Text("Current");
ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf | ImGuiColorEditFlags_NoTooltip;
ColorButton("##current", col_v4, (flags & sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2));
if (ref_col != NULL)
{
Text("Original");
ImVec4 ref_col_v4(ref_col[0], ref_col[1], ref_col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : ref_col[3]);
if (ColorButton("##original", ref_col_v4, (flags & sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2)))
{
memcpy(col, ref_col, components * sizeof(float));
value_changed = true;
}
}
PopItemFlag();
EndGroup();
}
// Convert back color to RGB
if (value_changed_h || value_changed_sv)
{
if (flags & ImGuiColorEditFlags_InputRGB)
{
ColorConvertHSVtoRGB(H >= 1.0f ? H - 10 * 1e-6f : H, S > 0.0f ? S : 10*1e-6f, V > 0.0f ? V : 1e-6f, col[0], col[1], col[2]);
}
else if (flags & ImGuiColorEditFlags_InputHSV)
{
col[0] = H;
col[1] = S;
col[2] = V;
}
}
// R,G,B and H,S,V slider color editor
bool value_changed_fix_hue_wrap = false;
if ((flags & ImGuiColorEditFlags_NoInputs) == 0)
{
PushItemWidth((alpha_bar ? bar1_pos_x : bar0_pos_x) + bars_width - picker_pos.x);
ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoSmallPreview | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf;
ImGuiColorEditFlags sub_flags = (flags & sub_flags_to_forward) | ImGuiColorEditFlags_NoPicker;
if (flags & ImGuiColorEditFlags_DisplayRGB || (flags & ImGuiColorEditFlags__DisplayMask) == 0)
if (ColorEdit4("##rgb", col, sub_flags | ImGuiColorEditFlags_DisplayRGB))
{
// FIXME: Hackily differenciating using the DragInt (ActiveId != 0 && !ActiveIdAllowOverlap) vs. using the InputText or DropTarget.
// For the later we don't want to run the hue-wrap canceling code. If you are well versed in HSV picker please provide your input! (See #2050)
value_changed_fix_hue_wrap = (g.ActiveId != 0 && !g.ActiveIdAllowOverlap);
value_changed = true;
}
if (flags & ImGuiColorEditFlags_DisplayHSV || (flags & ImGuiColorEditFlags__DisplayMask) == 0)
value_changed |= ColorEdit4("##hsv", col, sub_flags | ImGuiColorEditFlags_DisplayHSV);
if (flags & ImGuiColorEditFlags_DisplayHex || (flags & ImGuiColorEditFlags__DisplayMask) == 0)
value_changed |= ColorEdit4("##hex", col, sub_flags | ImGuiColorEditFlags_DisplayHex);
PopItemWidth();
}
// Try to cancel hue wrap (after ColorEdit4 call), if any
if (value_changed_fix_hue_wrap && (flags & ImGuiColorEditFlags_InputRGB))
{
float new_H, new_S, new_V;
ColorConvertRGBtoHSV(col[0], col[1], col[2], new_H, new_S, new_V);
if (new_H <= 0 && H > 0)
{
if (new_V <= 0 && V != new_V)
ColorConvertHSVtoRGB(H, S, new_V <= 0 ? V * 0.5f : new_V, col[0], col[1], col[2]);
else if (new_S <= 0)
ColorConvertHSVtoRGB(H, new_S <= 0 ? S * 0.5f : new_S, new_V, col[0], col[1], col[2]);
}
}
if (value_changed)
{
if (flags & ImGuiColorEditFlags_InputRGB)
{
R = col[0];
G = col[1];
B = col[2];
ColorConvertRGBtoHSV(R, G, B, H, S, V);
}
else if (flags & ImGuiColorEditFlags_InputHSV)
{
H = col[0];
S = col[1];
V = col[2];
ColorConvertHSVtoRGB(H, S, V, R, G, B);
}
}
ImVec4 hue_color_f(1, 1, 1, 1); ColorConvertHSVtoRGB(H, 1, 1, hue_color_f.x, hue_color_f.y, hue_color_f.z);
ImU32 hue_color32 = ColorConvertFloat4ToU32(hue_color_f);
ImU32 col32_no_alpha = ColorConvertFloat4ToU32(ImVec4(R, G, B, 1.0f));
const ImU32 hue_colors[6+1] = { IM_COL32(255,0,0,255), IM_COL32(255,255,0,255), IM_COL32(0,255,0,255), IM_COL32(0,255,255,255), IM_COL32(0,0,255,255), IM_COL32(255,0,255,255), IM_COL32(255,0,0,255) };
ImVec2 sv_cursor_pos;
if (flags & ImGuiColorEditFlags_PickerHueWheel)
{
// Render Hue Wheel
const float aeps = 1.5f / wheel_r_outer; // Half a pixel arc length in radians (2pi cancels out).
const int segment_per_arc = ImMax(4, (int)wheel_r_outer / 12);
for (int n = 0; n < 6; n++)
{
const float a0 = (n) /6.0f * 2.0f * IM_PI - aeps;
const float a1 = (n+1.0f)/6.0f * 2.0f * IM_PI + aeps;
const int vert_start_idx = draw_list->VtxBuffer.Size;
draw_list->PathArcTo(wheel_center, (wheel_r_inner + wheel_r_outer)*0.5f, a0, a1, segment_per_arc);
draw_list->PathStroke(IM_COL32_WHITE, false, wheel_thickness);
const int vert_end_idx = draw_list->VtxBuffer.Size;
// Paint colors over existing vertices
ImVec2 gradient_p0(wheel_center.x + ImCos(a0) * wheel_r_inner, wheel_center.y + ImSin(a0) * wheel_r_inner);
ImVec2 gradient_p1(wheel_center.x + ImCos(a1) * wheel_r_inner, wheel_center.y + ImSin(a1) * wheel_r_inner);
ShadeVertsLinearColorGradientKeepAlpha(draw_list, vert_start_idx, vert_end_idx, gradient_p0, gradient_p1, hue_colors[n], hue_colors[n+1]);
}
// Render Cursor + preview on Hue Wheel
float cos_hue_angle = ImCos(H * 2.0f * IM_PI);
float sin_hue_angle = ImSin(H * 2.0f * IM_PI);
ImVec2 hue_cursor_pos(wheel_center.x + cos_hue_angle * (wheel_r_inner+wheel_r_outer)*0.5f, wheel_center.y + sin_hue_angle * (wheel_r_inner+wheel_r_outer)*0.5f);
float hue_cursor_rad = value_changed_h ? wheel_thickness * 0.65f : wheel_thickness * 0.55f;
int hue_cursor_segments = ImClamp((int)(hue_cursor_rad / 1.4f), 9, 32);
draw_list->AddCircleFilled(hue_cursor_pos, hue_cursor_rad, hue_color32, hue_cursor_segments);
draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad+1, IM_COL32(128,128,128,255), hue_cursor_segments);
draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad, IM_COL32_WHITE, hue_cursor_segments);
// Render SV triangle (rotated according to hue)
ImVec2 tra = wheel_center + ImRotate(triangle_pa, cos_hue_angle, sin_hue_angle);
ImVec2 trb = wheel_center + ImRotate(triangle_pb, cos_hue_angle, sin_hue_angle);
ImVec2 trc = wheel_center + ImRotate(triangle_pc, cos_hue_angle, sin_hue_angle);
ImVec2 uv_white = GetFontTexUvWhitePixel();
draw_list->PrimReserve(6, 6);
draw_list->PrimVtx(tra, uv_white, hue_color32);
draw_list->PrimVtx(trb, uv_white, hue_color32);
draw_list->PrimVtx(trc, uv_white, IM_COL32_WHITE);
draw_list->PrimVtx(tra, uv_white, IM_COL32_BLACK_TRANS);
draw_list->PrimVtx(trb, uv_white, IM_COL32_BLACK);
draw_list->PrimVtx(trc, uv_white, IM_COL32_BLACK_TRANS);
draw_list->AddTriangle(tra, trb, trc, IM_COL32(128,128,128,255), 1.5f);
sv_cursor_pos = ImLerp(ImLerp(trc, tra, ImSaturate(S)), trb, ImSaturate(1 - V));
}
else if (flags & ImGuiColorEditFlags_PickerHueBar)
{
// Render SV Square
draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), IM_COL32_WHITE, hue_color32, hue_color32, IM_COL32_WHITE);
draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), IM_COL32_BLACK_TRANS, IM_COL32_BLACK_TRANS, IM_COL32_BLACK, IM_COL32_BLACK);
RenderFrameBorder(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), 0.0f);
sv_cursor_pos.x = ImClamp((float)(int)(picker_pos.x + ImSaturate(S) * sv_picker_size + 0.5f), picker_pos.x + 2, picker_pos.x + sv_picker_size - 2); // Sneakily prevent the circle to stick out too much
sv_cursor_pos.y = ImClamp((float)(int)(picker_pos.y + ImSaturate(1 - V) * sv_picker_size + 0.5f), picker_pos.y + 2, picker_pos.y + sv_picker_size - 2);
// Render Hue Bar
for (int i = 0; i < 6; ++i)
draw_list->AddRectFilledMultiColor(ImVec2(bar0_pos_x, picker_pos.y + i * (sv_picker_size / 6)), ImVec2(bar0_pos_x + bars_width, picker_pos.y + (i + 1) * (sv_picker_size / 6)), hue_colors[i], hue_colors[i], hue_colors[i + 1], hue_colors[i + 1]);
float bar0_line_y = (float)(int)(picker_pos.y + H * sv_picker_size + 0.5f);
RenderFrameBorder(ImVec2(bar0_pos_x, picker_pos.y), ImVec2(bar0_pos_x + bars_width, picker_pos.y + sv_picker_size), 0.0f);
RenderArrowsForVerticalBar(draw_list, ImVec2(bar0_pos_x - 1, bar0_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f);
}
// Render cursor/preview circle (clamp S/V within 0..1 range because floating points colors may lead HSV values to be out of range)
float sv_cursor_rad = value_changed_sv ? 10.0f : 6.0f;
draw_list->AddCircleFilled(sv_cursor_pos, sv_cursor_rad, col32_no_alpha, 12);
draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad+1, IM_COL32(128,128,128,255), 12);
draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad, IM_COL32_WHITE, 12);
// Render alpha bar
if (alpha_bar)
{
float alpha = ImSaturate(col[3]);
ImRect bar1_bb(bar1_pos_x, picker_pos.y, bar1_pos_x + bars_width, picker_pos.y + sv_picker_size);
RenderColorRectWithAlphaCheckerboard(bar1_bb.Min, bar1_bb.Max, IM_COL32(0,0,0,0), bar1_bb.GetWidth() / 2.0f, ImVec2(0.0f, 0.0f));
draw_list->AddRectFilledMultiColor(bar1_bb.Min, bar1_bb.Max, col32_no_alpha, col32_no_alpha, col32_no_alpha & ~IM_COL32_A_MASK, col32_no_alpha & ~IM_COL32_A_MASK);
float bar1_line_y = (float)(int)(picker_pos.y + (1.0f - alpha) * sv_picker_size + 0.5f);
RenderFrameBorder(bar1_bb.Min, bar1_bb.Max, 0.0f);
RenderArrowsForVerticalBar(draw_list, ImVec2(bar1_pos_x - 1, bar1_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f);
}
EndGroup();
if (value_changed && memcmp(backup_initial_col, col, components * sizeof(float)) == 0)
value_changed = false;
if (value_changed)
MarkItemEdited(window->DC.LastItemId);
PopID();
return value_changed;
}
// A little colored square. Return true when clicked.
// FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip.
// 'desc_id' is not called 'label' because we don't display it next to the button, but only in the tooltip.
// Note that 'col' may be encoded in HSV if ImGuiColorEditFlags_InputHSV is set.
bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags, ImVec2 size)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiID id = window->GetID(desc_id);
float default_size = GetFrameHeight();
if (size.x == 0.0f)
size.x = default_size;
if (size.y == 0.0f)
size.y = default_size;
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
ItemSize(bb, (size.y >= default_size) ? g.Style.FramePadding.y : 0.0f);
if (!ItemAdd(bb, id))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
if (flags & ImGuiColorEditFlags_NoAlpha)
flags &= ~(ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf);
ImVec4 col_rgb = col;
if (flags & ImGuiColorEditFlags_InputHSV)
ColorConvertHSVtoRGB(col_rgb.x, col_rgb.y, col_rgb.z, col_rgb.x, col_rgb.y, col_rgb.z);
ImVec4 col_rgb_without_alpha(col_rgb.x, col_rgb.y, col_rgb.z, 1.0f);
float grid_step = ImMin(size.x, size.y) / 2.99f;
float rounding = ImMin(g.Style.FrameRounding, grid_step * 0.5f);
ImRect bb_inner = bb;
float off = -0.75f; // The border (using Col_FrameBg) tends to look off when color is near-opaque and rounding is enabled. This offset seemed like a good middle ground to reduce those artifacts.
bb_inner.Expand(off);
if ((flags & ImGuiColorEditFlags_AlphaPreviewHalf) && col_rgb.w < 1.0f)
{
float mid_x = (float)(int)((bb_inner.Min.x + bb_inner.Max.x) * 0.5f + 0.5f);
RenderColorRectWithAlphaCheckerboard(ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col_rgb), grid_step, ImVec2(-grid_step + off, off), rounding, ImDrawCornerFlags_TopRight| ImDrawCornerFlags_BotRight);
window->DrawList->AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), GetColorU32(col_rgb_without_alpha), rounding, ImDrawCornerFlags_TopLeft|ImDrawCornerFlags_BotLeft);
}
else
{
// Because GetColorU32() multiplies by the global style Alpha and we don't want to display a checkerboard if the source code had no alpha
ImVec4 col_source = (flags & ImGuiColorEditFlags_AlphaPreview) ? col_rgb : col_rgb_without_alpha;
if (col_source.w < 1.0f)
RenderColorRectWithAlphaCheckerboard(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), grid_step, ImVec2(off, off), rounding);
else
window->DrawList->AddRectFilled(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), rounding, ImDrawCornerFlags_All);
}
RenderNavHighlight(bb, id);
if (g.Style.FrameBorderSize > 0.0f)
RenderFrameBorder(bb.Min, bb.Max, rounding);
else
window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), rounding); // Color button are often in need of some sort of border
// Drag and Drop Source
// NB: The ActiveId test is merely an optional micro-optimization, BeginDragDropSource() does the same test.
if (g.ActiveId == id && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropSource())
{
if (flags & ImGuiColorEditFlags_NoAlpha)
SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F, &col_rgb, sizeof(float) * 3, ImGuiCond_Once);
else
SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, &col_rgb, sizeof(float) * 4, ImGuiCond_Once);
ColorButton(desc_id, col, flags);
SameLine();
TextEx("Color");
EndDragDropSource();
}
// Tooltip
if (!(flags & ImGuiColorEditFlags_NoTooltip) && hovered)
ColorTooltip(desc_id, &col.x, flags & (ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf));
if (pressed)
MarkItemEdited(id);
return pressed;
}
// Initialize/override default color options
void ImGui::SetColorEditOptions(ImGuiColorEditFlags flags)
{
ImGuiContext& g = *GImGui;
if ((flags & ImGuiColorEditFlags__DisplayMask) == 0)
flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__DisplayMask;
if ((flags & ImGuiColorEditFlags__DataTypeMask) == 0)
flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__DataTypeMask;
if ((flags & ImGuiColorEditFlags__PickerMask) == 0)
flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__PickerMask;
if ((flags & ImGuiColorEditFlags__InputMask) == 0)
flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__InputMask;
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__DisplayMask)); // Check only 1 option is selected
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__DataTypeMask)); // Check only 1 option is selected
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__PickerMask)); // Check only 1 option is selected
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__InputMask)); // Check only 1 option is selected
g.ColorEditOptions = flags;
}
// Note: only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags)
{
ImGuiContext& g = *GImGui;
BeginTooltipEx(0, true);
const char* text_end = text ? FindRenderedTextEnd(text, NULL) : text;
if (text_end > text)
{
TextEx(text, text_end);
Separator();
}
ImVec2 sz(g.FontSize * 3 + g.Style.FramePadding.y * 2, g.FontSize * 3 + g.Style.FramePadding.y * 2);
ImVec4 cf(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]);
ColorButton("##preview", cf, (flags & (ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)) | ImGuiColorEditFlags_NoTooltip, sz);
SameLine();
if ((flags & ImGuiColorEditFlags_InputRGB) || !(flags & ImGuiColorEditFlags__InputMask))
{
if (flags & ImGuiColorEditFlags_NoAlpha)
Text("#%02X%02X%02X\nR: %d, G: %d, B: %d\n(%.3f, %.3f, %.3f)", cr, cg, cb, cr, cg, cb, col[0], col[1], col[2]);
else
Text("#%02X%02X%02X%02X\nR:%d, G:%d, B:%d, A:%d\n(%.3f, %.3f, %.3f, %.3f)", cr, cg, cb, ca, cr, cg, cb, ca, col[0], col[1], col[2], col[3]);
}
else if (flags & ImGuiColorEditFlags_InputHSV)
{
if (flags & ImGuiColorEditFlags_NoAlpha)
Text("H: %.3f, S: %.3f, V: %.3f", col[0], col[1], col[2]);
else
Text("H: %.3f, S: %.3f, V: %.3f, A: %.3f", col[0], col[1], col[2], col[3]);
}
EndTooltip();
}
void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags)
{
bool allow_opt_inputs = !(flags & ImGuiColorEditFlags__DisplayMask);
bool allow_opt_datatype = !(flags & ImGuiColorEditFlags__DataTypeMask);
if ((!allow_opt_inputs && !allow_opt_datatype) || !BeginPopup("context"))
return;
ImGuiContext& g = *GImGui;
ImGuiColorEditFlags opts = g.ColorEditOptions;
if (allow_opt_inputs)
{
if (RadioButton("RGB", (opts & ImGuiColorEditFlags_DisplayRGB) != 0)) opts = (opts & ~ImGuiColorEditFlags__DisplayMask) | ImGuiColorEditFlags_DisplayRGB;
if (RadioButton("HSV", (opts & ImGuiColorEditFlags_DisplayHSV) != 0)) opts = (opts & ~ImGuiColorEditFlags__DisplayMask) | ImGuiColorEditFlags_DisplayHSV;
if (RadioButton("Hex", (opts & ImGuiColorEditFlags_DisplayHex) != 0)) opts = (opts & ~ImGuiColorEditFlags__DisplayMask) | ImGuiColorEditFlags_DisplayHex;
}
if (allow_opt_datatype)
{
if (allow_opt_inputs) Separator();
if (RadioButton("0..255", (opts & ImGuiColorEditFlags_Uint8) != 0)) opts = (opts & ~ImGuiColorEditFlags__DataTypeMask) | ImGuiColorEditFlags_Uint8;
if (RadioButton("0.00..1.00", (opts & ImGuiColorEditFlags_Float) != 0)) opts = (opts & ~ImGuiColorEditFlags__DataTypeMask) | ImGuiColorEditFlags_Float;
}
if (allow_opt_inputs || allow_opt_datatype)
Separator();
if (Button("Copy as..", ImVec2(-1,0)))
OpenPopup("Copy");
if (BeginPopup("Copy"))
{
int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]);
char buf[64];
ImFormatString(buf, IM_ARRAYSIZE(buf), "(%.3ff, %.3ff, %.3ff, %.3ff)", col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
if (Selectable(buf))
SetClipboardText(buf);
ImFormatString(buf, IM_ARRAYSIZE(buf), "(%d,%d,%d,%d)", cr, cg, cb, ca);
if (Selectable(buf))
SetClipboardText(buf);
if (flags & ImGuiColorEditFlags_NoAlpha)
ImFormatString(buf, IM_ARRAYSIZE(buf), "0x%02X%02X%02X", cr, cg, cb);
else
ImFormatString(buf, IM_ARRAYSIZE(buf), "0x%02X%02X%02X%02X", cr, cg, cb, ca);
if (Selectable(buf))
SetClipboardText(buf);
EndPopup();
}
g.ColorEditOptions = opts;
EndPopup();
}
void ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags flags)
{
bool allow_opt_picker = !(flags & ImGuiColorEditFlags__PickerMask);
bool allow_opt_alpha_bar = !(flags & ImGuiColorEditFlags_NoAlpha) && !(flags & ImGuiColorEditFlags_AlphaBar);
if ((!allow_opt_picker && !allow_opt_alpha_bar) || !BeginPopup("context"))
return;
ImGuiContext& g = *GImGui;
if (allow_opt_picker)
{
ImVec2 picker_size(g.FontSize * 8, ImMax(g.FontSize * 8 - (GetFrameHeight() + g.Style.ItemInnerSpacing.x), 1.0f)); // FIXME: Picker size copied from main picker function
PushItemWidth(picker_size.x);
for (int picker_type = 0; picker_type < 2; picker_type++)
{
// Draw small/thumbnail version of each picker type (over an invisible button for selection)
if (picker_type > 0) Separator();
PushID(picker_type);
ImGuiColorEditFlags picker_flags = ImGuiColorEditFlags_NoInputs|ImGuiColorEditFlags_NoOptions|ImGuiColorEditFlags_NoLabel|ImGuiColorEditFlags_NoSidePreview|(flags & ImGuiColorEditFlags_NoAlpha);
if (picker_type == 0) picker_flags |= ImGuiColorEditFlags_PickerHueBar;
if (picker_type == 1) picker_flags |= ImGuiColorEditFlags_PickerHueWheel;
ImVec2 backup_pos = GetCursorScreenPos();
if (Selectable("##selectable", false, 0, picker_size)) // By default, Selectable() is closing popup
g.ColorEditOptions = (g.ColorEditOptions & ~ImGuiColorEditFlags__PickerMask) | (picker_flags & ImGuiColorEditFlags__PickerMask);
SetCursorScreenPos(backup_pos);
ImVec4 dummy_ref_col;
memcpy(&dummy_ref_col, ref_col, sizeof(float) * ((picker_flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4));
ColorPicker4("##dummypicker", &dummy_ref_col.x, picker_flags);
PopID();
}
PopItemWidth();
}
if (allow_opt_alpha_bar)
{
if (allow_opt_picker) Separator();
CheckboxFlags("Alpha Bar", (unsigned int*)&g.ColorEditOptions, ImGuiColorEditFlags_AlphaBar);
}
EndPopup();
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: TreeNode, CollapsingHeader, etc.
//-------------------------------------------------------------------------
// - TreeNode()
// - TreeNodeV()
// - TreeNodeEx()
// - TreeNodeExV()
// - TreeNodeBehavior() [Internal]
// - TreePush()
// - TreePop()
// - TreeAdvanceToLabelPos()
// - GetTreeNodeToLabelSpacing()
// - SetNextTreeNodeOpen()
// - CollapsingHeader()
//-------------------------------------------------------------------------
bool ImGui::TreeNode(const char* str_id, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
bool is_open = TreeNodeExV(str_id, 0, fmt, args);
va_end(args);
return is_open;
}
bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
bool is_open = TreeNodeExV(ptr_id, 0, fmt, args);
va_end(args);
return is_open;
}
bool ImGui::TreeNode(const char* label)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
return TreeNodeBehavior(window->GetID(label), 0, label, NULL);
}
bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args)
{
return TreeNodeExV(str_id, 0, fmt, args);
}
bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args)
{
return TreeNodeExV(ptr_id, 0, fmt, args);
}
bool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
return TreeNodeBehavior(window->GetID(label), flags, label, NULL);
}
bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
bool is_open = TreeNodeExV(str_id, flags, fmt, args);
va_end(args);
return is_open;
}
bool ImGui::TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
bool is_open = TreeNodeExV(ptr_id, flags, fmt, args);
va_end(args);
return is_open;
}
bool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
return TreeNodeBehavior(window->GetID(str_id), flags, g.TempBuffer, label_end);
}
bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
return TreeNodeBehavior(window->GetID(ptr_id), flags, g.TempBuffer, label_end);
}
bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags)
{
if (flags & ImGuiTreeNodeFlags_Leaf)
return true;
// We only write to the tree storage if the user clicks (or explicitly use SetNextTreeNode*** functions)
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiStorage* storage = window->DC.StateStorage;
bool is_open;
if (g.NextTreeNodeOpenCond != 0)
{
if (g.NextTreeNodeOpenCond & ImGuiCond_Always)
{
is_open = g.NextTreeNodeOpenVal;
storage->SetInt(id, is_open);
}
else
{
// We treat ImGuiCond_Once and ImGuiCond_FirstUseEver the same because tree node state are not saved persistently.
const int stored_value = storage->GetInt(id, -1);
if (stored_value == -1)
{
is_open = g.NextTreeNodeOpenVal;
storage->SetInt(id, is_open);
}
else
{
is_open = stored_value != 0;
}
}
g.NextTreeNodeOpenCond = 0;
}
else
{
is_open = storage->GetInt(id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0;
}
// When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior).
// NB- If we are above max depth we still allow manually opened nodes to be logged.
if (g.LogEnabled && !(flags & ImGuiTreeNodeFlags_NoAutoOpenOnLog) && (window->DC.TreeDepth - g.LogDepthRef) < g.LogDepthToExpand)
is_open = true;
return is_open;
}
bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0;
const ImVec2 padding = (display_frame || (flags & ImGuiTreeNodeFlags_FramePadding)) ? style.FramePadding : ImVec2(style.FramePadding.x, 0.0f);
if (!label_end)
label_end = FindRenderedTextEnd(label);
const ImVec2 label_size = CalcTextSize(label, label_end, false);
// We vertically grow up to current line height up the typical widget height.
const float text_base_offset_y = ImMax(padding.y, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it
const float frame_height = ImMax(ImMin(window->DC.CurrentLineSize.y, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2);
ImRect frame_bb = ImRect(window->DC.CursorPos, ImVec2(window->Pos.x + GetContentRegionMax().x, window->DC.CursorPos.y + frame_height));
if (display_frame)
{
// Framed header expand a little outside the default padding
frame_bb.Min.x -= (float)(int)(window->WindowPadding.x*0.5f) - 1;
frame_bb.Max.x += (float)(int)(window->WindowPadding.x*0.5f) - 1;
}
const float text_offset_x = (g.FontSize + (display_frame ? padding.x*3 : padding.x*2)); // Collapser arrow width + Spacing
const float text_width = g.FontSize + (label_size.x > 0.0f ? label_size.x + padding.x*2 : 0.0f); // Include collapser
ItemSize(ImVec2(text_width, frame_height), text_base_offset_y);
// For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing
// (Ideally we'd want to add a flag for the user to specify if we want the hit test to be done up to the right side of the content or not)
const ImRect interact_bb = display_frame ? frame_bb : ImRect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + text_width + style.ItemSpacing.x*2, frame_bb.Max.y);
bool is_open = TreeNodeBehaviorIsOpen(id, flags);
bool is_leaf = (flags & ImGuiTreeNodeFlags_Leaf) != 0;
// Store a flag for the current depth to tell if we will allow closing this node when navigating one of its child.
// For this purpose we essentially compare if g.NavIdIsAlive went from 0 to 1 between TreeNode() and TreePop().
// This is currently only support 32 level deep and we are fine with (1 << Depth) overflowing into a zero.
if (is_open && !g.NavIdIsAlive && (flags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
window->DC.TreeDepthMayJumpToParentOnPop |= (1 << window->DC.TreeDepth);
bool item_add = ItemAdd(interact_bb, id);
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HasDisplayRect;
window->DC.LastItemDisplayRect = frame_bb;
if (!item_add)
{
if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
TreePushRawID(id);
IMGUI_TEST_ENGINE_ITEM_INFO(window->DC.LastItemId, label, window->DC.ItemFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0));
return is_open;
}
// Flags that affects opening behavior:
// - 0 (default) .................... single-click anywhere to open
// - OpenOnDoubleClick .............. double-click anywhere to open
// - OpenOnArrow .................... single-click on arrow to open
// - OpenOnDoubleClick|OpenOnArrow .. single-click on arrow or double-click anywhere to open
ImGuiButtonFlags button_flags = ImGuiButtonFlags_NoKeyModifiers;
if (flags & ImGuiTreeNodeFlags_AllowItemOverlap)
button_flags |= ImGuiButtonFlags_AllowItemOverlap;
if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
button_flags |= ImGuiButtonFlags_PressedOnDoubleClick | ((flags & ImGuiTreeNodeFlags_OpenOnArrow) ? ImGuiButtonFlags_PressedOnClickRelease : 0);
if (!is_leaf)
button_flags |= ImGuiButtonFlags_PressedOnDragDropHold;
bool selected = (flags & ImGuiTreeNodeFlags_Selected) != 0;
bool hovered, held;
bool pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags);
bool toggled = false;
if (!is_leaf)
{
if (pressed)
{
toggled = !(flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)) || (g.NavActivateId == id);
if (flags & ImGuiTreeNodeFlags_OpenOnArrow)
toggled |= IsMouseHoveringRect(interact_bb.Min, ImVec2(interact_bb.Min.x + text_offset_x, interact_bb.Max.y)) && (!g.NavDisableMouseHover);
if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
toggled |= g.IO.MouseDoubleClicked[0];
if (g.DragDropActive && is_open) // When using Drag and Drop "hold to open" we keep the node highlighted after opening, but never close it again.
toggled = false;
}
if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Left && is_open)
{
toggled = true;
NavMoveRequestCancel();
}
if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Right && !is_open) // If there's something upcoming on the line we may want to give it the priority?
{
toggled = true;
NavMoveRequestCancel();
}
if (toggled)
{
is_open = !is_open;
window->DC.StateStorage->SetInt(id, is_open);
}
}
if (flags & ImGuiTreeNodeFlags_AllowItemOverlap)
SetItemAllowOverlap();
// Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
const ImVec2 text_pos = frame_bb.Min + ImVec2(text_offset_x, text_base_offset_y);
ImGuiNavHighlightFlags nav_highlight_flags = ImGuiNavHighlightFlags_TypeThin;
if (display_frame)
{
// Framed type
RenderFrame(frame_bb.Min, frame_bb.Max, col, true, style.FrameRounding);
RenderNavHighlight(frame_bb, id, nav_highlight_flags);
RenderArrow(frame_bb.Min + ImVec2(padding.x, text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 1.0f);
if (g.LogEnabled)
{
// NB: '##' is normally used to hide text (as a library-wide feature), so we need to specify the text range to make sure the ## aren't stripped out here.
const char log_prefix[] = "\n##";
const char log_suffix[] = "##";
LogRenderedText(&text_pos, log_prefix, log_prefix+3);
RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size);
LogRenderedText(&text_pos, log_suffix, log_suffix+2);
}
else
{
RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size);
}
}
else
{
// Unframed typed for tree nodes
if (hovered || selected)
{
RenderFrame(frame_bb.Min, frame_bb.Max, col, false);
RenderNavHighlight(frame_bb, id, nav_highlight_flags);
}
if (flags & ImGuiTreeNodeFlags_Bullet)
RenderBullet(frame_bb.Min + ImVec2(text_offset_x * 0.5f, g.FontSize*0.50f + text_base_offset_y));
else if (!is_leaf)
RenderArrow(frame_bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 0.70f);
if (g.LogEnabled)
LogRenderedText(&text_pos, ">");
RenderText(text_pos, label, label_end, false);
}
if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
TreePushRawID(id);
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0));
return is_open;
}
void ImGui::TreePush(const char* str_id)
{
ImGuiWindow* window = GetCurrentWindow();
Indent();
window->DC.TreeDepth++;
PushID(str_id ? str_id : "#TreePush");
}
void ImGui::TreePush(const void* ptr_id)
{
ImGuiWindow* window = GetCurrentWindow();
Indent();
window->DC.TreeDepth++;
PushID(ptr_id ? ptr_id : (const void*)"#TreePush");
}
void ImGui::TreePushRawID(ImGuiID id)
{
ImGuiWindow* window = GetCurrentWindow();
Indent();
window->DC.TreeDepth++;
window->IDStack.push_back(id);
}
void ImGui::TreePop()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
Unindent();
window->DC.TreeDepth--;
if (g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet())
if (g.NavIdIsAlive && (window->DC.TreeDepthMayJumpToParentOnPop & (1 << window->DC.TreeDepth)))
{
SetNavID(window->IDStack.back(), g.NavLayer);
NavMoveRequestCancel();
}
window->DC.TreeDepthMayJumpToParentOnPop &= (1 << window->DC.TreeDepth) - 1;
IM_ASSERT(window->IDStack.Size > 1); // There should always be 1 element in the IDStack (pushed during window creation). If this triggers you called TreePop/PopID too much.
PopID();
}
void ImGui::TreeAdvanceToLabelPos()
{
ImGuiContext& g = *GImGui;
g.CurrentWindow->DC.CursorPos.x += GetTreeNodeToLabelSpacing();
}
// Horizontal distance preceding label when using TreeNode() or Bullet()
float ImGui::GetTreeNodeToLabelSpacing()
{
ImGuiContext& g = *GImGui;
return g.FontSize + (g.Style.FramePadding.x * 2.0f);
}
void ImGui::SetNextTreeNodeOpen(bool is_open, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
if (g.CurrentWindow->SkipItems)
return;
g.NextTreeNodeOpenVal = is_open;
g.NextTreeNodeOpenCond = cond ? cond : ImGuiCond_Always;
}
// CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags_NoTreePushOnOpen flag).
// This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags_CollapsingHeader). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode().
bool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
return TreeNodeBehavior(window->GetID(label), flags | ImGuiTreeNodeFlags_CollapsingHeader, label);
}
bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
if (p_open && !*p_open)
return false;
ImGuiID id = window->GetID(label);
bool is_open = TreeNodeBehavior(id, flags | ImGuiTreeNodeFlags_CollapsingHeader | (p_open ? ImGuiTreeNodeFlags_AllowItemOverlap : 0), label);
if (p_open)
{
// Create a small overlapping close button // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc.
ImGuiContext& g = *GImGui;
ImGuiItemHoveredDataBackup last_item_backup;
float button_radius = g.FontSize * 0.5f;
ImVec2 button_center = ImVec2(ImMin(window->DC.LastItemRect.Max.x, window->ClipRect.Max.x) - g.Style.FramePadding.x - button_radius, window->DC.LastItemRect.GetCenter().y);
if (CloseButton(window->GetID((void*)((intptr_t)id+1)), button_center, button_radius))
*p_open = false;
last_item_backup.Restore();
}
return is_open;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: Selectable
//-------------------------------------------------------------------------
// - Selectable()
//-------------------------------------------------------------------------
// Tip: pass a non-visible label (e.g. "##dummy") then you can use the space to draw other text or image.
// But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID or use ##unique_id.
bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet) // FIXME-OPT: Avoid if vertically clipped.
PopClipRect();
ImGuiID id = window->GetID(label);
ImVec2 label_size = CalcTextSize(label, NULL, true);
ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y);
ImVec2 pos = window->DC.CursorPos;
pos.y += window->DC.CurrentLineTextBaseOffset;
ImRect bb_inner(pos, pos + size);
ItemSize(bb_inner);
// Fill horizontal space.
ImVec2 window_padding = window->WindowPadding;
float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? GetWindowContentRegionMax().x : GetContentRegionMax().x;
float w_draw = ImMax(label_size.x, window->Pos.x + max_x - window_padding.x - pos.x);
ImVec2 size_draw((size_arg.x != 0 && !(flags & ImGuiSelectableFlags_DrawFillAvailWidth)) ? size_arg.x : w_draw, size_arg.y != 0.0f ? size_arg.y : size.y);
ImRect bb(pos, pos + size_draw);
if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_DrawFillAvailWidth))
bb.Max.x += window_padding.x;
// Selectables are tightly packed together, we extend the box to cover spacing between selectable.
float spacing_L = (float)(int)(style.ItemSpacing.x * 0.5f);
float spacing_U = (float)(int)(style.ItemSpacing.y * 0.5f);
float spacing_R = style.ItemSpacing.x - spacing_L;
float spacing_D = style.ItemSpacing.y - spacing_U;
bb.Min.x -= spacing_L;
bb.Min.y -= spacing_U;
bb.Max.x += spacing_R;
bb.Max.y += spacing_D;
bool item_add;
if (flags & ImGuiSelectableFlags_Disabled)
{
ImGuiItemFlags backup_item_flags = window->DC.ItemFlags;
window->DC.ItemFlags |= ImGuiItemFlags_Disabled | ImGuiItemFlags_NoNavDefaultFocus;
item_add = ItemAdd(bb, id);
window->DC.ItemFlags = backup_item_flags;
}
else
{
item_add = ItemAdd(bb, id);
}
if (!item_add)
{
if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet)
PushColumnClipRect();
return false;
}
// We use NoHoldingActiveID on menus so user can click and _hold_ on a menu then drag to browse child entries
ImGuiButtonFlags button_flags = 0;
if (flags & ImGuiSelectableFlags_NoHoldingActiveID) button_flags |= ImGuiButtonFlags_NoHoldingActiveID;
if (flags & ImGuiSelectableFlags_PressedOnClick) button_flags |= ImGuiButtonFlags_PressedOnClick;
if (flags & ImGuiSelectableFlags_PressedOnRelease) button_flags |= ImGuiButtonFlags_PressedOnRelease;
if (flags & ImGuiSelectableFlags_Disabled) button_flags |= ImGuiButtonFlags_Disabled;
if (flags & ImGuiSelectableFlags_AllowDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick;
if (flags & ImGuiSelectableFlags_Disabled)
selected = false;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags);
// Hovering selectable with mouse updates NavId accordingly so navigation can be resumed with gamepad/keyboard (this doesn't happen on most widgets)
if (pressed || hovered)
if (!g.NavDisableMouseHover && g.NavWindow == window && g.NavLayer == window->DC.NavLayerCurrent)
{
g.NavDisableHighlight = true;
SetNavID(id, window->DC.NavLayerCurrent);
}
if (pressed)
MarkItemEdited(id);
// Render
if (hovered || selected)
{
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
RenderFrame(bb.Min, bb.Max, col, false, 0.0f);
RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding);
}
if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet)
{
PushColumnClipRect();
bb.Max.x -= (GetContentRegionMax().x - max_x);
}
if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
RenderTextClipped(bb_inner.Min, bb_inner.Max, label, NULL, &label_size, style.SelectableTextAlign, &bb);
if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor();
// Automatically close popups
if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_DontClosePopups) && !(window->DC.ItemFlags & ImGuiItemFlags_SelectableDontClosePopup))
CloseCurrentPopup();
return pressed;
}
bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)
{
if (Selectable(label, *p_selected, flags, size_arg))
{
*p_selected = !*p_selected;
return true;
}
return false;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: ListBox
//-------------------------------------------------------------------------
// - ListBox()
// - ListBoxHeader()
// - ListBoxFooter()
//-------------------------------------------------------------------------
// FIXME: In principle this function should be called BeginListBox(). We should rename it after re-evaluating if we want to keep the same signature.
// Helper to calculate the size of a listbox and display a label on the right.
// Tip: To have a list filling the entire window width, PushItemWidth(-1) and pass an non-visible label e.g. "##empty"
bool ImGui::ListBoxHeader(const char* label, const ImVec2& size_arg)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
const ImGuiStyle& style = GetStyle();
const ImGuiID id = GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
// Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar.
ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y);
ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y));
ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);
ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
window->DC.LastItemRect = bb; // Forward storage for ListBoxFooter.. dodgy.
if (!IsRectVisible(bb.Min, bb.Max))
{
ItemSize(bb.GetSize(), style.FramePadding.y);
ItemAdd(bb, 0, &frame_bb);
return false;
}
BeginGroup();
if (label_size.x > 0)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
BeginChildFrame(id, frame_bb.GetSize());
return true;
}
// FIXME: In principle this function should be called EndListBox(). We should rename it after re-evaluating if we want to keep the same signature.
bool ImGui::ListBoxHeader(const char* label, int items_count, int height_in_items)
{
// Size default to hold ~7.25 items.
// We add +25% worth of item height to allow the user to see at a glance if there are more items up/down, without looking at the scrollbar.
// We don't add this extra bit if items_count <= height_in_items. It is slightly dodgy, because it means a dynamic list of items will make the widget resize occasionally when it crosses that size.
// I am expecting that someone will come and complain about this behavior in a remote future, then we can advise on a better solution.
if (height_in_items < 0)
height_in_items = ImMin(items_count, 7);
const ImGuiStyle& style = GetStyle();
float height_in_items_f = (height_in_items < items_count) ? (height_in_items + 0.25f) : (height_in_items + 0.00f);
// We include ItemSpacing.y so that a list sized for the exact number of items doesn't make a scrollbar appears. We could also enforce that by passing a flag to BeginChild().
ImVec2 size;
size.x = 0.0f;
size.y = GetTextLineHeightWithSpacing() * height_in_items_f + style.FramePadding.y * 2.0f;
return ListBoxHeader(label, size);
}
// FIXME: In principle this function should be called EndListBox(). We should rename it after re-evaluating if we want to keep the same signature.
void ImGui::ListBoxFooter()
{
ImGuiWindow* parent_window = GetCurrentWindow()->ParentWindow;
const ImRect bb = parent_window->DC.LastItemRect;
const ImGuiStyle& style = GetStyle();
EndChildFrame();
// Redeclare item size so that it includes the label (we have stored the full size in LastItemRect)
// We call SameLine() to restore DC.CurrentLine* data
SameLine();
parent_window->DC.CursorPos = bb.Min;
ItemSize(bb, style.FramePadding.y);
EndGroup();
}
bool ImGui::ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_items)
{
const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items);
return value_changed;
}
bool ImGui::ListBox(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items)
{
if (!ListBoxHeader(label, items_count, height_in_items))
return false;
// Assume all items have even height (= 1 line of text). If you need items of different or variable sizes you can create a custom version of ListBox() in your code without using the clipper.
ImGuiContext& g = *GImGui;
bool value_changed = false;
ImGuiListClipper clipper(items_count, GetTextLineHeightWithSpacing()); // We know exactly our line height here so we pass it as a minor optimization, but generally you don't need to.
while (clipper.Step())
for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
{
const bool item_selected = (i == *current_item);
const char* item_text;
if (!items_getter(data, i, &item_text))
item_text = "*Unknown item*";
PushID(i);
if (Selectable(item_text, item_selected))
{
*current_item = i;
value_changed = true;
}
if (item_selected)
SetItemDefaultFocus();
PopID();
}
ListBoxFooter();
if (value_changed)
MarkItemEdited(g.CurrentWindow->DC.LastItemId);
return value_changed;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: PlotLines, PlotHistogram
//-------------------------------------------------------------------------
// - PlotEx() [Internal]
// - PlotLines()
// - PlotHistogram()
//-------------------------------------------------------------------------
void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 frame_size)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
if (frame_size.x == 0.0f)
frame_size.x = CalcItemWidth();
if (frame_size.y == 0.0f)
frame_size.y = label_size.y + (style.FramePadding.y * 2);
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);
const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding);
const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0));
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, 0, &frame_bb))
return;
const bool hovered = ItemHoverable(frame_bb, id);
// Determine scale from values if not specified
if (scale_min == FLT_MAX || scale_max == FLT_MAX)
{
float v_min = FLT_MAX;
float v_max = -FLT_MAX;
for (int i = 0; i < values_count; i++)
{
const float v = values_getter(data, i);
v_min = ImMin(v_min, v);
v_max = ImMax(v_max, v);
}
if (scale_min == FLT_MAX)
scale_min = v_min;
if (scale_max == FLT_MAX)
scale_max = v_max;
}
RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
const int values_count_min = (plot_type == ImGuiPlotType_Lines) ? 2 : 1;
if (values_count >= values_count_min)
{
int res_w = ImMin((int)frame_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);
int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);
// Tooltip on hover
int v_hovered = -1;
if (hovered && inner_bb.Contains(g.IO.MousePos))
{
const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f);
const int v_idx = (int)(t * item_count);
IM_ASSERT(v_idx >= 0 && v_idx < values_count);
const float v0 = values_getter(data, (v_idx + values_offset) % values_count);
const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count);
if (plot_type == ImGuiPlotType_Lines)
SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx+1, v1);
else if (plot_type == ImGuiPlotType_Histogram)
SetTooltip("%d: %8.4g", v_idx, v0);
v_hovered = v_idx;
}
const float t_step = 1.0f / (float)res_w;
const float inv_scale = (scale_min == scale_max) ? 0.0f : (1.0f / (scale_max - scale_min));
float v0 = values_getter(data, (0 + values_offset) % values_count);
float t0 = 0.0f;
ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) * inv_scale) ); // Point in the normalized space of our target rectangle
float histogram_zero_line_t = (scale_min * scale_max < 0.0f) ? (-scale_min * inv_scale) : (scale_min < 0.0f ? 0.0f : 1.0f); // Where does the zero line stands
const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram);
const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered);
for (int n = 0; n < res_w; n++)
{
const float t1 = t0 + t_step;
const int v1_idx = (int)(t0 * item_count + 0.5f);
IM_ASSERT(v1_idx >= 0 && v1_idx < values_count);
const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count);
const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) * inv_scale) );
// NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU.
ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0);
ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, histogram_zero_line_t));
if (plot_type == ImGuiPlotType_Lines)
{
window->DrawList->AddLine(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base);
}
else if (plot_type == ImGuiPlotType_Histogram)
{
if (pos1.x >= pos0.x + 2.0f)
pos1.x -= 1.0f;
window->DrawList->AddRectFilled(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base);
}
t0 = t1;
tp0 = tp1;
}
}
// Text overlay
if (overlay_text)
RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, NULL, NULL, ImVec2(0.5f,0.0f));
if (label_size.x > 0.0f)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label);
}
struct ImGuiPlotArrayGetterData
{
const float* Values;
int Stride;
ImGuiPlotArrayGetterData(const float* values, int stride) { Values = values; Stride = stride; }
};
static float Plot_ArrayGetter(void* data, int idx)
{
ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data;
const float v = *(const float*)(const void*)((const unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride);
return v;
}
void ImGui::PlotLines(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride)
{
ImGuiPlotArrayGetterData data(values, stride);
PlotEx(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
}
void ImGui::PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size)
{
PlotEx(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
}
void ImGui::PlotHistogram(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride)
{
ImGuiPlotArrayGetterData data(values, stride);
PlotEx(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
}
void ImGui::PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size)
{
PlotEx(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: Value helpers
// Those is not very useful, legacy API.
//-------------------------------------------------------------------------
// - Value()
//-------------------------------------------------------------------------
void ImGui::Value(const char* prefix, bool b)
{
Text("%s: %s", prefix, (b ? "true" : "false"));
}
void ImGui::Value(const char* prefix, int v)
{
Text("%s: %d", prefix, v);
}
void ImGui::Value(const char* prefix, unsigned int v)
{
Text("%s: %d", prefix, v);
}
void ImGui::Value(const char* prefix, float v, const char* float_format)
{
if (float_format)
{
char fmt[64];
ImFormatString(fmt, IM_ARRAYSIZE(fmt), "%%s: %s", float_format);
Text(fmt, prefix, v);
}
else
{
Text("%s: %.3f", prefix, v);
}
}
//-------------------------------------------------------------------------
// [SECTION] MenuItem, BeginMenu, EndMenu, etc.
//-------------------------------------------------------------------------
// - ImGuiMenuColumns [Internal]
// - BeginMainMenuBar()
// - EndMainMenuBar()
// - BeginMenuBar()
// - EndMenuBar()
// - BeginMenu()
// - EndMenu()
// - MenuItem()
//-------------------------------------------------------------------------
// Helpers for internal use
ImGuiMenuColumns::ImGuiMenuColumns()
{
Spacing = Width = NextWidth = 0.0f;
memset(Pos, 0, sizeof(Pos));
memset(NextWidths, 0, sizeof(NextWidths));
}
void ImGuiMenuColumns::Update(int count, float spacing, bool clear)
{
IM_ASSERT(count == IM_ARRAYSIZE(Pos));
Width = NextWidth = 0.0f;
Spacing = spacing;
if (clear)
memset(NextWidths, 0, sizeof(NextWidths));
for (int i = 0; i < IM_ARRAYSIZE(Pos); i++)
{
if (i > 0 && NextWidths[i] > 0.0f)
Width += Spacing;
Pos[i] = (float)(int)Width;
Width += NextWidths[i];
NextWidths[i] = 0.0f;
}
}
float ImGuiMenuColumns::DeclColumns(float w0, float w1, float w2) // not using va_arg because they promote float to double
{
NextWidth = 0.0f;
NextWidths[0] = ImMax(NextWidths[0], w0);
NextWidths[1] = ImMax(NextWidths[1], w1);
NextWidths[2] = ImMax(NextWidths[2], w2);
for (int i = 0; i < IM_ARRAYSIZE(Pos); i++)
NextWidth += NextWidths[i] + ((i > 0 && NextWidths[i] > 0.0f) ? Spacing : 0.0f);
return ImMax(Width, NextWidth);
}
float ImGuiMenuColumns::CalcExtraSpace(float avail_w)
{
return ImMax(0.0f, avail_w - Width);
}
// For the main menu bar, which cannot be moved, we honor g.Style.DisplaySafeAreaPadding to ensure text can be visible on a TV set.
bool ImGui::BeginMainMenuBar()
{
ImGuiContext& g = *GImGui;
g.NextWindowData.MenuBarOffsetMinVal = ImVec2(g.Style.DisplaySafeAreaPadding.x, ImMax(g.Style.DisplaySafeAreaPadding.y - g.Style.FramePadding.y, 0.0f));
SetNextWindowPos(ImVec2(0.0f, 0.0f));
SetNextWindowSize(ImVec2(g.IO.DisplaySize.x, g.NextWindowData.MenuBarOffsetMinVal.y + g.FontBaseSize + g.Style.FramePadding.y));
PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0,0));
ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_MenuBar;
bool is_open = Begin("##MainMenuBar", NULL, window_flags) && BeginMenuBar();
PopStyleVar(2);
g.NextWindowData.MenuBarOffsetMinVal = ImVec2(0.0f, 0.0f);
if (!is_open)
{
End();
return false;
}
return true; //-V1020
}
void ImGui::EndMainMenuBar()
{
EndMenuBar();
// When the user has left the menu layer (typically: closed menus through activation of an item), we restore focus to the previous window
ImGuiContext& g = *GImGui;
if (g.CurrentWindow == g.NavWindow && g.NavLayer == 0)
FocusPreviousWindowIgnoringOne(g.NavWindow);
End();
}
bool ImGui::BeginMenuBar()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
if (!(window->Flags & ImGuiWindowFlags_MenuBar))
return false;
IM_ASSERT(!window->DC.MenuBarAppending);
BeginGroup(); // Backup position on layer 0
PushID("##menubar");
// We don't clip with current window clipping rectangle as it is already set to the area below. However we clip with window full rect.
// We remove 1 worth of rounding to Max.x to that text in long menus and small windows don't tend to display over the lower-right rounded area, which looks particularly glitchy.
ImRect bar_rect = window->MenuBarRect();
ImRect clip_rect(ImFloor(bar_rect.Min.x + 0.5f), ImFloor(bar_rect.Min.y + window->WindowBorderSize + 0.5f), ImFloor(ImMax(bar_rect.Min.x, bar_rect.Max.x - window->WindowRounding) + 0.5f), ImFloor(bar_rect.Max.y + 0.5f));
clip_rect.ClipWith(window->OuterRectClipped);
PushClipRect(clip_rect.Min, clip_rect.Max, false);
window->DC.CursorPos = ImVec2(bar_rect.Min.x + window->DC.MenuBarOffset.x, bar_rect.Min.y + window->DC.MenuBarOffset.y);
window->DC.LayoutType = ImGuiLayoutType_Horizontal;
window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu);
window->DC.MenuBarAppending = true;
AlignTextToFramePadding();
return true;
}
void ImGui::EndMenuBar()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
// Nav: When a move request within one of our child menu failed, capture the request to navigate among our siblings.
if (NavMoveRequestButNoResultYet() && (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right) && (g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
{
ImGuiWindow* nav_earliest_child = g.NavWindow;
while (nav_earliest_child->ParentWindow && (nav_earliest_child->ParentWindow->Flags & ImGuiWindowFlags_ChildMenu))
nav_earliest_child = nav_earliest_child->ParentWindow;
if (nav_earliest_child->ParentWindow == window && nav_earliest_child->DC.ParentLayoutType == ImGuiLayoutType_Horizontal && g.NavMoveRequestForward == ImGuiNavForward_None)
{
// To do so we claim focus back, restore NavId and then process the movement request for yet another frame.
// This involve a one-frame delay which isn't very problematic in this situation. We could remove it by scoring in advance for multiple window (probably not worth the hassle/cost)
IM_ASSERT(window->DC.NavLayerActiveMaskNext & 0x02); // Sanity check
FocusWindow(window);
SetNavIDWithRectRel(window->NavLastIds[1], 1, window->NavRectRel[1]);
g.NavLayer = ImGuiNavLayer_Menu;
g.NavDisableHighlight = true; // Hide highlight for the current frame so we don't see the intermediary selection.
g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued;
NavMoveRequestCancel();
}
}
IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar);
IM_ASSERT(window->DC.MenuBarAppending);
PopClipRect();
PopID();
window->DC.MenuBarOffset.x = window->DC.CursorPos.x - window->MenuBarRect().Min.x; // Save horizontal position so next append can reuse it. This is kinda equivalent to a per-layer CursorPos.
window->DC.GroupStack.back().AdvanceCursor = false;
EndGroup(); // Restore position on layer 0
window->DC.LayoutType = ImGuiLayoutType_Vertical;
window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
window->DC.MenuBarAppending = false;
}
bool ImGui::BeginMenu(const char* label, bool enabled)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
ImVec2 label_size = CalcTextSize(label, NULL, true);
bool pressed;
bool menu_is_open = IsPopupOpen(id);
bool menuset_is_open = !(window->Flags & ImGuiWindowFlags_Popup) && (g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].OpenParentId == window->IDStack.back());
ImGuiWindow* backed_nav_window = g.NavWindow;
if (menuset_is_open)
g.NavWindow = window; // Odd hack to allow hovering across menus of a same menu-set (otherwise we wouldn't be able to hover parent)
// The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu,
// However the final position is going to be different! It is choosen by FindBestWindowPosForPopup().
// e.g. Menus tend to overlap each other horizontally to amplify relative Z-ordering.
ImVec2 popup_pos, pos = window->DC.CursorPos;
if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
{
// Menu inside an horizontal menu bar
// Selectable extend their highlight by half ItemSpacing in each direction.
// For ChildMenu, the popup position will be overwritten by the call to FindBestWindowPosForPopup() in Begin()
popup_pos = ImVec2(pos.x - 1.0f - (float)(int)(style.ItemSpacing.x * 0.5f), pos.y - style.FramePadding.y + window->MenuBarHeight());
window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f);
PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f);
float w = label_size.x;
pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_NoHoldingActiveID | ImGuiSelectableFlags_PressedOnClick | ImGuiSelectableFlags_DontClosePopups | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f));
PopStyleVar();
window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar().
}
else
{
// Menu inside a menu
popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y);
float w = window->MenuColumns.DeclColumns(label_size.x, 0.0f, (float)(int)(g.FontSize * 1.20f)); // Feedback to next frame
float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w);
pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_NoHoldingActiveID | ImGuiSelectableFlags_PressedOnClick | ImGuiSelectableFlags_DontClosePopups | ImGuiSelectableFlags_DrawFillAvailWidth | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f));
if (!enabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
RenderArrow(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.30f, 0.0f), ImGuiDir_Right);
if (!enabled) PopStyleColor();
}
const bool hovered = enabled && ItemHoverable(window->DC.LastItemRect, id);
if (menuset_is_open)
g.NavWindow = backed_nav_window;
bool want_open = false, want_close = false;
if (window->DC.LayoutType == ImGuiLayoutType_Vertical) // (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu))
{
// Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive.
bool moving_within_opened_triangle = false;
if (g.HoveredWindow == window && g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].ParentWindow == window && !(window->Flags & ImGuiWindowFlags_MenuBar))
{
if (ImGuiWindow* next_window = g.OpenPopupStack[g.BeginPopupStack.Size].Window)
{
// FIXME-DPI: Values should be derived from a master "scale" factor.
ImRect next_window_rect = next_window->Rect();
ImVec2 ta = g.IO.MousePos - g.IO.MouseDelta;
ImVec2 tb = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetTL() : next_window_rect.GetTR();
ImVec2 tc = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetBL() : next_window_rect.GetBR();
float extra = ImClamp(ImFabs(ta.x - tb.x) * 0.30f, 5.0f, 30.0f); // add a bit of extra slack.
ta.x += (window->Pos.x < next_window->Pos.x) ? -0.5f : +0.5f; // to avoid numerical issues
tb.y = ta.y + ImMax((tb.y - extra) - ta.y, -100.0f); // triangle is maximum 200 high to limit the slope and the bias toward large sub-menus // FIXME: Multiply by fb_scale?
tc.y = ta.y + ImMin((tc.y + extra) - ta.y, +100.0f);
moving_within_opened_triangle = ImTriangleContainsPoint(ta, tb, tc, g.IO.MousePos);
//window->DrawList->PushClipRectFullScreen(); window->DrawList->AddTriangleFilled(ta, tb, tc, moving_within_opened_triangle ? IM_COL32(0,128,0,128) : IM_COL32(128,0,0,128)); window->DrawList->PopClipRect(); // Debug
}
}
want_close = (menu_is_open && !hovered && g.HoveredWindow == window && g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrame != id && !moving_within_opened_triangle);
want_open = (!menu_is_open && hovered && !moving_within_opened_triangle) || (!menu_is_open && hovered && pressed);
if (g.NavActivateId == id)
{
want_close = menu_is_open;
want_open = !menu_is_open;
}
if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Right) // Nav-Right to open
{
want_open = true;
NavMoveRequestCancel();
}
}
else
{
// Menu bar
if (menu_is_open && pressed && menuset_is_open) // Click an open menu again to close it
{
want_close = true;
want_open = menu_is_open = false;
}
else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // First click to open, then hover to open others
{
want_open = true;
}
else if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Down) // Nav-Down to open
{
want_open = true;
NavMoveRequestCancel();
}
}
if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu("options", has_object)) { ..use object.. }'
want_close = true;
if (want_close && IsPopupOpen(id))
ClosePopupToLevel(g.BeginPopupStack.Size, true);
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags | ImGuiItemStatusFlags_Openable | (menu_is_open ? ImGuiItemStatusFlags_Opened : 0));
if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.BeginPopupStack.Size)
{
// Don't recycle same menu level in the same frame, first close the other menu and yield for a frame.
OpenPopup(label);
return false;
}
menu_is_open |= want_open;
if (want_open)
OpenPopup(label);
if (menu_is_open)
{
// Sub-menus are ChildWindow so that mouse can be hovering across them (otherwise top-most popup menu would steal focus and not allow hovering on parent menu)
SetNextWindowPos(popup_pos, ImGuiCond_Always);
ImGuiWindowFlags flags = ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus;
if (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu))
flags |= ImGuiWindowFlags_ChildWindow;
menu_is_open = BeginPopupEx(id, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
}
return menu_is_open;
}
void ImGui::EndMenu()
{
// Nav: When a left move request _within our child menu_ failed, close ourselves (the _parent_ menu).
// A menu doesn't close itself because EndMenuBar() wants the catch the last Left<>Right inputs.
// However, it means that with the current code, a BeginMenu() from outside another menu or a menu-bar won't be closable with the Left direction.
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavWindow && g.NavWindow->ParentWindow == window && g.NavMoveDir == ImGuiDir_Left && NavMoveRequestButNoResultYet() && window->DC.LayoutType == ImGuiLayoutType_Vertical)
{
ClosePopupToLevel(g.BeginPopupStack.Size, true);
NavMoveRequestCancel();
}
EndPopup();
}
bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
ImVec2 pos = window->DC.CursorPos;
ImVec2 label_size = CalcTextSize(label, NULL, true);
ImGuiSelectableFlags flags = ImGuiSelectableFlags_PressedOnRelease | (enabled ? 0 : ImGuiSelectableFlags_Disabled);
bool pressed;
if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
{
// Mimic the exact layout spacing of BeginMenu() to allow MenuItem() inside a menu bar, which is a little misleading but may be useful
// Note that in this situation we render neither the shortcut neither the selected tick mark
float w = label_size.x;
window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f);
PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f);
pressed = Selectable(label, false, flags, ImVec2(w, 0.0f));
PopStyleVar();
window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar().
}
else
{
ImVec2 shortcut_size = shortcut ? CalcTextSize(shortcut, NULL) : ImVec2(0.0f, 0.0f);
float w = window->MenuColumns.DeclColumns(label_size.x, shortcut_size.x, (float)(int)(g.FontSize * 1.20f)); // Feedback for next frame
float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w);
pressed = Selectable(label, false, flags | ImGuiSelectableFlags_DrawFillAvailWidth, ImVec2(w, 0.0f));
if (shortcut_size.x > 0.0f)
{
PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
RenderText(pos + ImVec2(window->MenuColumns.Pos[1] + extra_w, 0.0f), shortcut, NULL, false);
PopStyleColor();
}
if (selected)
RenderCheckMark(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.40f, g.FontSize * 0.134f * 0.5f), GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled), g.FontSize * 0.866f);
}
IMGUI_TEST_ENGINE_ITEM_INFO(window->DC.LastItemId, label, window->DC.ItemFlags | ImGuiItemStatusFlags_Checkable | (selected ? ImGuiItemStatusFlags_Checked : 0));
return pressed;
}
bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled)
{
if (MenuItem(label, shortcut, p_selected ? *p_selected : false, enabled))
{
if (p_selected)
*p_selected = !*p_selected;
return true;
}
return false;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: BeginTabBar, EndTabBar, etc.
//-------------------------------------------------------------------------
// [BETA API] API may evolve! This code has been extracted out of the Docking branch,
// and some of the construct which are not used in Master may be left here to facilitate merging.
//-------------------------------------------------------------------------
// - BeginTabBar()
// - BeginTabBarEx() [Internal]
// - EndTabBar()
// - TabBarLayout() [Internal]
// - TabBarCalcTabID() [Internal]
// - TabBarCalcMaxTabWidth() [Internal]
// - TabBarFindTabById() [Internal]
// - TabBarRemoveTab() [Internal]
// - TabBarCloseTab() [Internal]
// - TabBarScrollClamp()v
// - TabBarScrollToTab() [Internal]
// - TabBarQueueChangeTabOrder() [Internal]
// - TabBarScrollingButtons() [Internal]
// - TabBarTabListPopupButton() [Internal]
//-------------------------------------------------------------------------
namespace ImGui
{
static void TabBarLayout(ImGuiTabBar* tab_bar);
static ImU32 TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label);
static float TabBarCalcMaxTabWidth();
static float TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling);
static void TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab);
static ImGuiTabItem* TabBarScrollingButtons(ImGuiTabBar* tab_bar);
static ImGuiTabItem* TabBarTabListPopupButton(ImGuiTabBar* tab_bar);
}
ImGuiTabBar::ImGuiTabBar()
{
ID = 0;
SelectedTabId = NextSelectedTabId = VisibleTabId = 0;
CurrFrameVisible = PrevFrameVisible = -1;
ContentsHeight = 0.0f;
OffsetMax = OffsetNextTab = 0.0f;
ScrollingAnim = ScrollingTarget = ScrollingTargetDistToVisibility = ScrollingSpeed = 0.0f;
Flags = ImGuiTabBarFlags_None;
ReorderRequestTabId = 0;
ReorderRequestDir = 0;
WantLayout = VisibleTabWasSubmitted = false;
LastTabItemIdx = -1;
}
static int IMGUI_CDECL TabItemComparerByVisibleOffset(const void* lhs, const void* rhs)
{
const ImGuiTabItem* a = (const ImGuiTabItem*)lhs;
const ImGuiTabItem* b = (const ImGuiTabItem*)rhs;
return (int)(a->Offset - b->Offset);
}
static int IMGUI_CDECL TabBarSortItemComparer(const void* lhs, const void* rhs)
{
const ImGuiTabBarSortItem* a = (const ImGuiTabBarSortItem*)lhs;
const ImGuiTabBarSortItem* b = (const ImGuiTabBarSortItem*)rhs;
if (int d = (int)(b->Width - a->Width))
return d;
return (b->Index - a->Index);
}
static ImGuiTabBar* GetTabBarFromTabBarRef(const ImGuiTabBarRef& ref)
{
ImGuiContext& g = *GImGui;
return ref.Ptr ? ref.Ptr : g.TabBars.GetByIndex(ref.IndexInMainPool);
}
static ImGuiTabBarRef GetTabBarRefFromTabBar(ImGuiTabBar* tab_bar)
{
ImGuiContext& g = *GImGui;
if (g.TabBars.Contains(tab_bar))
return ImGuiTabBarRef(g.TabBars.GetIndex(tab_bar));
return ImGuiTabBarRef(tab_bar);
}
bool ImGui::BeginTabBar(const char* str_id, ImGuiTabBarFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return false;
ImGuiID id = window->GetID(str_id);
ImGuiTabBar* tab_bar = g.TabBars.GetOrAddByKey(id);
ImRect tab_bar_bb = ImRect(window->DC.CursorPos.x, window->DC.CursorPos.y, window->InnerClipRect.Max.x, window->DC.CursorPos.y + g.FontSize + g.Style.FramePadding.y * 2);
tab_bar->ID = id;
return BeginTabBarEx(tab_bar, tab_bar_bb, flags | ImGuiTabBarFlags_IsFocused);
}
bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImGuiTabBarFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return false;
if ((flags & ImGuiTabBarFlags_DockNode) == 0)
window->IDStack.push_back(tab_bar->ID);
// Add to stack
g.CurrentTabBarStack.push_back(GetTabBarRefFromTabBar(tab_bar));
g.CurrentTabBar = tab_bar;
if (tab_bar->CurrFrameVisible == g.FrameCount)
{
//IMGUI_DEBUG_LOG("BeginTabBarEx already called this frame\n", g.FrameCount);
IM_ASSERT(0);
return true;
}
// When toggling back from ordered to manually-reorderable, shuffle tabs to enforce the last visible order.
// Otherwise, the most recently inserted tabs would move at the end of visible list which can be a little too confusing or magic for the user.
if ((flags & ImGuiTabBarFlags_Reorderable) && !(tab_bar->Flags & ImGuiTabBarFlags_Reorderable) && tab_bar->Tabs.Size > 1 && tab_bar->PrevFrameVisible != -1)
ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerByVisibleOffset);
// Flags
if ((flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0)
flags |= ImGuiTabBarFlags_FittingPolicyDefault_;
tab_bar->Flags = flags;
tab_bar->BarRect = tab_bar_bb;
tab_bar->WantLayout = true; // Layout will be done on the first call to ItemTab()
tab_bar->PrevFrameVisible = tab_bar->CurrFrameVisible;
tab_bar->CurrFrameVisible = g.FrameCount;
tab_bar->FramePadding = g.Style.FramePadding;
// Layout
ItemSize(ImVec2(tab_bar->OffsetMax, tab_bar->BarRect.GetHeight()));
window->DC.CursorPos.x = tab_bar->BarRect.Min.x;
// Draw separator
const ImU32 col = GetColorU32((flags & ImGuiTabBarFlags_IsFocused) ? ImGuiCol_TabActive : ImGuiCol_Tab);
const float y = tab_bar->BarRect.Max.y - 1.0f;
{
const float separator_min_x = tab_bar->BarRect.Min.x - window->WindowPadding.x;
const float separator_max_x = tab_bar->BarRect.Max.x + window->WindowPadding.x;
window->DrawList->AddLine(ImVec2(separator_min_x, y), ImVec2(separator_max_x, y), col, 1.0f);
}
return true;
}
void ImGui::EndTabBar()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return;
ImGuiTabBar* tab_bar = g.CurrentTabBar;
if (tab_bar == NULL)
{
IM_ASSERT(tab_bar != NULL && "Mismatched BeginTabBar()/EndTabBar()!");
return; // FIXME-ERRORHANDLING
}
if (tab_bar->WantLayout)
TabBarLayout(tab_bar);
// Restore the last visible height if no tab is visible, this reduce vertical flicker/movement when a tabs gets removed without calling SetTabItemClosed().
const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount);
if (tab_bar->VisibleTabWasSubmitted || tab_bar->VisibleTabId == 0 || tab_bar_appearing)
tab_bar->ContentsHeight = ImMax(window->DC.CursorPos.y - tab_bar->BarRect.Max.y, 0.0f);
else
window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->ContentsHeight;
if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0)
PopID();
g.CurrentTabBarStack.pop_back();
g.CurrentTabBar = g.CurrentTabBarStack.empty() ? NULL : GetTabBarFromTabBarRef(g.CurrentTabBarStack.back());
}
// This is called only once a frame before by the first call to ItemTab()
// The reason we're not calling it in BeginTabBar() is to leave a chance to the user to call the SetTabItemClosed() functions.
static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar)
{
ImGuiContext& g = *GImGui;
tab_bar->WantLayout = false;
// Garbage collect
int tab_dst_n = 0;
for (int tab_src_n = 0; tab_src_n < tab_bar->Tabs.Size; tab_src_n++)
{
ImGuiTabItem* tab = &tab_bar->Tabs[tab_src_n];
if (tab->LastFrameVisible < tab_bar->PrevFrameVisible)
{
if (tab->ID == tab_bar->SelectedTabId)
tab_bar->SelectedTabId = 0;
continue;
}
if (tab_dst_n != tab_src_n)
tab_bar->Tabs[tab_dst_n] = tab_bar->Tabs[tab_src_n];
tab_dst_n++;
}
if (tab_bar->Tabs.Size != tab_dst_n)
tab_bar->Tabs.resize(tab_dst_n);
// Setup next selected tab
ImGuiID scroll_track_selected_tab_id = 0;
if (tab_bar->NextSelectedTabId)
{
tab_bar->SelectedTabId = tab_bar->NextSelectedTabId;
tab_bar->NextSelectedTabId = 0;
scroll_track_selected_tab_id = tab_bar->SelectedTabId;
}
// Process order change request (we could probably process it when requested but it's just saner to do it in a single spot).
if (tab_bar->ReorderRequestTabId != 0)
{
if (ImGuiTabItem* tab1 = TabBarFindTabByID(tab_bar, tab_bar->ReorderRequestTabId))
{
//IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_Reorderable); // <- this may happen when using debug tools
int tab2_order = tab_bar->GetTabOrder(tab1) + tab_bar->ReorderRequestDir;
if (tab2_order >= 0 && tab2_order < tab_bar->Tabs.Size)
{
ImGuiTabItem* tab2 = &tab_bar->Tabs[tab2_order];
ImGuiTabItem item_tmp = *tab1;
*tab1 = *tab2;
*tab2 = item_tmp;
if (tab2->ID == tab_bar->SelectedTabId)
scroll_track_selected_tab_id = tab2->ID;
tab1 = tab2 = NULL;
}
if (tab_bar->Flags & ImGuiTabBarFlags_SaveSettings)
MarkIniSettingsDirty();
}
tab_bar->ReorderRequestTabId = 0;
}
// Tab List Popup (will alter tab_bar->BarRect and therefore the available width!)
const bool tab_list_popup_button = (tab_bar->Flags & ImGuiTabBarFlags_TabListPopupButton) != 0;
if (tab_list_popup_button)
if (ImGuiTabItem* tab_to_select = TabBarTabListPopupButton(tab_bar)) // NB: Will alter BarRect.Max.x!
scroll_track_selected_tab_id = tab_bar->SelectedTabId = tab_to_select->ID;
ImVector<ImGuiTabBarSortItem>& width_sort_buffer = g.TabSortByWidthBuffer;
width_sort_buffer.resize(tab_bar->Tabs.Size);
// Compute ideal widths
float width_total_contents = 0.0f;
ImGuiTabItem* most_recently_selected_tab = NULL;
bool found_selected_tab_id = false;
for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
{
ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
IM_ASSERT(tab->LastFrameVisible >= tab_bar->PrevFrameVisible);
if (most_recently_selected_tab == NULL || most_recently_selected_tab->LastFrameSelected < tab->LastFrameSelected)
most_recently_selected_tab = tab;
if (tab->ID == tab_bar->SelectedTabId)
found_selected_tab_id = true;
// Refresh tab width immediately, otherwise changes of style e.g. style.FramePadding.x would noticeably lag in the tab bar.
// Additionally, when using TabBarAddTab() to manipulate tab bar order we occasionally insert new tabs that don't have a width yet,
// and we cannot wait for the next BeginTabItem() call. We cannot compute this width within TabBarAddTab() because font size depends on the active window.
const char* tab_name = tab_bar->GetTabName(tab);
tab->WidthContents = TabItemCalcSize(tab_name, (tab->Flags & ImGuiTabItemFlags_NoCloseButton) ? false : true).x;
width_total_contents += (tab_n > 0 ? g.Style.ItemInnerSpacing.x : 0.0f) + tab->WidthContents;
// Store data so we can build an array sorted by width if we need to shrink tabs down
width_sort_buffer[tab_n].Index = tab_n;
width_sort_buffer[tab_n].Width = tab->WidthContents;
}
// Compute width
const float width_avail = tab_bar->BarRect.GetWidth();
float width_excess = (width_avail < width_total_contents) ? (width_total_contents - width_avail) : 0.0f;
if (width_excess > 0.0f && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyResizeDown))
{
// If we don't have enough room, resize down the largest tabs first
if (tab_bar->Tabs.Size > 1)
ImQsort(width_sort_buffer.Data, (size_t)width_sort_buffer.Size, sizeof(ImGuiTabBarSortItem), TabBarSortItemComparer);
int tab_count_same_width = 1;
while (width_excess > 0.0f && tab_count_same_width < tab_bar->Tabs.Size)
{
while (tab_count_same_width < tab_bar->Tabs.Size && width_sort_buffer[0].Width == width_sort_buffer[tab_count_same_width].Width)
tab_count_same_width++;
float width_to_remove_per_tab_max = (tab_count_same_width < tab_bar->Tabs.Size) ? (width_sort_buffer[0].Width - width_sort_buffer[tab_count_same_width].Width) : (width_sort_buffer[0].Width - 1.0f);
float width_to_remove_per_tab = ImMin(width_excess / tab_count_same_width, width_to_remove_per_tab_max);
for (int tab_n = 0; tab_n < tab_count_same_width; tab_n++)
width_sort_buffer[tab_n].Width -= width_to_remove_per_tab;
width_excess -= width_to_remove_per_tab * tab_count_same_width;
}
for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
tab_bar->Tabs[width_sort_buffer[tab_n].Index].Width = (float)(int)width_sort_buffer[tab_n].Width;
}
else
{
const float tab_max_width = TabBarCalcMaxTabWidth();
for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
{
ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
tab->Width = ImMin(tab->WidthContents, tab_max_width);
}
}
// Layout all active tabs
float offset_x = 0.0f;
for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
{
ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
tab->Offset = offset_x;
if (scroll_track_selected_tab_id == 0 && g.NavJustMovedToId == tab->ID)
scroll_track_selected_tab_id = tab->ID;
offset_x += tab->Width + g.Style.ItemInnerSpacing.x;
}
tab_bar->OffsetMax = ImMax(offset_x - g.Style.ItemInnerSpacing.x, 0.0f);
tab_bar->OffsetNextTab = 0.0f;
// Horizontal scrolling buttons
const bool scrolling_buttons = (tab_bar->OffsetMax > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll);
if (scrolling_buttons)
if (ImGuiTabItem* tab_to_select = TabBarScrollingButtons(tab_bar)) // NB: Will alter BarRect.Max.x!
scroll_track_selected_tab_id = tab_bar->SelectedTabId = tab_to_select->ID;
// If we have lost the selected tab, select the next most recently active one
if (found_selected_tab_id == false)
tab_bar->SelectedTabId = 0;
if (tab_bar->SelectedTabId == 0 && tab_bar->NextSelectedTabId == 0 && most_recently_selected_tab != NULL)
scroll_track_selected_tab_id = tab_bar->SelectedTabId = most_recently_selected_tab->ID;
// Lock in visible tab
tab_bar->VisibleTabId = tab_bar->SelectedTabId;
tab_bar->VisibleTabWasSubmitted = false;
// Update scrolling
if (scroll_track_selected_tab_id)
if (ImGuiTabItem* scroll_track_selected_tab = TabBarFindTabByID(tab_bar, scroll_track_selected_tab_id))
TabBarScrollToTab(tab_bar, scroll_track_selected_tab);
tab_bar->ScrollingAnim = TabBarScrollClamp(tab_bar, tab_bar->ScrollingAnim);
tab_bar->ScrollingTarget = TabBarScrollClamp(tab_bar, tab_bar->ScrollingTarget);
if (tab_bar->ScrollingAnim != tab_bar->ScrollingTarget)
{
// Scrolling speed adjust itself so we can always reach our target in 1/3 seconds.
// Teleport if we are aiming far off the visible line
tab_bar->ScrollingSpeed = ImMax(tab_bar->ScrollingSpeed, 70.0f * g.FontSize);
tab_bar->ScrollingSpeed = ImMax(tab_bar->ScrollingSpeed, ImFabs(tab_bar->ScrollingTarget - tab_bar->ScrollingAnim) / 0.3f);
const bool teleport = (tab_bar->PrevFrameVisible + 1 < g.FrameCount) || (tab_bar->ScrollingTargetDistToVisibility > 10.0f * g.FontSize);
tab_bar->ScrollingAnim = teleport ? tab_bar->ScrollingTarget : ImLinearSweep(tab_bar->ScrollingAnim, tab_bar->ScrollingTarget, g.IO.DeltaTime * tab_bar->ScrollingSpeed);
}
else
{
tab_bar->ScrollingSpeed = 0.0f;
}
// Clear name buffers
if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0)
tab_bar->TabsNames.Buf.resize(0);
}
// Dockables uses Name/ID in the global namespace. Non-dockable items use the ID stack.
static ImU32 ImGui::TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label)
{
if (tab_bar->Flags & ImGuiTabBarFlags_DockNode)
{
ImGuiID id = ImHashStr(label, 0);
KeepAliveID(id);
return id;
}
else
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->GetID(label);
}
}
static float ImGui::TabBarCalcMaxTabWidth()
{
ImGuiContext& g = *GImGui;
return g.FontSize * 20.0f;
}
ImGuiTabItem* ImGui::TabBarFindTabByID(ImGuiTabBar* tab_bar, ImGuiID tab_id)
{
if (tab_id != 0)
for (int n = 0; n < tab_bar->Tabs.Size; n++)
if (tab_bar->Tabs[n].ID == tab_id)
return &tab_bar->Tabs[n];
return NULL;
}
// The *TabId fields be already set by the docking system _before_ the actual TabItem was created, so we clear them regardless.
void ImGui::TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id)
{
if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id))
tab_bar->Tabs.erase(tab);
if (tab_bar->VisibleTabId == tab_id) { tab_bar->VisibleTabId = 0; }
if (tab_bar->SelectedTabId == tab_id) { tab_bar->SelectedTabId = 0; }
if (tab_bar->NextSelectedTabId == tab_id) { tab_bar->NextSelectedTabId = 0; }
}
// Called on manual closure attempt
void ImGui::TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab)
{
if ((tab_bar->VisibleTabId == tab->ID) && !(tab->Flags & ImGuiTabItemFlags_UnsavedDocument))
{
// This will remove a frame of lag for selecting another tab on closure.
// However we don't run it in the case where the 'Unsaved' flag is set, so user gets a chance to fully undo the closure
tab->LastFrameVisible = -1;
tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = 0;
}
else if ((tab_bar->VisibleTabId != tab->ID) && (tab->Flags & ImGuiTabItemFlags_UnsavedDocument))
{
// Actually select before expecting closure
tab_bar->NextSelectedTabId = tab->ID;
}
}
static float ImGui::TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling)
{
scrolling = ImMin(scrolling, tab_bar->OffsetMax - tab_bar->BarRect.GetWidth());
return ImMax(scrolling, 0.0f);
}
static void ImGui::TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab)
{
ImGuiContext& g = *GImGui;
float margin = g.FontSize * 1.0f; // When to scroll to make Tab N+1 visible always make a bit of N visible to suggest more scrolling area (since we don't have a scrollbar)
int order = tab_bar->GetTabOrder(tab);
float tab_x1 = tab->Offset + (order > 0 ? -margin : 0.0f);
float tab_x2 = tab->Offset + tab->Width + (order + 1 < tab_bar->Tabs.Size ? margin : 1.0f);
tab_bar->ScrollingTargetDistToVisibility = 0.0f;
if (tab_bar->ScrollingTarget > tab_x1)
{
tab_bar->ScrollingTargetDistToVisibility = ImMax(tab_bar->ScrollingAnim - tab_x2, 0.0f);
tab_bar->ScrollingTarget = tab_x1;
}
else if (tab_bar->ScrollingTarget < tab_x2 - tab_bar->BarRect.GetWidth())
{
tab_bar->ScrollingTargetDistToVisibility = ImMax((tab_x1 - tab_bar->BarRect.GetWidth()) - tab_bar->ScrollingAnim, 0.0f);
tab_bar->ScrollingTarget = tab_x2 - tab_bar->BarRect.GetWidth();
}
}
void ImGui::TabBarQueueChangeTabOrder(ImGuiTabBar* tab_bar, const ImGuiTabItem* tab, int dir)
{
IM_ASSERT(dir == -1 || dir == +1);
IM_ASSERT(tab_bar->ReorderRequestTabId == 0);
tab_bar->ReorderRequestTabId = tab->ID;
tab_bar->ReorderRequestDir = dir;
}
static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImVec2 arrow_button_size(g.FontSize - 2.0f, g.FontSize + g.Style.FramePadding.y * 2.0f);
const float scrolling_buttons_width = arrow_button_size.x * 2.0f;
const ImVec2 backup_cursor_pos = window->DC.CursorPos;
//window->DrawList->AddRect(ImVec2(tab_bar->BarRect.Max.x - scrolling_buttons_width, tab_bar->BarRect.Min.y), ImVec2(tab_bar->BarRect.Max.x, tab_bar->BarRect.Max.y), IM_COL32(255,0,0,255));
const ImRect avail_bar_rect = tab_bar->BarRect;
bool want_clip_rect = !avail_bar_rect.Contains(ImRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(scrolling_buttons_width, 0.0f)));
if (want_clip_rect)
PushClipRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max + ImVec2(g.Style.ItemInnerSpacing.x, 0.0f), true);
ImGuiTabItem* tab_to_select = NULL;
int select_dir = 0;
ImVec4 arrow_col = g.Style.Colors[ImGuiCol_Text];
arrow_col.w *= 0.5f;
PushStyleColor(ImGuiCol_Text, arrow_col);
PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));
const float backup_repeat_delay = g.IO.KeyRepeatDelay;
const float backup_repeat_rate = g.IO.KeyRepeatRate;
g.IO.KeyRepeatDelay = 0.250f;
g.IO.KeyRepeatRate = 0.200f;
window->DC.CursorPos = ImVec2(tab_bar->BarRect.Max.x - scrolling_buttons_width, tab_bar->BarRect.Min.y);
if (ArrowButtonEx("##<", ImGuiDir_Left, arrow_button_size, ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_Repeat))
select_dir = -1;
window->DC.CursorPos = ImVec2(tab_bar->BarRect.Max.x - scrolling_buttons_width + arrow_button_size.x, tab_bar->BarRect.Min.y);
if (ArrowButtonEx("##>", ImGuiDir_Right, arrow_button_size, ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_Repeat))
select_dir = +1;
PopStyleColor(2);
g.IO.KeyRepeatRate = backup_repeat_rate;
g.IO.KeyRepeatDelay = backup_repeat_delay;
if (want_clip_rect)
PopClipRect();
if (select_dir != 0)
if (ImGuiTabItem* tab_item = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
{
int selected_order = tab_bar->GetTabOrder(tab_item);
int target_order = selected_order + select_dir;
tab_to_select = &tab_bar->Tabs[(target_order >= 0 && target_order < tab_bar->Tabs.Size) ? target_order : selected_order]; // If we are at the end of the list, still scroll to make our tab visible
}
window->DC.CursorPos = backup_cursor_pos;
tab_bar->BarRect.Max.x -= scrolling_buttons_width + 1.0f;
return tab_to_select;
}
static ImGuiTabItem* ImGui::TabBarTabListPopupButton(ImGuiTabBar* tab_bar)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
// We use g.Style.FramePadding.y to match the square ArrowButton size
const float tab_list_popup_button_width = g.FontSize + g.Style.FramePadding.y;
const ImVec2 backup_cursor_pos = window->DC.CursorPos;
window->DC.CursorPos = ImVec2(tab_bar->BarRect.Min.x - g.Style.FramePadding.y, tab_bar->BarRect.Min.y);
tab_bar->BarRect.Min.x += tab_list_popup_button_width;
ImVec4 arrow_col = g.Style.Colors[ImGuiCol_Text];
arrow_col.w *= 0.5f;
PushStyleColor(ImGuiCol_Text, arrow_col);
PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));
bool open = BeginCombo("##v", NULL, ImGuiComboFlags_NoPreview);
PopStyleColor(2);
ImGuiTabItem* tab_to_select = NULL;
if (open)
{
for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
{
ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
const char* tab_name = tab_bar->GetTabName(tab);
if (Selectable(tab_name, tab_bar->SelectedTabId == tab->ID))
tab_to_select = tab;
}
EndCombo();
}
window->DC.CursorPos = backup_cursor_pos;
return tab_to_select;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: BeginTabItem, EndTabItem, etc.
//-------------------------------------------------------------------------
// [BETA API] API may evolve! This code has been extracted out of the Docking branch,
// and some of the construct which are not used in Master may be left here to facilitate merging.
//-------------------------------------------------------------------------
// - BeginTabItem()
// - EndTabItem()
// - TabItemEx() [Internal]
// - SetTabItemClosed()
// - TabItemCalcSize() [Internal]
// - TabItemBackground() [Internal]
// - TabItemLabelAndCloseButton() [Internal]
//-------------------------------------------------------------------------
bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags flags)
{
ImGuiContext& g = *GImGui;
if (g.CurrentWindow->SkipItems)
return false;
ImGuiTabBar* tab_bar = g.CurrentTabBar;
if (tab_bar == NULL)
{
IM_ASSERT(tab_bar && "Needs to be called between BeginTabBar() and EndTabBar()!");
return false; // FIXME-ERRORHANDLING
}
bool ret = TabItemEx(tab_bar, label, p_open, flags);
if (ret && !(flags & ImGuiTabItemFlags_NoPushId))
{
ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx];
g.CurrentWindow->IDStack.push_back(tab->ID); // We already hashed 'label' so push into the ID stack directly instead of doing another hash through PushID(label)
}
return ret;
}
void ImGui::EndTabItem()<|fim▁hole|> return;
ImGuiTabBar* tab_bar = g.CurrentTabBar;
if (tab_bar == NULL)
{
IM_ASSERT(tab_bar != NULL && "Needs to be called between BeginTabBar() and EndTabBar()!");
return;
}
IM_ASSERT(tab_bar->LastTabItemIdx >= 0);
ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx];
if (!(tab->Flags & ImGuiTabItemFlags_NoPushId))
g.CurrentWindow->IDStack.pop_back();
}
bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags)
{
// Layout whole tab bar if not already done
if (tab_bar->WantLayout)
TabBarLayout(tab_bar);
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return false;
const ImGuiStyle& style = g.Style;
const ImGuiID id = TabBarCalcTabID(tab_bar, label);
// If the user called us with *p_open == false, we early out and don't render. We make a dummy call to ItemAdd() so that attempts to use a contextual popup menu with an implicit ID won't use an older ID.
if (p_open && !*p_open)
{
PushItemFlag(ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus, true);
ItemAdd(ImRect(), id);
PopItemFlag();
return false;
}
// Calculate tab contents size
ImVec2 size = TabItemCalcSize(label, p_open != NULL);
// Acquire tab data
ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, id);
bool tab_is_new = false;
if (tab == NULL)
{
tab_bar->Tabs.push_back(ImGuiTabItem());
tab = &tab_bar->Tabs.back();
tab->ID = id;
tab->Width = size.x;
tab_is_new = true;
}
tab_bar->LastTabItemIdx = (short)tab_bar->Tabs.index_from_ptr(tab);
tab->WidthContents = size.x;
if (p_open == NULL)
flags |= ImGuiTabItemFlags_NoCloseButton;
const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount);
const bool tab_bar_focused = (tab_bar->Flags & ImGuiTabBarFlags_IsFocused) != 0;
const bool tab_appearing = (tab->LastFrameVisible + 1 < g.FrameCount);
tab->LastFrameVisible = g.FrameCount;
tab->Flags = flags;
// Append name with zero-terminator
tab->NameOffset = tab_bar->TabsNames.size();
tab_bar->TabsNames.append(label, label + strlen(label) + 1);
// If we are not reorderable, always reset offset based on submission order.
// (We already handled layout and sizing using the previous known order, but sizing is not affected by order!)
if (!tab_appearing && !(tab_bar->Flags & ImGuiTabBarFlags_Reorderable))
{
tab->Offset = tab_bar->OffsetNextTab;
tab_bar->OffsetNextTab += tab->Width + g.Style.ItemInnerSpacing.x;
}
// Update selected tab
if (tab_appearing && (tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs) && tab_bar->NextSelectedTabId == 0)
if (!tab_bar_appearing || tab_bar->SelectedTabId == 0)
tab_bar->NextSelectedTabId = id; // New tabs gets activated
if ((flags & ImGuiTabItemFlags_SetSelected) && (tab_bar->SelectedTabId != id)) // SetSelected can only be passed on explicit tab bar
tab_bar->NextSelectedTabId = id;
// Lock visibility
bool tab_contents_visible = (tab_bar->VisibleTabId == id);
if (tab_contents_visible)
tab_bar->VisibleTabWasSubmitted = true;
// On the very first frame of a tab bar we let first tab contents be visible to minimize appearing glitches
if (!tab_contents_visible && tab_bar->SelectedTabId == 0 && tab_bar_appearing)
if (tab_bar->Tabs.Size == 1 && !(tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs))
tab_contents_visible = true;
if (tab_appearing && !(tab_bar_appearing && !tab_is_new))
{
PushItemFlag(ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus, true);
ItemAdd(ImRect(), id);
PopItemFlag();
return tab_contents_visible;
}
if (tab_bar->SelectedTabId == id)
tab->LastFrameSelected = g.FrameCount;
// Backup current layout position
const ImVec2 backup_main_cursor_pos = window->DC.CursorPos;
// Layout
size.x = tab->Width;
window->DC.CursorPos = tab_bar->BarRect.Min + ImVec2((float)(int)tab->Offset - tab_bar->ScrollingAnim, 0.0f);
ImVec2 pos = window->DC.CursorPos;
ImRect bb(pos, pos + size);
// We don't have CPU clipping primitives to clip the CloseButton (until it becomes a texture), so need to add an extra draw call (temporary in the case of vertical animation)
bool want_clip_rect = (bb.Min.x < tab_bar->BarRect.Min.x) || (bb.Max.x >= tab_bar->BarRect.Max.x);
if (want_clip_rect)
PushClipRect(ImVec2(ImMax(bb.Min.x, tab_bar->BarRect.Min.x), bb.Min.y - 1), ImVec2(tab_bar->BarRect.Max.x, bb.Max.y), true);
ItemSize(bb, style.FramePadding.y);
if (!ItemAdd(bb, id))
{
if (want_clip_rect)
PopClipRect();
window->DC.CursorPos = backup_main_cursor_pos;
return tab_contents_visible;
}
// Click to Select a tab
ImGuiButtonFlags button_flags = (ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_AllowItemOverlap);
if (g.DragDropActive)
button_flags |= ImGuiButtonFlags_PressedOnDragDropHold;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags);
if (pressed)
tab_bar->NextSelectedTabId = id;
hovered |= (g.HoveredId == id);
// Allow the close button to overlap unless we are dragging (in which case we don't want any overlapping tabs to be hovered)
if (!held)
SetItemAllowOverlap();
// Drag and drop: re-order tabs
if (held && !tab_appearing && IsMouseDragging(0))
{
if (!g.DragDropActive && (tab_bar->Flags & ImGuiTabBarFlags_Reorderable))
{
// While moving a tab it will jump on the other side of the mouse, so we also test for MouseDelta.x
if (g.IO.MouseDelta.x < 0.0f && g.IO.MousePos.x < bb.Min.x)
{
if (tab_bar->Flags & ImGuiTabBarFlags_Reorderable)
TabBarQueueChangeTabOrder(tab_bar, tab, -1);
}
else if (g.IO.MouseDelta.x > 0.0f && g.IO.MousePos.x > bb.Max.x)
{
if (tab_bar->Flags & ImGuiTabBarFlags_Reorderable)
TabBarQueueChangeTabOrder(tab_bar, tab, +1);
}
}
}
#if 0
if (hovered && g.HoveredIdNotActiveTimer > 0.50f && bb.GetWidth() < tab->WidthContents)
{
// Enlarge tab display when hovering
bb.Max.x = bb.Min.x + (float)(int)ImLerp(bb.GetWidth(), tab->WidthContents, ImSaturate((g.HoveredIdNotActiveTimer - 0.40f) * 6.0f));
display_draw_list = GetForegroundDrawList(window);
TabItemBackground(display_draw_list, bb, flags, GetColorU32(ImGuiCol_TitleBgActive));
}
#endif
// Render tab shape
ImDrawList* display_draw_list = window->DrawList;
const ImU32 tab_col = GetColorU32((held || hovered) ? ImGuiCol_TabHovered : tab_contents_visible ? (tab_bar_focused ? ImGuiCol_TabActive : ImGuiCol_TabUnfocusedActive) : (tab_bar_focused ? ImGuiCol_Tab : ImGuiCol_TabUnfocused));
TabItemBackground(display_draw_list, bb, flags, tab_col);
RenderNavHighlight(bb, id);
// Select with right mouse button. This is so the common idiom for context menu automatically highlight the current widget.
const bool hovered_unblocked = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup);
if (hovered_unblocked && (IsMouseClicked(1) || IsMouseReleased(1)))
tab_bar->NextSelectedTabId = id;
if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
// Render tab label, process close button
const ImGuiID close_button_id = p_open ? window->GetID((void*)((intptr_t)id + 1)) : 0;
bool just_closed = TabItemLabelAndCloseButton(display_draw_list, bb, flags, tab_bar->FramePadding, label, id, close_button_id);
if (just_closed && p_open != NULL)
{
*p_open = false;
TabBarCloseTab(tab_bar, tab);
}
// Restore main window position so user can draw there
if (want_clip_rect)
PopClipRect();
window->DC.CursorPos = backup_main_cursor_pos;
// Tooltip (FIXME: Won't work over the close button because ItemOverlap systems messes up with HoveredIdTimer)
// We test IsItemHovered() to discard e.g. when another item is active or drag and drop over the tab bar (which g.HoveredId ignores)
if (g.HoveredId == id && !held && g.HoveredIdNotActiveTimer > 0.50f && IsItemHovered())
if (!(tab_bar->Flags & ImGuiTabBarFlags_NoTooltip))
SetTooltip("%.*s", (int)(FindRenderedTextEnd(label) - label), label);
return tab_contents_visible;
}
// [Public] This is call is 100% optional but it allows to remove some one-frame glitches when a tab has been unexpectedly removed.
// To use it to need to call the function SetTabItemClosed() after BeginTabBar() and before any call to BeginTabItem()
void ImGui::SetTabItemClosed(const char* label)
{
ImGuiContext& g = *GImGui;
bool is_within_manual_tab_bar = g.CurrentTabBar && !(g.CurrentTabBar->Flags & ImGuiTabBarFlags_DockNode);
if (is_within_manual_tab_bar)
{
ImGuiTabBar* tab_bar = g.CurrentTabBar;
IM_ASSERT(tab_bar->WantLayout); // Needs to be called AFTER BeginTabBar() and BEFORE the first call to BeginTabItem()
ImGuiID tab_id = TabBarCalcTabID(tab_bar, label);
TabBarRemoveTab(tab_bar, tab_id);
}
}
ImVec2 ImGui::TabItemCalcSize(const char* label, bool has_close_button)
{
ImGuiContext& g = *GImGui;
ImVec2 label_size = CalcTextSize(label, NULL, true);
ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x, label_size.y + g.Style.FramePadding.y * 2.0f);
if (has_close_button)
size.x += g.Style.FramePadding.x + (g.Style.ItemInnerSpacing.x + g.FontSize); // We use Y intentionally to fit the close button circle.
else
size.x += g.Style.FramePadding.x + 1.0f;
return ImVec2(ImMin(size.x, TabBarCalcMaxTabWidth()), size.y);
}
void ImGui::TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col)
{
// While rendering tabs, we trim 1 pixel off the top of our bounding box so they can fit within a regular frame height while looking "detached" from it.
ImGuiContext& g = *GImGui;
const float width = bb.GetWidth();
IM_UNUSED(flags);
IM_ASSERT(width > 0.0f);
const float rounding = ImMax(0.0f, ImMin(g.Style.TabRounding, width * 0.5f - 1.0f));
const float y1 = bb.Min.y + 1.0f;
const float y2 = bb.Max.y - 1.0f;
draw_list->PathLineTo(ImVec2(bb.Min.x, y2));
draw_list->PathArcToFast(ImVec2(bb.Min.x + rounding, y1 + rounding), rounding, 6, 9);
draw_list->PathArcToFast(ImVec2(bb.Max.x - rounding, y1 + rounding), rounding, 9, 12);
draw_list->PathLineTo(ImVec2(bb.Max.x, y2));
draw_list->PathFillConvex(col);
if (g.Style.TabBorderSize > 0.0f)
{
draw_list->PathLineTo(ImVec2(bb.Min.x + 0.5f, y2));
draw_list->PathArcToFast(ImVec2(bb.Min.x + rounding + 0.5f, y1 + rounding + 0.5f), rounding, 6, 9);
draw_list->PathArcToFast(ImVec2(bb.Max.x - rounding - 0.5f, y1 + rounding + 0.5f), rounding, 9, 12);
draw_list->PathLineTo(ImVec2(bb.Max.x - 0.5f, y2));
draw_list->PathStroke(GetColorU32(ImGuiCol_Border), false, g.Style.TabBorderSize);
}
}
// Render text label (with custom clipping) + Unsaved Document marker + Close Button logic
// We tend to lock style.FramePadding for a given tab-bar, hence the 'frame_padding' parameter.
bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id)
{
ImGuiContext& g = *GImGui;
ImVec2 label_size = CalcTextSize(label, NULL, true);
if (bb.GetWidth() <= 1.0f)
return false;
// Render text label (with clipping + alpha gradient) + unsaved marker
const char* TAB_UNSAVED_MARKER = "*";
ImRect text_pixel_clip_bb(bb.Min.x + frame_padding.x, bb.Min.y + frame_padding.y, bb.Max.x - frame_padding.x, bb.Max.y);
if (flags & ImGuiTabItemFlags_UnsavedDocument)
{
text_pixel_clip_bb.Max.x -= CalcTextSize(TAB_UNSAVED_MARKER, NULL, false).x;
ImVec2 unsaved_marker_pos(ImMin(bb.Min.x + frame_padding.x + label_size.x + 2, text_pixel_clip_bb.Max.x), bb.Min.y + frame_padding.y + (float)(int)(-g.FontSize * 0.25f));
RenderTextClippedEx(draw_list, unsaved_marker_pos, bb.Max - frame_padding, TAB_UNSAVED_MARKER, NULL, NULL);
}
ImRect text_ellipsis_clip_bb = text_pixel_clip_bb;
// Close Button
// We are relying on a subtle and confusing distinction between 'hovered' and 'g.HoveredId' which happens because we are using ImGuiButtonFlags_AllowOverlapMode + SetItemAllowOverlap()
// 'hovered' will be true when hovering the Tab but NOT when hovering the close button
// 'g.HoveredId==id' will be true when hovering the Tab including when hovering the close button
// 'g.ActiveId==close_button_id' will be true when we are holding on the close button, in which case both hovered booleans are false
bool close_button_pressed = false;
bool close_button_visible = false;
if (close_button_id != 0)
if (g.HoveredId == tab_id || g.HoveredId == close_button_id || g.ActiveId == close_button_id)
close_button_visible = true;
if (close_button_visible)
{
ImGuiItemHoveredDataBackup last_item_backup;
const float close_button_sz = g.FontSize * 0.5f;
if (CloseButton(close_button_id, ImVec2(bb.Max.x - frame_padding.x - close_button_sz, bb.Min.y + frame_padding.y + close_button_sz), close_button_sz))
close_button_pressed = true;
last_item_backup.Restore();
// Close with middle mouse button
if (!(flags & ImGuiTabItemFlags_NoCloseWithMiddleMouseButton) && IsMouseClicked(2))
close_button_pressed = true;
text_pixel_clip_bb.Max.x -= close_button_sz * 2.0f;
}
// Label with ellipsis
// FIXME: This should be extracted into a helper but the use of text_pixel_clip_bb and !close_button_visible makes it tricky to abstract at the moment
const char* label_display_end = FindRenderedTextEnd(label);
if (label_size.x > text_ellipsis_clip_bb.GetWidth())
{
const int ellipsis_dot_count = 3;
const float ellipsis_width = (1.0f + 1.0f) * ellipsis_dot_count - 1.0f;
const char* label_end = NULL;
float label_size_clipped_x = g.Font->CalcTextSizeA(g.FontSize, text_ellipsis_clip_bb.GetWidth() - ellipsis_width + 1.0f, 0.0f, label, label_display_end, &label_end).x;
if (label_end == label && label_end < label_display_end) // Always display at least 1 character if there's no room for character + ellipsis
{
label_end = label + ImTextCountUtf8BytesFromChar(label, label_display_end);
label_size_clipped_x = g.Font->CalcTextSizeA(g.FontSize, FLT_MAX, 0.0f, label, label_end).x;
}
while (label_end > label && ImCharIsBlankA(label_end[-1])) // Trim trailing space
{
label_end--;
label_size_clipped_x -= g.Font->CalcTextSizeA(g.FontSize, FLT_MAX, 0.0f, label_end, label_end + 1).x; // Ascii blanks are always 1 byte
}
RenderTextClippedEx(draw_list, text_pixel_clip_bb.Min, text_pixel_clip_bb.Max, label, label_end, &label_size, ImVec2(0.0f, 0.0f));
const float ellipsis_x = text_pixel_clip_bb.Min.x + label_size_clipped_x + 1.0f;
if (!close_button_visible && ellipsis_x + ellipsis_width <= bb.Max.x)
RenderPixelEllipsis(draw_list, ImVec2(ellipsis_x, text_pixel_clip_bb.Min.y), ellipsis_dot_count, GetColorU32(ImGuiCol_Text));
}
else
{
RenderTextClippedEx(draw_list, text_pixel_clip_bb.Min, text_pixel_clip_bb.Max, label, label_display_end, &label_size, ImVec2(0.0f, 0.0f));
}
return close_button_pressed;
}<|fim▁end|>
|
{
ImGuiContext& g = *GImGui;
if (g.CurrentWindow->SkipItems)
|
<|file_name|>curves.rs<|end_file_name|><|fim▁begin|>use std::fmt;
use std::default::Default;
use std::num::FromStrRadix;
use num::{BigUint, Zero, One};
use num::bigint::ToBigUint;
use fields::{Field, FieldElem, P192, R192, P256, R256, P521, R521};
#[allow(non_snake_case)]
// Weierstrass curve with large characteristic field.
pub trait Curve<F: Field, G: Field>: Clone + Default { // To do: Implement binary curves.
fn AN3(&self) -> bool; // If A = -3
fn unserialize(&self, s: &Vec<uint>) -> AffinePoint<Self, F, G>;
// Standard curve paraemters:
fn A(&self) -> FieldElem<F>;
fn B(&self) -> FieldElem<F>;
fn G(&self) -> AffinePoint<Self, F, G>;
}
#[deriving(Clone)]
pub struct AffinePoint<C: Curve<F, G>, F: Field, G: Field> {
pub x: FieldElem<F>,
pub y: FieldElem<F>,
}
#[deriving(Clone)]
pub struct JacobianPoint<C: Curve<F, G>, F: Field, G: Field> {
pub x: FieldElem<F>,
pub y: FieldElem<F>,
pub z: FieldElem<F>,
}
// Constant-time exponentiation/scalar-multiplication.
fn pow<T: Zero + Add<T, T> + Clone>(this: &T, cand_exp: &BigUint, order: &BigUint) -> T {
// Montgomery Ladder.
let zer: BigUint = Zero::zero();
let one: BigUint = One::one();
let mut exp: BigUint = *cand_exp + *order;
if exp.bits() == order.bits() { exp = exp + *order; }
let m = exp.bits() + 1;
let mut r0: T = Zero::zero();
let mut r1: T = (*this).clone();
for i in range(0u, m) {
if ((one << (m - i - 1)) & exp) == zer {
r1 = r0 + r1;
r0 = r0 + r0;
} else {
r0 = r0 + r1;
r1 = r1 + r1;
}
}
r0
}
impl<C: Curve<F, G>, F: Field, G: Field> PartialEq for AffinePoint<C, F, G> {
fn eq(&self, other: &AffinePoint<C, F, G>) -> bool {
self.x == other.x && self.y == other.y
}
}
impl<C: Curve<F, G>, F: Field, G: Field> PartialEq for JacobianPoint<C, F, G> {
fn eq(&self, other: &JacobianPoint<C, F, G>) -> bool {
self.to_affine() == other.to_affine()
}
}
// Notes: Ordering is omitted because elliptic curve groups have no norm.
impl<C: Curve<F, G>, F: Field, G: Field> Add<AffinePoint<C, F, G>, AffinePoint<C, F, G>> for AffinePoint<C, F, G> {
fn add(&self, other: &AffinePoint<C, F, G>) -> AffinePoint<C, F, G> {
if (*self).is_zero() {
(*other).clone()
} else if (*other).is_zero() {
(*self).clone()
} else if self.x != other.x {
let m = (other.y - self.y) / (other.x - self.x);
let x3 = (m * m) - self.x - other.x;
let y3 = m * (self.x - x3) - self.y;
AffinePoint { x: x3, y: y3 }
} else if self.y != other.y || self.y.limbs.bits() == 0 {
Zero::zero()
} else {
let c: C = Default::default();
let two: FieldElem<F> = FieldElem {
limbs: 2i.to_biguint().unwrap(),
};
let three: FieldElem<F> = FieldElem {
limbs: 3i.to_biguint().unwrap(),
};
let m = ((three * (self.x * self.x)) + c.A()) / (two * self.y);
let x3 = (m * m) - (self.x * two);
let y3 = m * (self.x - x3) - self.y;
AffinePoint { x: x3, y: y3 }
}
}
}
impl<C: Curve<F, G>, F: Field, G: Field> Add<JacobianPoint<C, F, G>, JacobianPoint<C, F, G>> for JacobianPoint<C, F, G> {
fn add(&self, other: &JacobianPoint<C, F, G>) -> JacobianPoint<C, F, G> {
if (*self).is_zero() {
(*other).clone()
} else if (*other).is_zero() {
(*self).clone()
} else if self.x == other.x && self.y == other.y && self.z == other.z {
self.double()
} else {
let z12 = self.z * self.z;
let z13 = z12 * self.z;
let z22 = other.z * other.z;
let z23 = z22 * other.z;
let u1 = self.x * z22;
let u2 = other.x * z12;
let s1 = self.y * z23;
let s2 = other.y * z13;
if u1 == u2 {
if s1 != s2 { // P1 = +/- P2
Zero::zero()
} else {
self.double()
}
} else {
let h = u2 - u1;
let h2 = h * h;
let h3 = h2 * h;
let r = s2 - s1;
let u1h2 = u1 * h2;
let x3 = (r * r) - h3 - u1h2 - u1h2;
let y3 = r * (u1h2 - x3) - (s1 * h3);
let z3 = h * self.z * other.z;
JacobianPoint { x: x3, y: y3, z: z3 }
}
}
}
}
fn add_jacobian_to_affine<C: Curve<F, G>, F: Field, G: Field>(this: &JacobianPoint<C, F, G>, other: &AffinePoint<C, F, G>) -> JacobianPoint<C, F, G> {
if this.is_zero() {
(*other).to_jacobian()
} else if other.is_zero() {
(*this).clone()
} else {
let z2 = this.z * this.z;
let c = (other.x * z2) - this.x;
if c.is_zero() {
if (other.y * z2 * this.z) == this.y { // Same point
this.double()
} else { // Negatives
Zero::zero()
}
} else {
let d = (other.y * z2 * this.z) - this.y;
let c2 = c * c;
let x3 = (d * d) - (c2 * c) - (c2 * (this.x + this.x));
let y3 = d * ((this.x * c2) - x3) - (this.y * c2 * c);
let z3 = this.z * c;
JacobianPoint { x: x3, y: y3, z: z3 }
}
}
}
impl<C: Curve<F, G>, F: Field, G: Field> Add<JacobianPoint<C, F, G>, JacobianPoint<C, F, G>> for AffinePoint<C, F, G> {
fn add(&self, other: &JacobianPoint<C, F, G>) -> JacobianPoint<C, F, G> { add_jacobian_to_affine(other, self) }
}
impl<C: Curve<F, G>, F: Field, G: Field> Add<AffinePoint<C, F, G>, JacobianPoint<C, F, G>> for JacobianPoint<C, F, G> {
fn add(&self, other: &AffinePoint<C, F, G>) -> JacobianPoint<C, F, G> { add_jacobian_to_affine(self, other) }
}
impl<C: Curve<F, G>, F: Field, G: Field> Sub<AffinePoint<C, F, G>, AffinePoint<C, F, G>> for AffinePoint<C, F, G> {
fn sub(&self, other: &AffinePoint<C, F, G>) -> AffinePoint<C, F, G> { *self + (-*other) }
}
impl<C: Curve<F, G>, F: Field, G: Field> Sub<JacobianPoint<C, F, G>, JacobianPoint<C, F, G>> for AffinePoint<C, F, G> {
fn sub(&self, other: &JacobianPoint<C, F, G>) -> JacobianPoint<C, F, G> { *self + (-*other) }
}
impl<C: Curve<F, G>, F: Field, G: Field> Sub<JacobianPoint<C, F, G>, JacobianPoint<C, F, G>> for JacobianPoint<C, F, G> {
fn sub(&self, other: &JacobianPoint<C, F, G>) -> JacobianPoint<C, F, G> { *self + (-*other) }
}
impl<C: Curve<F, G>, F: Field, G: Field> Sub<AffinePoint<C, F, G>, JacobianPoint<C, F, G>> for JacobianPoint<C, F, G> {
fn sub(&self, other: &AffinePoint<C, F, G>) -> JacobianPoint<C, F, G> { *self + (-*other) }<|fim▁hole|>}
impl<C: Curve<F, G>, F:Field, G: Field> Mul<AffinePoint<C, F, G>, AffinePoint<C, F, G>> for FieldElem<G> {
fn mul(&self, other: &AffinePoint<C, F, G>) -> AffinePoint<C, F, G> { other.pow(&self.limbs) }
}
impl<C: Curve<F, G>, F:Field, G: Field> Mul<FieldElem<G>, JacobianPoint<C, F, G>> for JacobianPoint<C, F, G> {
fn mul(&self, other: &FieldElem<G>) -> JacobianPoint<C, F, G> { self.pow(&other.limbs) }
}
impl<C: Curve<F, G>, F:Field, G: Field> Mul<JacobianPoint<C, F, G>, JacobianPoint<C, F, G>> for FieldElem<G> {
fn mul(&self, other: &JacobianPoint<C, F, G>) -> JacobianPoint<C, F, G> { other.pow(&self.limbs) }
}
impl<C: Curve<F, G>, F:Field, G: Field> Mul<BigUint, AffinePoint<C, F, G>> for AffinePoint<C, F, G> {
fn mul(&self, other: &BigUint) -> AffinePoint<C, F, G> { self.pow(other) }
}
impl<C: Curve<F, G>, F:Field, G: Field> Mul<AffinePoint<C, F, G>, AffinePoint<C, F, G>> for BigUint {
fn mul(&self, other: &AffinePoint<C, F, G>) -> AffinePoint<C, F, G> { other.pow(self) }
}
impl<C: Curve<F, G>, F:Field, G: Field> Mul<BigUint, JacobianPoint<C, F, G>> for JacobianPoint<C, F, G> {
fn mul(&self, other: &BigUint) -> JacobianPoint<C, F, G> { self.pow(other) }
}
impl<C: Curve<F, G>, F:Field, G: Field> Mul<JacobianPoint<C, F, G>, JacobianPoint<C, F, G>> for BigUint {
fn mul(&self, other: &JacobianPoint<C, F, G>) -> JacobianPoint<C, F, G> { other.pow(self) }
}
impl<C: Curve<F, G>, F: Field, G: Field> Neg<AffinePoint<C, F, G>> for AffinePoint<C, F, G> {
fn neg(&self) -> AffinePoint<C, F, G> {
AffinePoint { x: self.x.clone(), y: -(self.y.clone()) }
}
}
impl<C: Curve<F, G>, F: Field, G: Field> Neg<JacobianPoint<C, F, G>> for JacobianPoint<C, F, G> {
fn neg(&self) -> JacobianPoint<C, F, G> {
JacobianPoint { x: self.x.clone(), y: -(self.y.clone()), z: self.z.clone() }
}
}
impl<C: Curve<F, G>, F: Field, G: Field> Zero for AffinePoint<C, F, G> {
fn zero() -> AffinePoint<C, F, G> {
AffinePoint { x: Zero::zero(), y: Zero::zero() }
}
fn is_zero(&self) -> bool { self.x.is_zero() && self.y.is_zero() }
}
impl<C: Curve<F, G>, F: Field, G: Field> Zero for JacobianPoint<C, F, G> {
fn zero() -> JacobianPoint<C, F, G> {
JacobianPoint { x: One::one(), y: One::one(), z: Zero::zero() }
}
fn is_zero(&self) -> bool { self.z.is_zero() }
}
impl<C: Curve<F, G>, F: Field, G: Field> AffinePoint<C, F, G> {
pub fn is_valid(&self) -> bool {
if self.is_zero() {
true
} else {
let c: C = Default::default();
let y2 = self.y * self.y;
let x = (self.x * self.x * self.x) + (c.A() * self.x) + c.B();
y2 == x
}
}
pub fn serialize(&self) -> Vec<uint> {
let mut out: Vec<uint> = self.x.serialize();
if self.y.limbs < (-self.y).limbs { out.push(0) }
else { out.push(1) }
out
}
fn pow(&self, exp: &BigUint) -> AffinePoint<C, F, G> {
let g: G = Default::default();
pow(self, exp, &g.modulus())
}
pub fn to_jacobian(&self) -> JacobianPoint<C, F, G> {
let p = JacobianPoint {
x: self.x.clone(),
y: self.y.clone(),
z: One::one()
};
if self.is_zero() {
Zero::zero()
} else {
p
}
}
}
impl<C: Curve<F, G>, F: Field, G: Field> JacobianPoint<C, F, G> {
pub fn is_valid(&self) -> bool {
if self.is_zero() {
true
} else {
let c: C = Default::default();
let z4 = self.z * self.z * self.z * self.z;
let y2 = self.y * self.y;
let x = (self.x * self.x * self.x) + (c.A() * self.x * z4)
+ (c.B() * z4 * self.z * self.x);
y2 == x
}
}
fn pow(&self, exp: &BigUint) -> JacobianPoint<C, F, G> { // Replace with generic
let g: G = Default::default();
pow(self, exp, &g.modulus())
}
pub fn double(&self) -> JacobianPoint<C, F, G> {
let c: C = Default::default();
let f: F = Default::default();
let y2 = self.y * self.y;
let y4 = y2 * y2;
let z2 = self.z * self.z;
let xy2 = self.x * y2;
let yz = self.y * self.z;
let v = xy2 + xy2 + xy2 + xy2;
let w: FieldElem<F>;
if c.AN3() {
let tmp = (self.x + z2) * (self.x - z2);
w = tmp + tmp + tmp;
} else {
let x2 = self.x * self.x;
let z4 = z2 * z2;
w = x2 + x2 + x2 + (c.A() * z4);
}
let v2 = f.reduce(v.limbs << 1);
let y84 = f.reduce(y4.limbs << 3);
let xf = (w * w) - v2;
let yf = (w * (v - xf)) - y84;
let zf = yz + yz;
JacobianPoint { x: xf, y: yf, z: zf }
}
pub fn to_affine(&self) -> AffinePoint<C, F, G> {
if self.is_zero() {
Zero::zero()
} else {
let zinv = self.z.invert();
AffinePoint {
x: self.x * zinv * zinv,
y: self.y * zinv * zinv * zinv
}
}
}
}
impl<C: Curve<F, G>, F: Field, G: Field> fmt::Show for AffinePoint<C, F, G> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.is_zero() {
return write!(f, "0");
} else {
return write!(f, "({}, {})", self.x.limbs, self.y.limbs)
}
}
}
impl<C: Curve<F, G>, F: Field, G: Field> fmt::Show for JacobianPoint<C, F, G> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.is_zero() {
return write!(f, "0");
} else {
return write!(f, "({} : {} : {})", self.x.limbs, self.y.limbs, self.z.limbs)
}
}
}
fn unserialize<C: Curve<F, G>, F: Field, G: Field>(c: &C, s: &Vec<uint>) -> (FieldElem<F>, FieldElem<F>) {
let f: F = Default::default();
let mut t = s.clone();
let sign = t.pop().unwrap();
let x = f.unserialize(&t);
let (y1, y2) = ((x * x * x) + (c.A() * x) + c.B()).sqrt();
if (sign == 0) ^ (y1.limbs < (y2).limbs) {
(x, y2)
} else {
(x, y1)
}
}
#[deriving(Clone, Default)]
pub struct C192<P192, R192>;
impl Curve<P192, R192> for C192<P192, R192> {
fn AN3(&self) -> bool { true }
fn A(&self) -> FieldElem<P192> {
-(FieldElem { limbs: 3i.to_biguint().unwrap() })
}
fn B(&self) -> FieldElem<P192> {
FieldElem { limbs: FromStrRadix::from_str_radix("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16).unwrap() }
}
fn G(&self) -> AffinePoint<C192<P192, R192>, P192, R192> {
AffinePoint {
x: FieldElem { // To do: Implement FromStrRadix for FieldElem
limbs: FromStrRadix::from_str_radix("188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012", 16).unwrap()
},
y: FieldElem {
limbs: FromStrRadix::from_str_radix("07192b95ffc8da78631011ed6b24cdd573f977a11e794811", 16).unwrap()
}
}
}
fn unserialize(&self, s: &Vec<uint>) -> AffinePoint<C192<P192, R192>, P192, R192> {
let (x, y) = unserialize(self, s);
AffinePoint { x: x, y: y }
}
}
#[deriving(Clone, Default)]
pub struct C256<P256, R256>;
impl Curve<P256, R256> for C256<P256, R256> {
fn AN3(&self) -> bool { true }
fn A(&self) -> FieldElem<P256> {
-(FieldElem { limbs: 3i.to_biguint().unwrap() })
}
fn B(&self) -> FieldElem<P256> {
FieldElem { limbs: FromStrRadix::from_str_radix("5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b", 16).unwrap() }
}
fn G(&self) -> AffinePoint<C256<P256, R256>, P256, R256> {
AffinePoint {
x: FieldElem { // To do: Implement FromStrRadix for FieldElem
limbs: FromStrRadix::from_str_radix("6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296", 16).unwrap()
},
y: FieldElem {
limbs: FromStrRadix::from_str_radix("4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5", 16).unwrap()
}
}
}
fn unserialize(&self, s: &Vec<uint>) -> AffinePoint<C256<P256, R256>, P256, R256> {
let (x, y) = unserialize(self, s);
AffinePoint { x: x, y: y }
}}
#[deriving(Clone, Default)]
pub struct C521<P521, R521>;
impl Curve<P521, R521> for C521<P521, R521> {
fn AN3(&self) -> bool { true }
fn A(&self) -> FieldElem<P521> {
-(FieldElem {
limbs: 3i.to_biguint().unwrap(),
})
}
fn B(&self) -> FieldElem<P521> {
FieldElem {
limbs: FromStrRadix::from_str_radix("051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00", 16).unwrap()
}
}
fn G(&self) -> AffinePoint<C521<P521, R521>, P521, R521> {
AffinePoint {
x: FieldElem { // To do: Implement FromStrRadix for FieldElem
limbs: FromStrRadix::from_str_radix("c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66", 16).unwrap()
},
y: FieldElem {
limbs: FromStrRadix::from_str_radix("11839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650", 16).unwrap()
}
}
}
fn unserialize(&self, s: &Vec<uint>) -> AffinePoint<C521<P521, R521>, P521, R521> {
let (x, y) = unserialize(self, s);
AffinePoint { x: x, y: y }
}}
// -------------------------------------------------------------------------
// Unit Tests
// -------------------------------------------------------------------------
#[cfg(test)]
mod tests {
extern crate test;
use self::test::Bencher;
use std::num::FromStrRadix;
use num::{BigUint, One};
use num::bigint::ToBigUint;
use fields::{FieldElem, P192, R192, P256, R256, P521, R521};
use super::{AffinePoint, Curve, C192, C256, C521};
#[test]
fn accept_valid_point() {
let c: C192<P192, R192> = C192;
assert_eq!(c.G().is_valid(), true)
}
#[test]
fn reject_invalid_point() {
let c: C192<P192, R192> = C192;
let p = AffinePoint {
x: c.G().x,
y: FieldElem { limbs: c.G().y.limbs + One::one() }
};
assert_eq!(p.is_valid(), false)
}
#[test]
fn base_point_field_is_r192() {
let c: C192<P192, R192> = C192;
let one: FieldElem<R192> = FieldElem { limbs: One::one() };
let x: FieldElem<R192> = FieldElem { limbs: 3i.to_biguint().unwrap() };
let y = x.invert();
let a = x * c.G();
let b = y * a;
assert!(x != y);
assert!((x * y) == one);
assert!(c.G() != a);
assert!(c.G() == b);
}
#[test]
fn affine_point_multiplication() {
let sec: BigUint = FromStrRadix::from_str_radix("7e48c5ab7f43e4d9c17bd9712627dcc76d4df2099af7c8e5", 16).unwrap();
let x: BigUint = FromStrRadix::from_str_radix("48162eae1116dbbd5b7a0d9494ff0c9b414a31ce3d8b273f", 16).unwrap();
let y: BigUint = FromStrRadix::from_str_radix("4c221e09f96b3229c95af490487612c8e3bd81704724eeda", 16).unwrap();
let c: C192<P192, R192> = C192;
let a = sec * c.G();
assert_eq!(a.x.limbs, x);
assert_eq!(a.y.limbs, y);
}
#[test]
fn jacobian_point_multiplication_c192() {
let sec: BigUint = FromStrRadix::from_str_radix("7e48c5ab7f43e4d9c17bd9712627dcc76d4df2099af7c8e5", 16).unwrap();
let x: BigUint = FromStrRadix::from_str_radix("48162eae1116dbbd5b7a0d9494ff0c9b414a31ce3d8b273f", 16).unwrap();
let y: BigUint = FromStrRadix::from_str_radix("4c221e09f96b3229c95af490487612c8e3bd81704724eeda", 16).unwrap();
let c: C192<P192, R192> = C192;
let a = (sec * c.G().to_jacobian()).to_affine();
assert_eq!(a.x.limbs, x);
assert_eq!(a.y.limbs, y);
}
#[test]
fn mixed_point_addition_c192() {
let c: C192<P192, R192> = C192;
let a = c.G().to_jacobian().double() + c.G();
let b = c.G() + c.G().to_jacobian().double();
let c = c.G().to_jacobian().double() + c.G().to_jacobian();
assert_eq!(a, c);
assert_eq!(b, c);
}
#[test]
fn jacobian_point_multiplication_c256() {
let sec: BigUint = FromStrRadix::from_str_radix("26254a72f6a0ce35958ce62ff0cea754b84ac449b2b340383faef50606d03b01", 16).unwrap();
let x: BigUint = FromStrRadix::from_str_radix("6ee12372b80bad6f5432d0e6a3f02199db2b1617414f7fd8fe90b6bcf8b7aa68", 16).unwrap();
let y: BigUint = FromStrRadix::from_str_radix("5c71967784765fe888995bfd9a1fb76f329630018430e1d9aca7b59dc672cad8", 16).unwrap();
let c: C256<P256, R256> = C256;
let a = (sec * c.G().to_jacobian()).to_affine();
assert_eq!(a.x.limbs, x);
assert_eq!(a.y.limbs, y);
}
#[bench]
fn bench_point_mult_c192(b: &mut Bencher) {
let c: C192<P192, R192> = C192;
let sec: BigUint = FromStrRadix::from_str_radix("7e48c5ab7f43e4d9c17bd9712627dcc76d4df2099af7c8e5", 16).unwrap();
let p = c.G().to_jacobian();
b.iter(|| { sec * p })
}
#[bench]
fn bench_point_mult_c192_right_zeroes(b: &mut Bencher) {
let c: C192<P192, R192> = C192;
let sec: BigUint = FromStrRadix::from_str_radix("7e0000000000000000000000000000000000000000000000", 16).unwrap();
let p = c.G().to_jacobian();
b.iter(|| { sec * p })
}
#[bench]
fn bench_point_mult_c192_left_zeroes(b: &mut Bencher) {
let c: C192<P192, R192> = C192;
let sec: BigUint = 3i.to_biguint().unwrap();
let p = c.G().to_jacobian();
b.iter(|| { sec * p })
}
#[bench]
fn bench_point_mult_c521(b: &mut Bencher) {
let c: C521<P521, R521> = C521;
let sec: BigUint = FromStrRadix::from_str_radix("7e48c5ab7f43e4d9c17bd9712627dcc76d4df2099af7c8e5", 16).unwrap();
let p = c.G().to_jacobian();
b.iter(|| { sec * p })
}
}<|fim▁end|>
|
}
impl<C: Curve<F, G>, F:Field, G: Field> Mul<FieldElem<G>, AffinePoint<C, F, G>> for AffinePoint<C, F, G> {
fn mul(&self, other: &FieldElem<G>) -> AffinePoint<C, F, G> { self.pow(&other.limbs) }
|
<|file_name|>datadialog.ts<|end_file_name|><|fim▁begin|>namespace RIAPP.MOD.datadialog {
import utilsMOD = RIAPP.MOD.utils;
import templMOD = RIAPP.MOD.template;
import mvvm = RIAPP.MOD.mvvm;
var utils: utilsMOD.Utils;
RIAPP.global.addOnInitialize((s, args) => {
utils = s.utils;
});
export const enum DIALOG_ACTION { Default = 0, StayOpen = 1 };
export interface IDialogConstructorOptions {
dataContext?: any;
templateID: string;
width?: any;
height?: any;
title?: string;
submitOnOK?: boolean;
canRefresh?: boolean;
canCancel?: boolean;
fn_OnClose?: (dialog: DataEditDialog) => void;
fn_OnOK?: (dialog: DataEditDialog) => number;
fn_OnShow?: (dialog: DataEditDialog) => void;
fn_OnCancel?: (dialog: DataEditDialog) => number;
fn_OnTemplateCreated?: (template: templMOD.Template) => void;
fn_OnTemplateDestroy?: (template: templMOD.Template) => void;
}
export interface IButton {
id: string;
text: string;
'class': string;
click: () => void;
}
interface IDialogOptions {
width: any;
height: any;
title: string;
autoOpen: boolean;
modal: boolean;
close: (event: any, ui: any) => void;
buttons: IButton[];
}
var DLG_EVENTS = {
close: 'close',
refresh: 'refresh'
};
var PROP_NAME = {
dataContext: 'dataContext',
isSubmitOnOK: 'isSubmitOnOK',
width: 'width',
height: 'height',
title: 'title',
canRefresh: 'canRefresh',
canCancel: 'canCancel'
};
export class DataEditDialog extends BaseObject implements templMOD.ITemplateEvents {
private _objId: string;
private _dataContext: any;
private _templateID: string;
private _submitOnOK: boolean;
private _canRefresh: boolean;
private _canCancel: boolean;
private _fn_OnClose: (dialog: DataEditDialog) => void;
private _fn_OnOK: (dialog: DataEditDialog) => number;
private _fn_OnShow: (dialog: DataEditDialog) => void;
private _fn_OnCancel: (dialog: DataEditDialog) => number;
private _fn_OnTemplateCreated: (template: templMOD.Template) => void;
private _fn_OnTemplateDestroy: (template: templMOD.Template) => void;
private _isEditable: RIAPP.IEditable;
private _template: templMOD.Template;
private _$template: JQuery;
private _result: string;
private _options: IDialogOptions;
private _dialogCreated: boolean;
private _fn_submitOnOK: () => RIAPP.IVoidPromise;
private _app: Application;
//save the global's currentSelectable before showing and restore it on dialog's closing
private _currentSelectable: RIAPP.ISelectableProvider;
constructor(app: RIAPP.Application, options: IDialogConstructorOptions) {
super();
var self = this;
options = utils.extend(false, {
dataContext: null,
templateID: null,
width: 500,
height: 350,
title: 'data edit dialog',
submitOnOK: false,
canRefresh: false,
canCancel: true,
fn_OnClose: null,
fn_OnOK: null,
fn_OnShow: null,
fn_OnCancel: null,
fn_OnTemplateCreated: null,
fn_OnTemplateDestroy: null
}, options);
this._objId = 'dlg' + baseUtils.getNewID();
this._app = app;
this._dataContext = options.dataContext;
this._templateID = options.templateID;
this._submitOnOK = options.submitOnOK;
this._canRefresh = options.canRefresh;
this._canCancel = options.canCancel;
this._fn_OnClose = options.fn_OnClose;
this._fn_OnOK = options.fn_OnOK;
this._fn_OnShow = options.fn_OnShow;
this._fn_OnCancel = options.fn_OnCancel;
this._fn_OnTemplateCreated = options.fn_OnTemplateCreated;
this._fn_OnTemplateDestroy = options.fn_OnTemplateDestroy;
this._isEditable = null;
this._template = null;
this._$template = null;
this._result = null;
this._currentSelectable = null;
this._fn_submitOnOK = function () {
var iSubmittable = utils.getSubmittable(self._dataContext);
if (!iSubmittable || !iSubmittable.isCanSubmit) {
//signals immediatly
return utils.createDeferred().resolve();
}
return iSubmittable.submitChanges();
};
this._updateIsEditable();
this._options = {
width: options.width,
height: options.height,
title: options.title,
autoOpen: false,
modal: true,
close: function (event, ui) {
self._onClose();
},
buttons: self._getButtons()
};
this._dialogCreated = false;
this._createDialog();
}
handleError(error: any, source: any): boolean {
var isHandled = super.handleError(error, source);
if (!isHandled) {
return this._app.handleError(error, source);
}
return isHandled;
}
addOnClose(fn: TEventHandler<DataEditDialog, any>, nmspace?: string, context?: BaseObject) {
this._addHandler(DLG_EVENTS.close, fn, nmspace, context);
}
removeOnClose(nmspace?: string) {
this._removeHandler(DLG_EVENTS.close, nmspace);
}
addOnRefresh(fn: TEventHandler<DataEditDialog, { isHandled: boolean; }>, nmspace?: string, context?: BaseObject) {
this._addHandler(DLG_EVENTS.refresh, fn, nmspace, context);
}
removeOnRefresh(nmspace?: string) {
this._removeHandler(DLG_EVENTS.refresh, nmspace);
}
protected _updateIsEditable() {
this._isEditable = utils.getEditable(this._dataContext);
}
protected _createDialog() {
if (this._dialogCreated)
return;
try {
this._template = this._createTemplate();
this._$template = global.$(this._template.el);
global.document.body.appendChild(this._template.el);
(<any>this._$template).dialog(this._options);
this._dialogCreated = true;
}
catch (ex) {
RIAPP.reThrow(ex, this.handleError(ex, this));
}
}
protected _getEventNames() {
var base_events = super._getEventNames();
return [DLG_EVENTS.close, DLG_EVENTS.refresh].concat(base_events);
}
templateLoading(template: templMOD.Template): void {
//noop
}
templateLoaded(template: templMOD.Template): void {
if (this._isDestroyCalled)
return;
if (!!this._fn_OnTemplateCreated) {
this._fn_OnTemplateCreated(template);
}
}
templateUnLoading(template: templMOD.Template): void {
if (!!this._fn_OnTemplateDestroy) {
this._fn_OnTemplateDestroy(template);
}
}
protected _createTemplate() {
return new templMOD.Template({
app: this.app,
templateID: this._templateID,
dataContext: null,
templEvents: this
});
}
protected _destroyTemplate() {
if (!!this._template)
this._template.destroy();
}
protected _getButtons(): IButton[] {
var self = this, buttons = [
{
'id': self._objId + 'Refresh',
'text': localizable.TEXT.txtRefresh,
'class': 'btn btn-info',
'click': function () {
self._onRefresh();
}
},
{
'id': self._objId + 'Ok',
'text': localizable.TEXT.txtOk,
'class': 'btn btn-info',
'click': function () {
self._onOk();
}
},
{
'id': self._objId + 'Cancel',
'text': localizable.TEXT.txtCancel,
'class': 'btn btn-info',
'click': function () {
self._onCancel();
}
}
];
if (!this.canRefresh) {
buttons.shift();
}
if (!this.canCancel) {
buttons.pop();
}
return buttons;
}
protected _getOkButton() {
return $("#" + this._objId + 'Ok');
}
protected _getCancelButton() {
return $("#" + this._objId + 'Cancel');
}
protected _getRefreshButton() {
return $("#" + this._objId + 'Refresh');
}
protected _getAllButtons() {
return [this._getOkButton(), this._getCancelButton(), this._getRefreshButton()];
}
protected _disableButtons(isDisable: boolean) {
var btns = this._getAllButtons();
btns.forEach(function ($btn) {
$btn.prop("disabled", !!isDisable);
});
}
protected _onOk() {
var self = this, canCommit: boolean, action = DIALOG_ACTION.Default;
if (!!this._fn_OnOK) {
action = this._fn_OnOK(this);
}
if (action == DIALOG_ACTION.StayOpen)
return;
if (!this._dataContext) {
self.hide();
return;
}
if (!!this._isEditable)
canCommit = this._isEditable.endEdit();
else<|fim▁hole|> canCommit = true;
if (canCommit) {
if (this._submitOnOK) {
this._disableButtons(true);
var title = this.title;
this.title = localizable.TEXT.txtSubmitting;
var promise = this._fn_submitOnOK();
promise.always(function () {
self._disableButtons(false);
self.title = title;
});
promise.done(function () {
self._result = 'ok';
self.hide();
});
promise.fail(function () {
//resume editing if fn_onEndEdit callback returns false in isOk argument
if (!!self._isEditable) {
if (!self._isEditable.beginEdit()) {
self._result = 'cancel';
self.hide();
}
}
});
}
else {
self._result = 'ok';
self.hide();
}
}
}
protected _onCancel() {
var action = DIALOG_ACTION.Default;
if (!!this._fn_OnCancel) {
action = this._fn_OnCancel(this);
}
if (action == DIALOG_ACTION.StayOpen)
return;
if (!!this._isEditable)
this._isEditable.cancelEdit();
this._result = 'cancel';
this.hide();
}
protected _onRefresh() {
var args = { isHandled: false };
this.raiseEvent(DLG_EVENTS.refresh, args);
if (args.isHandled)
return;
var dctx = this._dataContext;
if (!!dctx) {
if (utils.check.isFunction(dctx.refresh)) {
dctx.refresh();
}
else if (!!dctx._aspect && utils.check.isFunction(dctx._aspect.refresh)) {
dctx._aspect.refresh();
}
}
}
protected _onClose() {
try {
if (this._result != 'ok' && !!this._dataContext) {
if (!!this._isEditable)
this._isEditable.cancelEdit();
if (this._submitOnOK) {
var subm = utils.getSubmittable(this._dataContext);
if (!!subm)
subm.rejectChanges();
}
}
if (!!this._fn_OnClose)
this._fn_OnClose(this);
this.raiseEvent(DLG_EVENTS.close, {});
}
finally {
this._template.dataContext = null;
}
var csel = this._currentSelectable;
this._currentSelectable = null;
setTimeout(function () { global.currentSelectable = csel; csel = null; }, 50);
}
protected _onShow() {
this._currentSelectable = global.currentSelectable;
if (!!this._fn_OnShow) {
this._fn_OnShow(this);
}
}
show() {
var self = this;
self._result = null;
(<any>self._$template).dialog("option", "buttons", this._getButtons());
this._template.dataContext = this._dataContext;
self._onShow();
(<any>self._$template).dialog("open");
}
hide() {
var self = this;
if (!self._$template)
return;
(<any>self._$template).dialog("close");
}
getOption(name: string) {
if (!this._$template)
return undefined;
return (<any>this._$template).dialog('option', name);
}
setOption(name: string, value: any) {
var self = this;
(<any>self._$template).dialog('option', name, value);
}
destroy() {
if (this._isDestroyed)
return;
this._isDestroyCalled = true;
this.hide();
this._destroyTemplate();
this._$template = null;
this._template = null;
this._dialogCreated = false;
this._dataContext = null;
this._fn_submitOnOK = null;
this._isEditable = null;
this._app = null;
super.destroy();
}
get app() { return this._app; }
get dataContext() { return this._dataContext; }
set dataContext(v) {
if (v !== this._dataContext) {
this._dataContext = v;
this._updateIsEditable();
this.raisePropertyChanged(PROP_NAME.dataContext);
}
}
get result() { return this._result; }
get template() { return this._template; }
get isSubmitOnOK() { return this._submitOnOK; }
set isSubmitOnOK(v) {
if (this._submitOnOK !== v) {
this._submitOnOK = v;
this.raisePropertyChanged(PROP_NAME.isSubmitOnOK);
}
}
get width() { return this.getOption('width'); }
set width(v) {
var x = this.getOption('width');
if (v !== x) {
this.setOption('width', v);
this.raisePropertyChanged(PROP_NAME.width);
}
}
get height() { return this.getOption('height'); }
set height(v) {
var x = this.getOption('height');
if (v !== x) {
this.setOption('height', v);
this.raisePropertyChanged(PROP_NAME.height);
}
}
get title() { return this.getOption('title'); }
set title(v) {
var x = this.getOption('title');
if (v !== x) {
this.setOption('title', v);
this.raisePropertyChanged(PROP_NAME.title);
}
}
get canRefresh() { return this._canRefresh; }
set canRefresh(v) {
var x = this._canRefresh;
if (v !== x) {
this._canRefresh = v;
this.raisePropertyChanged(PROP_NAME.canRefresh);
}
}
get canCancel() { return this._canCancel; }
set canCancel(v) {
var x = this._canCancel;
if (v !== x) {
this._canCancel = v;
this.raisePropertyChanged(PROP_NAME.canCancel);
}
}
}
export class DialogVM extends mvvm.BaseViewModel {
_dialogs: { [name: string]: () => DataEditDialog; };
constructor(app: Application) {
super(app);
this._dialogs = {};
}
createDialog(name: string, options: IDialogConstructorOptions) {
var self = this;
//the map stores functions those create dialogs (aka factories)
this._dialogs[name] = function () {
var dialog = new DataEditDialog(self.app, options);
var f = function () {
return dialog;
};
self._dialogs[name] = f;
return f();
};
return this._dialogs[name];
}
showDialog(name: string, dataContext: any) {
var dlg = this.getDialog(name);
if (!dlg)
throw new Error(utils.format('Invalid Dialog name: {0}', name));
dlg.dataContext = dataContext;
dlg.show();
return dlg;
}
getDialog(name: string) {
var factory = this._dialogs[name];
if (!factory)
return null;
return factory();
}
destroy() {
if (this._isDestroyed)
return;
this._isDestroyCalled = true;
var keys = Object.keys(this._dialogs);
keys.forEach(function (key: string) {
this._dialogs[key].destroy();
}, this);
this._dialogs = {};
super.destroy();
}
}
_isModuleLoaded = true;
}<|fim▁end|>
| |
<|file_name|>prp_CamClasses.py<|end_file_name|><|fim▁begin|># Copyright (C) 2008 Guild of Writers PyPRP Project Team
# See the file AUTHORS for more info about the team
#
# 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
#
# Please see the file LICENSE for the full license.
try:
import Blender
try:
from Blender import Mesh
from Blender import Lamp
except Exception, detail:
print detail
except ImportError:
pass
import md5, random, binascii, cStringIO, copy, Image, math, struct, StringIO, os, os.path, pickle
from prp_Types import *
from prp_DXTConv import *
from prp_HexDump import *
from prp_GeomClasses import *
#from prp_LogicClasses import *
from prp_Functions import *
from prp_ConvexHull import *
from prp_VolumeIsect import *
from prp_AlcScript import *
from prp_RefParser import *
from prp_Messages import *
import prp_Config, prp_HexDump
################# Rework of the camera classes ###################
class CamTrans:
def __init__(self,parent):
self.parent = parent
self.fTransTo = UruObjectRef()
self.fCutPos = False # boolean
self.fCutPOA = False # boolean
self.fIgnore = False # boolean
self.fAccel = 60.0
self.fDecel = 60.0
self.fVelocity = 60.0
self.fPOAAccel = 60.0
self.fPOADecel = 60.0
self.fPOAVelocity = 60.0
def read(self,stream):
print "w"
self.fTransTo.read(stream)
print "v"
self.fCutPos = stream.ReadBool()
self.fCutPOA = stream.ReadBool()
self.fIgnore = stream.ReadBool()
self.fVelocity = stream.ReadFloat()
self.fAccel = stream.ReadFloat()
self.fDecel = stream.ReadFloat()
self.fPOAVelocity = stream.ReadFloat()
self.fPOAAccel = stream.ReadFloat()
self.fPOADecel = stream.ReadFloat()
def write(self,stream):
self.fTransTo.write(stream)
stream.WriteBool(self.fCutPos)
stream.WriteBool(self.fCutPOA)
stream.WriteBool(self.fIgnore)
stream.WriteFloat(self.fVelocity)
stream.WriteFloat(self.fAccel)
stream.WriteFloat(self.fDecel)
stream.WriteFloat(self.fPOAVelocity)
stream.WriteFloat(self.fPOAAccel)
stream.WriteFloat(self.fPOADecel)
def import_obj(self,obj,count):
pass
def export_script(self,script):
self.fAccel = float(FindInDict(script,"accel",self.fAccel))
self.fDecel = float(FindInDict(script,"decel",self.fDecel))
self.fVelocity = float(FindInDict(script,"velocity",self.fVelocity))
self.fPOAAccel = float(FindInDict(script,"poaaccel",self.fPOAAccel))
self.fPOADecel = float(FindInDict(script,"poadecel",self.fPOADecel))
self.fPOCVelocity = float(FindInDict(script,"poavelocity",self.fPOAVelocity))
self.fCutPos = bool(str(FindInDict(script,"cutpos",str(self.fCutPos))).lower() == "true")
self.fCutPOA = bool(str(FindInDict(script,"cutpoa",str(self.fCutPOA))).lower() == "true")
self.fIgnore = bool(str(FindInDict(script,"ignore",str(self.fIgnore))).lower() == "true")
transto = FindInDict(script,"to",None)
# do something with that...
refparser = ScriptRefParser(self.parent.getRoot(),False,"scnobj",[0x0001])
self.fSubjectKey = refparser.MixedRef_FindCreateRef(transto)
pass
class plCameraModifier1(plSingleModifier): # actually descends from plSingleModifer, but doesn't use those read/write functions
def __init__(self,parent,name="unnamed",type=0x009B):
plSingleModifier.__init__(self,parent,name,type)
#format
self.fBrain=UruObjectRef()
self.fTrans = [] #CamTrans Fields
#Ending is almost always like this:
self.fFOVw = 45.0 # Field of View
self.fFOVh = 33.75 #
self.fMessageQueue = []
self.fFOVInstructions = []
self.fAnimated = False
self.fStartAnimOnPush = False
self.fStopAnimOnPop = False
self.fResetAnimOnPop = False
def _Find(page,name):
return page.find(0x009B,name,0)
Find = staticmethod(_Find)
def _FindCreate(page,name):
return page.find(0x009B,name,1)
FindCreate = staticmethod(_FindCreate)
def changePageRaw(self,sid,did,stype,dtype):
hsKeyedObject.changePageRaw(self,sid,did,stype,dtype)
def read(self,stream,size):
start = stream.tell()
hsKeyedObject.read(self,stream)
self.fBrain.read(stream)
count = stream.Read32()
for i in range(count):
cam = CamTrans(self)
cam.read(stream) # not like this in Plasma, but makes it easier here :)
self.fTrans.append(cam)
self.fFOVw = stream.ReadFloat()
self.fFOVh = stream.ReadFloat()
count = stream.Read32()
# we now should read in a message queue, which is hard because of incomplete message implementations
try:
print "Y"
for i in range(count):
Msg = PrpMessage.FromStream(stream)
self.fMessageQueue.add(Msg.data)
print "Z"
for msg in self.fMessageQueue:
msg.fSender.read(stream)
# read in queue of plCameraMSgs
self.fFOVInstructions = []
count = stream.Read32()
for i in range(count):
Msg = PrpMessage.FromStream(stream)
self.fFOVInstructions.append(FovMsg.data)
except ValueError, detail:
print "/---------------------------------------------------------"
print "| WARNING:"
print "| Got Value Error:" , detail, ":"
print "| Skipping message arrays of plCameraModifier1..."
print "| -> Skipping %i bytes ahead " % ( (start + size -4) - stream.tell())
print "| -> Total object size: %i bytes"% (size)
print "\---------------------------------------------------------\n"
stream.seek(start + size - 4) #reposition the stream to read in the last 4 bytes
self.fAnimated = stream.ReadBool()
self.fStartAnimOnPush = stream.ReadBool()
self.fStopAnimOnPop = stream.ReadBool()
self.fResetAnimOnPop = stream.ReadBool()
def write(self,stream):
hsKeyedObject.write(self,stream)
self.fBrain.write(stream)
stream.Write32(len(self.fTrans))
for cam in self.fTrans:
cam.write(stream)
stream.WriteFloat(self.fFOVw)
stream.WriteFloat(self.fFOVh)
stream.Write32(len(self.fMessageQueue))
for msg in self.fMessageQueue:
PrpMessage.ToStream(stream,msg)
for msg in self.fMessageQueue:
msg.fSender.write(stream)
stream.Write32(len(self.fFOVInstructions))
for msg in self.fFOVInstructions:
PrpMessage.ToStream(stream,msg)
stream.WriteBool(self.fAnimated)
stream.WriteBool(self.fStartAnimOnPush)
stream.WriteBool(self.fStopAnimOnPop)
stream.WriteBool(self.fResetAnimOnPop)
def import_obj(self,obj):
root = self.getRoot()
# calculate the camera lens (blender has 32 mm camera)
radian_fFOVh = self.fFOVh / (360/(2*math.pi))
lens = 32/(2*math.tan(radian_fFOVh/2))
# now set the blender lens property
obj.data.setLens(lens)
c = 0
for cam in self.fTrans:
cam.import_obj(obj,c)
c = c+1
cbrain = root.findref(self.fBrain)
cbrain.data.import_obj(obj)
pass
def export_obj(self,obj):
root = self.getRoot()
print "Exporting Camera Modifier Object"
# --- Find the camera's script object ----
objscript = AlcScript.objects.Find(obj.name)
# check if it's animated
self.fAnimated = FindInDict(objscript,"camera.animated",False)
# --------- FOV --------------
if(obj.data.getType() == 0): # check for perspective camera
lens = obj.data.getLens()
print "Calculating FOV for lens is %i mm" % lens
self.fFOVh = 2 * math.atan(32/(2*lens)) * (360/(2*math.pi))
self.fFOVw = self.fFOVh / 0.750 # I divide by 0.750 becaus I hope it's more accurate than multiplying by 1.33
else:
#default them to default values (45:33.75):
print "Camera is not perpective - please changeit to perspective"
pass
# -------- Camera Brains --------
# get brain type from logic property first
cambraintype = getTextPropertyOrDefault(obj,"cambrain","fixed")
# load it in from AlcScript (overrides logic properties)
scriptbrain = FindInDict(objscript,"camera.brain.type","fixed")
scriptbrain = str(scriptbrain).lower()
if scriptbrain in ["fixed","circle","avatar","firstperson","simple"]:
cambraintype = scriptbrain
print " Camera Brain: %s" % cambraintype
# determine the camera brain
if(cambraintype == "fixed"):
# fixed camera brain
cambrain = plCameraBrain1_Fixed.FindCreate(root,str(self.Key.name))
elif(cambraintype == "circle"):
# Circle camera brain
cambrain = plCameraBrain1_Circle.FindCreate(root,str(self.Key.name))
elif(cambraintype == "avatar"):
# Avatar camera brain
cambrain = plCameraBrain1_Avatar.FindCreate(root,str(self.Key.name))
elif(cambraintype == "firstperson"):
# First Person Camera Brain
cambrain = plCameraBrain1_FirstPerson.FindCreate(root,str(self.Key.name))
else:
# simple and default camera brain
cambrain = plCameraBrain1.FindCreate(root,str(self.Key.name))
cambrain.data.export_obj(obj)
self.fBrain = cambrain.data.getRef()
# -------- Camera Transitions ---------
transitions = list(FindInDict(objscript,"camera.transitions",[]))
for transitionscript in transitions:
cam = CamTrans(self)
cam.export_script(transitionscript)
self.fTrans.append(cam)
if len(self.fTrans) == 0:
cam = CamTrans(self)
self.fTrans.append(cam)
def _Export(page,obj,scnobj,name):
# -------- Camera Modifier 1 -------------
cameramod = plCameraModifier1.FindCreate(page,name)
cameramod.data.export_obj(obj)
# now link the camera modifier to the object (twice, since that appears to be what cyan does
scnobj.data.addModifier(cameramod)
scnobj.data.addModifier(cameramod)
Export = staticmethod(_Export)
## Needs to be moved to plCameraModifier1.Export(self,obj,scnobj,name)
def _Import(scnobj,prp,obj):
# Lights
for c_ref in scnobj.data1.vector:
if c_ref.Key.object_type in [0x009B,]:
cam=prp.findref(c_ref)
cam.data.import_obj(obj)
obj.layers=[5,]
break
Import = staticmethod(_Import)
class plCameraBrain1(hsKeyedObject):
Flags = {
"kCutPos" : 0,
"kCutPosOnce" : 1,
"kCutPOA" : 2,
"kCutPOAOnce" : 3,
"kAnimateFOV" : 4,
"kFollowLocalAvatar" : 5,
"kPanicVelocity" : 6,
"kRailComponent" : 7,
"kSubject" : 8,
"kCircleTarget" : 9,
"kMaintainLOS" : 10,
"kZoomEnabled" : 11,
"kIsTransitionCamera" : 12,
"kWorldspacePOA" : 13,
"kWorldspacePos" : 14,
"kCutPosWhilePan" : 15,
"kCutPOAWhilePan" : 16,
"kNonPhys" : 17,
"kNeverAnimateFOV" : 18,
"kIgnoreSubworldMovement" : 19,
"kFalling" : 20,
"kRunning" : 21,
"kVerticalWhenFalling" : 22,
"kSpeedUpWhenRunning" : 23,
"kFallingStopped" : 24,
"kBeginFalling" : 25
}
ScriptFlags = {
"cutpos" : 0,
"cutposonce" : 1,
"cutpoa" : 2,
"cutpoaonce" : 3,
"animatefov" : 4,
"followlocalavatar" : 5,
"panicvelocity" : 6,
"railcomponent" : 7,
"subject" : 8,
"circletarget" : 9,
"maintainlos" : 10,
"zoomenabled" : 11,
"istransitioncamera" : 12,
"worldspacepoa" : 13,
"worldspacepos" : 14,
"cutposwhilepan" : 15,
"cutpoawhilepan" : 16,
"nonphys" : 17,
"neveranimatefov" : 18,
"ignoresubworldmovement" : 19,
"falling" : 20,
"running" : 21,
"verticalwhenfalling" : 22,
"speedupwhenrunning" : 23,
"fallingstopped" : 24,
"beginfalling" : 25
}
def __init__(self,parent,name="unnamed",type=0x0099):
hsKeyedObject.__init__(self,parent,name,type)
#format
self.fFlags=hsBitVector()
# -------- Initialize default settings
# only set in export_obj if there is no flag block in script
#self.fFlags.SetBit(plCameraBrain1.Flags["kFollowLocalAvatar"])
self.fPOAOffset = Vertex(0.0,0.0,6.0)
self.fSubjectKey=UruObjectRef()
self.fRail=UruObjectRef()
self.fAccel = 30
self.fDecel = 30
self.fVelocity = 30
self.fPOAAccel = 30
self.fPOADecel = 30
self.fPOAVelocity = 30
self.fXPanLimit = 0
self.fZPanLimit = 0
self.fZoomRate = 0
self.fZoomMin = 0
self.fZoomMax = 0
def _Find(page,name):
return page.find(0x0099,name,0)
Find = staticmethod(_Find)
def _FindCreate(page,name):
return page.find(0x0099,name,1)
FindCreate = staticmethod(_FindCreate)
def changePageRaw(self,sid,did,stype,dtype):
hsKeyedObject.changePageRaw(self,sid,did,stype,dtype)
self.fSubjectKey.changePageRaw(sid,did,stype,dtype)
self.fRail.changePageRaw(sid,did,stype,dtype)
def read(self,stream):
hsKeyedObject.read(self,stream)
self.fPOAOffset.read(stream)
self.fSubjectKey.read(stream)
self.fRail.read(stream)
self.fFlags.read(stream)
self.fAccel = stream.ReadFloat()
self.fDecel = stream.ReadFloat()
self.fVelocity = stream.ReadFloat()
self.fPOAAccel = stream.ReadFloat()
self.fPOADecel = stream.ReadFloat()
self.fPOAVelocity = stream.ReadFloat()
self.fXPanLimit = stream.ReadFloat()
self.fZPanLimit = stream.ReadFloat()
self.fZoomRate = stream.ReadFloat()
self.fZoomMin = stream.ReadFloat()
self.fZoomMax = stream.ReadFloat()
def write(self,stream):
hsKeyedObject.write(self,stream)
self.fPOAOffset.write(stream)
self.fSubjectKey.write(stream)
self.fRail.write(stream)
self.fFlags.write(stream)
stream.WriteFloat(self.fAccel)
stream.WriteFloat(self.fDecel)
stream.WriteFloat(self.fVelocity)
stream.WriteFloat(self.fPOAAccel)
stream.WriteFloat(self.fPOADecel)
stream.WriteFloat(self.fPOAVelocity)
stream.WriteFloat(self.fXPanLimit)
stream.WriteFloat(self.fZPanLimit)
stream.WriteFloat(self.fZoomRate)
stream.WriteFloat(self.fZoomMin)
stream.WriteFloat(self.fZoomMax)
def import_obj(self,obj):
objscript = AlcScript.objects.FindCreate(obj.name)
StoreInDict(objscript,"camera.brain.type","simple")
StoreInDict(objscript,"camera.brain.poa","%f,%f,%f"%(float(self.fPOAOffset.x),float(self.fOAOffset.y),float(self.fPOAOffset.z)))
StoreInDict(objscript,"camera.brain.accel",self.fAccel)
StoreInDict(objscript,"camera.brain.decel",self.fDecel)
StoreInDict(objscript,"camera.brain.velocity",self.fVelocity)
StoreInDict(objscript,"camera.brain.poaaccel",self.fPOAAccel)
StoreInDict(objscript,"camera.brain.poadecel",self.fPOADecel)
StoreInDict(objscript,"camera.brain.poavelocity",self.fPOAVelocity)
StoreInDict(objscript,"camera.brain.xpanlimit",self.fXPanLimit)
StoreInDict(objscript,"camera.brain.zpanlimit",self.fZPanLimit)
StoreInDict(objscript,"camera.brain.zoomrate",self.fZoomRate)
StoreInDict(objscript,"camera.brain.zoommin",self.fZoomMin)
StoreInDict(objscript,"camera.brain.zoommax",self.fZoomMax)
if not self.fRail.isNull():
StoreInDict(objscript,"camera.brain.rail","%0x%X:%s"%(int(self.fSubjectKey.object_type),str(self.fSubjectKey.Key.Name)))
if not self.fSubjectKey.isNull():
StoreInDict(objscript,"camera.brain.subjectkey","%0x%X:%s"%(int(self.fSubjectKey.object_type),str(self.fSubjectKey.Key.Name)))
def export_obj(self,obj):
print "Exporting CameraBrain1"
# ------ Obtain the AlcScript Object ------
objscript = AlcScript.objects.Find(obj.name)
self.fAccel = float(FindInDict(objscript,"camera.brain.accel",self.fAccel))
self.fDecel = float(FindInDict(objscript,"camera.brain.decel",self.fDecel))
self.fVelocity = float(FindInDict(objscript,"camera.brain.velocity",self.fVelocity))
self.fPOAAccel = float(FindInDict(objscript,"camera.brain.poaaccel",self.fPOAAccel))
self.fPOADecel = float(FindInDict(objscript,"camera.brain.poadecel",self.fPOADecel))
self.fPOCVelocity = float(FindInDict(objscript,"camera.brain.poavelocity",self.fPOAVelocity))
self.fXPanLimit= float(FindInDict(objscript,"camera.brain.xpanlimit",self.fXPanLimit))
self.fZPanLimit= float(FindInDict(objscript,"camera.brain.zpanlimit",self.fZPanLimit))
self.fZoomRate= float(FindInDict(objscript,"camera.brain.zoomrate",self.fZoomRate))
self.fZoomMin= float(FindInDict(objscript,"camera.brain.zoommin",self.fZoomMin))
self.fZoomMax= float(FindInDict(objscript,"camera.brain.zoommax",self.fZoomMax))
# AlcScript: camera.brain.subjectkey
subject = FindInDict(objscript,"camera.brain.subjectkey",None)
# do something with that...
refparser = ScriptRefParser(self.getRoot(),"",False,[])
self.fSubjectKey = refparser.MixedRef_FindCreateRef(subject)
# AlcScript: camera.brain.subjectkey
rail = FindInDict(objscript,"camera.brain.rail",None)
# do something with that...
refparser = ScriptRefParser(self.getRoot(),"",False,[])
self.fRail = refparser.MixedRef_FindCreateRef(rail)
# ------ Process ------
# AlcScript: camera.brain.poa = "<float X>,<float Y>,<float Z>"
poa = str(FindInDict(objscript,"camera.brain.poa","0,0,0"))
try:
X,Y,Z, = poa.split(',')
self.fPOAOffset = Vertex(float(X),float(Y),float(Z))
except ValueError, detail:
print " Error parsing camera.brain.poa (Value:",poa,") : ",detail
flags = FindInDict(objscript,"camera.brain.flags",None)
if type(flags) == list:
self.fFlags = hsBitVector() # reset
for flag in flags:
if flag.lower() in plCameraBrain1.ScriptFlags:
idx = plCameraBrain1.ScriptFlags[flag.lower()]<|fim▁hole|> self.fFlags.SetBit(idx)
else:
print " No camera flags list, setting default"
self.fFlags.SetBit(plCameraBrain1.Flags["kFollowLocalAvatar"])
class plCameraBrain1_Fixed(plCameraBrain1):
def __init__(self,parent,name="unnamed",type=0x009F):
plCameraBrain1.__init__(self,parent,name,type)
# set the Camerabrain1 floats to match defaults for this brain type
self.fAccel = 30
self.fDecel = 30
self.fVelocity = 30
self.fPOAAccel = 30
self.fPOADecel = 30
self.fPOAVelocity = 30
self.fXPanLimit = 0
self.fZPanLimit = 0
self.fZoomRate = 0
self.fZoomMin = 0
self.fZoomMax = 0
#format
self.fTargetPoint=UruObjectRef()
def _Find(page,name):
return page.find(0x009F,name,0)
Find = staticmethod(_Find)
def _FindCreate(page,name):
return page.find(0x009F,name,1)
FindCreate = staticmethod(_FindCreate)
def changePageRaw(self,sid,did,stype,dtype):
plCameraBrain1.changePageRaw(self,sid,did,stype,dtype)
self.fTargetPoint.changePageRaw(sid,did,stype,dtype)
def read(self,stream):
plCameraBrain1.read(self,stream)
self.fTargetPoint.read(stream)
def write(self,stream):
plCameraBrain1.write(self,stream)
self.fTargetPoint.write(stream)
def import_obj(self,obj):
plCameraBrain1.import_obj(self,obj)
objscript = AlcScript.objects.FindCreate(obj.name)
StoreInDict(objscript,"camera.brain.type","fixed")
if not self.fTargetPoint.isNull():
StoreInDict(objscript,"camera.brain.target","%0x%X:%s"%(int(self.fSubjectKey.object_type),str(self.fSubjectKey.Key.Name)))
def export_obj(self,obj):
plCameraBrain1.export_obj(self,obj)
print "Exporting CameraBrain1_Fixed"
# ------ Obtain the AlcScript Object ------
objscript = AlcScript.objects.Find(obj.name)
# ------ Conintue if it's set ------
# AlcScript: camera.brain.target = string
target = FindInDict(objscript,"camera.brain.target",None)
# do something with that...
refparser = ScriptRefParser(self.getRoot(),"","scnobj",[0x0001])
self.fTargetPoint = refparser.MixedRef_FindCreateRef(target)
class plCameraBrain1_Circle(plCameraBrain1_Fixed):
CircleFlags = {
"kLagged" : 0x1,
"kAbsoluteLag" : 0x3,
"kFarthest" : 0x4,
"kTargetted" : 0x8,
"kHasCenterObject" : 0x10,
"kPOAObject" : 0x20,
"kCircleLocalAvatar" : 0x40
}
ScriptCircleFlags = {
"lagged" : 0x1,
"absolutelag" : 0x3,
"farthest" : 0x4,
"targetted" : 0x8,
"hascenterobject" : 0x10,
"poaobject" : 0x20,
"circlelocalavatar" : 0x40
}
def __init__(self,parent,name="unnamed",type=0x00C2):
plCameraBrain1_Fixed.__init__(self,parent,name,type)
# set the Camerabrain1 floats to match defaults for this brain type
self.fAccel = 10
self.fDecel = 10
self.fVelocity = 15
self.fPOAAccel = 10
self.fPOADecel = 10
self.fPOAVelocity = 15
self.fXPanLimit = 0
self.fZPanLimit = 0
self.fZoomRate = 0
self.fZoomMin = 0
self.fZoomMax = 0
#format
self.fCircleFlags = 0
self.fCircleFlags |= plCameraBrain1_Circle.CircleFlags['kCircleLocalAvatar'] | \
plCameraBrain1_Circle.CircleFlags['kFarthest']
self.fCenter = Vertex(0.0,0.0,0.0)
self.fRadius = 0
self.fCenterObject = UruObjectRef()
self.fPOAObj = UruObjectRef()
self.fCirPerSec = 0.10 # virtually always 0.10
def _Find(page,name):
return page.find(0x00C2,name,0)
Find = staticmethod(_Find)
def _FindCreate(page,name):
return page.find(0x00C2,name,1)
FindCreate = staticmethod(_FindCreate)
def changePageRaw(self,sid,did,stype,dtype):
plCameraBrain1.changePageRaw(self,sid,did,stype,dtype)
self.fCenterObject.changePageRaw(sid,did,stype,dtype)
self.fPOAObj.changePageRaw(sid,did,stype,dtype)
def read(self,stream):
plCameraBrain1.read(self,stream) # yes, this is correct, it uses the plCameraBrain1 read/write functions
self.fCircleFlags = stream.Read32()
self.fCenter.read(stream)
self.fRadius = stream.ReadFloat()
self.fCenterObject.read(stream)
self.fPOAObj.read(stream)
self.fCirPerSec = stream.ReadFloat()
def write(self,stream):
plCameraBrain1.write(self,stream) # yes, this is correct, it uses the plCameraBrain1 read/write functions
stream.Write32(self.fCircleFlags)
self.fCenter.write(stream)
stream.WriteFloat(self.fRadius)
self.fCenterObject.write(stream)
self.fPOAObj.write(stream)
stream.WriteFloat(self.fCirPerSec)
def import_obj(self,obj):
plCameraBrain1.import_obj(self,obj)
objscript = AlcScript.objects.FindCreate(obj.name)
StoreInDict(objscript,"camera.brain.type","circle")
obj.data.setClipEnd(self.fRadius)
obj.data.setMode("showLimits")
flaglist = []
for flag in plCameraBrain1_Circle.ScriptCircleFlags.keys():
if self.fCicleFlags & plCameraBrain1_Circle.ScriptCircleFlags[flag] > 0:
flaglist.append(flag)
StoreInDict(objscript,"camera.brain.cicleflags",flaglist)
def export_obj(self,obj):
plCameraBrain1_Fixed.export_obj(self,obj)
# -------- Export based on blender object -------
# get the matrices
LocalToWorld=hsMatrix44()
m=getMatrix(obj)
m.transpose()
LocalToWorld.set(m)
# convert the clip-end to the Center point of the camera
if obj.getType() == 'Camera':
clip_end = obj.data.getClipEnd()
self.fCenter = Vertex(0,0,0 - clip_end) # camera points to local -Z
self.fCenter.transform(LocalToWorld)
self.fRadius = clip_end # always seems to define distance from camera to rotation point
# -------Continue based on AlcScript object ------
objscript = AlcScript.objects.Find(obj.name)
# ------ Conintue if it's set ------
flags = FindInDict(objscript,"camera.brain.circleflags",None)
if type(flags) == list:
self.fCircleFlags = 0
for flag in flags:
if flag.lower() in plCameraBrain1_Circle.ScriptCircleFlags:
self.fCircleFlags |= plCameraBrain1_Circle.ScriptCircleFlags[flag.lower()]
class plCameraBrain1_Avatar(plCameraBrain1):
def __init__(self,parent,name="unnamed",type=0x009E):
plCameraBrain1.__init__(self,parent,name,type)
# Set default flag...
self.fFlags.SetBit(plCameraBrain1.Flags["kMaintainLOS"])
# set the Camerabrain1 floats to match defaults for this brain type
self.fAccel = 10
self.fDecel = 10
self.fVelocity = 50
self.fPOAAccel = 10
self.fPOADecel = 10
self.fPOAVelocity = 50
self.fXPanLimit = 0
self.fZPanLimit = 0
self.fZoomRate = 0
self.fZoomMin = 0
self.fZoomMax = 0
#format
self.fOffset = Vertex(0,0,0)
def _Find(page,name):
return page.find(0x009E,name,0)
Find = staticmethod(_Find)
def _FindCreate(page,name):
return page.find(0x009E,name,1)
FindCreate = staticmethod(_FindCreate)
def changePageRaw(self,sid,did,stype,dtype):
plCameraBrain1.changePageRaw(self,sid,did,stype,dtype)
def read(self,stream):
plCameraBrain1.read(self,stream)
self.fOffset.read(stream)
def write(self,stream):
plCameraBrain1.write(self,stream)
self.fOffset.write(stream)
def import_obj(self,obj):
plCameraBrain1.import_obj(self,obj)
objscript = AlcScript.objects.FindCreate(obj.name)
StoreInDict(objscript,"camera.brain.type","avatar")
StoreInDict(objscript,"camera.brain.fpoffset","%f,%f,%f"%(float(self.fOffset.x),float(self.fOffset.y),float(self.fOffset.z)))
def export_obj(self,obj):
plCameraBrain1.export_obj(self,obj)
# ------ Obtain the AlcScript Object ------
objscript = AlcScript.objects.Find(obj.name)
# ------ Conintue if it's set ------
# AlcScript: camera.brain.offset = "<float X>,<float Y>,<float Z>"
offset = str(FindInDict(objscript,"camera.brain.offset","0,0,0"))
try:
X,Y,Z, = offset.split(',')
self.fOffset = Vertex(float(X),float(Y),float(Z))
except ValueError, detail:
print " Error parsing camera.brain.offset (Value:",offset,") : ",detail
class plCameraBrain1_FirstPerson(plCameraBrain1_Avatar):
def __init__(self,parent,name="unnamed",type=0x00B3):
plCameraBrain1_Avatar.__init__(self,parent,name,type)
def _Find(page,name):
return page.find(0x00B3,name,0)
Find = staticmethod(_Find)
def _FindCreate(page,name):
return page.find(0x00B3,name,1)
FindCreate = staticmethod(_FindCreate)
def changePageRaw(self,sid,did,stype,dtype):
plCameraBrain1_Avatar.changePageRaw(self,sid,did,stype,dtype)
def read(self,stream):
plCameraBrain1_Avatar.read(self,stream)
def write(self,stream):
plCameraBrain1_Avatar.write(self,stream)
def import_obj(self,obj):
plCameraBrain1_Avatar.import_obj(self,obj)
StoreInDict(objscript,"camera.brain.type","firstperson")
def export_obj(self,obj):
plCameraBrain1_Avatar.export_obj(self,obj)
class plPostEffectMod(plSingleModifier):
def __init__(self,parent,name="unnamed",type=0x007A):
plSingleModifier.__init__(self,parent,name,type)
self.fState = hsBitVector()
self.fHither = 1.0
self.fYon = 100.0
self.fFOVX = 45.00
self.fFOVY = 33.75
self.fNodeKey = UruObjectRef(self.getVersion())
self.fC2W = hsMatrix44()
self.fW2C = hsMatrix44()
def _Find(page,name):
return page.find(0x007A,name,0)
Find = staticmethod(_Find)
def _FindCreate(page,name):
return page.find(0x007A,name,1)
FindCreate = staticmethod(_FindCreate)
def read(self,stream):
plSingleModifier.read(self,stream)
self.fState.read(stream)
self.fHither = stream.ReadFloat()
self.fYon - stream.ReadFloat()
self.fFOVX = stream.ReadFloat()
self.fFOVY = stream.ReadFloat()
self.fNodeKey.read(stream)
self.fW2C.read(stream)
self.fC2W.read(stream)
def write(self,stream):
plSingleModifier.write(self,stream)
self.fState.write(stream)
stream.WriteFloat(self.fHither)
stream.WriteFloat(self.fYon)
stream.WriteFloat(self.fFOVX)
stream.WriteFloat(self.fFOVY)
self.fNodeKey.write(stream)
self.fW2C.write(stream)
self.fC2W.write(stream)
def export_obj(self, obj, sceneNode):
script = AlcScript.objects.Find(obj.name)
m = getMatrix(obj)
m.transpose()
self.fC2W.set(m)
m.invert()
self.fW2C.set(m)
self.fNodeKey = sceneNode
self.fHither = float(FindInDict(script, "camera.hither", 1.0))
self.fYon = float(FindInDict(script, "camera.yon", 100.0))<|fim▁end|>
| |
<|file_name|>stereo.hpp<|end_file_name|><|fim▁begin|>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#ifndef __OPENCV_STEREO_HPP__
#define __OPENCV_STEREO_HPP__
#include "opencv2/core.hpp"
#include "opencv2/stereo/descriptor.hpp"
#include <opencv2/stereo/quasi_dense_stereo.hpp>
/**
@defgroup stereo Stereo Correspondance Algorithms
*/
namespace cv
{
namespace stereo
{
//! @addtogroup stereo
//! @{
/** @brief Filters off small noise blobs (speckles) in the disparity map
@param img The input 16-bit signed disparity image
@param newVal The disparity value used to paint-off the speckles
@param maxSpeckleSize The maximum speckle size to consider it a speckle. Larger blobs are not
affected by the algorithm
@param maxDiff Maximum difference between neighbor disparity pixels to put them into the same
blob. Note that since StereoBM, StereoSGBM and may be other algorithms return a fixed-point
disparity map, where disparity values are multiplied by 16, this scale factor should be taken into
account when specifying this parameter value.
@param buf The optional temporary buffer to avoid memory allocation within the function.
*/
/** @brief The base class for stereo correspondence algorithms.
*/
class StereoMatcher : public Algorithm
{
public:
enum { DISP_SHIFT = 4,
DISP_SCALE = (1 << DISP_SHIFT)
};
/** @brief Computes disparity map for the specified stereo pair
@param left Left 8-bit single-channel image.
@param right Right image of the same size and the same type as the left one.
@param disparity Output disparity map. It has the same size as the input images. Some algorithms,
like StereoBM or StereoSGBM compute 16-bit fixed-point disparity map (where each disparity value
has 4 fractional bits), whereas other algorithms output 32-bit floating-point disparity map.
*/
virtual void compute( InputArray left, InputArray right,
OutputArray disparity ) = 0;
virtual int getMinDisparity() const = 0;
virtual void setMinDisparity(int minDisparity) = 0;
virtual int getNumDisparities() const = 0;
virtual void setNumDisparities(int numDisparities) = 0;
virtual int getBlockSize() const = 0;
virtual void setBlockSize(int blockSize) = 0;
virtual int getSpeckleWindowSize() const = 0;
virtual void setSpeckleWindowSize(int speckleWindowSize) = 0;
virtual int getSpeckleRange() const = 0;
virtual void setSpeckleRange(int speckleRange) = 0;
virtual int getDisp12MaxDiff() const = 0;
virtual void setDisp12MaxDiff(int disp12MaxDiff) = 0;
};
//!speckle removal algorithms. These algorithms have the purpose of removing small regions
enum {
CV_SPECKLE_REMOVAL_ALGORITHM, CV_SPECKLE_REMOVAL_AVG_ALGORITHM
};
//!subpixel interpolationm methods for disparities.
enum{
CV_QUADRATIC_INTERPOLATION, CV_SIMETRICV_INTERPOLATION
};
/** @brief Class for computing stereo correspondence using the block matching algorithm, introduced and
contributed to OpenCV by K. Konolige.
*/
class StereoBinaryBM : public StereoMatcher
{
public:
enum { PREFILTER_NORMALIZED_RESPONSE = 0,
PREFILTER_XSOBEL = 1
};
virtual int getPreFilterType() const = 0;
virtual void setPreFilterType(int preFilterType) = 0;
virtual int getPreFilterSize() const = 0;
virtual void setPreFilterSize(int preFilterSize) = 0;
virtual int getPreFilterCap() const = 0;
virtual void setPreFilterCap(int preFilterCap) = 0;
virtual int getTextureThreshold() const = 0;
virtual void setTextureThreshold(int textureThreshold) = 0;
virtual int getUniquenessRatio() const = 0;
virtual void setUniquenessRatio(int uniquenessRatio) = 0;
virtual int getSmallerBlockSize() const = 0;
virtual void setSmallerBlockSize(int blockSize) = 0;
virtual int getScalleFactor() const = 0 ;
virtual void setScalleFactor(int factor) = 0;
virtual int getSpekleRemovalTechnique() const = 0 ;
virtual void setSpekleRemovalTechnique(int factor) = 0;
virtual bool getUsePrefilter() const = 0 ;
virtual void setUsePrefilter(bool factor) = 0;
virtual int getBinaryKernelType() const = 0;
virtual void setBinaryKernelType(int value) = 0;
virtual int getAgregationWindowSize() const = 0;
virtual void setAgregationWindowSize(int value) = 0;
/** @brief Creates StereoBM object
@param numDisparities the disparity search range. For each pixel algorithm will find the best
disparity from 0 (default minimum disparity) to numDisparities. The search range can then be
shifted by changing the minimum disparity.
@param blockSize the linear size of the blocks compared by the algorithm. The size should be odd
(as the block is centered at the current pixel). Larger block size implies smoother, though less
accurate disparity map. Smaller block size gives more detailed disparity map, but there is higher
chance for algorithm to find a wrong correspondence.
The function create StereoBM object. You can then call StereoBM::compute() to compute disparity for
a specific stereo pair.
*/
CV_EXPORTS static Ptr< cv::stereo::StereoBinaryBM > create(int numDisparities = 0, int blockSize = 9);
};
/** @brief The class implements the modified H. Hirschmuller algorithm @cite HH08 that differs from the original
one as follows:
- By default, the algorithm is single-pass, which means that you consider only 5 directions
instead of 8. Set mode=StereoSGBM::MODE_HH in createStereoSGBM to run the full variant of the
algorithm but beware that it may consume a lot of memory.
- The algorithm matches blocks, not individual pixels. Though, setting blockSize=1 reduces the
blocks to single pixels.
- Mutual information cost function is not implemented. Instead, a simpler Birchfield-Tomasi
sub-pixel metric from @cite BT98 is used. Though, the color images are supported as well.
- Some pre- and post- processing steps from K. Konolige algorithm StereoBM are included, for
example: pre-filtering (StereoBM::PREFILTER_XSOBEL type) and post-filtering (uniqueness
check, quadratic interpolation and speckle filtering).
@note
- (Python) An example illustrating the use of the StereoSGBM matching algorithm can be found
at opencv_source_code/samples/python2/stereo_match.py
*/
class StereoBinarySGBM : public StereoMatcher
{
public:
enum
{
MODE_SGBM = 0,
MODE_HH = 1
};
virtual int getPreFilterCap() const = 0;
virtual void setPreFilterCap(int preFilterCap) = 0;
virtual int getUniquenessRatio() const = 0;
virtual void setUniquenessRatio(int uniquenessRatio) = 0;
virtual int getP1() const = 0;
virtual void setP1(int P1) = 0;
virtual int getP2() const = 0;
virtual void setP2(int P2) = 0;
virtual int getMode() const = 0;
virtual void setMode(int mode) = 0;
virtual int getSpekleRemovalTechnique() const = 0 ;
virtual void setSpekleRemovalTechnique(int factor) = 0;
virtual int getBinaryKernelType() const = 0;
virtual void setBinaryKernelType(int value) = 0;
virtual int getSubPixelInterpolationMethod() const = 0;
virtual void setSubPixelInterpolationMethod(int value) = 0;
/** @brief Creates StereoSGBM object
@param minDisparity Minimum possible disparity value. Normally, it is zero but sometimes
rectification algorithms can shift images, so this parameter needs to be adjusted accordingly.
@param numDisparities Maximum disparity minus minimum disparity. The value is always greater than
zero. In the current implementation, this parameter must be divisible by 16.
@param blockSize Matched block size. It must be an odd number \>=1 . Normally, it should be
somewhere in the 3..11 range.
@param P1 The first parameter controlling the disparity smoothness.This parameter is used for the case of slanted surfaces (not fronto parallel).
@param P2 The second parameter controlling the disparity smoothness.This parameter is used for "solving" the depth discontinuities problem.
The larger the values are, the smoother the disparity is. P1 is the penalty on the disparity change by plus or minus 1
between neighbor pixels. P2 is the penalty on the disparity change by more than 1 between neighbor
pixels. The algorithm requires P2 \> P1 . See stereo_match.cpp sample where some reasonably good
P1 and P2 values are shown (like 8\*number_of_image_channels\*SADWindowSize\*SADWindowSize and
32\*number_of_image_channels\*SADWindowSize\*SADWindowSize , respectively).
@param disp12MaxDiff Maximum allowed difference (in integer pixel units) in the left-right
disparity check. Set it to a non-positive value to disable the check.
@param preFilterCap Truncation value for the prefiltered image pixels. The algorithm first
computes x-derivative at each pixel and clips its value by [-preFilterCap, preFilterCap] interval.
The result values are passed to the Birchfield-Tomasi pixel cost function.
@param uniquenessRatio Margin in percentage by which the best (minimum) computed cost function
value should "win" the second best value to consider the found match correct. Normally, a value
within the 5-15 range is good enough.
@param speckleWindowSize Maximum size of smooth disparity regions to consider their noise speckles
and invalidate. Set it to 0 to disable speckle filtering. Otherwise, set it somewhere in the
50-200 range.
@param speckleRange Maximum disparity variation within each connected component. If you do speckle
filtering, set the parameter to a positive value, it will be implicitly multiplied by 16.
Normally, 1 or 2 is good enough.
@param mode Set it to StereoSGBM::MODE_HH to run the full-scale two-pass dynamic programming
algorithm. It will consume O(W\*H\*numDisparities) bytes, which is large for 640x480 stereo and
huge for HD-size pictures. By default, it is set to false .
The first constructor initializes StereoSGBM with all the default parameters. So, you only have to
set StereoSGBM::numDisparities at minimum. The second constructor enables you to set each parameter
to a custom value.
*/<|fim▁hole|> int speckleWindowSize = 400, int speckleRange = 200,
int mode = StereoBinarySGBM::MODE_SGBM);
};
//! @}
}//stereo
} // cv
#endif<|fim▁end|>
|
CV_EXPORTS static Ptr<cv::stereo::StereoBinarySGBM> create(int minDisparity, int numDisparities, int blockSize,
int P1 = 100, int P2 = 1000, int disp12MaxDiff = 1,
int preFilterCap = 0, int uniquenessRatio = 5,
|
<|file_name|>image.cc<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2006 Samuel Weinig ([email protected])
* Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
*/
#include "third_party/blink/renderer/platform/graphics/image.h"
#include <math.h>
#include <tuple>
#include "base/numerics/checked_math.h"
#include "build/build_config.h"
#include "cc/tiles/software_image_decode_cache.h"
#include "third_party/blink/public/mojom/webpreferences/web_preferences.mojom-blink.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_data.h"
#include "third_party/blink/renderer/platform/geometry/float_rect.h"
#include "third_party/blink/renderer/platform/geometry/float_size.h"
#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/graphics/bitmap_image.h"
#include "third_party/blink/renderer/platform/graphics/dark_mode_filter_helper.h"
#include "third_party/blink/renderer/platform/graphics/dark_mode_image_cache.h"
#include "third_party/blink/renderer/platform/graphics/dark_mode_image_classifier.h"
#include "third_party/blink/renderer/platform/graphics/deferred_image_decoder.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_image.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_recorder.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_shader.h"
#include "third_party/blink/renderer/platform/graphics/scoped_interpolation_quality.h"
#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/shared_buffer.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/skia_conversions.h"
namespace blink {
Image::Image(ImageObserver* observer, bool is_multipart)
: image_observer_disabled_(false),
image_observer_(observer),
stable_image_id_(PaintImage::GetNextId()),
is_multipart_(is_multipart) {}
Image::~Image() = default;
Image* Image::NullImage() {
DCHECK(IsMainThread());
DEFINE_STATIC_REF(Image, null_image, (BitmapImage::Create()));
return null_image;
}
// static
cc::ImageDecodeCache& Image::SharedCCDecodeCache(SkColorType color_type) {
// This denotes the allocated locked memory budget for the cache used for
// book-keeping. The cache indicates when the total memory locked exceeds this
// budget in cc::DecodedDrawImage.
DCHECK(color_type == kN32_SkColorType || color_type == kRGBA_F16_SkColorType);
static const size_t kLockedMemoryLimitBytes = 64 * 1024 * 1024;
if (color_type == kRGBA_F16_SkColorType) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
cc::SoftwareImageDecodeCache, image_decode_cache,
(kRGBA_F16_SkColorType, kLockedMemoryLimitBytes,
PaintImage::kDefaultGeneratorClientId));
return image_decode_cache;
}
DEFINE_THREAD_SAFE_STATIC_LOCAL(cc::SoftwareImageDecodeCache,
image_decode_cache,
(kN32_SkColorType, kLockedMemoryLimitBytes,
PaintImage::kDefaultGeneratorClientId));
return image_decode_cache;
}
scoped_refptr<Image> Image::LoadPlatformResource(
int resource_id,
ui::ResourceScaleFactor scale_factor) {
const WebData& resource =
Platform::Current()->GetDataResource(resource_id, scale_factor);
if (resource.IsEmpty())
return Image::NullImage();
scoped_refptr<Image> image = BitmapImage::Create();
image->SetData(resource, true);
return image;
}
// static
PaintImage Image::ResizeAndOrientImage(
const PaintImage& image,
ImageOrientation orientation,
gfx::Vector2dF image_scale,
float opacity,
InterpolationQuality interpolation_quality) {
gfx::Size size(image.width(), image.height());
size = gfx::ScaleToFlooredSize(size, image_scale.x(), image_scale.y());
AffineTransform transform;
if (orientation != ImageOrientationEnum::kDefault) {
if (orientation.UsesWidthAsHeight())
size.Transpose();
transform *= orientation.TransformFromDefault(gfx::SizeF(size));
}
transform.ScaleNonUniform(image_scale.x(), image_scale.y());
if (size.IsEmpty())
return PaintImage();
if (transform.IsIdentity() && opacity == 1) {
// Nothing to adjust, just use the original.
DCHECK_EQ(image.width(), size.width());
DCHECK_EQ(image.height(), size.height());
return image;
}
const SkImageInfo info =
SkImageInfo::MakeN32(size.width(), size.height(), kPremul_SkAlphaType,
SkColorSpace::MakeSRGB());
sk_sp<SkSurface> surface = SkSurface::MakeRaster(info);
if (!surface)
return PaintImage();
SkPaint paint;
DCHECK_GE(opacity, 0);
DCHECK_LE(opacity, 1);
paint.setAlpha(opacity * 255);
SkSamplingOptions sampling;
if (interpolation_quality != kInterpolationNone)
sampling = SkSamplingOptions(SkCubicResampler::CatmullRom());
SkCanvas* canvas = surface->getCanvas();
canvas->concat(AffineTransformToSkMatrix(transform));
canvas->drawImage(image.GetSwSkImage(), 0, 0, sampling, &paint);
return PaintImageBuilder::WithProperties(std::move(image))
.set_image(surface->makeImageSnapshot(), PaintImage::GetNextContentId())
.TakePaintImage();
}
Image::SizeAvailability Image::SetData(scoped_refptr<SharedBuffer> data,
bool all_data_received) {
encoded_image_data_ = std::move(data);
if (!encoded_image_data_.get())
return kSizeAvailable;
size_t length = encoded_image_data_->size();
if (!length)
return kSizeAvailable;
return DataChanged(all_data_received);
}
String Image::FilenameExtension() const {
return String();
}
namespace {
sk_sp<PaintShader> CreatePatternShader(const PaintImage& image,
const SkMatrix& shader_matrix,
const SkSamplingOptions& sampling,
bool should_antialias,
const gfx::SizeF& spacing,
SkTileMode tmx,
SkTileMode tmy,
const gfx::Rect& subset_rect) {
if (spacing.IsZero() &&
subset_rect == gfx::Rect(image.width(), image.height())) {
return PaintShader::MakeImage(image, tmx, tmy, &shader_matrix);
}
// Arbitrary tiling is currently only supported for SkPictureShader, so we use
// that instead of a plain bitmap shader to implement spacing.
const SkRect tile_rect =
SkRect::MakeWH(subset_rect.width() + spacing.width(),
subset_rect.height() + spacing.height());
PaintRecorder recorder;
cc::PaintCanvas* canvas = recorder.beginRecording(tile_rect);
PaintFlags flags;
flags.setAntiAlias(should_antialias);
canvas->drawImageRect(
image, gfx::RectToSkRect(subset_rect),
SkRect::MakeWH(subset_rect.width(), subset_rect.height()), sampling,
&flags, SkCanvas::kStrict_SrcRectConstraint);
return PaintShader::MakePaintRecord(recorder.finishRecordingAsPicture(),
tile_rect, tmx, tmy, &shader_matrix);
}
SkTileMode ComputeTileMode(float left, float right, float min, float max) {
DCHECK(left < right);
return left >= min && right <= max ? SkTileMode::kClamp : SkTileMode::kRepeat;
}
} // anonymous namespace
void Image::DrawPattern(GraphicsContext& context,
const cc::PaintFlags& base_flags,
const gfx::RectF& dest_rect,
const ImageTilingInfo& tiling_info,
const ImageDrawOptions& draw_options) {
TRACE_EVENT0("skia", "Image::drawPattern");
if (dest_rect.IsEmpty())
return; // nothing to draw
PaintImage image = PaintImageForCurrentFrame();
if (!image)
return; // nothing to draw
// Fetch orientation data if needed.
ImageOrientation orientation = ImageOrientationEnum::kDefault;
if (draw_options.respect_orientation)
orientation = CurrentFrameOrientation();
// |tiling_info.image_rect| is in source image space, unscaled but oriented.
// image-resolution information is baked into |tiling_info.scale|,
// so we do not want to use it in computing the subset. That requires
// explicitly applying orientation here.
gfx::Rect subset_rect = gfx::ToEnclosingRect(tiling_info.image_rect);
gfx::Size oriented_image_size(image.width(), image.height());
if (orientation.UsesWidthAsHeight())
oriented_image_size.Transpose();
subset_rect.Intersect(gfx::Rect(oriented_image_size));
if (subset_rect.IsEmpty())
return; // nothing to draw
// Apply image orientation, if necessary
if (orientation != ImageOrientationEnum::kDefault)
image = ResizeAndOrientImage(image, orientation);
// We also need to translate it such that the origin of the pattern is the
// origin of the destination rect, which is what Blink expects. Skia uses
// the coordinate system origin as the base for the pattern. If Blink wants
// a shifted image, it will shift it from there using the localMatrix.
gfx::RectF tile_rect(subset_rect);
tile_rect.Scale(tiling_info.scale.x(), tiling_info.scale.y());
tile_rect.Offset(tiling_info.phase.OffsetFromOrigin());
tile_rect.Outset(0, 0, tiling_info.spacing.width(),
tiling_info.spacing.height());
SkMatrix local_matrix;
local_matrix.setTranslate(tile_rect.x(), tile_rect.y());
// Apply the scale to have the subset correctly fill the destination.
local_matrix.preScale(tiling_info.scale.x(), tiling_info.scale.y());
const auto tmx = ComputeTileMode(dest_rect.x(), dest_rect.right(),
tile_rect.x(), tile_rect.right());
const auto tmy = ComputeTileMode(dest_rect.y(), dest_rect.bottom(),
tile_rect.y(), tile_rect.bottom());
// Fetch this now as subsetting may swap the image.
auto image_id = image.stable_id();
SkSamplingOptions sampling_to_use =
context.ComputeSamplingOptions(this, dest_rect, gfx::RectF(subset_rect));
sk_sp<PaintShader> tile_shader = CreatePatternShader(
image, local_matrix, sampling_to_use, context.ShouldAntialias(),
gfx::SizeF(tiling_info.spacing.width() / tiling_info.scale.x(),
tiling_info.spacing.height() / tiling_info.scale.y()),
tmx, tmy, subset_rect);
// If the shader could not be instantiated (e.g. non-invertible matrix),
// draw transparent.
// Note: we can't simply bail, because of arbitrary blend mode.
PaintFlags flags(base_flags);
flags.setColor(tile_shader ? SK_ColorBLACK : SK_ColorTRANSPARENT);
flags.setShader(std::move(tile_shader));
if (draw_options.apply_dark_mode) {
DarkModeFilter* dark_mode_filter = draw_options.dark_mode_filter;
DarkModeFilterHelper::ApplyToImageIfNeeded(*dark_mode_filter, this, &flags,
gfx::RectToSkRect(subset_rect),
gfx::RectFToSkRect(dest_rect));
}
context.DrawRect(gfx::RectFToSkRect(dest_rect), flags,
AutoDarkMode::Disabled());
StartAnimation();
if (CurrentFrameIsLazyDecoded()) {
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
"Draw LazyPixelRef", TRACE_EVENT_SCOPE_THREAD,
"LazyPixelRef", image_id);
}
}
mojom::blink::ImageAnimationPolicy Image::AnimationPolicy() {
return mojom::blink::ImageAnimationPolicy::kImageAnimationPolicyAllowed;
}
scoped_refptr<Image> Image::ImageForDefaultFrame() {
scoped_refptr<Image> image(this);
return image;
}
PaintImageBuilder Image::CreatePaintImageBuilder() {
auto animation_type = MaybeAnimated() ? PaintImage::AnimationType::ANIMATED
: PaintImage::AnimationType::STATIC;
return PaintImageBuilder::WithDefault()
.set_id(stable_image_id_)
.set_animation_type(animation_type)
.set_is_multipart(is_multipart_);
}
bool Image::ApplyShader(PaintFlags& flags,
const SkMatrix& local_matrix,
const gfx::RectF& dst_rect,
const gfx::RectF& src_rect,
const ImageDrawOptions& draw_options) {
// Default shader impl: attempt to build a shader based on the current frame<|fim▁hole|>
if (draw_options.apply_dark_mode) {
DarkModeFilter* dark_mode_filter = draw_options.dark_mode_filter;
DarkModeFilterHelper::ApplyToImageIfNeeded(*dark_mode_filter, this, &flags,
gfx::RectFToSkRect(src_rect),
gfx::RectFToSkRect(dst_rect));
}
flags.setShader(PaintShader::MakeImage(image, SkTileMode::kClamp,
SkTileMode::kClamp, &local_matrix));
if (!flags.HasShader())
return false;
// Animation is normally refreshed in draw() impls, which we don't call when
// painting via shaders.
StartAnimation();
return true;
}
SkBitmap Image::AsSkBitmapForCurrentFrame(
RespectImageOrientationEnum respect_image_orientation) {
PaintImage paint_image = PaintImageForCurrentFrame();
if (!paint_image)
return {};
if (auto* bitmap_image = DynamicTo<BitmapImage>(this)) {
const gfx::Size paint_image_size(paint_image.width(), paint_image.height());
const gfx::Size density_corrected_size =
bitmap_image->DensityCorrectedSize();
ImageOrientation orientation = ImageOrientationEnum::kDefault;
if (respect_image_orientation == kRespectImageOrientation)
orientation = bitmap_image->CurrentFrameOrientation();
gfx::Vector2dF image_scale(1, 1);
if (density_corrected_size != paint_image_size) {
image_scale = gfx::Vector2dF(
density_corrected_size.width() / paint_image_size.width(),
density_corrected_size.height() / paint_image_size.height());
}
paint_image = ResizeAndOrientImage(paint_image, orientation, image_scale);
if (!paint_image)
return {};
}
sk_sp<SkImage> sk_image = paint_image.GetSwSkImage();
if (!sk_image)
return {};
SkBitmap bitmap;
sk_image->asLegacyBitmap(&bitmap);
return bitmap;
}
DarkModeImageCache* Image::GetDarkModeImageCache() {
if (!dark_mode_image_cache_)
dark_mode_image_cache_ = std::make_unique<DarkModeImageCache>();
return dark_mode_image_cache_.get();
}
gfx::RectF Image::CorrectSrcRectForImageOrientation(gfx::SizeF image_size,
gfx::RectF src_rect) const {
ImageOrientation orientation = CurrentFrameOrientation();
DCHECK(orientation != ImageOrientationEnum::kDefault);
AffineTransform forward_map = orientation.TransformFromDefault(image_size);
AffineTransform inverse_map = forward_map.Inverse();
return inverse_map.MapRect(src_rect);
}
} // namespace blink<|fim▁end|>
|
// SkImage.
PaintImage image = PaintImageForCurrentFrame();
if (!image)
return false;
|
<|file_name|>font.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/. */
//! Generic types for font stuff.
use cssparser::Parser;
use num_traits::One;
use parser::{Parse, ParserContext};
use std::fmt::{self, Write};
use style_traits::{CssWriter, ParseError, ToCss};
use values::distance::{ComputeSquaredDistance, SquaredDistance};
use values::specified::font::FontTag;
/// https://drafts.csswg.org/css-fonts-4/#feature-tag-value
#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, ToComputedValue)]
pub struct FeatureTagValue<Integer> {
/// A four-character tag, packed into a u32 (one byte per character).
pub tag: FontTag,
/// The actual value.
pub value: Integer,
}
impl<Integer> ToCss for FeatureTagValue<Integer>
where
Integer: One + ToCss + PartialEq,
{
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
self.tag.to_css(dest)?;
// Don't serialize the default value.
if self.value != Integer::one() {
dest.write_char(' ')?;
self.value.to_css(dest)?;
}
Ok(())
}
}
/// Variation setting for a single feature, see:
///
/// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def
#[derive(Animate, Clone, Debug, Eq, MallocSizeOf, PartialEq, ToComputedValue, ToCss)]
pub struct VariationValue<Number> {
/// A four-character tag, packed into a u32 (one byte per character).
#[animation(constant)]
pub tag: FontTag,
/// The actual value.
pub value: Number,<|fim▁hole|>impl<Number> ComputeSquaredDistance for VariationValue<Number>
where
Number: ComputeSquaredDistance,
{
#[inline]
fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> {
if self.tag != other.tag {
return Err(());
}
self.value.compute_squared_distance(&other.value)
}
}
/// A value both for font-variation-settings and font-feature-settings.
#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, ToComputedValue)]
pub struct FontSettings<T>(pub Box<[T]>);
impl<T> FontSettings<T> {
/// Default value of font settings as `normal`.
#[inline]
pub fn normal() -> Self {
FontSettings(vec![].into_boxed_slice())
}
}
impl<T: Parse> Parse for FontSettings<T> {
/// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-feature-settings
/// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
if input.try(|i| i.expect_ident_matching("normal")).is_ok() {
return Ok(Self::normal());
}
Ok(FontSettings(
input.parse_comma_separated(|i| T::parse(context, i))?.into_boxed_slice()
))
}
}
impl<T: ToCss> ToCss for FontSettings<T> {
/// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-feature-settings
/// https://drafts.csswg.org/css-fonts-4/#font-variation-settings-def
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
if self.0.is_empty() {
return dest.write_str("normal");
}
let mut first = true;
for item in self.0.iter() {
if !first {
dest.write_str(", ")?;
}
first = false;
item.to_css(dest)?;
}
Ok(())
}
}<|fim▁end|>
|
}
|
<|file_name|>get_all_labels.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
#
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This code example gets all labels.
To create labels, run create_labels.py. This feature is only available to DFP
premium solution networks."""
# Import appropriate modules from the client library.
from googleads import dfp
<|fim▁hole|> label_service = client.GetService('LabelService', version='v201502')
# Create statement to get all labels
statement = dfp.FilterStatement()
# Get labels by statement.
while True:
response = label_service.getLabelsByStatement(statement.ToStatement())
if 'results' in response:
# Display results.
for label in response['results']:
print ('Label with id \'%s\' and name \'%s\' was found.'
% (label['id'], label['name']))
statement.offset += dfp.SUGGESTED_PAGE_LIMIT
else:
break
print '\nNumber of results found: %s' % response['totalResultSetSize']
if __name__ == '__main__':
# Initialize client object.
dfp_client = dfp.DfpClient.LoadFromStorage()
main(dfp_client)<|fim▁end|>
|
def main(client):
# Initialize appropriate service.
|
<|file_name|>dialogflow_generated_dialogflow_v2_entity_types_batch_create_entities_async.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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.
#<|fim▁hole|># NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-dialogflow
# [START dialogflow_generated_dialogflow_v2_EntityTypes_BatchCreateEntities_async]
from google.cloud import dialogflow_v2
async def sample_batch_create_entities():
# Create a client
client = dialogflow_v2.EntityTypesAsyncClient()
# Initialize request argument(s)
entities = dialogflow_v2.Entity()
entities.value = "value_value"
entities.synonyms = ['synonyms_value_1', 'synonyms_value_2']
request = dialogflow_v2.BatchCreateEntitiesRequest(
parent="parent_value",
entities=entities,
)
# Make the request
operation = client.batch_create_entities(request=request)
print("Waiting for operation to complete...")
response = await operation.result()
# Handle the response
print(response)
# [END dialogflow_generated_dialogflow_v2_EntityTypes_BatchCreateEntities_async]<|fim▁end|>
|
# Generated code. DO NOT EDIT!
#
# Snippet for BatchCreateEntities
|
<|file_name|>co.py<|end_file_name|><|fim▁begin|>from django.contrib.localflavor.co.forms import CODepartmentSelect
from utils import LocalFlavorTestCase
class COLocalFlavorTests(LocalFlavorTestCase):
def test_CODepartmentSelect(self):
d = CODepartmentSelect()<|fim▁hole|><option value="ATL">Atl\xe1ntico</option>
<option value="DC">Bogot\xe1</option>
<option value="BOL">Bol\xedvar</option>
<option value="BOY">Boyac\xe1</option>
<option value="CAL">Caldas</option>
<option value="CAQ">Caquet\xe1</option>
<option value="CAS">Casanare</option>
<option value="CAU">Cauca</option>
<option value="CES">Cesar</option>
<option value="CHO">Choc\xf3</option>
<option value="COR" selected="selected">C\xf3rdoba</option>
<option value="CUN">Cundinamarca</option>
<option value="GUA">Guain\xeda</option>
<option value="GUV">Guaviare</option>
<option value="HUI">Huila</option>
<option value="LAG">La Guajira</option>
<option value="MAG">Magdalena</option>
<option value="MET">Meta</option>
<option value="NAR">Nari\xf1o</option>
<option value="NSA">Norte de Santander</option>
<option value="PUT">Putumayo</option>
<option value="QUI">Quind\xedo</option>
<option value="RIS">Risaralda</option>
<option value="SAP">San Andr\xe9s and Providencia</option>
<option value="SAN">Santander</option>
<option value="SUC">Sucre</option>
<option value="TOL">Tolima</option>
<option value="VAC">Valle del Cauca</option>
<option value="VAU">Vaup\xe9s</option>
<option value="VID">Vichada</option>
</select>"""
self.assertEqual(d.render('department', 'COR'), out)<|fim▁end|>
|
out = u"""<select name="department">
<option value="AMA">Amazonas</option>
<option value="ANT">Antioquia</option>
<option value="ARA">Arauca</option>
|
<|file_name|>basevariantprotocol.cpp<|end_file_name|><|fim▁begin|>/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei ([email protected])
*
* This file is part of crtmpserver.
* crtmpserver 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.
*
* crtmpserver 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 crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAS_PROTOCOL_VAR
#include "protocols/variant/basevariantprotocol.h"
#include "protocols/variant/basevariantappprotocolhandler.h"
#include "protocols/http/outboundhttpprotocol.h"
#include "application/baseclientapplication.h"
#include "protocols/protocolmanager.h"
BaseVariantProtocol::BaseVariantProtocol(uint64_t type)
: BaseProtocol(type) {
_pProtocolHandler = NULL;
}
BaseVariantProtocol::~BaseVariantProtocol() {
}
bool BaseVariantProtocol::Initialize(Variant ¶meters) {
return true;
}
void BaseVariantProtocol::SetApplication(BaseClientApplication *pApplication) {
BaseProtocol::SetApplication(pApplication);
if (pApplication != NULL) {
_pProtocolHandler = (BaseVariantAppProtocolHandler *)
pApplication->GetProtocolHandler(this);
} else {
_pProtocolHandler = NULL;
}
}
IOBuffer * BaseVariantProtocol::GetOutputBuffer() {
if (GETAVAILABLEBYTESCOUNT(_outputBuffer) == 0)
return NULL;
return &_outputBuffer;
}
bool BaseVariantProtocol::AllowFarProtocol(uint64_t type) {
return type == PT_TCP
|| type == PT_OUTBOUND_HTTP
|| type == PT_INBOUND_HTTP;
}
bool BaseVariantProtocol::AllowNearProtocol(uint64_t type) {
ASSERT("This is an endpoint protocol");
return false;
}
bool BaseVariantProtocol::SignalInputData(int32_t recvAmount) {
ASSERT("OPERATION NOT SUPPORTED");
return false;
}
bool BaseVariantProtocol::SignalInputData(IOBuffer &buffer) {
if (_pProtocolHandler == NULL) {
FATAL("This protocol is not registered to any application yet");
return false;
}
if (_pFarProtocol->GetType() == PT_OUTBOUND_HTTP
|| _pFarProtocol->GetType() == PT_INBOUND_HTTP) {
#ifdef HAS_PROTOCOL_HTTP
//1. This is a HTTP based transfer. We only start doing stuff
//after a complete request is made.
BaseHTTPProtocol *pHTTPProtocol = (BaseHTTPProtocol *) _pFarProtocol;
if (!pHTTPProtocol->TransferCompleted())
return true;
if (!Deserialize(GETIBPOINTER(buffer), pHTTPProtocol->GetContentLength(),
_lastReceived)) {
FATAL("Unable to deserialize content");
return false;
}
buffer.Ignore(pHTTPProtocol->GetContentLength());
_lastReceived.Compact();
return _pProtocolHandler->ProcessMessage(this, _lastSent, _lastReceived);
#else
FATAL("HTTP protocol not supported");
return false;
#endif /* HAS_PROTOCOL_HTTP */
} else if (_pFarProtocol->GetType() == PT_TCP) {
while (GETAVAILABLEBYTESCOUNT(buffer) > 4) {
uint32_t size = ENTOHLP(GETIBPOINTER(buffer));
if (size > 1024 * 128) {
FATAL("Size too big: %u", size);
return false;
}
if (GETAVAILABLEBYTESCOUNT(buffer) < size + 4) {
FINEST("Need more data");
return true;
}
if (!Deserialize(GETIBPOINTER(buffer) + 4, size, _lastReceived)) {
FATAL("Unable to deserialize variant");
return false;
}
buffer.Ignore(size + 4);
_lastReceived.Compact();
if (!_pProtocolHandler->ProcessMessage(this, _lastSent, _lastReceived)) {
FATAL("Unable to process message");
return false;
}
}
return true;
} else {
FATAL("Invalid protocol stack");
return false;
}
}
bool BaseVariantProtocol::Send(Variant &variant) {
//1. Do we have a protocol?
if (_pFarProtocol == NULL) {
FATAL("This protocol is not linked");
return false;
}
//2. Save the variant
_lastSent = variant;
//3. Depending on the far protocol, we do different stuff
string rawContent = "";
switch (_pFarProtocol->GetType()) {
case PT_TCP:
{
//5. Serialize it
if (!Serialize(rawContent, variant)) {
FATAL("Unable to serialize variant");
return false;
}
_outputBuffer.ReadFromRepeat(0, 4);
uint32_t rawContentSize = rawContent.size();
EHTONLP(GETIBPOINTER(_outputBuffer), rawContentSize);
_outputBuffer.ReadFromString(rawContent);
//6. enqueue for outbound
return EnqueueForOutbound();
}
case PT_OUTBOUND_HTTP:
{
#ifdef HAS_PROTOCOL_HTTP
//7. This is a HTTP request. So, first things first: get the http protocol
OutboundHTTPProtocol *pHTTP = (OutboundHTTPProtocol *) _pFarProtocol;
//8. We wish to disconnect after the transfer is complete
pHTTP->SetDisconnectAfterTransfer(true);
//9. This will always be a POST
pHTTP->Method(HTTP_METHOD_POST);
//10. Our document and the host
pHTTP->Document(variant["document"]);
pHTTP->Host(variant["host"]);
//11. Serialize it
if (!Serialize(rawContent, variant["payload"])) {
FATAL("Unable to serialize variant");
return false;
}
_outputBuffer.ReadFromString(rawContent);
//12. enqueue for outbound
return EnqueueForOutbound();
#else
FATAL("HTTP protocol not supported");
return false;
#endif /* HAS_PROTOCOL_HTTP */
}
case PT_INBOUND_HTTP:
{
#ifdef HAS_PROTOCOL_HTTP
if (!Serialize(rawContent, variant)) {
FATAL("Unable to serialize variant");
return false;
}
_outputBuffer.ReadFromString(rawContent);
return EnqueueForOutbound();
#else
FATAL("HTTP protocol not supported");
return false;
#endif /* HAS_PROTOCOL_HTTP */
}
default:<|fim▁hole|> }
}
#endif /* HAS_PROTOCOL_VAR */<|fim▁end|>
|
{
ASSERT("We should not be here");
return false;
}
|
<|file_name|>d3-stack.js<|end_file_name|><|fim▁begin|>import Ember from 'ember';
import { stack } from 'd3-shape';
import addOptionsToStack from '../utils/add-options-to-stack';
export function d3Stack( [ data, args ], hash={}) {
return addOptionsToStack(stack(data, args), hash);
}
<|fim▁hole|><|fim▁end|>
|
export default Ember.Helper.helper(d3Stack);
|
<|file_name|>stylesheets.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/. */
use cssparser::{self, Parser as CssParser, SourcePosition};
use html5ever_atoms::{Namespace as NsAtom};
use media_queries::CSSErrorReporterTest;
use parking_lot::RwLock;
use selectors::parser::*;
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::borrow::ToOwned;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::AtomicBool;
use style::error_reporting::ParseErrorReporter;
use style::keyframes::{Keyframe, KeyframeSelector, KeyframePercentage};
use style::parser::ParserContextExtraData;
use style::properties::Importance;
use style::properties::{CSSWideKeyword, PropertyDeclaration, PropertyDeclarationBlock};
use style::properties::{DeclaredValue, longhands};
use style::properties::longhands::animation_play_state;
use style::stylesheets::{Origin, Namespaces};
use style::stylesheets::{Stylesheet, NamespaceRule, CssRule, CssRules, StyleRule, KeyframesRule};
use style::values::specified::{LengthOrPercentageOrAuto, Percentage};
pub fn block_from<I>(iterable: I) -> PropertyDeclarationBlock
where I: IntoIterator<Item=(PropertyDeclaration, Importance)> {
let mut block = PropertyDeclarationBlock::new();
for (d, i) in iterable {
block.push(d, i)
}
block
}
#[test]
fn test_parse_stylesheet() {
let css = r"
@namespace url(http://www.w3.org/1999/xhtml);
/* FIXME: only if scripting is enabled */
input[type=hidden i] {
display: block !important;
display: none !important;
display: inline;
--a: b !important;
--a: inherit !important;
--a: c;
}
html , body /**/ {
display: none;
display: block;
}
#d1 > .ok { background: blue; }
@keyframes foo {
from { width: 0% }
to {
width: 100%;
width: 50% !important; /* !important not allowed here */
animation-name: 'foo'; /* animation properties not allowed here */
animation-play-state: running; /* … except animation-play-state */
}
}";
let url = ServoUrl::parse("about::test").unwrap();
let stylesheet = Stylesheet::from_str(css, url.clone(), Origin::UserAgent, Default::default(),
None,
Box::new(CSSErrorReporterTest),
ParserContextExtraData::default());
let mut namespaces = Namespaces::default();
namespaces.default = Some(ns!(html));
let expected = Stylesheet {
origin: Origin::UserAgent,
media: Default::default(),
namespaces: RwLock::new(namespaces),
base_url: url,
dirty_on_viewport_size_change: AtomicBool::new(false),
disabled: AtomicBool::new(false),
rules: CssRules::new(vec![
CssRule::Namespace(Arc::new(RwLock::new(NamespaceRule {
prefix: None,
url: NsAtom::from("http://www.w3.org/1999/xhtml")
}))),
CssRule::Style(Arc::new(RwLock::new(StyleRule {
selectors: SelectorList(vec![
Selector {
complex_selector: Arc::new(ComplexSelector {
compound_selector: vec![
SimpleSelector::Namespace(Namespace {
prefix: None,
url: NsAtom::from("http://www.w3.org/1999/xhtml")
}),
SimpleSelector::LocalName(LocalName {
name: local_name!("input"),
lower_name: local_name!("input"),
}),
SimpleSelector::AttrEqual(AttrSelector {
name: local_name!("type"),
lower_name: local_name!("type"),
namespace: NamespaceConstraint::Specific(Namespace {
prefix: None,
url: ns!()
}),
}, "hidden".to_owned(), CaseSensitivity::CaseInsensitive)
],
next: None,
}),
pseudo_element: None,
specificity: (0 << 20) + (1 << 10) + (1 << 0),
},
]),
block: Arc::new(RwLock::new(block_from(vec![
(PropertyDeclaration::Display(DeclaredValue::Value(
longhands::display::SpecifiedValue::none)),
Importance::Important),
(PropertyDeclaration::Custom(Atom::from("a"),
DeclaredValue::CSSWideKeyword(CSSWideKeyword::Inherit)),
Importance::Important),
]))),
}))),
CssRule::Style(Arc::new(RwLock::new(StyleRule {
selectors: SelectorList(vec![
Selector {
complex_selector: Arc::new(ComplexSelector {
compound_selector: vec![
SimpleSelector::Namespace(Namespace {
prefix: None,
url: NsAtom::from("http://www.w3.org/1999/xhtml")
}),
SimpleSelector::LocalName(LocalName {
name: local_name!("html"),
lower_name: local_name!("html"),
}),
],
next: None,
}),
pseudo_element: None,
specificity: (0 << 20) + (0 << 10) + (1 << 0),
},
Selector {
complex_selector: Arc::new(ComplexSelector {
compound_selector: vec![
SimpleSelector::Namespace(Namespace {
prefix: None,
url: NsAtom::from("http://www.w3.org/1999/xhtml")
}),
SimpleSelector::LocalName(LocalName {
name: local_name!("body"),
lower_name: local_name!("body"),
}),
],
next: None,
}),
pseudo_element: None,
specificity: (0 << 20) + (0 << 10) + (1 << 0),
},
]),
block: Arc::new(RwLock::new(block_from(vec![
(PropertyDeclaration::Display(DeclaredValue::Value(
longhands::display::SpecifiedValue::block)),
Importance::Normal),
]))),
}))),
CssRule::Style(Arc::new(RwLock::new(StyleRule {
selectors: SelectorList(vec![
Selector {
complex_selector: Arc::new(ComplexSelector {
compound_selector: vec![
SimpleSelector::Namespace(Namespace {
prefix: None,
url: NsAtom::from("http://www.w3.org/1999/xhtml")
}),
SimpleSelector::Class(Atom::from("ok")),
],
next: Some((Arc::new(ComplexSelector {
compound_selector: vec![
SimpleSelector::Namespace(Namespace {
prefix: None,
url: NsAtom::from("http://www.w3.org/1999/xhtml")
}),
SimpleSelector::ID(Atom::from("d1")),
],
next: None,
}), Combinator::Child)),
}),
pseudo_element: None,
specificity: (1 << 20) + (1 << 10) + (0 << 0),
},
]),
block: Arc::new(RwLock::new(block_from(vec![
(PropertyDeclaration::BackgroundColor(DeclaredValue::Value(
longhands::background_color::SpecifiedValue {
authored: Some("blue".to_owned().into_boxed_str()),
parsed: cssparser::Color::RGBA(cssparser::RGBA::new(0, 0, 255, 255)),
}
)),
Importance::Normal),
(PropertyDeclaration::BackgroundPositionX(DeclaredValue::Value(
longhands::background_position_x::SpecifiedValue(
vec![longhands::background_position_x::single_value
::get_initial_position_value()]))),
Importance::Normal),
(PropertyDeclaration::BackgroundPositionY(DeclaredValue::Value(
longhands::background_position_y::SpecifiedValue(
vec![longhands::background_position_y::single_value
::get_initial_position_value()]))),
Importance::Normal),
(PropertyDeclaration::BackgroundRepeat(DeclaredValue::Value(
longhands::background_repeat::SpecifiedValue(
vec![longhands::background_repeat::single_value
::get_initial_specified_value()]))),
Importance::Normal),
(PropertyDeclaration::BackgroundAttachment(DeclaredValue::Value(
longhands::background_attachment::SpecifiedValue(
vec![longhands::background_attachment::single_value
::get_initial_specified_value()]))),
Importance::Normal),
(PropertyDeclaration::BackgroundImage(DeclaredValue::Value(
longhands::background_image::SpecifiedValue(
vec![longhands::background_image::single_value
::get_initial_specified_value()]))),
Importance::Normal),
(PropertyDeclaration::BackgroundSize(DeclaredValue::Value(
longhands::background_size::SpecifiedValue(
vec![longhands::background_size::single_value
::get_initial_specified_value()]))),
Importance::Normal),
(PropertyDeclaration::BackgroundOrigin(DeclaredValue::Value(
longhands::background_origin::SpecifiedValue(
vec![longhands::background_origin::single_value
::get_initial_specified_value()]))),
Importance::Normal),
(PropertyDeclaration::BackgroundClip(DeclaredValue::Value(
longhands::background_clip::SpecifiedValue(
vec![longhands::background_clip::single_value
::get_initial_specified_value()]))),
Importance::Normal),
]))),
}))),
CssRule::Keyframes(Arc::new(RwLock::new(KeyframesRule {
name: "foo".into(),
keyframes: vec![
Arc::new(RwLock::new(Keyframe {
selector: KeyframeSelector::new_for_unit_testing(
vec![KeyframePercentage::new(0.)]),
block: Arc::new(RwLock::new(block_from(vec![
(PropertyDeclaration::Width(DeclaredValue::Value(
LengthOrPercentageOrAuto::Percentage(Percentage(0.)))),
Importance::Normal),
])))
})),
Arc::new(RwLock::new(Keyframe {
selector: KeyframeSelector::new_for_unit_testing(
vec![KeyframePercentage::new(1.)]),
block: Arc::new(RwLock::new(block_from(vec![
(PropertyDeclaration::Width(DeclaredValue::Value(<|fim▁hole|> vec![animation_play_state::SingleSpecifiedValue::running]))),
Importance::Normal),
]))),
})),
]
})))
]),
};
assert_eq!(format!("{:#?}", stylesheet), format!("{:#?}", expected));
}
struct CSSError {
pub url : ServoUrl,
pub line: usize,
pub column: usize,
pub message: String
}
struct CSSInvalidErrorReporterTest {
pub errors: Arc<Mutex<Vec<CSSError>>>
}
impl CSSInvalidErrorReporterTest {
pub fn new() -> CSSInvalidErrorReporterTest {
return CSSInvalidErrorReporterTest{
errors: Arc::new(Mutex::new(Vec::new()))
}
}
}
impl ParseErrorReporter for CSSInvalidErrorReporterTest {
fn report_error(&self, input: &mut CssParser, position: SourcePosition, message: &str,
url: &ServoUrl) {
let location = input.source_location(position);
let errors = self.errors.clone();
let mut errors = errors.lock().unwrap();
errors.push(
CSSError{
url: url.clone(),
line: location.line,
column: location.column,
message: message.to_owned()
}
);
}
fn clone(&self) -> Box<ParseErrorReporter + Send + Sync> {
return Box::new(
CSSInvalidErrorReporterTest{
errors: self.errors.clone()
}
);
}
}
#[test]
fn test_report_error_stylesheet() {
let css = r"
div {
background-color: red;
display: invalid;
invalid: true;
}
";
let url = ServoUrl::parse("about::test").unwrap();
let error_reporter = Box::new(CSSInvalidErrorReporterTest::new());
let errors = error_reporter.errors.clone();
Stylesheet::from_str(css, url.clone(), Origin::UserAgent, Default::default(),
None,
error_reporter,
ParserContextExtraData::default());
let mut errors = errors.lock().unwrap();
let error = errors.pop().unwrap();
assert_eq!("Unsupported property declaration: 'invalid: true;'", error.message);
assert_eq!(5, error.line);
assert_eq!(9, error.column);
let error = errors.pop().unwrap();
assert_eq!("Unsupported property declaration: 'display: invalid;'", error.message);
assert_eq!(4, error.line);
assert_eq!(9, error.column);
// testing for the url
assert_eq!(url, error.url);
}<|fim▁end|>
|
LengthOrPercentageOrAuto::Percentage(Percentage(1.)))),
Importance::Normal),
(PropertyDeclaration::AnimationPlayState(DeclaredValue::Value(
animation_play_state::SpecifiedValue(
|
<|file_name|>selectmany.go<|end_file_name|><|fim▁begin|><|fim▁hole|>// Example: Fetch many rows and allow cancel the query by Ctrl+C.
package main
import (
"context"
"database/sql"
"flag"
"fmt"
"log"
"os"
"os/signal"
"runtime/pprof"
"strconv"
_ "net/http/pprof"
"runtime/debug"
sf "github.com/snowflakedb/gosnowflake"
)
var (
cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
memprofile = flag.String("memprofile", "", "write memory profile to this file")
)
// getDSN constructs a DSN based on the test connection parameters
func getDSN() (string, *sf.Config, error) {
env := func(k string, failOnMissing bool) string {
if value := os.Getenv(k); value != "" {
return value
}
if failOnMissing {
log.Fatalf("%v environment variable is not set.", k)
}
return ""
}
account := env("SNOWFLAKE_TEST_ACCOUNT", true)
user := env("SNOWFLAKE_TEST_USER", true)
password := env("SNOWFLAKE_TEST_PASSWORD", true)
host := env("SNOWFLAKE_TEST_HOST", false)
port := env("SNOWFLAKE_TEST_PORT", false)
protocol := env("SNOWFLAKE_TEST_PROTOCOL", false)
portStr, err := strconv.Atoi(port)
if err != nil {
return "", nil, err
}
cfg := &sf.Config{
Account: account,
User: user,
Password: password,
Host: host,
Port: portStr,
Protocol: protocol,
}
dsn, err := sf.DSN(cfg)
return dsn, cfg, err
}
// run is an actual main
func run(dsn string) {
// handler interrupt signal
ctx, cancel := context.WithCancel(context.Background())
c := make(chan os.Signal, 1)
defer close(c)
signal.Notify(c, os.Interrupt)
defer func() {
signal.Stop(c)
}()
go func() {
select {
case <-c:
cancel()
case <-ctx.Done():
}
}()
db, err := sql.Open("snowflake", dsn)
if err != nil {
log.Fatalf("failed to connect. err: %v", err)
}
defer db.Close()
query := `select * from
(select 0 a union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) A,
(select 0 b union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) B,
(select 0 c union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) C,
(select 0 d union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) E,
(select 0 e union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) F,
(select 0 f union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) G,
(select 0 f union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) H`
fmt.Printf("Executing a query. It may take long. You may stop by Ctrl+C.\n")
rows, err := db.QueryContext(ctx, query)
if err != nil {
log.Fatalf("failed to run a query. %v, err: %v", query, err)
}
defer rows.Close()
var v1, v2, v3, v4, v5, v6, v7 int
fmt.Printf("Fetching the results. It may take long. You may stop by Ctrl+C.\n")
counter := 0
for rows.Next() {
if err = rows.Scan(&v1, &v2, &v3, &v4, &v5, &v6, &v7); err != nil {
log.Fatalf("failed to get result. err: %v", err)
}
if counter%10000 == 0 {
fmt.Printf("data: %v, %v, %v, %v, %v, %v, %v\n", v1, v2, v3, v4, v5, v6, v7)
}
if counter%1000000 == 0 {
debug.FreeOSMemory()
}
counter++
}
if rows.Err() != nil {
fmt.Printf("ERROR: %v\n", rows.Err())
return
}
fmt.Printf("Congrats! You have successfully run %v with Snowflake DB!\n", query)
}
func main() {
if !flag.Parsed() {
flag.Parse()
}
dsn, cfg, err := getDSN()
if err != nil {
log.Fatalf("failed to create DSN from Config: %v, err: %v", cfg, err)
}
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
run(dsn)
if *memprofile != "" {
f, err := os.Create(*memprofile)
if err != nil {
log.Fatal(err)
}
pprof.WriteHeapProfile(f)
f.Close()
return
}
}<|fim▁end|>
| |
<|file_name|>StundenplanManager.java<|end_file_name|><|fim▁begin|>package de.maxgb.vertretungsplan.manager;
import android.content.Context;
import android.os.AsyncTask;
import de.maxgb.android.util.Logger;
import de.maxgb.vertretungsplan.util.Constants;
import de.maxgb.vertretungsplan.util.Stunde;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class StundenplanManager {
public static final int BEGINN_NACHMITTAG = 8;
public static final int ANZAHL_SAMSTAG = 4;
public static final int ANZAHL_NACHMITTAG = 2;
private static StundenplanManager instance;
public static synchronized StundenplanManager getInstance(Context context) {
if (instance == null) {
instance = new StundenplanManager(context);
}
return instance;
}
private final String TAG = "StundenplanManager";
private int lastResult = 0;
private ArrayList<Stunde[]> woche;
private Context context;
// Listener-------------
private ArrayList<OnUpdateListener> listener = new ArrayList<OnUpdateListener>();
private StundenplanManager(Context context) {
this.context = context;
auswerten();
}
public void asyncAuswerten() {
AuswertenTask task = new AuswertenTask();
task.execute();
}
public void auswerten() {
lastResult = dateiAuswerten();
if (lastResult == -1) {
} else {
woche = null;
}
}
public void auswertenWithNotify() {
auswerten();
notifyListener();
}
public ArrayList<Stunde[]> getClonedStundenplan() {
if (woche == null) return null;
ArrayList<Stunde[]> clone;
try {
clone = new ArrayList<Stunde[]>(woche.size());
for (Stunde[] item : woche) {
Stunde[] clone2 = new Stunde[item.length];
for (int i = 0; i < item.length; i++) {
clone2[i] = item[i].clone();
}
clone.add(clone2);
}
return clone;
} catch (NullPointerException e) {
Logger.e(TAG, "Failed to clone stundenplan", e);
return null;
}
}
public String getLastResult() {
switch (lastResult) {
case -1:
return "Erfolgreich ausgewertet";
case 1:
return "Datei existiert nicht";
case 2:
return "Kann Datei nicht lesen";
case 3:
return "Zugriffsfehler";
case 4:
return "Parsingfehler";
default:
return "Noch nicht ausgewertet";
}
}
public ArrayList<Stunde[]> getStundenplan() {
return woche;
}
public void notifyListener() {
for (int i = 0; i < listener.size(); i++) {
if (listener.get(i) != null) {
listener.get(i).onStundenplanUpdate();
}<|fim▁hole|> }
public void registerOnUpdateListener(OnUpdateListener listener) {
this.listener.add(listener);
}
public void unregisterOnUpdateListener(OnUpdateListener listener) {
this.listener.remove(listener);
}
private Stunde[] convertJSONArrayToStundenArray(JSONArray tag) throws JSONException {
Stunde[] result = new Stunde[BEGINN_NACHMITTAG - 1 + ANZAHL_NACHMITTAG];
for (int i = 0; i < BEGINN_NACHMITTAG - 1 + ANZAHL_NACHMITTAG; i++) {
JSONArray stunde = tag.getJSONArray(i);
if (i >= BEGINN_NACHMITTAG - 1) {
result[i] = new Stunde(stunde.getString(0), stunde.getString(1), i + 1, stunde.getString(2));
} else {
result[i] = new Stunde(stunde.getString(0), stunde.getString(1), i + 1);
}
}
return result;
}
/**
* Wertet die Stundenplandatei aus
*
* @return Fehlercode -1 bei Erfolg,1 Datei existiert nicht, 2 Datei kann nicht gelesen werden,3 Fehler beim Lesen,4 Fehler
* beim Parsen
*
*/
private int dateiAuswerten() {
File loadoutFile = new File(context.getFilesDir(), Constants.SP_FILE_NAME);
ArrayList<Stunde[]> w = new ArrayList<Stunde[]>();
if (!loadoutFile.exists()) {
Logger.w(TAG, "Stundenplan file doesn´t exist");
return 1;
}
if (!loadoutFile.canRead()) {
Logger.w(TAG, "Can´t read Stundenplan file");
return 2;
}
try {
BufferedReader br = new BufferedReader(new FileReader(loadoutFile));
String line = br.readLine();
br.close();
JSONObject stundenplan = new JSONObject(line);
JSONArray mo = stundenplan.getJSONArray("mo");
JSONArray di = stundenplan.getJSONArray("di");
JSONArray mi = stundenplan.getJSONArray("mi");
JSONArray d = stundenplan.getJSONArray("do");
JSONArray fr = stundenplan.getJSONArray("fr");
JSONObject sa = stundenplan.getJSONObject("sa");
// Samstag
Stunde[] samstag = new Stunde[9];
JSONArray eins = sa.getJSONArray("0");
JSONArray zwei = sa.getJSONArray("1");
JSONArray drei = sa.getJSONArray("2");
JSONArray vier = sa.getJSONArray("3");
JSONArray acht = sa.getJSONArray("7");
JSONArray neun = sa.getJSONArray("8");
samstag[0] = new Stunde(eins.getString(0), eins.getString(1), 1);
samstag[1] = new Stunde(zwei.getString(0), zwei.getString(1), 2);
samstag[2] = new Stunde(drei.getString(0), drei.getString(1), 3);
samstag[3] = new Stunde(vier.getString(0), vier.getString(1), 4);
samstag[4] = new Stunde("", "", 5);
samstag[5] = new Stunde("", "", 6);
samstag[6] = new Stunde("", "", 7);
samstag[7] = new Stunde(acht.getString(0), acht.getString(1), 8, acht.getString(2));
samstag[8] = new Stunde(neun.getString(0), neun.getString(1), 9, neun.getString(2));
w.add(convertJSONArrayToStundenArray(mo));
w.add(convertJSONArrayToStundenArray(di));
w.add(convertJSONArrayToStundenArray(mi));
w.add(convertJSONArrayToStundenArray(d));
w.add(convertJSONArrayToStundenArray(fr));
w.add(samstag);
/*
* for(int i=0;i<w.size();i++){ for(int j=0;j<w.get(i).length;j++){ System.out.println(w.get(i)[j].toString()); } }
*/
} catch (IOException e) {
Logger.e(TAG, "Fehler beim Lesen der Datei", e);
return 3;
} catch (JSONException e) {
Logger.e(TAG, "Fehler beim Parsen der Datei", e);
return 4;
}
woche = w;
return -1;
}
public interface OnUpdateListener {
void onStundenplanUpdate();
}
// ------------------------
private class AuswertenTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
auswerten();
return null;
}
@Override
protected void onPostExecute(Void v) {
notifyListener();
}
}
}<|fim▁end|>
|
}
|
<|file_name|>sr_mult.py<|end_file_name|><|fim▁begin|>from list_node import ListNode
from instruction import Instruction, Subneg4Instruction
def sr_mult(WM, LM):
namespace_bak = WM.getNamespace(string=False)
WM.setNamespace(["sr","mult"])
c_0 = WM.const(0)
c_1 = WM.const(1)
c_m1 = WM.const(-1)
c_32 = WM.const(32)
a = WM.addDataWord(0, "arg1")
b = WM.addDataWord(0, "arg2")
ret_addr = WM.addDataPtrWord(0, "ret_addr")
temp = WM.addDataWord(0, "temp")
count = WM.addDataWord(0, "count")
hi = WM.addDataWord(0, "hi")
lo = WM.addDataWord(0, "lo")
sign = WM.addDataWord(0, "sign")
NEXT = WM.getNext()
#HALT = WM.getHalt()
LNs = (
LM.new(ListNode("sr_mult", sys = True)),
LM.new(ListNode(Subneg4Instruction(
c_1.getPtr(),
a.getPtr(),
temp.getPtr(),
WM.label("sr_mult_L010")
)), "sr_mult_start"),
LM.new(ListNode(Subneg4Instruction(
c_0.getPtr(),
c_0.getPtr(),
sign.getPtr(),
NEXT
))),
LM.new(ListNode(Subneg4Instruction(
c_0.getPtr(),
c_m1.getPtr(),
temp.getPtr(),
WM.label("sr_mult_L020")
))),
LM.new(ListNode(Subneg4Instruction(
a.getPtr(),
c_0.getPtr(),
a.getPtr(),
NEXT
)),"sr_mult_L010"),
LM.new(ListNode(Subneg4Instruction(
c_0.getPtr(),
c_1.getPtr(),
sign.getPtr(),
NEXT
))),
LM.new(ListNode(Subneg4Instruction(
c_1.getPtr(),
b.getPtr(),
temp.getPtr(),
WM.label("sr_mult_L030")
)),"sr_mult_L020"),
LM.new(ListNode(Subneg4Instruction(
c_32.getPtr(),
c_0.getPtr(),
count.getPtr(),
WM.label("sr_mult_L050")
))),
LM.new(ListNode(Subneg4Instruction(
b.getPtr(),
c_0.getPtr(),
b.getPtr(),
NEXT
)),"sr_mult_L030"),
LM.new(ListNode(Subneg4Instruction(
sign.getPtr(),
c_m1.getPtr(),
sign.getPtr(),
NEXT
))),
LM.new(ListNode(Subneg4Instruction(
c_32.getPtr(),
c_0.getPtr(),
count.getPtr(),
NEXT
)),"sr_mult_L040"),
LM.new(ListNode(Subneg4Instruction(
c_0.getPtr(),
c_0.getPtr(),
hi.getPtr(),
NEXT
)),"sr_mult_L050"),
LM.new(ListNode(Subneg4Instruction(
c_0.getPtr(),
c_0.getPtr(),
lo.getPtr(),
NEXT
))),
LM.new(ListNode(Subneg4Instruction(
hi.getPtr(),
c_0.getPtr(),
temp.getPtr(),
NEXT
)),"sr_mult_L100"),
LM.new(ListNode(Subneg4Instruction(
temp.getPtr(),
hi.getPtr(),
hi.getPtr(),
NEXT
))),
LM.new(ListNode(Subneg4Instruction(
lo.getPtr(),
c_m1.getPtr(),
temp.getPtr(),
WM.label("sr_mult_L110")
))),
LM.new(ListNode(Subneg4Instruction(
c_m1.getPtr(),
hi.getPtr(),
hi.getPtr(),
NEXT
))),
LM.new(ListNode(Subneg4Instruction(
lo.getPtr(),
c_0.getPtr(),
temp.getPtr(),
NEXT
)),"sr_mult_L110"),
LM.new(ListNode(Subneg4Instruction(
temp.getPtr(),
lo.getPtr(),
lo.getPtr(),
NEXT
))),
LM.new(ListNode(Subneg4Instruction(
a.getPtr(),
c_m1.getPtr(),
temp.getPtr(),
WM.label("sr_mult_L800")
))),
LM.new(ListNode(Subneg4Instruction(
b.getPtr(),
c_0.getPtr(),
temp.getPtr(),
NEXT
)),"sr_mult_L200"),
LM.new(ListNode(Subneg4Instruction(
temp.getPtr(),
lo.getPtr(),
lo.getPtr(),
WM.label("sr_mult_L300")
))),
LM.new(ListNode(Subneg4Instruction(
c_0.getPtr(),
b.getPtr(),
temp.getPtr(),
WM.label("sr_mult_L500")
))),
LM.new(ListNode(Subneg4Instruction(
b.getPtr(),
lo.getPtr(),
temp.getPtr(),
WM.label("sr_mult_L500")
))),
LM.new(ListNode(Subneg4Instruction(
c_0.getPtr(),
c_m1.getPtr(),
temp.getPtr(),
WM.label("sr_mult_L800")
))),
LM.new(ListNode(Subneg4Instruction(
b.getPtr(),
c_m1.getPtr(),
temp.getPtr(),
WM.label("sr_mult_L800")
)),"sr_mult_L300"),
LM.new(ListNode(Subneg4Instruction(
b.getPtr(),
lo.getPtr(),
temp.getPtr(),
WM.label("sr_mult_L800")
))),
LM.new(ListNode(Subneg4Instruction(
c_m1.getPtr(),
hi.getPtr(),
hi.getPtr(),
NEXT
)),"sr_mult_L500"),
LM.new(ListNode(Subneg4Instruction(
a.getPtr(),
c_0.getPtr(),
temp.getPtr(),
NEXT
)),"sr_mult_L800"),
LM.new(ListNode(Subneg4Instruction(
temp.getPtr(),
a.getPtr(),
a.getPtr(),
<|fim▁hole|> NEXT
))),
LM.new(ListNode(Subneg4Instruction(
c_m1.getPtr(),
count.getPtr(),
count.getPtr(),
WM.label("sr_mult_L100")
))),
LM.new(ListNode(Subneg4Instruction(
sign.getPtr(),
c_m1.getPtr(),
temp.getPtr(),
WM.label("sr_mult_L990")
)),"sr_mult_L900"),
LM.new(ListNode(Subneg4Instruction(
lo.getPtr(),
c_0.getPtr(),
lo.getPtr(),
NEXT
))),
LM.new(ListNode(Subneg4Instruction(
hi.getPtr(),
c_0.getPtr(),
hi.getPtr(),
NEXT
))),
LM.new(ListNode(Subneg4Instruction(
c_0.getPtr(),
hi.getPtr(),
temp.getPtr(),
NEXT
)),"sr_mult_L990"),
LM.new(ListNode(Subneg4Instruction(
c_0.getPtr(),
lo.getPtr(),
temp.getPtr(),
NEXT
))),
LM.new(ListNode(Subneg4Instruction(
c_0.getPtr(),
c_m1.getPtr(),
temp.getPtr(),
ret_addr
)))
)
WM.setNamespace(namespace_bak)
return LNs, a, b, ret_addr, lo<|fim▁end|>
| |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from .context import CorpusContext
from .audio import AudioContext
from .importable import ImportContext
from .lexical import LexicalContext
from .pause import PauseContext
from .utterance import UtteranceContext
from .structured import StructuredContext<|fim▁hole|>from .syllabic import SyllabicContext
from .spoken import SpokenContext<|fim▁end|>
| |
<|file_name|>webGrid.js<|end_file_name|><|fim▁begin|>/// <reference path="jquery-1.4.4-vsdoc.js" />
$(document).ready(function () {
function updateGrid(e) {
e.preventDefault();
// find the containing element's id then reload the grid
var url = $(this).attr('href');
var grid = $(this).parents('.ajaxGrid'); // get the grid
var id = grid.attr('id');<|fim▁hole|> $('.ajaxGrid table tfoot tr a').live('click', updateGrid); // hook up ajax refresh for paging links (note: this doesn't handle the separate Pager() call!)
});<|fim▁end|>
|
grid.load(url + ' #' + id);
};
$('.ajaxGrid table thead tr a').live('click', updateGrid); // hook up ajax refresh for sorting links
|
<|file_name|>message.rs<|end_file_name|><|fim▁begin|>use regex::Regex;
#[derive(Debug, PartialEq)]
pub struct Message {
pub data: String,
}<|fim▁hole|> }
pub fn decompress_v1(&self) -> u64 {
let marker_finder: Regex = Regex::new(r"\((\d+)x(\d+)\)").unwrap();
decompressed_string_length_v1(&self.data, marker_finder)
}
pub fn decompress_v2(&self) -> u64 {
let marker_finder: Regex = Regex::new(r"\((\d+)x(\d+)\)").unwrap();
decompress_string_v2(&self.data, &marker_finder)
}
}
fn decompressed_string_length_v1(message: &str, marker_regex: Regex) -> u64 {
let mut decompressed_length: u64 = 0;
let mut str_index: usize = 0;
while let Some(matched) = marker_regex.find(&message[str_index..]) {
let captured = marker_regex.captures(&message[str_index..]).unwrap();
decompressed_length += matched.start() as u64;
let number_of_chars: usize = (&captured[1]).parse().unwrap();
let number_of_repeats: usize = (&captured[2]).parse().unwrap();
str_index += matched.end() + number_of_chars;
decompressed_length += (number_of_repeats * number_of_chars) as u64;
}
if str_index < message.len() {
decompressed_length += (message.len() - str_index) as u64;
}
decompressed_length
}
fn decompress_string_v2(message: &str, marker_regex: &Regex) -> u64 {
let mut decompressed_length: u64 = 0;
let mut str_index: usize = 0;
while let Some(matched) = marker_regex.find(&message[str_index..]) {
let captured = marker_regex.captures(&message[str_index..]).unwrap();
decompressed_length += matched.start() as u64;
let number_of_chars: usize = (&captured[1]).parse().unwrap();
let number_of_repeats: u64 = (&captured[2]).parse().unwrap();
str_index += matched.end() + number_of_chars;
decompressed_length +=
number_of_repeats *
decompress_string_v2(&message[(str_index - number_of_chars)..str_index], marker_regex);
}
if str_index < message.len() {
decompressed_length += (message.len() - str_index) as u64;
}
decompressed_length
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_decompress_v1() {
let test_data = vec![Message::new("ADVENT").decompress_v1(),
Message::new("A(1x5)BC").decompress_v1(),
Message::new("(3x3)XYZ").decompress_v1(),
Message::new("A(2x2)BCD(2x2)EFG").decompress_v1(),
Message::new("(6x1)(1x3)A").decompress_v1(),
Message::new("X(8x2)(3x3)ABCY").decompress_v1()];
assert_eq!(test_data, vec![6, 7, 9, 11, 6, 18]);
}
#[test]
fn test_decompress_v2() {
let test_data = vec![Message::new("(3X3)XYZ").decompress_v2(),
Message::new("X(8x2)(3x3)ABCY").decompress_v2(),
Message::new("(27x12)(20x12)(13x14)(7x10)(1x12)A").decompress_v2(),
Message::new("(25x3)(3x3)ABC(2x3)XY(5x2)PQRSTX(18x9)(3x2)TWO(5x7)SEVEN")
.decompress_v2()];
assert_eq!(test_data, vec![9, 20, 241920, 445]);
}
}<|fim▁end|>
|
impl Message {
pub fn new(data: &str) -> Message {
Message { data: data.to_string() }
|
<|file_name|>MachineWatcherController.java<|end_file_name|><|fim▁begin|>package org.iatoki.judgels.michael.controllers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.EnumUtils;
import org.iatoki.judgels.play.InternalLink;
import org.iatoki.judgels.play.LazyHtml;
import org.iatoki.judgels.play.controllers.AbstractJudgelsController;
import org.iatoki.judgels.play.views.html.layouts.headingLayout;
import org.iatoki.judgels.play.views.html.layouts.headingWithActionLayout;
import org.iatoki.judgels.play.views.html.layouts.tabLayout;
import org.iatoki.judgels.michael.Machine;
import org.iatoki.judgels.michael.MachineNotFoundException;
import org.iatoki.judgels.michael.services.MachineService;
import org.iatoki.judgels.michael.MachineWatcher;
import org.iatoki.judgels.michael.adapters.MachineWatcherConfAdapter;
import org.iatoki.judgels.michael.MachineWatcherNotFoundException;
import org.iatoki.judgels.michael.services.MachineWatcherService;
import org.iatoki.judgels.michael.MachineWatcherType;
import org.iatoki.judgels.michael.MachineWatcherUtils;
import org.iatoki.judgels.michael.controllers.securities.LoggedIn;
import org.iatoki.judgels.michael.views.html.machine.watcher.listMachineWatchersView;
import play.data.Form;
import play.db.jpa.Transactional;
import play.filters.csrf.AddCSRFToken;
import play.filters.csrf.RequireCSRFCheck;
import play.i18n.Messages;
import play.mvc.Result;
import play.mvc.Security;
import play.twirl.api.Html;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import java.util.List;
@Security.Authenticated(value = LoggedIn.class)
@Singleton
@Named
public final class MachineWatcherController extends AbstractJudgelsController {
private final MachineService machineService;
private final MachineWatcherService machineWatcherService;
@Inject
public MachineWatcherController(MachineService machineService, MachineWatcherService machineWatcherService) {
this.machineService = machineService;
this.machineWatcherService = machineWatcherService;
}
@Transactional(readOnly = true)
public Result viewMachineWatchers(long machineId) throws MachineNotFoundException {
Machine machine = machineService.findByMachineId(machineId);
List<MachineWatcherType> enabledWatchers = machineWatcherService.findEnabledWatcherByMachineJid(machine.getJid());
List<MachineWatcherType> unenabledWatchers = Lists.newArrayList(MachineWatcherType.values());
unenabledWatchers.removeAll(enabledWatchers);
LazyHtml content = new LazyHtml(listMachineWatchersView.render(machine.getId(), enabledWatchers, unenabledWatchers));
content.appendLayout(c -> headingLayout.render(Messages.get("machine.watcher.list"), c));
appendTabLayout(content, machine);
ControllerUtils.getInstance().appendSidebarLayout(content);
ControllerUtils.getInstance().appendBreadcrumbsLayout(content, ImmutableList.of(
new InternalLink(Messages.get("machine.machines"), routes.MachineController.index()),
new InternalLink(Messages.get("machine.watcher.list"), routes.MachineWatcherController.viewMachineWatchers(machine.getId()))
));
ControllerUtils.getInstance().appendTemplateLayout(content, "Machine - Watchers");
return ControllerUtils.getInstance().lazyOk(content);
}
@Transactional(readOnly = true)
@AddCSRFToken
public Result activateMachineWatcher(long machineId, String watcherType) throws MachineNotFoundException {
Machine machine = machineService.findByMachineId(machineId);
if (EnumUtils.isValidEnum(MachineWatcherType.class, watcherType)) {
if (!machineWatcherService.isWatcherActivated(machine.getJid(), MachineWatcherType.valueOf(watcherType))) {
MachineWatcherConfAdapter adapter = MachineWatcherUtils.getMachineWatcherConfAdapter(machine, MachineWatcherType.valueOf(watcherType));
if (adapter != null) {
return showActivateMachineWatcher(machine, watcherType, adapter.getConfHtml(adapter.generateForm(), org.iatoki.judgels.michael.controllers.routes.MachineWatcherController.postActivateMachineWatcher(machine.getId(), watcherType), Messages.get("machine.watcher.activate")));
} else {
throw new UnsupportedOperationException();
}
} else {
return redirect(routes.MachineWatcherController.viewMachineWatchers(machine.getId()));
}
} else {
throw new UnsupportedOperationException();
}
}
@Transactional
@RequireCSRFCheck
public Result postActivateMachineWatcher(long machineId, String watcherType) throws MachineNotFoundException {
Machine machine = machineService.findByMachineId(machineId);
if (EnumUtils.isValidEnum(MachineWatcherType.class, watcherType)) {
if (!machineWatcherService.isWatcherActivated(machine.getJid(), MachineWatcherType.valueOf(watcherType))) {
MachineWatcherConfAdapter adapter = MachineWatcherUtils.getMachineWatcherConfAdapter(machine, MachineWatcherType.valueOf(watcherType));
if (adapter != null) {
Form form = adapter.bindFormFromRequest(request());
if (form.hasErrors() || form.hasGlobalErrors()) {
return showActivateMachineWatcher(machine, watcherType, adapter.getConfHtml(form, org.iatoki.judgels.michael.controllers.routes.MachineWatcherController.postActivateMachineWatcher(machine.getId(), watcherType), Messages.get("machine.watcher.activate")));
} else {
String conf = adapter.processRequestForm(form);
machineWatcherService.createWatcher(machine.getJid(), MachineWatcherType.valueOf(watcherType), conf);
return redirect(routes.MachineWatcherController.viewMachineWatchers(machine.getId()));
}
} else {
throw new UnsupportedOperationException();
}
} else {
return redirect(routes.MachineWatcherController.viewMachineWatchers(machine.getId()));
}
} else {
throw new UnsupportedOperationException();
}
}
@Transactional(readOnly = true)
@AddCSRFToken
public Result updateMachineWatcher(long machineId, String watcherType) throws MachineNotFoundException {
Machine machine = machineService.findByMachineId(machineId);
if (EnumUtils.isValidEnum(MachineWatcherType.class, watcherType)) {
if (machineWatcherService.isWatcherActivated(machine.getJid(), MachineWatcherType.valueOf(watcherType))) {
MachineWatcherConfAdapter adapter = MachineWatcherUtils.getMachineWatcherConfAdapter(machine, MachineWatcherType.valueOf(watcherType));
if (adapter != null) {
MachineWatcher machineWatcher = machineWatcherService.findByMachineJidAndWatcherType(machine.getJid(), MachineWatcherType.valueOf(watcherType));
return showUpdateMachineWatcher(machine, watcherType, adapter.getConfHtml(adapter.generateForm(machineWatcher.getConf()), org.iatoki.judgels.michael.controllers.routes.MachineWatcherController.postUpdateMachineWatcher(machine.getId(), machineWatcher.getId(), watcherType), Messages.get("machine.watcher.update")));
} else {
throw new UnsupportedOperationException();
}
} else {
return redirect(routes.MachineWatcherController.viewMachineWatchers(machine.getId()));
}
} else {
throw new UnsupportedOperationException();
}
}
@Transactional
@RequireCSRFCheck
public Result postUpdateMachineWatcher(long machineId, long machineWatcherId, String watcherType) throws MachineNotFoundException, MachineWatcherNotFoundException {
Machine machine = machineService.findByMachineId(machineId);
MachineWatcher machineWatcher = machineWatcherService.findByWatcherId(machineWatcherId);
if (EnumUtils.isValidEnum(MachineWatcherType.class, watcherType)) {
if (machineWatcherService.isWatcherActivated(machine.getJid(), MachineWatcherType.valueOf(watcherType))) {
MachineWatcherConfAdapter adapter = MachineWatcherUtils.getMachineWatcherConfAdapter(machine, MachineWatcherType.valueOf(watcherType));
if (adapter != null) {
Form form = adapter.bindFormFromRequest(request());
if (form.hasErrors() || form.hasGlobalErrors()) {
return showUpdateMachineWatcher(machine, watcherType, adapter.getConfHtml(form, org.iatoki.judgels.michael.controllers.routes.MachineWatcherController.postActivateMachineWatcher(machine.getId(), watcherType), Messages.get("machine.watcher.update")));
} else {
if (machine.getJid().equals(machineWatcher.getMachineJid())) {
String conf = adapter.processRequestForm(form);
machineWatcherService.updateWatcher(machineWatcher.getId(), machine.getJid(), MachineWatcherType.valueOf(watcherType), conf);
return redirect(routes.MachineWatcherController.viewMachineWatchers(machine.getId()));
} else {
form.reject("error.notMachineWatcher");
return showUpdateMachineWatcher(machine, watcherType, adapter.getConfHtml(form, org.iatoki.judgels.michael.controllers.routes.MachineWatcherController.postActivateMachineWatcher(machine.getId(), watcherType), Messages.get("machine.watcher.update")));
}
}
} else {
throw new UnsupportedOperationException();
}
} else {
return redirect(routes.MachineWatcherController.viewMachineWatchers(machine.getId()));
}
} else {
throw new UnsupportedOperationException();
}
}
@Transactional
public Result deactivateMachineWatcher(long machineId, String watcherType) throws MachineNotFoundException {
Machine machine = machineService.findByMachineId(machineId);
if (EnumUtils.isValidEnum(MachineWatcherType.class, watcherType)) {
if (machineWatcherService.isWatcherActivated(machine.getJid(), MachineWatcherType.valueOf(watcherType))) {
machineWatcherService.removeWatcher(machine.getJid(), MachineWatcherType.valueOf(watcherType));
}
return redirect(routes.MachineWatcherController.viewMachineWatchers(machine.getId()));
} else {
throw new UnsupportedOperationException();
}<|fim▁hole|> content.appendLayout(c -> headingLayout.render(Messages.get("machine.watcher.activate"), c));
appendTabLayout(content, machine);
ControllerUtils.getInstance().appendSidebarLayout(content);
ControllerUtils.getInstance().appendBreadcrumbsLayout(content, ImmutableList.of(
new InternalLink(Messages.get("machine.machines"), routes.MachineController.index()),
new InternalLink(Messages.get("machine.watcher.list"), routes.MachineWatcherController.viewMachineWatchers(machine.getId())),
new InternalLink(Messages.get("machine.watcher.activate"), routes.MachineWatcherController.activateMachineWatcher(machine.getId(), watcherType))
));
ControllerUtils.getInstance().appendTemplateLayout(content, "Machine - Watchers");
return ControllerUtils.getInstance().lazyOk(content);
}
private Result showUpdateMachineWatcher(Machine machine, String watcherType, Html html) {
LazyHtml content = new LazyHtml(html);
content.appendLayout(c -> headingLayout.render(Messages.get("machine.watcher.update"), c));
appendTabLayout(content, machine);
ControllerUtils.getInstance().appendSidebarLayout(content);
ControllerUtils.getInstance().appendBreadcrumbsLayout(content, ImmutableList.of(
new InternalLink(Messages.get("machine.machines"), routes.MachineController.index()),
new InternalLink(Messages.get("machine.watcher.list"), routes.MachineWatcherController.viewMachineWatchers(machine.getId())),
new InternalLink(Messages.get("machine.watcher.update"), routes.MachineWatcherController.updateMachineWatcher(machine.getId(), watcherType))
));
ControllerUtils.getInstance().appendTemplateLayout(content, "Machine - Watchers");
return ControllerUtils.getInstance().lazyOk(content);
}
private void appendTabLayout(LazyHtml content, Machine machine) {
content.appendLayout(c -> tabLayout.render(ImmutableList.of(
new InternalLink(Messages.get("machine.update"), routes.MachineController.updateMachineGeneral(machine.getId())),
new InternalLink(Messages.get("machine.access"), routes.MachineAccessController.viewMachineAccesses(machine.getId())),
new InternalLink(Messages.get("machine.watcher"), routes.MachineWatcherController.viewMachineWatchers(machine.getId()))
), c));
content.appendLayout(c -> headingWithActionLayout.render(Messages.get("machine.machine") + " #" + machine.getId() + ": " + machine.getDisplayName(), new InternalLink(Messages.get("commons.enter"), routes.MachineController.viewMachine(machine.getId())), c));
}
}<|fim▁end|>
|
}
private Result showActivateMachineWatcher(Machine machine, String watcherType, Html html) {
LazyHtml content = new LazyHtml(html);
|
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>extern crate serial;
extern crate num_cpus;
use std::io;
use std::io::{Read, BufReader, BufRead, Write};
use std::fs::File;
use std::str::FromStr;
use std::thread::sleep;
use std::time::Duration;
use std::num::ParseFloatError;
use std::collections::VecDeque;
use serial::prelude::*;
use serial::SerialDevice;
#[derive(Debug)]
enum SysInfoError {
Io(io::Error),
ParseFloat(ParseFloatError),
Format(String),
}
impl From<io::Error> for SysInfoError {
fn from(e: io::Error) -> SysInfoError {
SysInfoError::Io(e)
}
}
impl From<ParseFloatError> for SysInfoError {
fn from(e: ParseFloatError) -> SysInfoError {
SysInfoError::ParseFloat(e)
}
}
#[derive(Debug)]
struct Uptime {
uptime: f64,
idle: f64,
}
const WINDOW: usize = 10;
struct CpuMeasureState {
cpus: usize,
uptimes: VecDeque<Uptime>,
}
fn uptime() -> Result<Uptime, SysInfoError> {
let mut f = File::open("/proc/uptime")?;
let mut content = String::new();
f.read_to_string(&mut content)?;
let mut iter = content.split_whitespace();
let uptime_str = iter.next().ok_or(SysInfoError::Format("Missing uptime".to_string()))?;
let idle_str = iter.next().ok_or(SysInfoError::Format("Missing idle time".to_string()))?;
Ok(Uptime {
uptime: f64::from_str(uptime_str)?,
idle: f64::from_str(idle_str)?,
})
}
fn init_cpu_measurement() -> Result<CpuMeasureState, SysInfoError> {
let mut v = VecDeque::new();
v.push_back(uptime()?);
Ok(CpuMeasureState {
cpus: num_cpus::get(),
uptimes: v,
})
}
fn cpu_usage(s: &mut CpuMeasureState) -> Result<f64, SysInfoError> {
let last_uptime = uptime()?;
if s.uptimes.len() > WINDOW {
s.uptimes.pop_front();
}
s.uptimes.push_back(last_uptime);
let du = s.uptimes.back().unwrap().uptime - s.uptimes.front().unwrap().uptime;
if du < 0.001 {
return Ok(0.0);
}
let cpus = s.cpus as f64;
let di = (s.uptimes.back().unwrap().idle - s.uptimes.front().unwrap().idle) / cpus;
return Ok(1.0 - (di / du));
}
fn scale(v: f64, old_min: f64, old_max: f64, new_min: f64, new_max: f64) -> u8 {
let mut f = (v - old_min) * (new_max - new_min) / (old_max - old_min) + new_min;
f = f.min(new_max).max(new_min);
f as u8
}
fn send_info(port: &mut serial::SystemPort, cpu_used: f64, mem_used: f64) -> serial::Result<()> {
let cpu_used_scaled = scale(cpu_used, 0.0, 1.0, 0.0, 235.0);
let mem_used_scaled = scale(mem_used, 0.0, 1.0, 0.0, 235.0);
port.write_all(&[33, mem_used_scaled, cpu_used_scaled])?;
port.flush()?;
Ok(())
}
fn open_serial_port() -> serial::Result<serial::SystemPort> {
let mut port = serial::open("/dev/ttyUSB0")?;
let mut settings = port.read_settings()?;
settings.set_baud_rate(serial::Baud9600)?;
settings.set_parity(serial::ParityNone);
settings.set_stop_bits(serial::Stop1);
port.write_settings(&settings)?;
Ok(port)
}
fn two_words(s: String) -> Option<(String, String)> {
let mut iter = s.split_whitespace();<|fim▁hole|> }
}
None
}
fn get_mem_usage() -> io::Result<f64> {
let f = BufReader::new(File::open("/proc/meminfo")?);
let (total, avail) = f.lines()
.map(|l| l.unwrap())
.map(two_words)
.filter_map(|x| x)
.scan((None, None), |state, item| {
let (key, val) = item;
if key == "MemTotal:" {
state.0 = Some(val.parse::<f64>().unwrap_or(1.0));
return Some(*state);
}
if key == "MemAvailable:" {
state.1 = Some(val.parse::<f64>().unwrap_or(0.0));
return Some(*state);
}
Some(*state)
})
.filter_map(|state| {
let (total_option, avail_option) = state;
if let Some(total) = total_option {
if let Some(avail) = avail_option {
return Some((total, avail));
}
}
None
})
.next()
.unwrap();
Ok(1.0 - avail / total)
}
fn main() {
let mut port = open_serial_port().unwrap();
let mut cm = init_cpu_measurement().unwrap();
let delay = Duration::from_millis(100);
loop {
sleep(delay);
let cpu_usage = cpu_usage(&mut cm).unwrap();
let mem_usage = get_mem_usage().unwrap();
send_info(&mut port, cpu_usage, mem_usage).unwrap();
}
}<|fim▁end|>
|
if let Some(first) = iter.next() {
if let Some(second) = iter.next() {
return Some((first.to_string(), second.to_string()));
|
<|file_name|>test_products.py<|end_file_name|><|fim▁begin|>from sympy import (symbols, product, factorial, rf, sqrt, cos,
Function, Product, Rational)
a, k, n = symbols('a,k,n', integer=True)
def test_simple_products():
assert product(2, (k, a, n)) == 2**(n-a+1)
assert product(k, (k, 1, n)) == factorial(n)
assert product(k**3, (k, 1, n)) == factorial(n)**3
assert product(k+1, (k, 0, n-1)) == factorial(n)
assert product(k+1, (k, a, n-1)) == rf(1+a, n-a)
assert product(cos(k), (k, 0, 5)) == cos(1)*cos(2)*cos(3)*cos(4)*cos(5)
assert product(cos(k), (k, 3, 5)) == cos(3)*cos(4)*cos(5)
assert product(cos(k), (k, 1, Rational(5, 2))) == cos(1)*cos(2)
assert isinstance(product(k**k, (k, 1, n)), Product)
def test_rational_products():
assert product(1+1/k, (k, 1, n)) == rf(2, n)/factorial(n)
<|fim▁hole|> assert product((4*k)**2 / (4*k**2-1), (k, 1, n)) == \
4**n*factorial(n)**2/rf(Rational(1, 2), n)/rf(Rational(3, 2), n)
# Euler's product formula for sin
assert product(1 + a/k**2, (k, 1, n)) == \
rf(1 - sqrt(-a), n)*rf(1 + sqrt(-a), n)/factorial(n)**2
def test__eval_product():
from sympy.abc import i, n
# 1710
a = Function('a')
assert product(2*a(i), (i, 1, n)) == 2**n * Product(a(i), (i, 1, n))
# 1711
assert product(2**i, (i, 1, n)) == 2**(n/2 + n**2/2)<|fim▁end|>
|
def test_special_products():
# Wallis product
|
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
from __future__ import division, print_function, absolute_import
from os.path import join
def configuration(parent_package='', top_path=None):
import warnings
from numpy.distutils.misc_util import Configuration
from numpy.distutils.system_info import get_info, BlasNotFoundError
config = Configuration('odr', parent_package, top_path)
libodr_files = ['d_odr.f',
'd_mprec.f',
'dlunoc.f']
blas_info = get_info('blas_opt')
if blas_info:
libodr_files.append('d_lpk.f')<|fim▁hole|> else:
warnings.warn(BlasNotFoundError.__doc__)
libodr_files.append('d_lpkbls.f')
odrpack_src = [join('odrpack', x) for x in libodr_files]
config.add_library('odrpack', sources=odrpack_src)
sources = ['__odrpack.c']
libraries = ['odrpack'] + blas_info.pop('libraries', [])
include_dirs = ['.'] + blas_info.pop('include_dirs', [])
config.add_extension('__odrpack',
sources=sources,
libraries=libraries,
include_dirs=include_dirs,
depends=(['odrpack.h'] + odrpack_src),
**blas_info
)
config.add_data_dir('tests')
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())<|fim▁end|>
| |
<|file_name|>ShaderPhongTexture.cpp<|end_file_name|><|fim▁begin|>// Shader Code
#include <windows.h>
#include <string>
#include <fstream>
#include <d3d9.h>
#include <d3dx9.h>
#include "../../math/Math.h"
#include "../../base/base.h"
#include "../../etc/Utility.h"
#include <vector>
#include <map>
#include <sstream>
#pragma comment( lib, "d3d9.lib" )
#pragma comment( lib, "d3dx9.lib" )
#pragma comment( lib, "winmm.lib" )
using namespace std;
using namespace graphic;
LPDIRECT3DDEVICE9 g_pDevice = NULL;
const int WINSIZE_X = 1024; //Ãʱâ À©µµ¿ì °¡·Î Å©±â
const int WINSIZE_Y = 768; //Ãʱâ À©µµ¿ì ¼¼·Î Å©±â
const int WINPOS_X = 0; //Ãʱâ À©µµ¿ì ½ÃÀÛ À§Ä¡ X
const int WINPOS_Y = 0; //Ãʱâ À©µµ¿ì ½ÃÀÛ À§Ä¡ Y
POINT g_CurPos;
bool g_LButtonDown = false;
bool g_RButtonDown = false;
Matrix44 g_LocalTm;
Vector3 g_camPos(0,100,-200);
Vector3 g_lookAtPos(0,0,0);
Matrix44 g_matProj;
Matrix44 g_matView;
graphic::cShader g_shader;
graphic::cSphere g_sphere;
graphic::cTexture g_texture;
LPDIRECT3DDEVICE9 graphic::GetDevice()
{
return g_pDevice;
}
// Äݹé ÇÁ·Î½ÃÁ® ÇÔ¼ö ÇÁ·ÎÅä ŸÀÔ
LRESULT CALLBACK WndProc( HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam );
bool InitVertexBuffer();
void Render(int timeDelta);
void UpdateCamera();
void GetRay(int sx, int sy, Vector3 &orig, Vector3 &dir);
bool IntersectTriangle( const D3DXVECTOR3& orig, const D3DXVECTOR3& dir,
D3DXVECTOR3& v0, D3DXVECTOR3& v1, D3DXVECTOR3& v2,
FLOAT* t, FLOAT* u, FLOAT* v );
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
wchar_t className[32] = L"Shader_Phong";
wchar_t windowName[32] = L"Shader_Phong";
//À©µµ¿ì Ŭ·¹½º Á¤º¸ »ý¼º
//³»°¡ ÀÌ·¯ÇÑ À©µµ¸¦ ¸¸µé°Ú´Ù ¶ó´Â Á¤º¸
WNDCLASS WndClass;
WndClass.cbClsExtra = 0; //À©µµ¿ì¿¡¼ »ç¿ëÇÏ´Â ¿©ºÐÀÇ ¸Þ¸ð¸®¼³Á¤( ±×³É 0 ÀÌ´Ù ½Å°æ¾²Áö¸»ÀÚ )
WndClass.cbWndExtra = 0; //À©µµ¿ì¿¡¼ »ç¿ëÇÏ´Â ¿©ºÐÀÇ ¸Þ¸ð¸®¼³Á¤( ±×³É 0 ÀÌ´Ù ½Å°æ¾²Áö¸»ÀÚ )
WndClass.hbrBackground = (HBRUSH)GetStockObject(GRAY_BRUSH); //À©µµ¿ì ¹è°æ»ö»ó
WndClass.hCursor = LoadCursor( NULL, IDC_ARROW ); //À©µµ¿ìÀÇ Ä¿¼¸ð¾ç °áÁ¤
WndClass.hIcon = LoadIcon( NULL, IDI_APPLICATION ); //À©µµ¿ì¾ÆÀÌÄܸð¾ç °áÁ¤
WndClass.hInstance = hInstance; //ÇÁ·Î±×·¥ÀνºÅϽºÇÚµé
WndClass.lpfnWndProc = (WNDPROC)WndProc; //À©µµ¿ì ÇÁ·Î½ÃÁ® ÇÔ¼ö Æ÷ÀÎÅÍ
WndClass.lpszMenuName = NULL; //¸Þ´ºÀ̸§ ¾øÀ¸¸é NULL
WndClass.lpszClassName = className; //Áö±Ý ÀÛ¼ºÇϰí ÀÖ´Â À©µµ¿ì Ŭ·¹½ºÀÇ À̸§
WndClass.style = CS_HREDRAW | CS_VREDRAW; //À©µµ¿ì ±×¸®±â ¹æ½Ä ¼³Á¤ ( »çÀÌÁî°¡ º¯°æµÉ¶§ ȸ鰻½Å CS_HREDRAW | CS_VREDRAW )
//À§¿¡¼ ÀÛ¼ºÇÑ À©µµ¿ì Ŭ·¹½ºÁ¤º¸ µî·Ï
RegisterClass( &WndClass );
//À©µµ¿ì »ý¼º
//»ý¼ºµÈ À©µµ¿ì ÇÚµéÀ» Àü¿ªº¯¼ö g_hWnd °¡ ¹Þ´Â´Ù.
HWND hWnd = CreateWindow(
className, //»ý¼ºµÇ´Â À©µµ¿ìÀÇ Å¬·¡½ºÀ̸§
windowName, //À©µµ¿ì ŸÀÌÆ²¹Ù¿¡ Ãâ·ÂµÇ´Â À̸§
WS_OVERLAPPEDWINDOW, //À©µµ¿ì ½ºÅ¸ÀÏ WS_OVERLAPPEDWINDOW
WINPOS_X, //À©µµ¿ì ½ÃÀÛ À§Ä¡ X
WINPOS_Y, //À©µµ¿ì ½ÃÀÛ À§Ä¡ Y
WINSIZE_X, //À©µµ¿ì °¡·Î Å©±â ( ÀÛ¾÷¿µ¿ªÀÇ Å©±â°¡ ¾Æ´Ô )
WINSIZE_Y, //À©µµ¿ì ¼¼·Î Å©±â ( ÀÛ¾÷¿µ¿ªÀÇ Å©±â°¡ ¾Æ´Ô )
GetDesktopWindow(), //ºÎ¸ð À©µµ¿ì ÇÚµé ( ÇÁ·Î±×·¥¿¡¼ ÃÖ»óÀ§ À©µµ¿ì¸é NULL ¶Ç´Â GetDesktopWindow() )
NULL, //¸Þ´º ID ( ÀÚ½ÅÀÇ ÄÁÆ®·Ñ °´Ã¼ÀÇ À©µµ¿ìÀΰæ¿ì ÄÁÆ®·Ñ ID °¡ µÈ
hInstance, //ÀÌ À©µµ¿ì°¡ ¹°¸± ÇÁ·Î±×·¥ ÀνºÅϽº ÇÚµé
NULL //Ãß°¡ Á¤º¸ NULL ( ½Å°æ²ôÀÚ )
);
//À©µµ¿ì¸¦ Á¤È®ÇÑ ÀÛ¾÷¿µ¿ª Å©±â·Î ¸ÂÃá´Ù
RECT rcClient = { 0, 0, WINSIZE_X, WINSIZE_Y };
AdjustWindowRect( &rcClient, WS_OVERLAPPEDWINDOW, FALSE ); //rcClient Å©±â¸¦ ÀÛ¾÷ ¿µ¿µÀ¸·Î ÇÒ À©µµ¿ì Å©±â¸¦ rcClient ¿¡ ´ëÀÔµÇ¾î ³ª¿Â´Ù.
//À©µµ¿ì Å©±â¿Í À©µµ¿ì À§Ä¡¸¦ ¹Ù²Ù¾îÁØ´Ù.
SetWindowPos( hWnd, NULL, 0, 0, rcClient.right - rcClient.left, rcClient.bottom - rcClient.top,
SWP_NOZORDER | SWP_NOMOVE );
if (!graphic::InitDirectX(hWnd, WINSIZE_X, WINSIZE_Y, g_pDevice))
{
return 0;
}
InitVertexBuffer();
ShowWindow( hWnd, nCmdShow );
//¸Þ½ÃÁö ±¸Á¶Ã¼
MSG msg;
ZeroMemory( &msg, sizeof( MSG ) );
int oldT = GetTickCount();
while (msg.message != WM_QUIT)
{
//PeekMessage ´Â ¸Þ½ÃÁö Å¥¿¡ ¸Þ½ÃÁö°¡ ¾ø¾îµµ ÇÁ·Î±×·¥ÀÌ ¸ØÃ߱⠾ʰí ÁøÇàÀÌ µÈ´Ù.
//À̶§ ¸Þ½ÃÁöÅ¥¿¡ ¸Þ½ÃÁö°¡ ¾øÀ¸¸é false °¡ ¸®ÅÏµÇ°í ¸Þ½ÃÁö°¡ ÀÖÀ¸¸é true °¡ ¸®ÅÏÀ̵ȴÙ.
if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
{
TranslateMessage( &msg ); //´¸° Űº¸µå ÀÇ ¹®ÀÚ¸¦ ¹ø¿ªÇÏ¿© WM_CHAR ¸Þ½ÃÁö¸¦ ¹ß»ý½ÃŲ´Ù.
DispatchMessage( &msg ); //¹Þ¾Æ¿Â ¸Þ½ÃÁö Á¤º¸·Î À©µµ¿ì ÇÁ·Î½ÃÁ® ÇÔ¼ö¸¦ ½ÇÇà½ÃŲ´Ù.
}
else
{
const int curT = timeGetTime();
const int elapseT = curT - oldT;
//if (elapseT > 15)
//{
oldT = curT;
Render(elapseT);
//}
}
}
if (g_pDevice)
g_pDevice->Release();
return 0;
}
//
// À©µµ¿ì ÇÁ·Î½ÃÁ® ÇÔ¼ö ( ¸Þ½ÃÁö Å¥¿¡¼ ¹Þ¾Æ¿Â ¸Þ½ÃÁö¸¦ ó¸®ÇÑ´Ù )
//
LRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
switch (msg)
{
case WM_KEYDOWN:
if (wParam == VK_ESCAPE)
::DestroyWindow(hWnd);
else if (wParam == VK_TAB)
{
static bool flag = false;
g_pDevice->SetRenderState(D3DRS_CULLMODE, flag);
g_pDevice->SetRenderState(D3DRS_FILLMODE, flag? D3DFILL_SOLID : D3DFILL_WIREFRAME);
flag = !flag;
}
else if (wParam == VK_SPACE)
{
}
break;
case WM_LBUTTONDOWN:
{
g_LButtonDown = true;<|fim▁hole|> g_CurPos.y = HIWORD(lParam);
}
break;
case WM_RBUTTONDOWN:
{
g_RButtonDown = true;
g_CurPos.x = LOWORD(lParam);
g_CurPos.y = HIWORD(lParam);
}
break;
case WM_LBUTTONUP:
g_LButtonDown = false;
break;
case WM_RBUTTONUP:
g_RButtonDown = false;
break;
case WM_MOUSEMOVE:
if (g_LButtonDown)
{
POINT pos;
pos.x = LOWORD(lParam);
pos.y = HIWORD(lParam);
const int x = pos.x - g_CurPos.x;
const int y = pos.y - g_CurPos.y;
g_CurPos = pos;
Matrix44 mat1;
mat1.SetRotationY( -x * 0.01f );
Matrix44 mat2;
mat2.SetRotationX( -y * 0.01f );
g_LocalTm *= (mat1 * mat2);
}
if (g_RButtonDown)
{
POINT pos;
pos.x = LOWORD(lParam);
pos.y = HIWORD(lParam);
const int x = pos.x - g_CurPos.x;
const int y = pos.y - g_CurPos.y;
g_CurPos = pos;
Matrix44 rx;
rx.SetRotationY( x * 0.005f );
Matrix44 ry;
ry.SetRotationX( y * 0.005f );
Matrix44 m = rx * ry;
g_camPos *= m;
UpdateCamera();
}
else
{
g_CurPos.x = LOWORD(lParam);
g_CurPos.y = HIWORD(lParam);
}
break;
case WM_MOUSEWHEEL:
{
const int fwKeys = GET_KEYSTATE_WPARAM(wParam);
const int zDelta = GET_WHEEL_DELTA_WPARAM(wParam);
Vector3 dir = g_lookAtPos - g_camPos;
dir.Normalize();
g_camPos += (zDelta < 0)? dir * -50 : dir*50;
UpdateCamera();
}
break;
case WM_DESTROY: //À©µµ¿ì°¡ ÆÄ±«µÈ´Ù¸é..
PostQuitMessage(0); //ÇÁ·Î±×·¥ Á¾·á ¿äû ( ¸Þ½ÃÁö ·çÇÁ¸¦ ºüÁ®³ª°¡°Ô µÈ´Ù )
break;
}
return DefWindowProc( hWnd, msg, wParam, lParam );
}
//·£´õ
void Render(int timeDelta)
{
//ȸé û¼Ò
if (SUCCEEDED(g_pDevice->Clear(
0, //û¼ÒÇÒ ¿µ¿ªÀÇ D3DRECT ¹è¿ °¹¼ö ( Àüü Ŭ¸®¾î 0 )
NULL, //û¼ÒÇÒ ¿µ¿ªÀÇ D3DRECT ¹è¿ Æ÷ÀÎÅÍ ( Àüü Ŭ¸®¾î NULL )
D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, //û¼ÒµÉ ¹öÆÛ Ç÷¹±× ( D3DCLEAR_TARGET Ä÷¯¹öÆÛ, D3DCLEAR_ZBUFFER ±íÀ̹öÆÛ, D3DCLEAR_STENCIL ½ºÅٽǹöÆÛ
D3DCOLOR_XRGB(150, 150, 150), //Ä÷¯¹öÆÛ¸¦ û¼ÒÇϰí ä¿öÁú »ö»ó( 0xAARRGGBB )
1.0f, //±íÀ̹öÆÛ¸¦ û¼ÒÇÒ°ª ( 0 ~ 1 0 ÀÌ Ä«¸Þ¶ó¿¡¼ Á¦Àϰ¡±î¿î 1 ÀÌ Ä«¸Þ¶ó¿¡¼ Á¦ÀÏ ¸Õ )
0 //½ºÅÙ½Ç ¹öÆÛ¸¦ ä¿ï°ª
)))
{
//ȸé û¼Ò°¡ ¼º°øÀûÀ¸·Î ÀÌ·ç¾î Á³´Ù¸é... ·£´õ¸µ ½ÃÀÛ
g_pDevice->BeginScene();
RenderFPS(timeDelta);
RenderAxis();
Matrix44 matS;
matS.SetScale(Vector3(1,2,1));
Matrix44 tm = matS * g_LocalTm;
g_shader.SetVector("vLightDir", Vector3(0,-1,0));
g_shader.SetMatrix("mWVP", tm * g_matView * g_matProj);
g_shader.SetVector("vEyePos", g_camPos);
Matrix44 mWIT = tm.Inverse();
mWIT.Transpose();
g_shader.SetMatrix("mWIT", mWIT);
g_shader.Begin();
g_shader.BeginPass(0);
g_texture.Bind(0);
g_sphere.Render(tm);
g_shader.EndPass();
g_shader.End();
//·£´õ¸µ ³¡
g_pDevice->EndScene();
//·£´õ¸µÀÌ ³¡³µÀ¸¸é ·£´õ¸µµÈ ³»¿ë ȸéÀ¸·Î Àü¼Û
g_pDevice->Present( NULL, NULL, NULL, NULL );
}
}
bool InitVertexBuffer()
{
g_shader.Create("hlsl_box_normal_phong_tex.fx", "TShader" );
g_texture.Create("../../media/°¼Ò¶ó.jpg");
g_sphere.Create(30, 20, 20);
// Ä«¸Þ¶ó, Åõ¿µÇà·Ä »ý¼º
UpdateCamera();
g_matProj.SetProjection(D3DX_PI * 0.5f, (float)WINSIZE_X / (float) WINSIZE_Y, 1.f, 10000.0f) ;
g_pDevice->SetTransform(D3DTS_PROJECTION, (D3DXMATRIX*)&g_matProj) ;
g_pDevice->SetRenderState(D3DRS_LIGHTING, false);
return true;
}
void UpdateCamera()
{
Vector3 dir = g_lookAtPos - g_camPos;
dir.Normalize();
g_matView.SetView(g_camPos, dir, Vector3(0,1,0));
graphic::GetDevice()->SetTransform(D3DTS_VIEW, (D3DXMATRIX*)&g_matView);
}<|fim▁end|>
|
g_CurPos.x = LOWORD(lParam);
|
<|file_name|>AddIgnoredIdentifierQuickFix.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.inspections.quickfix;
import com.intellij.codeInsight.intention.LowPriorityAction;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ex.InspectionProfileModifiableModelKt;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.QualifiedName;
import com.jetbrains.python.inspections.unresolvedReference.PyUnresolvedReferencesInspection;
import org.jetbrains.annotations.NotNull;
/**
* @author yole
*/
public class AddIgnoredIdentifierQuickFix implements LocalQuickFix, LowPriorityAction {
public static final String END_WILDCARD = ".*";
@NotNull private final QualifiedName myIdentifier;
private final boolean myIgnoreAllAttributes;
public AddIgnoredIdentifierQuickFix(@NotNull QualifiedName identifier, boolean ignoreAllAttributes) {
myIdentifier = identifier;
myIgnoreAllAttributes = ignoreAllAttributes;
}
@NotNull
@Override
public String getName() {
if (myIgnoreAllAttributes) {
return "Mark all unresolved attributes of '" + myIdentifier + "' as ignored";
}
else {
return "Ignore unresolved reference '" + myIdentifier + "'";
}
}
@NotNull
@Override
public String getFamilyName() {
return "Ignore unresolved reference";
}
@Override
public boolean startInWriteAction() {
return false;
}
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
final PsiElement context = descriptor.getPsiElement();
InspectionProfileModifiableModelKt.modifyAndCommitProjectProfile(project, model -> {
PyUnresolvedReferencesInspection inspection =
(PyUnresolvedReferencesInspection)model.getUnwrappedTool(PyUnresolvedReferencesInspection.class.getSimpleName(), context);
String name = myIdentifier.toString();
if (myIgnoreAllAttributes) {
name += END_WILDCARD;
}
assert inspection != null;
if (!inspection.ignoredIdentifiers.contains(name)) {
inspection.ignoredIdentifiers.add(name);
}
});<|fim▁hole|><|fim▁end|>
|
}
}
|
<|file_name|>concat-helper-tests.ts<|end_file_name|><|fim▁begin|>/// <reference path="../../include.d.ts" />
import * as should from "should";
import { create as createHandlebarsInstance } from "handlebars";
import { ConcatHelper } from "../../../src/services/template/concat-helper";
describe('ConcatHelper', function() {
it('concats single literal', function() {
// Arrange<|fim▁hole|> const handlebars = initHelper();
const template = `{{concat 'a'}}`;
const compiledTemplate = handlebars.compile(template);
// Act
const result = compiledTemplate({ });
// Assert
should(result).be.equal('a');
});
it('concats two literals', function() {
// Arrange
const handlebars = initHelper();
const template = `{{concat 'a' 'b'}}`;
const compiledTemplate = handlebars.compile(template);
// Act
const result = compiledTemplate({ });
// Assert
should(result).be.equal('ab');
});
it('concats literal with variable', function() {
// Arrange
const handlebars = initHelper();
const template = `{{concat 'a' value}}`;
const compiledTemplate = handlebars.compile(template);
// Act
const result = compiledTemplate({ value: 'b' });
// Assert
should(result).be.equal('ab');
});
});
function initHelper() {
const instance = createHandlebarsInstance();
const helper = new ConcatHelper();
instance.registerHelper(helper.name, helper.onExecute.bind(helper));
return instance;
}<|fim▁end|>
| |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>pub mod node;<|fim▁hole|><|fim▁end|>
|
pub mod list;
|
<|file_name|>KtekLoginEntity.java<|end_file_name|><|fim▁begin|>/*
*
* Copyright 2015 IK4-Tekniker All Rights Reserved
*
* This file is part of Health Questionnaire SE at FISTAR https://www.fi-star.eu/
*
* Health Questionnaire SE is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the<|fim▁hole|>*
* Health Questionnaire SE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Health Questionnaire SE. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* patricia.casla at tekniker dot es
*
* Author: Ignacio Lazaro Llorente
*/
package es.tekniker.framework.ktek.entity;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/*
* Class used as input parameter on login service
*/
@XmlRootElement(name = "KtekLoginEntity")
@XmlType(
namespace = "http://es.tekniker.framework.ktek",
propOrder = {"reference", "password", "coordinates"})
public class KtekLoginEntity implements Serializable{
private String reference;
private String password;
private KtekLoginCoordinatesEntity[] coordinates;
public boolean isRequiredDataDefined(){
boolean boolOK=true;
if(reference.equals(""))
boolOK=false;
if(password.equals(""))
boolOK=false;
if(coordinates == null)
boolOK=false;
if(coordinates.length !=3)
boolOK=false;
if(coordinates[0].getLetter()==null && coordinates[0].getLetter().equals(""))
boolOK=false;
if(coordinates[0].getValue()==null && coordinates[0].getValue().equals(""))
boolOK=false;
if(coordinates[1].getLetter()==null && coordinates[1].getLetter().equals(""))
boolOK=false;
if(coordinates[1].getValue()==null && coordinates[1].getValue().equals(""))
boolOK=false;
if(coordinates[2].getLetter()==null && coordinates[2].getLetter().equals(""))
boolOK=false;
if(coordinates[2].getValue()==null && coordinates[2].getValue().equals(""))
boolOK=false;
return boolOK;
}
/**
* @return the reference
*/
public String getReference() {
return reference;
}
/**
* @param reference the reference to set
*/
public void setReference(String reference) {
this.reference = reference;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return the coordinates
*/
public KtekLoginCoordinatesEntity[] getCoordinates() {
return coordinates;
}
/**
* @param coordinates the coordinates to set
*/
public void setCoordinates(KtekLoginCoordinatesEntity[] coordinates) {
this.coordinates = coordinates;
}
public String toString(){
String sData="reference:" + reference + " password:" + password ;
return sData;
}
}<|fim▁end|>
|
* License, or (at your option) any later version.
|
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>from setuptools import setup
setup(name='PyRankinity',
version='0.1',
description='Rankinity API Wrapper - See http://my.rankinity.com/api.en',
author='UpCounsel',
author_email='[email protected]',
url='https://www.github.com/upcounsel/pyrankinity',
packages=['pyrankinity'],<|fim▁hole|> license='MIT'
)<|fim▁end|>
|
install_requires=[
'requests',
],
|
<|file_name|>recipe.go<|end_file_name|><|fim▁begin|>package domain
// RecipeType blah blah
type RecipeType int
const (
pinRecipe RecipeType = iota
userRecipe
)
// RecipeIngredient is the link object between a recipe and an ingredient
type RecipeIngredient struct {
ID int
IngredientID int<|fim▁hole|>
// Recipe is the top level object that defines a recipe
type Recipe struct {
ID int
Name string
Type RecipeType
RecipeIngredientIDs []int
}<|fim▁end|>
|
Amount float32
Unit int
}
|
<|file_name|>fifa_spider.py<|end_file_name|><|fim▁begin|>from scrapy.spiders import Spider
from scrapy.selector import Selector
from scrapy.http import HtmlResponse
from FIFAscrape.items import PlayerItem
from urlparse import urlparse, urljoin
from scrapy.http.request import Request
from scrapy.conf import settings
import random
import time
class fifaSpider(Spider):
name = "fifa"
allowed_domains = ["futhead.com"]
start_urls = [
"http://www.futhead.com/16/players/?level=all_nif&bin_platform=ps"
]
<|fim▁hole|> url_list = sel.xpath('//a[@class="display-block padding-0"]/@href') #obtain a list of href links that contain relative links of players
for i in url_list:
relative_url = self.clean_str(i.extract()) #i is a selector and hence need to extract it to obtain unicode object
print urljoin(response.url, relative_url) #urljoin is able to merge absolute and relative paths to form 1 coherent link
req = Request(urljoin(response.url, relative_url),callback=self.parse_playerURL) #pass on request with new urls to parse_playerURL
req.headers["User-Agent"] = self.random_ua()
yield req
next_url=sel.xpath('//div[@class="right-nav pull-right"]/a[@rel="next"]/@href').extract_first()
if(next_url): #checks if next page exists
clean_next_url = self.clean_str(next_url)
reqNext = Request(urljoin(response.url, clean_next_url),callback=self.parse) #calls back this function to repeat process on new list of links
yield reqNext
def parse_playerURL(self, response):
#parses player specific data into items list
site = Selector(response)
items = []
item = PlayerItem()
item['1name'] = (response.url).rsplit("/")[-2].replace("-"," ")
title = self.clean_str(site.xpath('/html/head/title/text()').extract_first())
item['OVR'] = title.partition("FIFA 16 -")[1].split("-")[0]
item['POS'] = self.clean_str(site.xpath('//div[@class="playercard-position"]/text()').extract_first())
#stats = site.xpath('//div[@class="row player-center-container"]/div/a')
stat_names = site.xpath('//span[@class="player-stat-title"]')
stat_values = site.xpath('//span[contains(@class, "player-stat-value")]')
for index in range(len(stat_names)):
attr_name = stat_names[index].xpath('.//text()').extract_first()
item[attr_name] = stat_values[index].xpath('.//text()').extract_first()
items.append(item)
return items
def clean_str(self,ustring):
#removes wierd unicode chars (/u102 bla), whitespaces, tabspaces, etc to form clean string
return str(ustring.encode('ascii', 'replace')).strip()
def random_ua(self):
#randomise user-agent from list to reduce chance of being banned
ua = random.choice(settings.get('USER_AGENT_LIST'))
if ua:
ua='Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2226.0 Safari/537.36'
return ua<|fim▁end|>
|
def parse(self, response):
#obtains links from page to page and passes links to parse_playerURL
sel = Selector(response) #define selector based on response object (points to urls in start_urls by default)
|
<|file_name|>import_errors.py<|end_file_name|><|fim▁begin|>#
# Copyright (c) 2010, 2015, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
"""
import_errors test.
"""
import os
import subprocess
import import_basic
from mysql.utilities.exception import MUTLibError, UtilError
class test(import_basic.test):
"""Import Data
This test executes the import utility on a single server.
It tests the error conditions for importing data.
It uses the import_basic test for setup and teardown methods.
"""
perms_test_file = "not_readable.sql"
def check_prerequisites(self):
return import_basic.test.check_prerequisites(self)
def setup(self):
return import_basic.test.setup(self)
def run(self):
self.res_fname = "result.txt"
from_conn = "--server={0}".format(
self.build_connection_string(self.server1)
)
to_conn = "--server={0}".format(
self.build_connection_string(self.server2)
)
_FORMATS = ("CSV", "TAB", "GRID", "VERTICAL")
test_num = 1
for frmt in _FORMATS:
comment = ("Test Case {0} : Testing import with "
"{1} format and NAMES display").format(test_num, frmt)
# We test DEFINITIONS and DATA only in other tests
self.run_import_test(1, from_conn, to_conn, ['util_test'], frmt,
"BOTH", comment, " --display=NAMES")
self.drop_db(self.server2, "util_test")
test_num += 1
export_cmd = ("mysqldbexport.py {0} util_test --export=BOTH "
"--format=SQL --skip-gtid > "
"{1}").format(from_conn, self.export_import_file)
# First run the export to a file.
comment = "Running export..."
res = self.run_test_case(0, export_cmd, comment)
if not res:
raise MUTLibError("EXPORT: {0}: failed".format(comment))
import_cmd = "mysqldbimport.py {0}".format(to_conn)
comment = "Test case {0} - no file specified ".format(test_num)
cmd_str = "{0} --import=BOTH --format=SQL".format(import_cmd)
res = self.run_test_case(2, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
import_cmd = ("{0} {1} --import=BOTH "
"--format=SQL").format(import_cmd,
self.export_import_file)
test_num += 1
comment = "Test case {0} - bad --skip values".format(test_num)
cmd_str = "{0} --skip=events,wiki-waki,woo-woo".format(import_cmd)
res = self.run_test_case(1, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = ("Test case {0} - exporting data and skipping "
"data").format(test_num)
cmd_str = "{0} --skip=data --import=data".format(import_cmd)
res = self.run_test_case(1, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = "Test case {0} - cannot parse --server".format(test_num)
cmd_str = ("mysqldbimport.py --server=rocks_rocks_rocks "
"{0}").format(self.export_import_file)
res = self.run_test_case(2, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = ("Test case {0} - error: cannot connect to "
"server").format(test_num)
cmd_str = ("mysqldbimport.py --server=nope:nada@localhost:{0} "
"{1}").format(self.server0.port, self.export_import_file)
res = self.run_test_case(1, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
self.server2.exec_query("CREATE USER 'joe'@'localhost'")
# Watchout for Windows: it doesn't use sockets!
joe_conn = "--server=joe@localhost:{0}".format(self.server2.port)
if os.name == "posix" and self.server2.socket is not None:
joe_conn = "{0}:{1}".format(joe_conn, self.server2.socket)
test_num += 1
comment = ("Test case {0} - error: not enough "
"privileges").format(test_num)
cmd_str = "mysqldbimport.py {0} {1}".format(joe_conn,
self.export_import_file)
res = self.run_test_case(1, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = ("Test case {0} - error: not enough "
"privileges").format(test_num)
cmd_str = ("mysqldbimport.py {0} {1} "
"--import=definitions").format(joe_conn,
self.export_import_file)
res = self.run_test_case(1, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = "Test case {0} - error: bad SQL statements".format(test_num)
bad_sql_file = os.path.normpath("./std_data/bad_sql.sql")
cmd_str = ("mysqldbimport.py {0} {1} "
"--import=definitions").format(to_conn, bad_sql_file)
res = self.run_test_case(1, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
self.drop_db(self.server2, "util_test")
# Skipping create and doing the drop should be illegal.
test_num += 1
comment = ("Test case {0} - error: --skip=create_db & "
"--drop-first").format(test_num)
cmd_str = ("{0} {1} --skip=create_db --format=sql --import=data "
"--drop-first ").format(import_cmd, self.export_import_file)
res = self.run_test_case(1, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
self.drop_db(self.server2, "util_test")
import_cmd = "mysqldbimport.py {0}".format(to_conn)
test_num += 1
comment = "Test case {0} - warning: --skip-blobs".format(test_num)<|fim▁hole|> "{1}").format(import_cmd, self.export_import_file)
res = self.run_test_case(0, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = ("Test case {0} - error: --skip=data & "
"--import=data").format(test_num)
cmd_str = ("{0} --skip=data --format=sql --import=data "
"{1}").format(import_cmd, self.export_import_file)
res = self.run_test_case(1, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = ("Test case {0} - error: bad object "
"definition").format(test_num)
bad_csv_file = os.path.normpath("./std_data/bad_object.csv")
cmd_str = ("{0} --format=csv --import=both "
"{1}").format(import_cmd, bad_csv_file)
res = self.run_test_case(1, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
# Test database with backticks
_FORMATS_BACKTICKS = ("CSV", "TAB")
for frmt in _FORMATS_BACKTICKS:
comment = ("Test Case {0} : Testing import with {1} format and "
"NAMES display (using backticks)").format(test_num,
frmt)
self.run_import_test(1, from_conn, to_conn, ['`db``:db`'],
frmt, "BOTH", comment, " --display=NAMES")
self.drop_db(self.server2, '`db``:db`')
test_num += 1
comment = "Test case {0} - invalid --character-set".format(test_num)
cmd_str = ("mysqldbimport.py {0} {1} "
"--character-set=unsupported_charset"
"".format(self.export_import_file, to_conn))
res = self.run_test_case(1, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
# Run export to re-create the export file.
comment = "Running export to {0}...".format(self.export_import_file)
res = self.run_test_case(0, export_cmd, comment)
if not res:
raise MUTLibError("EXPORT: {0}: failed".format(comment))
test_num += 1
comment = ("Test case {0} - error: invalid multiprocess "
"value.").format(test_num)
cmd_str = ("{0} --format=sql --import=both --multiprocess=0.5 "
"{1}").format(import_cmd, self.export_import_file)
res = self.run_test_case(2, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = ("Test case {0} - error: multiprocess value smaller than "
"zero.").format(test_num)
cmd_str = ("{0} --format=sql --import=both --multiprocess=-1 "
"{1}").format(import_cmd, self.export_import_file)
res = self.run_test_case(2, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = ("Test case {0} - error: invalid max bulk insert "
"value.").format(test_num)
cmd_str = ("{0} --format=sql --import=both --max-bulk-insert=2.5 "
"{1}").format(import_cmd, self.export_import_file)
res = self.run_test_case(2, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = ("Test case {0} - error: max bulk insert value not greater "
"than one.").format(test_num)
cmd_str = ("{0} --format=sql --import=both --max-bulk-insert=1 "
"{1}").format(import_cmd, self.export_import_file)
res = self.run_test_case(2, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
self.drop_db(self.server2, "util_test")
test_num += 1
comment = ("Test case {0} - warning: max bulk insert ignored without "
"bulk insert option.").format(test_num)
cmd_str = ("{0} --format=sql --import=both --max-bulk-insert=10000 "
"{1}").format(import_cmd, self.export_import_file)
res = self.run_test_case(0, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = ("Test case {0} - error: Use --drop-first to drop the "
"database before importing.").format(test_num)
data_file = os.path.normpath("./std_data/basic_data.sql")
cmd_str = ("{0} --format=sql --import=both "
"{1}").format(import_cmd, data_file)
res = self.run_test_case(1, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = ("Test case {0} - error: Is not a valid path to a file."
"").format(test_num)
cmd_str = ("{0} --format=sql --import=both not_exist.sql"
"").format(import_cmd)
res = self.run_test_case(2, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
test_num += 1
comment = ("Test case {0} - error: Without permission to read a file."
"").format(test_num)
cmd_str = ("{0} --format=sql --import=both {1}"
"").format(import_cmd, self.perms_test_file)
# Create file without read permission.
with open(self.perms_test_file, "w"):
pass
if os.name == "posix":
os.chmod(self.perms_test_file, 0200)
else:
proc = subprocess.Popen(["icacls", self.perms_test_file, "/deny",
"everyone:(R)"], stdout=subprocess.PIPE)
proc.communicate()
res = self.run_test_case(2, cmd_str, comment)
if not res:
raise MUTLibError("{0}: failed".format(comment))
# Handle message with path (replace '\' by '/').
if os.name != "posix":
self.replace_result("# Importing definitions and data from "
"std_data\\bad_object.csv",
"# Importing definitions and data from "
"std_data/bad_object.csv.\n")
self.replace_result("# Importing definitions from "
"std_data\\bad_sql.sql",
"# Importing definitions from "
"std_data/bad_sql.sql.\n")
self.replace_result("# Importing definitions and data from "
"std_data\\basic_data.sql.",
"# Importing definitions and data from "
"std_data/basic_data.sql.\n")
# Mask known source and destination host name.
self.replace_substring("on localhost", "on XXXX-XXXX")
self.replace_substring("on [::1]", "on XXXX-XXXX")
self.replace_substring(" (28000)", "")
self.replace_result("ERROR: Query failed.", "ERROR: Query failed.\n")
self.replace_substring("Error 1045 (28000):", "Error")
self.replace_substring("Error 1045:", "Error")
self.replace_result("mysqldbimport: error: Server connection "
"values invalid",
"mysqldbimport: error: Server connection "
"values invalid\n")
self.replace_result("ERROR: Unknown error 1045",
"ERROR: Access denied for user 'nope'@'localhost' "
"(using password: YES)\n")
return True
def get_result(self):
return self.compare(__name__, self.results)
def record(self):
return self.save_result_file(__name__, self.results)
def cleanup(self):
try:
if os.path.exists(self.perms_test_file):
if os.name != "posix":
# Add write permission to the permissions test file so
# that its deletion is possible when using MS Windows.
proc = subprocess.Popen(["icacls", self.perms_test_file,
"/grant", "everyone:(W)"],
stdout=subprocess.PIPE)
proc.communicate()
os.unlink(self.perms_test_file)
except OSError:
pass
try:
self.server2.exec_query("DROP USER 'joe'@'localhost'")
except UtilError:
pass
return import_basic.test.drop_all(self)<|fim▁end|>
|
cmd_str = ("{0} --skip-blobs --format=sql --import=definitions "
|
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys<|fim▁hole|>from foobar.app import create_app
from foobar.user.models import User
from foobar.settings import DevConfig, ProdConfig
from foobar.database import db
if os.environ.get("FOOBAR_ENV") == 'prod':
app = create_app(ProdConfig)
else:
app = create_app(DevConfig)
HERE = os.path.abspath(os.path.dirname(__file__))
TEST_PATH = os.path.join(HERE, 'tests')
manager = Manager(app)
def _make_context():
"""Return context dict for a shell session so you can access
app, db, and the User model by default.
"""
return {'app': app, 'db': db, 'User': User}
@manager.command
def test():
"""Run the tests."""
import pytest
exit_code = pytest.main([TEST_PATH, '--verbose'])
return exit_code
manager.add_command('server', Server())
manager.add_command('shell', Shell(make_context=_make_context))
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()<|fim▁end|>
|
import subprocess
from flask.ext.script import Manager, Shell, Server
from flask.ext.migrate import MigrateCommand
|
<|file_name|>package-info.java<|end_file_name|><|fim▁begin|>//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.07.08 at 01:02:29 PM CEST
//
@XmlSchema(namespace = "http://uri.etsi.org/m2m",
xmlns = { @XmlNs(namespaceURI = "http://uri.etsi.org/m2m", prefix = "om2m")},
<|fim▁hole|>import javax.xml.bind.annotation.XmlSchema;<|fim▁end|>
|
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.eclipse.om2m.commons.resource;
import javax.xml.bind.annotation.XmlNs;
|
<|file_name|>find.go<|end_file_name|><|fim▁begin|>// Copyright (c) 2015-2021 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"bytes"
"context"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
"time"
"github.com/dustin/go-humanize"
"github.com/minio/mc/pkg/probe"
"github.com/minio/pkg/console"
// golang does not support flat keys for path matching, find does
"github.com/minio/pkg/wildcard"
)
// findMessage holds JSON and string values for printing find command output.
type findMessage struct {
contentMessage
}
// String calls tells the console what to print and how to print it.
func (f findMessage) String() string {
return console.Colorize("Find", f.contentMessage.Key)
}
// JSON formats output to be JSON output.
func (f findMessage) JSON() string {
return f.contentMessage.JSON()
}
// nameMatch is similar to filepath.Match but only matches the
// base path of the input, if we couldn't find a match we
// also proceed to look for similar strings alone and print it.
//
// pattern:
// { term }
// term:
// '*' matches any sequence of non-Separator characters
// '?' matches any single non-Separator character
// '[' [ '^' ] { character-range } ']'
// character class (must be non-empty)
// c matches character c (c != '*', '?', '\\', '[')
// '\\' c matches character c
// character-range:
// c matches character c (c != '\\', '-', ']')
// '\\' c matches character c
// lo '-' hi matches character c for lo <= c <= hi
//
func nameMatch(pattern, path string) bool {
matched, e := filepath.Match(pattern, filepath.Base(path))
errorIf(probe.NewError(e).Trace(pattern, path), "Unable to match with input pattern.")
if !matched {
for _, pathComponent := range strings.Split(path, "/") {
matched = pathComponent == pattern
if matched {
break
}
}
}
return matched
}
// pathMatch reports whether path matches the wildcard pattern.
// supports '*' and '?' wildcards in the pattern string.
// unlike path.Match(), considers a path as a flat name space
// while matching the pattern. The difference is illustrated in
// the example here https://play.golang.org/p/Ega9qgD4Qz .
func pathMatch(pattern, path string) bool {
return wildcard.Match(pattern, path)
}
// regexMatch reports whether path matches the regex pattern.
func regexMatch(pattern, path string) bool {
matched, e := regexp.MatchString(pattern, path)
errorIf(probe.NewError(e).Trace(pattern), "Unable to regex match with input pattern.")
return matched
}
func getExitStatus(err error) int {
if err == nil {
return 0
}
if pe, ok := err.(*exec.ExitError); ok {
if es, ok := pe.ProcessState.Sys().(syscall.WaitStatus); ok {
return es.ExitStatus()
}
}
return 1
}
// execFind executes the input command line, additionally formats input
// for the command line in accordance with subsititution arguments.
func execFind(command string) {
commandArgs := strings.Split(command, " ")
cmd := exec.Command(commandArgs[0], commandArgs[1:]...)
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
console.Print(console.Colorize("FindExecErr", stderr.String()))
// Return exit status of the command run
os.Exit(getExitStatus(err))
}
console.PrintC(out.String())
}
// watchFind - enables listening on the input path, listens for all file/object
// created actions. Asynchronously executes the input command line, also allows
// formatting for the command line in accordance with subsititution arguments.
func watchFind(ctxCtx context.Context, ctx *findContext) {
// Watch is not enabled, return quickly.
if !ctx.watch {
return
}
options := WatchOptions{
Recursive: true,
Events: []string{"put"},
}
watchObj, err := ctx.clnt.Watch(ctxCtx, options)
fatalIf(err.Trace(ctx.targetAlias), "Unable to watch with given options.")
// Loop until user CTRL-C the command line.
for {
select {
case <-globalContext.Done():
console.Println()
close(watchObj.DoneChan)
return
case events, ok := <-watchObj.Events():
if !ok {
return
}
for _, event := range events {
time, e := time.Parse(time.RFC3339, event.Time)
if e != nil {
errorIf(probe.NewError(e).Trace(event.Time), "Unable to parse event time.")
continue
}
find(ctxCtx, ctx, contentMessage{
Key: getAliasedPath(ctx, event.Path),
Time: time,
Size: event.Size,
})
}
case err, ok := <-watchObj.Errors():
if !ok {
return
}
errorIf(err, "Unable to watch for events.")
return
}
}
}
// Descend at most (a non-negative integer) levels of files
// below the starting-prefix and trims the suffix. This function
// returns path as is without manipulation if the maxDepth is 0
// i.e (not set).
func trimSuffixAtMaxDepth(startPrefix, path, separator string, maxDepth uint) string {
if maxDepth == 0 {
return path
}
// Remove the requested prefix from consideration, maxDepth is
// only considered for all other levels excluding the starting prefix.
path = strings.TrimPrefix(path, startPrefix)
pathComponents := strings.SplitAfter(path, separator)
if len(pathComponents) >= int(maxDepth) {
pathComponents = pathComponents[:maxDepth]
}
pathComponents = append([]string{startPrefix}, pathComponents...)
return strings.Join(pathComponents, "")
}
// Get aliased path used finally in printing, trim paths to ensure
// that we have removed the fully qualified paths and original
// start prefix (targetAlias) is retained. This function also honors
// maxDepth if set then the resultant path will be trimmed at requested
// maxDepth.
func getAliasedPath(ctx *findContext, path string) string {
separator := string(ctx.clnt.GetURL().Separator)
prefixPath := ctx.clnt.GetURL().String()
var aliasedPath string
if ctx.targetAlias != "" {
aliasedPath = ctx.targetAlias + strings.TrimPrefix(path, strings.TrimSuffix(ctx.targetFullURL, separator))
} else {
aliasedPath = path
// look for prefix path, if found filter at that, Watch calls
// for example always provide absolute path. So for relative
// prefixes we need to employ this kind of code.
if i := strings.Index(path, prefixPath); i > 0 {
aliasedPath = path[i:]
}
}
return trimSuffixAtMaxDepth(ctx.targetURL, aliasedPath, separator, ctx.maxDepth)
}
func find(ctxCtx context.Context, ctx *findContext, fileContent contentMessage) {
// Match the incoming content, didn't match return.
if !matchFind(ctx, fileContent) {
return
} // For all matching content
// proceed to either exec, format the output string.
if ctx.execCmd != "" {
execFind(stringsReplace(ctxCtx, ctx.execCmd, fileContent))
return
}
if ctx.printFmt != "" {
fileContent.Key = stringsReplace(ctxCtx, ctx.printFmt, fileContent)
}
printMsg(findMessage{fileContent})
}
// doFind - find is main function body which interprets and executes
// all the input parameters.
func doFind(ctxCtx context.Context, ctx *findContext) error {
// If watch is enabled we will wait on the prefix perpetually
// for all I/O events until canceled by user, if watch is not enabled
// following defer is a no-op.
defer watchFind(ctxCtx, ctx)
var prevKeyName string
<|fim▁hole|> switch content.Err.ToGoError().(type) {
// handle this specifically for filesystem related errors.
case BrokenSymlink:
errorIf(content.Err.Trace(ctx.clnt.GetURL().String()), "Unable to list broken link.")
continue
case TooManyLevelsSymlink:
errorIf(content.Err.Trace(ctx.clnt.GetURL().String()), "Unable to list too many levels link.")
continue
case PathNotFound:
errorIf(content.Err.Trace(ctx.clnt.GetURL().String()), "Unable to list folder.")
continue
case PathInsufficientPermission:
errorIf(content.Err.Trace(ctx.clnt.GetURL().String()), "Unable to list folder.")
continue
}
fatalIf(content.Err.Trace(ctx.clnt.GetURL().String()), "Unable to list folder.")
continue
}
if content.StorageClass == s3StorageClassGlacier {
continue
}
fileKeyName := getAliasedPath(ctx, content.URL.String())
fileContent := contentMessage{
Key: fileKeyName,
Time: content.Time.Local(),
Size: content.Size,
}
// Match the incoming content, didn't match return.
if !matchFind(ctx, fileContent) || prevKeyName == fileKeyName {
continue
} // For all matching content
prevKeyName = fileKeyName
// proceed to either exec, format the output string.
if ctx.execCmd != "" {
execFind(stringsReplace(ctxCtx, ctx.execCmd, fileContent))
continue
}
if ctx.printFmt != "" {
fileContent.Key = stringsReplace(ctxCtx, ctx.printFmt, fileContent)
}
printMsg(findMessage{fileContent})
}
// Success, notice watch will execute in defer only if enabled and this call
// will return after watch is canceled.
return nil
}
// stringsReplace - formats the string to remove {} and replace each
// with the appropriate argument
func stringsReplace(ctx context.Context, args string, fileContent contentMessage) string {
// replace all instances of {}
str := args
if strings.Contains(str, "{}") {
str = strings.Replace(str, "{}", fileContent.Key, -1)
}
// replace all instances of {""}
if strings.Contains(str, `{""}`) {
str = strings.Replace(str, `{""}`, strconv.Quote(fileContent.Key), -1)
}
// replace all instances of {base}
if strings.Contains(str, "{base}") {
str = strings.Replace(str, "{base}", filepath.Base(fileContent.Key), -1)
}
// replace all instances of {"base"}
if strings.Contains(str, `{"base"}`) {
str = strings.Replace(str, `{"base"}`, strconv.Quote(filepath.Base(fileContent.Key)), -1)
}
// replace all instances of {dir}
if strings.Contains(str, "{dir}") {
str = strings.Replace(str, "{dir}", filepath.Dir(fileContent.Key), -1)
}
// replace all instances of {"dir"}
if strings.Contains(str, `{"dir"}`) {
str = strings.Replace(str, `{"dir"}`, strconv.Quote(filepath.Dir(fileContent.Key)), -1)
}
// replace all instances of {size}
if strings.Contains(str, "{size}") {
str = strings.Replace(str, "{size}", humanize.IBytes(uint64(fileContent.Size)), -1)
}
// replace all instances of {"size"}
if strings.Contains(str, `{"size"}`) {
str = strings.Replace(str, `{"size"}`, strconv.Quote(humanize.IBytes(uint64(fileContent.Size))), -1)
}
// replace all instances of {time}
if strings.Contains(str, "{time}") {
str = strings.Replace(str, "{time}", fileContent.Time.Format(printDate), -1)
}
// replace all instances of {"time"}
if strings.Contains(str, `{"time"}`) {
str = strings.Replace(str, `{"time"}`, strconv.Quote(fileContent.Time.Format(printDate)), -1)
}
// replace all instances of {url}
if strings.Contains(str, "{url}") {
str = strings.Replace(str, "{url}", getShareURL(ctx, fileContent.Key), -1)
}
// replace all instances of {"url"}
if strings.Contains(str, `{"url"}`) {
str = strings.Replace(str, `{"url"}`, strconv.Quote(getShareURL(ctx, fileContent.Key)), -1)
}
return str
}
// matchFind matches whether fileContent matches appropriately with standard
// "pattern matching" flags requested by the user, such as "name", "path", "regex" ..etc.
func matchFind(ctx *findContext, fileContent contentMessage) (match bool) {
match = true
prefixPath := ctx.targetURL
// Add separator only if targetURL doesn't already have separator.
if !strings.HasPrefix(prefixPath, string(ctx.clnt.GetURL().Separator)) {
prefixPath = ctx.targetURL + string(ctx.clnt.GetURL().Separator)
}
// Trim the prefix such that we will apply file path matching techniques
// on path excluding the starting prefix.
path := strings.TrimPrefix(fileContent.Key, prefixPath)
if match && ctx.ignorePattern != "" {
match = !pathMatch(ctx.ignorePattern, path)
}
if match && ctx.namePattern != "" {
match = nameMatch(ctx.namePattern, path)
}
if match && ctx.pathPattern != "" {
match = pathMatch(ctx.pathPattern, path)
}
if match && ctx.regexPattern != "" {
match = regexMatch(ctx.regexPattern, path)
}
if match && ctx.olderThan != "" {
match = !isOlder(fileContent.Time, ctx.olderThan)
}
if match && ctx.newerThan != "" {
match = !isNewer(fileContent.Time, ctx.newerThan)
}
if match && ctx.largerSize > 0 {
match = int64(ctx.largerSize) < fileContent.Size
}
if match && ctx.smallerSize > 0 {
match = int64(ctx.smallerSize) > fileContent.Size
}
return match
}
// 7 days in seconds.
var defaultSevenDays = time.Duration(604800) * time.Second
// getShareURL is used in conjunction with the {url} substitution
// argument to generate and return presigned URLs, returns error if any.
func getShareURL(ctx context.Context, path string) string {
targetAlias, targetURLFull, _, err := expandAlias(path)
fatalIf(err.Trace(path), "Unable to expand alias.")
clnt, err := newClientFromAlias(targetAlias, targetURLFull)
fatalIf(err.Trace(targetAlias, targetURLFull), "Unable to initialize client instance from alias.")
content, err := clnt.Stat(ctx, StatOptions{})
fatalIf(err.Trace(targetURLFull, targetAlias), "Unable to lookup file/object.")
// Skip if its a directory.
if content.Type.IsDir() {
return ""
}
objectURL := content.URL.String()
newClnt, err := newClientFromAlias(targetAlias, objectURL)
fatalIf(err.Trace(targetAlias, objectURL), "Unable to initialize new client from alias.")
// Set default expiry for each url (point of no longer valid), to be 7 days
shareURL, err := newClnt.ShareDownload(ctx, "", defaultSevenDays)
fatalIf(err.Trace(targetAlias, objectURL), "Unable to generate share url.")
return shareURL
}<|fim▁end|>
|
// iterate over all content which is within the given directory
for content := range ctx.clnt.List(globalContext, ListOptions{Recursive: true, ShowDir: DirFirst}) {
if content.Err != nil {
|
<|file_name|>register.go<|end_file_name|><|fim▁begin|>/*<|fim▁hole|>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 v1
import (
"k8s.io/client-go/1.5/pkg/api/unversioned"
"k8s.io/client-go/1.5/pkg/api/v1"
"k8s.io/client-go/1.5/pkg/runtime"
versionedwatch "k8s.io/client-go/1.5/pkg/watch/versioned"
)
// GroupName is the group name use in this package
const GroupName = "batch"
// SchemeGroupVersion is group version used to register these objects
var SchemeGroupVersion = unversioned.GroupVersion{Group: GroupName, Version: "v1"}
var (
SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes, addDefaultingFuncs, addConversionFuncs)
AddToScheme = SchemeBuilder.AddToScheme
)
// Adds the list of known types to api.Scheme.
func addKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&Job{},
&JobList{},
&v1.ListOptions{},
&v1.DeleteOptions{},
)
versionedwatch.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil
}<|fim▁end|>
|
Copyright 2016 The Kubernetes Authors.
|
<|file_name|>robust_mutex.hpp<|end_file_name|><|fim▁begin|>//----------------------------------------------------------------------------
/// \file robust_mutex.hpp
/// \author Serge Aleynikov
//----------------------------------------------------------------------------
/// \brief Robust mutex that can be shared between processes.
//----------------------------------------------------------------------------
// Created: 2009-11-21
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
This file is part of the utxx open-source project.
Copyright (C) 2010 Serge Aleynikov <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
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
***** END LICENSE BLOCK *****
*/
#pragma once
#include <mutex>
#include <functional>
#include <utxx/error.hpp>
namespace utxx {
class robust_mutex {
public:
using self_type = robust_mutex;
using make_consistent_functor = std::function<int (robust_mutex&)>;
using native_handle_type = pthread_mutex_t*;
using scoped_lock = std::lock_guard<robust_mutex>;
using scoped_try_lock = std::unique_lock<robust_mutex>;
make_consistent_functor on_make_consistent;
explicit robust_mutex(bool a_destroy_on_exit = false)
: m(NULL), m_destroy(a_destroy_on_exit)
{}
robust_mutex(pthread_mutex_t& a_mutex,
bool a_init = false, bool a_destroy_on_exit = false)
{
if (a_init)
init(a_mutex);
else
set(a_mutex);
m_destroy = a_destroy_on_exit;
}
void set(pthread_mutex_t& a_mutex) { m = &a_mutex; }
void init(pthread_mutex_t& a_mutex, pthread_mutexattr_t* a_attr=NULL) {
m = &a_mutex;
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_t* mutex_attr = a_attr ? a_attr : &attr;
if (pthread_mutexattr_setpshared(mutex_attr, PTHREAD_PROCESS_SHARED) < 0)
UTXX_THROW_IO_ERROR(errno);
if (pthread_mutexattr_setrobust_np(mutex_attr, PTHREAD_MUTEX_ROBUST_NP) < 0)
UTXX_THROW_IO_ERROR(errno);
if (pthread_mutexattr_setprotocol(mutex_attr, PTHREAD_PRIO_INHERIT) < 0)
UTXX_THROW_IO_ERROR(errno);
if (pthread_mutex_init(m, mutex_attr) < 0)
UTXX_THROW_IO_ERROR(errno);
}
~robust_mutex() {
if (!m_destroy) return;
destroy();
}
void lock() {
assert(m);
int res;
while (1) {
res = pthread_mutex_lock(m);
switch (res) {
case 0:
return;
case EINTR:
continue;
case EOWNERDEAD:
res = on_make_consistent
? on_make_consistent(*this)
: make_consistent();
if (res)
UTXX_THROW_IO_ERROR(res);
return;
default:
// If ENOTRECOVERABLE - mutex is not recoverable, must be destroyed.
UTXX_THROW_IO_ERROR(res);
return;
}
}
}
void unlock() {
assert(m);
int ret;
do { ret = pthread_mutex_unlock(m); } while (ret == EINTR);
}
bool try_lock() {
assert(m);
int res;
do { res = pthread_mutex_trylock(m); } while (res == EINTR);
if ( res && (res!=EBUSY) )
UTXX_THROW_IO_ERROR(res);
return !res;
}
int make_consistent() {
assert(m);
return pthread_mutex_consistent_np(m);
}
void destroy() {
if (!m) return;
int ret;
do { ret = pthread_mutex_destroy(m); } while (ret == EINTR);
m = NULL;
}
native_handle_type native_handle() { return m; }
<|fim▁hole|> bool m_destroy;
robust_mutex(const robust_mutex&);
};
} // namespace utxx<|fim▁end|>
|
private:
pthread_mutex_t* m;
|
<|file_name|>regions-return-interior-of-option.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<|fim▁hole|>// 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 get<T>(opt: &Option<T>) -> &T {
match *opt {
Some(ref v) => v,
None => fail!("none")
}
}
pub fn main() {
let mut x = Some(23i);
{
let y = get(&x);
assert_eq!(*y, 23);
}
x = Some(24i);
{
let y = get(&x);
assert_eq!(*y, 24);
}
}<|fim▁end|>
| |
<|file_name|>generateProptypes.ts<|end_file_name|><|fim▁begin|>import * as path from 'path';
import * as fse from 'fs-extra';
import * as ttp from 'typescript-to-proptypes';
import * as prettier from 'prettier';
import * as globCallback from 'glob';
import { promisify } from 'util';
import * as _ from 'lodash';
import { fixBabelGeneratorIssues, fixLineEndings } from '../docs/scripts/helpers';
const glob = promisify(globCallback);
const ignoreCache = process.argv.includes('--disable-cache');
const verbose = process.argv.includes('--verbose');
enum GenerateResult {
Success,
Skipped,
NoComponent,
Failed,
}
const tsconfig = ttp.loadConfig(path.resolve(__dirname, '../tsconfig.json'));
const prettierConfig = prettier.resolveConfig.sync(process.cwd(), {
config: path.join(__dirname, '../prettier.config.js'),
});
async function generateProptypes(
tsFile: string,
jsFile: string,
program: ttp.ts.Program,
): Promise<GenerateResult> {
const proptypes = ttp.parseFromProgram(tsFile, program, {
shouldResolveObject: ({ name }) => {
if (name.toLowerCase().endsWith('classes') || name === 'theme' || name.endsWith('Props')) {
return false;
}
return undefined;
},
});
if (proptypes.body.length === 0) {
return GenerateResult.NoComponent;
}
proptypes.body.forEach(component => {
component.types.forEach(prop => {
if (prop.name === 'classes' && prop.jsDoc) {
prop.jsDoc += '\nSee [CSS API](#css) below for more details.';
} else if (prop.name === 'children' && !prop.jsDoc) {
prop.jsDoc = 'The content of the component.';
} else if (!prop.jsDoc) {
prop.jsDoc = '@ignore';
}
});
});
const jsContent = await fse.readFile(jsFile, 'utf8');
const result = ttp.inject(proptypes, jsContent, {
removeExistingPropTypes: true,
comment: [
'----------------------------- Warning --------------------------------',
'| These PropTypes are generated from the TypeScript type definitions |',
'| To update them edit the d.ts file and run "yarn proptypes" |',
'----------------------------------------------------------------------',
].join('\n'),
shouldInclude: ({ prop }) => {
if (prop.name === 'children') {
return true;
}
const documentRegExp = new RegExp(/\r?\n?@document/);
if (prop.jsDoc && documentRegExp.test(prop.jsDoc)) {
prop.jsDoc = prop.jsDoc.replace(documentRegExp, '');
return true;
}
return undefined;
},
});
if (!result) {
return GenerateResult.Failed;
}
const prettified = prettier.format(result, { ...prettierConfig, filepath: jsFile });
const formatted = fixBabelGeneratorIssues(prettified);
const correctedLineEndings = fixLineEndings(jsContent, formatted);
await fse.writeFile(jsFile, correctedLineEndings);
return GenerateResult.Success;
}
async function run() {
// Matches files where the folder and file both start with uppercase letters
// Example: AppBar/AppBar.d.ts
const allFiles = await Promise.all(
[
path.resolve(__dirname, '../packages/material-ui/src'),
path.resolve(__dirname, '../packages/material-ui-lab/src'),
].map(folderPath =>
glob('+([A-Z])*/+([A-Z])*.d.ts', {
absolute: true,
cwd: folderPath,
}),
),
);
const files = _.flatten(allFiles)
// Filter out files where the directory name and filename doesn't match
// Example: Modal/ModalManager.d.ts
.filter(filePath => {
const folderName = path.basename(path.dirname(filePath));
const fileName = path.basename(filePath, '.d.ts');
return fileName === folderName;
});
const program = ttp.createProgram(files, tsconfig);
const promises = files.map<Promise<GenerateResult>>(async tsFile => {
const jsFile = tsFile.replace('.d.ts', '.js');
if (!ignoreCache && (await fse.stat(jsFile)).mtimeMs > (await fse.stat(tsFile)).mtimeMs) {
// Javascript version is newer, skip file
return GenerateResult.Skipped;
}
return generateProptypes(tsFile, jsFile, program);
});
const results = await Promise.all(promises);
if (verbose) {
files.forEach((file, index) => {
console.log('%s - %s', GenerateResult[results[index]], path.basename(file, '.d.ts'));<|fim▁hole|> }
console.log('--- Summary ---');
const groups = _.groupBy(results, x => x);
_.forOwn(groups, (count, key) => {
console.log('%s: %d', GenerateResult[(key as unknown) as GenerateResult], count.length);
});
console.log('Total: %d', results.length);
}
run().catch(error => {
console.error(error);
process.exit(1);
});<|fim▁end|>
|
});
|
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>DESCRIPTION = """\
ACQ4 is a python-based platform for experimental neurophysiology.
It includes support for standard electrophysiology, multiphoton imaging,
scanning laser photostimulation, and many other experimental techniques. ACQ4 is
highly modular and extensible, allowing support to be added for new types of
devices, techniques, user-interface modules, and analyses.
"""
setupOpts = dict(
name='acq4',
description='Neurophysiology acquisition and analysis platform',
long_description=DESCRIPTION,
license='MIT',
url='http://www.acq4.org',<|fim▁hole|>
from setuptools import setup
import distutils.dir_util
import distutils.sysconfig
import os, sys, re
from subprocess import check_output
## generate list of all sub-packages
path = os.path.abspath(os.path.dirname(__file__))
n = len(path.split(os.path.sep))
subdirs = [i[0].split(os.path.sep)[n:] for i in os.walk(os.path.join(path, 'acq4')) if '__init__.py' in i[2]]
allPackages = ['.'.join(p) for p in subdirs]
## Make sure build directory is clean before installing
buildPath = os.path.join(path, 'build')
if os.path.isdir(buildPath):
distutils.dir_util.remove_tree(buildPath)
## Determine current version string
initfile = os.path.join(path, 'acq4', '__init__.py')
init = open(initfile).read()
m = re.search(r'__version__ = (\S+)\n', init)
if m is None or len(m.groups()) != 1:
raise Exception("Cannot determine __version__ from init file: '%s'!" % initfile)
version = m.group(1).strip('\'\"')
initVersion = version
# If this is a git checkout, try to generate a more decriptive version string
try:
if os.path.isdir(os.path.join(path, '.git')):
def gitCommit(name):
commit = check_output(['git', 'show', name], universal_newlines=True).split('\n')[0]
assert commit[:7] == 'commit '
return commit[7:]
# Find last tag matching "acq4-.*"
tagNames = check_output(['git', 'tag'], universal_newlines=True).strip().split('\n')
while True:
if len(tagNames) == 0:
raise Exception("Could not determine last tagged version.")
lastTagName = tagNames.pop()
if re.match(r'acq4-.*', lastTagName):
break
# is this commit an unchanged checkout of the last tagged version?
lastTag = gitCommit(lastTagName)
head = gitCommit('HEAD')
if head != lastTag:
branch = re.search(r'\* (.*)', check_output(['git', 'branch'], universal_newlines=True)).group(1)
version = version + "-%s-%s" % (branch, head[:10])
# any uncommitted modifications?
modified = False
status = check_output(['git', 'status', '-s'], universal_newlines=True).strip().split('\n')
for line in status:
if line.strip() != '' and line[:2] != '??':
modified = True
break
if modified:
version = version + '+'
sys.stderr.write("Detected git commit; will use version string: '%s'\n" % version)
except:
version = initVersion
sys.stderr.write("This appears to be a git checkout, but an error occurred "
"while attempting to determine a version string for the "
"current commit.\nUsing the unmodified version string "
"instead: '%s'\n" % version)
sys.excepthook(*sys.exc_info())
print("__init__ version: %s current version: %s" % (initVersion, version))
if 'upload' in sys.argv and version != initVersion:
print("Base version does not match current; stubbornly refusing to upload.")
exit()
import distutils.command.build
class Build(distutils.command.build.build):
def run(self):
ret = distutils.command.build.build.run(self)
# If the version in __init__ is different from the automatically-generated
# version string, then we will update __init__ in the build directory
global path, version, initVersion
if initVersion == version:
return ret
initfile = os.path.join(path, self.build_lib, 'acq4', '__init__.py')
if not os.path.isfile(initfile):
sys.stderr.write("Warning: setup detected a git install and attempted "
"to generate a descriptive version string; however, "
"the expected build file at %s was not found. "
"Installation will use the original version string "
"%s instead.\n" % (initfile, initVersion)
)
else:
data = open(initfile, 'r').read()
open(initfile, 'w').write(re.sub(r"__version__ = .*", "__version__ = '%s'" % version, data))
# If this is windows, we need to update acq4.bat to reference the correct python executable.
if sys.platform == 'win32':
runner = os.path.join(path, self.build_scripts, 'acq4.bat')
runcmd = "%s -m acq4" % sys.executable
data = open(runner, 'r').read()
open(runner, 'w').write(re.sub(r'python -m acq4', runcmd, data))
return ret
# copy config tree to system location
# if sys.platform == 'win32':
# dataRoot = os.path.join(os.environ['ProgramFiles'], 'acq4')
# elif sys.platform == 'darwin':
# dataRoot = 'Library/Application Support/acq4'
# else:
# dataRoot = '/etc/acq4'
# instead, just install config example to same path as package.
if sys.platform == 'win32':
#dataRoot = distutils.sysconfig.get_python_lib().replace(sys.prefix, '')
dataRoot = 'Lib/site-packages/acq4'
else:
#dataRoot = 'python%d.%d/site-packages/acq4' % (sys.version_info.major, sys.version_info.minor)
dataRoot = distutils.sysconfig.get_python_lib().replace(sys.prefix+'/', '') + '/acq4'
dataFiles = []
configRoot = os.path.join(path, 'config')
for subpath, _, files in os.walk(configRoot):
endPath = subpath[len(path):].lstrip(os.path.sep)
files = [os.path.join(endPath, f) for f in files]
dataFiles.append((os.path.join(dataRoot, endPath), files))
# print dataFiles[-1]
packageData = []
pkgRoot = os.path.join(path, 'acq4')
for subpath, _, files in os.walk(pkgRoot):
for f in files:
addTo = None
for ext in ['.png', '.cache', '.h', '.hpp', '.dll']:
if f.endswith(ext):
packageData.append(os.path.join(subpath, f)[len(pkgRoot):].lstrip(os.path.sep))
if sys.platform == 'win32':
scripts = ['bin/acq4.bat']
else:
scripts = ['bin/acq4']
setup(
version=version,
cmdclass={'build': Build},
packages=allPackages,
package_dir={},
package_data={'acq4': packageData},
data_files=dataFiles,
classifiers = [
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Development Status :: 4 - Beta",
"Environment :: Other Environment",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Scientific/Engineering",
],
install_requires = [
'numpy',
'scipy',
'h5py',
'pillow',
],
scripts = scripts,
**setupOpts
)<|fim▁end|>
|
author='Luke Campagnola',
author_email='[email protected]',
)
|
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>use crate::types::game::context::roleplay::fight::arena::ArenaRankInfos;
use crate::types::game::context::roleplay::fight::arena::LeagueFriendInformations;
use protocol_derive::{Decode, Encode};
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6282)]
pub struct GameRolePlayArenaUnregisterMessage<'a> {
pub _phantom: std::marker::PhantomData<&'a ()>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6785)]
pub struct GameRolePlayArenaLeagueRewardsMessage<'a> {
#[protocol(var)]
pub season_id: u16,
#[protocol(var)]
pub league_id: u16,
pub ladder_position: i32,
pub end_season_reward: bool,
pub _phantom: std::marker::PhantomData<&'a ()>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6574)]
pub struct GameRolePlayArenaSwitchToGameServerMessage<'a> {
pub valid_token: bool,
#[protocol(var)]
pub ticket: &'a [i8],
pub home_server_id: i16,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6280)]
pub struct GameRolePlayArenaRegisterMessage<'a> {
pub battle_mode: u32,
pub _phantom: std::marker::PhantomData<&'a ()>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6276)]
pub struct GameRolePlayArenaFightPropositionMessage<'a> {
#[protocol(var)]
pub fight_id: u16,
pub allies_id: std::borrow::Cow<'a, [f64]>,
#[protocol(var)]
pub duration: u16,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6575)]
pub struct GameRolePlayArenaSwitchToFightServerMessage<'a> {<|fim▁hole|> #[protocol(var)]
pub ticket: &'a [i8],
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6728)]
pub struct GameRolePlayArenaUpdatePlayerInfosAllQueuesMessage<'a> {
pub base: GameRolePlayArenaUpdatePlayerInfosMessage<'a>,
pub team: ArenaRankInfos<'a>,
pub duel: ArenaRankInfos<'a>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6284)]
pub struct GameRolePlayArenaRegistrationStatusMessage<'a> {
pub registered: bool,
pub step: u8,
pub battle_mode: u32,
pub _phantom: std::marker::PhantomData<&'a ()>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6281)]
pub struct GameRolePlayArenaFighterStatusMessage<'a> {
#[protocol(var)]
pub fight_id: u16,
pub player_id: f64,
pub accepted: bool,
pub _phantom: std::marker::PhantomData<&'a ()>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6279)]
pub struct GameRolePlayArenaFightAnswerMessage<'a> {
#[protocol(var)]
pub fight_id: u16,
pub accept: bool,
pub _phantom: std::marker::PhantomData<&'a ()>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6301)]
pub struct GameRolePlayArenaUpdatePlayerInfosMessage<'a> {
pub solo: ArenaRankInfos<'a>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6783)]
pub struct GameRolePlayArenaInvitationCandidatesAnswer<'a> {
pub candidates: std::borrow::Cow<'a, [LeagueFriendInformations<'a>]>,
}<|fim▁end|>
|
pub address: &'a str,
pub ports: std::borrow::Cow<'a, [u16]>,
|
<|file_name|>codemap.js<|end_file_name|><|fim▁begin|>// Copyright 2009 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. 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.
/**
* Constructs a mapper that maps addresses into code entries.
*
* @constructor
*/
function CodeMap() {
/**
* Dynamic code entries. Used for JIT compiled code.
*/
this.dynamics_ = new SplayTree();<|fim▁hole|> * Name generator for entries having duplicate names.
*/
this.dynamicsNameGen_ = new CodeMap.NameGenerator();
/**
* Static code entries. Used for statically compiled code.
*/
this.statics_ = new SplayTree();
/**
* Libraries entries. Used for the whole static code libraries.
*/
this.libraries_ = new SplayTree();
/**
* Map of memory pages occupied with static code.
*/
this.pages_ = [];
};
/**
* The number of alignment bits in a page address.
*/
CodeMap.PAGE_ALIGNMENT = 12;
/**
* Page size in bytes.
*/
CodeMap.PAGE_SIZE =
1 << CodeMap.PAGE_ALIGNMENT;
/**
* Adds a dynamic (i.e. moveable and discardable) code entry.
*
* @param {number} start The starting address.
* @param {CodeMap.CodeEntry} codeEntry Code entry object.
*/
CodeMap.prototype.addCode = function(start, codeEntry) {
this.deleteAllCoveredNodes_(this.dynamics_, start, start + codeEntry.size);
this.dynamics_.insert(start, codeEntry);
};
/**
* Moves a dynamic code entry. Throws an exception if there is no dynamic
* code entry with the specified starting address.
*
* @param {number} from The starting address of the entry being moved.
* @param {number} to The destination address.
*/
CodeMap.prototype.moveCode = function(from, to) {
var removedNode = this.dynamics_.remove(from);
this.deleteAllCoveredNodes_(this.dynamics_, to, to + removedNode.value.size);
this.dynamics_.insert(to, removedNode.value);
};
/**
* Discards a dynamic code entry. Throws an exception if there is no dynamic
* code entry with the specified starting address.
*
* @param {number} start The starting address of the entry being deleted.
*/
CodeMap.prototype.deleteCode = function(start) {
var removedNode = this.dynamics_.remove(start);
};
/**
* Adds a library entry.
*
* @param {number} start The starting address.
* @param {CodeMap.CodeEntry} codeEntry Code entry object.
*/
CodeMap.prototype.addLibrary = function(
start, codeEntry) {
this.markPages_(start, start + codeEntry.size);
this.libraries_.insert(start, codeEntry);
};
/**
* Adds a static code entry.
*
* @param {number} start The starting address.
* @param {CodeMap.CodeEntry} codeEntry Code entry object.
*/
CodeMap.prototype.addStaticCode = function(
start, codeEntry) {
this.statics_.insert(start, codeEntry);
};
/**
* @private
*/
CodeMap.prototype.markPages_ = function(start, end) {
for (var addr = start; addr <= end;
addr += CodeMap.PAGE_SIZE) {
this.pages_[addr >>> CodeMap.PAGE_ALIGNMENT] = 1;
}
};
/**
* @private
*/
CodeMap.prototype.deleteAllCoveredNodes_ = function(tree, start, end) {
var to_delete = [];
var addr = end - 1;
while (addr >= start) {
var node = tree.findGreatestLessThan(addr);
if (!node) break;
var start2 = node.key, end2 = start2 + node.value.size;
if (start2 < end && start < end2) to_delete.push(start2);
addr = start2 - 1;
}
for (var i = 0, l = to_delete.length; i < l; ++i) tree.remove(to_delete[i]);
};
/**
* @private
*/
CodeMap.prototype.isAddressBelongsTo_ = function(addr, node) {
return addr >= node.key && addr < (node.key + node.value.size);
};
/**
* @private
*/
CodeMap.prototype.findInTree_ = function(tree, addr) {
var node = tree.findGreatestLessThan(addr);
return node && this.isAddressBelongsTo_(addr, node) ? node : null;
};
/**
* Finds a code entry that contains the specified address. Both static and
* dynamic code entries are considered. Returns the code entry and the offset
* within the entry.
*
* @param {number} addr Address.
*/
CodeMap.prototype.findAddress = function(addr) {
var pageAddr = addr >>> CodeMap.PAGE_ALIGNMENT;
if (pageAddr in this.pages_) {
// Static code entries can contain "holes" of unnamed code.
// In this case, the whole library is assigned to this address.
var result = this.findInTree_(this.statics_, addr);
if (!result) {
result = this.findInTree_(this.libraries_, addr);
if (!result) return null;
}
return { entry : result.value, offset : addr - result.key };
}
var min = this.dynamics_.findMin();
var max = this.dynamics_.findMax();
if (max != null && addr < (max.key + max.value.size) && addr >= min.key) {
var dynaEntry = this.findInTree_(this.dynamics_, addr);
if (dynaEntry == null) return null;
// Dedupe entry name.
var entry = dynaEntry.value;
if (!entry.nameUpdated_) {
entry.name = this.dynamicsNameGen_.getName(entry.name);
entry.nameUpdated_ = true;
}
return { entry : entry, offset : addr - dynaEntry.key };
}
return null;
};
/**
* Finds a code entry that contains the specified address. Both static and
* dynamic code entries are considered.
*
* @param {number} addr Address.
*/
CodeMap.prototype.findEntry = function(addr) {
var result = this.findAddress(addr);
return result ? result.entry : null;
};
/**
* Returns a dynamic code entry using its starting address.
*
* @param {number} addr Address.
*/
CodeMap.prototype.findDynamicEntryByStartAddress =
function(addr) {
var node = this.dynamics_.find(addr);
return node ? node.value : null;
};
/**
* Returns an array of all dynamic code entries.
*/
CodeMap.prototype.getAllDynamicEntries = function() {
return this.dynamics_.exportValues();
};
/**
* Returns an array of pairs of all dynamic code entries and their addresses.
*/
CodeMap.prototype.getAllDynamicEntriesWithAddresses = function() {
return this.dynamics_.exportKeysAndValues();
};
/**
* Returns an array of all static code entries.
*/
CodeMap.prototype.getAllStaticEntries = function() {
return this.statics_.exportValues();
};
/**
* Returns an array of pairs of all static code entries and their addresses.
*/
CodeMap.prototype.getAllStaticEntriesWithAddresses = function() {
return this.statics_.exportKeysAndValues();
};
/**
* Returns an array of all libraries entries.
*/
CodeMap.prototype.getAllLibrariesEntries = function() {
return this.libraries_.exportValues();
};
/**
* Creates a code entry object.
*
* @param {number} size Code entry size in bytes.
* @param {string} opt_name Code entry name.
* @param {string} opt_type Code entry type, e.g. SHARED_LIB, CPP.
* @constructor
*/
CodeMap.CodeEntry = function(size, opt_name, opt_type) {
this.size = size;
this.name = opt_name || '';
this.type = opt_type || '';
this.nameUpdated_ = false;
};
CodeMap.CodeEntry.prototype.getName = function() {
return this.name;
};
CodeMap.CodeEntry.prototype.toString = function() {
return this.name + ': ' + this.size.toString(16);
};
CodeMap.NameGenerator = function() {
this.knownNames_ = {};
};
CodeMap.NameGenerator.prototype.getName = function(name) {
if (!(name in this.knownNames_)) {
this.knownNames_[name] = 0;
return name;
}
var count = ++this.knownNames_[name];
return name + ' {' + count + '}';
};<|fim▁end|>
|
/**
|
<|file_name|>freeze.py<|end_file_name|><|fim▁begin|>import re
import sys
import pip
from pip.req import InstallRequirement
from pip.log import logger
from pip.basecommand import Command
from pip.util import get_installed_distributions
import pkg_resources
class FreezeCommand(Command):
"""Output installed packages in requirements format."""
name = 'freeze'
usage = """
%prog [options]"""
summary = 'Output installed packages in requirements format.'
def __init__(self, *args, **kw):
super(FreezeCommand, self).__init__(*args, **kw)
self.cmd_opts.add_option(
'-r', '--requirement',
dest='requirement',
action='store',
default=None,
metavar='file',
help="Use the order in the given requirements file and it's comments when generating output.")
self.cmd_opts.add_option(
'-f', '--find-links',
dest='find_links',
action='append',
default=[],
metavar='URL',
help='URL for finding packages, which will be added to the output.')
self.cmd_opts.add_option(
'-l', '--local',
dest='local',
action='store_true',
default=False,
help='If in a virtualenv that has global access, do not output globally-installed packages.')
self.parser.insert_option_group(0, self.cmd_opts)
def setup_logging(self):
logger.move_stdout_to_stderr()
def run(self, options, args):
requirement = options.requirement
find_links = options.find_links or []
local_only = options.local
## FIXME: Obviously this should be settable:
find_tags = False
skip_match = None
skip_regex = options.skip_requirements_regex
if skip_regex:
skip_match = re.compile(skip_regex)
dependency_links = []
<|fim▁hole|> if dist.has_metadata('dependency_links.txt'):
dependency_links.extend(dist.get_metadata_lines('dependency_links.txt'))
for link in find_links:
if '#egg=' in link:
dependency_links.append(link)
for link in find_links:
f.write('-f %s\n' % link)
installations = {}
for dist in get_installed_distributions(local_only=local_only):
req = pip.FrozenRequirement.from_dist(dist, dependency_links, find_tags=find_tags)
installations[req.name] = req
if requirement:
req_f = open(requirement)
for line in req_f:
if not line.strip() or line.strip().startswith('#'):
f.write(line)
continue
if skip_match and skip_match.search(line):
f.write(line)
continue
elif line.startswith('-e') or line.startswith('--editable'):
if line.startswith('-e'):
line = line[2:].strip()
else:
line = line[len('--editable'):].strip().lstrip('=')
line_req = InstallRequirement.from_editable(line, default_vcs=options.default_vcs)
elif (line.startswith('-r') or line.startswith('--requirement')
or line.startswith('-Z') or line.startswith('--always-unzip')
or line.startswith('-f') or line.startswith('-i')
or line.startswith('--extra-index-url')
or line.startswith('--find-links')
or line.startswith('--index-url')):
f.write(line)
continue
else:
line_req = InstallRequirement.from_line(line)
if not line_req.name:
logger.notify("Skipping line because it's not clear what it would install: %s"
% line.strip())
logger.notify(" (add #egg=PackageName to the URL to avoid this warning)")
continue
if line_req.name not in installations:
logger.warn("Requirement file contains %s, but that package is not installed"
% line.strip())
continue
f.write(str(installations[line_req.name]))
del installations[line_req.name]
f.write('## The following requirements were added by pip --freeze:\n')
for installation in sorted(installations.values(), key=lambda x: x.name):
f.write(str(installation))<|fim▁end|>
|
f = sys.stdout
for dist in pkg_resources.working_set:
|
<|file_name|>main.js<|end_file_name|><|fim▁begin|>import answer from './answer';<|fim▁hole|><|fim▁end|>
|
var answer2 = answer;
export default answer2;
|
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use rustc::hir::def_id::DefId;
use rustc::middle::lang_items::DropInPlaceFnLangItem;
use rustc::traits;
use rustc::ty::adjustment::CustomCoerceUnsized;
use rustc::ty::{self, Ty, TyCtxt};
pub use rustc::ty::Instance;
pub use self::item::{MonoItem, MonoItemExt};
pub mod collector;
pub mod item;
pub mod partitioning;
#[inline(never)] // give this a place in the profiler
pub fn assert_symbols_are_distinct<'a, 'tcx, I>(tcx: TyCtxt<'a, 'tcx, 'tcx>, mono_items: I)
where I: Iterator<Item=&'a MonoItem<'tcx>>
{
let mut symbols: Vec<_> = mono_items.map(|mono_item| {
(mono_item, mono_item.symbol_name(tcx))
}).collect();
symbols.sort_by_key(|sym| sym.1);
for pair in symbols.windows(2) {
let sym1 = &pair[0].1;
let sym2 = &pair[1].1;
if sym1 == sym2 {
let mono_item1 = pair[0].0;
let mono_item2 = pair[1].0;
let span1 = mono_item1.local_span(tcx);
let span2 = mono_item2.local_span(tcx);
// Deterministically select one of the spans for error reporting
let span = match (span1, span2) {
(Some(span1), Some(span2)) => {
Some(if span1.lo().0 > span2.lo().0 {
span1
} else {
span2
})
}
(span1, span2) => span1.or(span2),
};
let error_message = format!("symbol `{}` is already defined", sym1);
if let Some(span) = span {
tcx.sess.span_fatal(span, &error_message)
} else {
tcx.sess.fatal(&error_message)
}
}
}
}<|fim▁hole|>fn fn_once_adapter_instance<'a, 'tcx>(
tcx: TyCtxt<'a, 'tcx, 'tcx>,
closure_did: DefId,
substs: ty::ClosureSubsts<'tcx>,
) -> Instance<'tcx> {
debug!("fn_once_adapter_shim({:?}, {:?})",
closure_did,
substs);
let fn_once = tcx.lang_items().fn_once_trait().unwrap();
let call_once = tcx.associated_items(fn_once)
.find(|it| it.kind == ty::AssociatedKind::Method)
.unwrap().def_id;
let def = ty::InstanceDef::ClosureOnceShim { call_once };
let self_ty = tcx.mk_closure(closure_did, substs);
let sig = substs.closure_sig(closure_did, tcx);
let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
assert_eq!(sig.inputs().len(), 1);
let substs = tcx.mk_substs_trait(self_ty, &[sig.inputs()[0].into()]);
debug!("fn_once_adapter_shim: self_ty={:?} sig={:?}", self_ty, sig);
Instance { def, substs }
}
fn needs_fn_once_adapter_shim(actual_closure_kind: ty::ClosureKind,
trait_closure_kind: ty::ClosureKind)
-> Result<bool, ()>
{
match (actual_closure_kind, trait_closure_kind) {
(ty::ClosureKind::Fn, ty::ClosureKind::Fn) |
(ty::ClosureKind::FnMut, ty::ClosureKind::FnMut) |
(ty::ClosureKind::FnOnce, ty::ClosureKind::FnOnce) => {
// No adapter needed.
Ok(false)
}
(ty::ClosureKind::Fn, ty::ClosureKind::FnMut) => {
// The closure fn `llfn` is a `fn(&self, ...)`. We want a
// `fn(&mut self, ...)`. In fact, at codegen time, these are
// basically the same thing, so we can just return llfn.
Ok(false)
}
(ty::ClosureKind::Fn, ty::ClosureKind::FnOnce) |
(ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
// The closure fn `llfn` is a `fn(&self, ...)` or `fn(&mut
// self, ...)`. We want a `fn(self, ...)`. We can produce
// this by doing something like:
//
// fn call_once(self, ...) { call_mut(&self, ...) }
// fn call_once(mut self, ...) { call_mut(&mut self, ...) }
//
// These are both the same at codegen time.
Ok(true)
}
_ => Err(()),
}
}
pub fn resolve_closure<'a, 'tcx> (
tcx: TyCtxt<'a, 'tcx, 'tcx>,
def_id: DefId,
substs: ty::ClosureSubsts<'tcx>,
requested_kind: ty::ClosureKind)
-> Instance<'tcx>
{
let actual_kind = substs.closure_kind(def_id, tcx);
match needs_fn_once_adapter_shim(actual_kind, requested_kind) {
Ok(true) => fn_once_adapter_instance(tcx, def_id, substs),
_ => Instance::new(def_id, substs.substs)
}
}
pub fn resolve_drop_in_place<'a, 'tcx>(
tcx: TyCtxt<'a, 'tcx, 'tcx>,
ty: Ty<'tcx>)
-> ty::Instance<'tcx>
{
let def_id = tcx.require_lang_item(DropInPlaceFnLangItem);
let substs = tcx.intern_substs(&[ty.into()]);
Instance::resolve(tcx, ty::ParamEnv::reveal_all(), def_id, substs).unwrap()
}
pub fn custom_coerce_unsize_info<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
source_ty: Ty<'tcx>,
target_ty: Ty<'tcx>)
-> CustomCoerceUnsized {
let def_id = tcx.lang_items().coerce_unsized_trait().unwrap();
let trait_ref = ty::Binder::bind(ty::TraitRef {
def_id: def_id,
substs: tcx.mk_substs_trait(source_ty, &[target_ty.into()])
});
match tcx.codegen_fulfill_obligation( (ty::ParamEnv::reveal_all(), trait_ref)) {
traits::VtableImpl(traits::VtableImplData { impl_def_id, .. }) => {
tcx.coerce_unsized_info(impl_def_id).custom_kind.unwrap()
}
vtable => {
bug!("invalid CoerceUnsized vtable: {:?}", vtable);
}
}
}<|fim▁end|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.