text
stringlengths 5
1.04M
|
|---|
// -*-c++-*-
/***************************************************************************
isocketstream.hpp - An istream for sockets
-------------------
begin : 08-JAN-2003
copyright : (C) 2003 by The RoboCup Soccer Server
Maintenance Group.
email : sserver-admin@lists.sourceforge.net
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU LGPL as published by the Free Software *
* Foundation; either version 2 of the License, or (at your option) any *
* later version. *
* *
***************************************************************************/
#ifndef RCSS_NET_ISOCKETSTREAM_HPP
#define RCSS_NET_ISOCKETSTREAM_HPP
#include "socketstreambuf.hpp"
namespace rcss
{
namespace net
{
class ISocketStream
: public SocketStreamBuf,
public std::istream
{
public:
ISocketStream( Socket& socket,
const Addr& dest,
ConnType conn = CONN_ON_READ,
int buffer_size = 8192 )
: SocketStreamBuf( socket, dest, conn, buffer_size ),
std::istream( this )
{}
ISocketStream( Socket& socket,
ConnType conn = NO_CONN,
int buffer_size = 8192 )
: SocketStreamBuf( socket, conn, buffer_size ),
std::istream( this )
{}
private:
// not for use
ISocketStream(const ISocketStream&);
ISocketStream& operator=(const ISocketStream&);
};
}
}
#endif
|
//
// Ponto.cpp
// OpenGLTest
//
// Created by Márcio Sarroglia Pinho on 18/08/20.
// Copyright © 2020 Márcio Sarroglia Pinho. All rights reserved.
//
#include "Ponto.h"
Ponto::Ponto ()
{
x=y=z=0;
}
Ponto::Ponto(float x, float y, float z)
{
this->x = x;
this->y = y;
this->z = z;
}
void Ponto::set(float x, float y, float z)
{
this->x = x;
this->y = y;
this->z = z;
}
void Ponto::imprime() {
cout << "(" << x << ", " << y << ")" << flush;
}
bool Ponto::operator==(const Ponto other) const
{
return (x == other.x) && (y == other.y);
}
|
#include "leetrpc/rpc_client.h"
#include "leetrpc/rpc_status.h"
#include "add_client_stub.h"
#include "libbase/buffer.h"
#include <memory>
#include <iostream>
#include <string>
#include <unistd.h>
using namespace network;
using namespace libbase;
using namespace leetrpc;
void Print(std::shared_ptr<double> ret) {
std::cout << "use asyn function: ret = " << *ret << std::endl;
}
int main() {
RpcClient client("127.0.0.1", 8080);
AddClientStub stub(client);
RpcStatus rs;
rs.TimeoutNotify();
int ret = stub.Add(1, 2, &rs, 2);
if (rs.Ok()) {
std::cout << ret << std::endl;
} else {
std::cout << rs.ToString() << std::endl;
}
std::cout << stub.Add(1, 2) << std::endl;
stub.Add(2, 4, Print, 2);
stub.Add(2, 3, Print);
std::cout << "Call asyn Add" << std::endl;
sleep(6);
return 0;
}
|
/*
+----------------------------------------------------------------------+
| Swoole |
+----------------------------------------------------------------------+
| This source file is subject to version 2.0 of the Apache license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.apache.org/licenses/LICENSE-2.0.html |
| If you did not receive a copy of the Apache2.0 license and are unable|
| to obtain it through the world-wide-web, please send a note to |
| license@swoole.com so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Tianfeng Han <mikan.tenny@gmail.com> |
+----------------------------------------------------------------------+
*/
#include "php_swoole_cxx.h"
#include "swoole_coroutine.h"
#include "socks5.h"
#include "mqtt.h"
#include "ext/standard/basic_functions.h"
enum client_property
{
client_property_callback = 0,
client_property_coroutine = 1,
client_property_socket = 2,
};
using namespace swoole;
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_client_coro_void, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_client_coro_construct, 0, 0, 1)
ZEND_ARG_INFO(0, type)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_client_coro_set, 0, 0, 1)
ZEND_ARG_ARRAY_INFO(0, settings, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_client_coro_connect, 0, 0, 1)
ZEND_ARG_INFO(0, host)
ZEND_ARG_INFO(0, port)
ZEND_ARG_INFO(0, timeout)
ZEND_ARG_INFO(0, sock_flag)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_client_coro_recv, 0, 0, 0)
ZEND_ARG_INFO(0, timeout)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_client_coro_send, 0, 0, 1)
ZEND_ARG_INFO(0, data)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_client_coro_peek, 0, 0, 0)
ZEND_ARG_INFO(0, length)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_client_coro_sendfile, 0, 0, 1)
ZEND_ARG_INFO(0, filename)
ZEND_ARG_INFO(0, offset)
ZEND_ARG_INFO(0, length)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_client_coro_sendto, 0, 0, 3)
ZEND_ARG_INFO(0, address)
ZEND_ARG_INFO(0, port)
ZEND_ARG_INFO(0, data)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_client_coro_recvfrom, 0, 0, 2)
ZEND_ARG_INFO(0, length)
ZEND_ARG_INFO(1, address)
ZEND_ARG_INFO(1, port)
ZEND_END_ARG_INFO()
static PHP_METHOD(swoole_client_coro, __construct);
static PHP_METHOD(swoole_client_coro, __destruct);
static PHP_METHOD(swoole_client_coro, set);
static PHP_METHOD(swoole_client_coro, connect);
static PHP_METHOD(swoole_client_coro, recv);
static PHP_METHOD(swoole_client_coro, peek);
static PHP_METHOD(swoole_client_coro, send);
static PHP_METHOD(swoole_client_coro, sendfile);
static PHP_METHOD(swoole_client_coro, sendto);
static PHP_METHOD(swoole_client_coro, recvfrom);
#ifdef SW_USE_OPENSSL
static PHP_METHOD(swoole_client_coro, enableSSL);
static PHP_METHOD(swoole_client_coro, getPeerCert);
static PHP_METHOD(swoole_client_coro, verifyPeerCert);
#endif
#ifdef SWOOLE_SOCKETS_SUPPORT
static PHP_METHOD(swoole_client_coro, getSocket);
#endif
static PHP_METHOD(swoole_client_coro, isConnected);
static PHP_METHOD(swoole_client_coro, getsockname);
static PHP_METHOD(swoole_client_coro, getpeername);
static PHP_METHOD(swoole_client_coro, close);
static void sw_coro_socket_set_ssl(Socket *cli, zval *zset);
static Socket* client_coro_new(zval *zobject, int port = 0);
bool php_swoole_client_coro_socket_free(Socket *cli);
static const zend_function_entry swoole_client_coro_methods[] =
{
PHP_ME(swoole_client_coro, __construct, arginfo_swoole_client_coro_construct, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, __destruct, arginfo_swoole_client_coro_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, set, arginfo_swoole_client_coro_set, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, connect, arginfo_swoole_client_coro_connect, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, recv, arginfo_swoole_client_coro_recv, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, peek, arginfo_swoole_client_coro_peek, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, send, arginfo_swoole_client_coro_send, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, sendfile, arginfo_swoole_client_coro_sendfile, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, sendto, arginfo_swoole_client_coro_sendto, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, recvfrom, arginfo_swoole_client_coro_recvfrom, ZEND_ACC_PUBLIC)
#ifdef SW_USE_OPENSSL
PHP_ME(swoole_client_coro, enableSSL, arginfo_swoole_client_coro_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, getPeerCert, arginfo_swoole_client_coro_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, verifyPeerCert, arginfo_swoole_client_coro_void, ZEND_ACC_PUBLIC)
#endif
PHP_ME(swoole_client_coro, isConnected, arginfo_swoole_client_coro_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, getsockname, arginfo_swoole_client_coro_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, getpeername, arginfo_swoole_client_coro_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, close, arginfo_swoole_client_coro_void, ZEND_ACC_PUBLIC)
#ifdef SWOOLE_SOCKETS_SUPPORT
PHP_ME(swoole_client_coro, getSocket, arginfo_swoole_client_coro_void, ZEND_ACC_PUBLIC)
#endif
PHP_FE_END
};
static zend_class_entry swoole_client_coro_ce;
zend_class_entry *swoole_client_coro_ce_ptr;
static zend_object_handlers swoole_client_coro_handlers;
void swoole_client_coro_init(int module_number)
{
SWOOLE_INIT_CLASS_ENTRY(swoole_client_coro, "Swoole\\Coroutine\\Client", NULL, "Co\\Client", swoole_client_coro_methods);
SWOOLE_SET_CLASS_SERIALIZABLE(swoole_client_coro, zend_class_serialize_deny, zend_class_unserialize_deny);
SWOOLE_SET_CLASS_CLONEABLE(swoole_client_coro, zend_class_clone_deny);
SWOOLE_SET_CLASS_UNSET_PROPERTY_HANDLER(swoole_client_coro, zend_class_unset_property_deny);
zend_declare_property_long(swoole_client_coro_ce_ptr, ZEND_STRL("errCode"), 0, ZEND_ACC_PUBLIC);
zend_declare_property_long(swoole_client_coro_ce_ptr, ZEND_STRL("sock"), -1, ZEND_ACC_PUBLIC);
zend_declare_property_long(swoole_client_coro_ce_ptr, ZEND_STRL("type"), 0, ZEND_ACC_PUBLIC);
zend_declare_property_null(swoole_client_coro_ce_ptr, ZEND_STRL("setting"), ZEND_ACC_PUBLIC);
zend_declare_property_bool(swoole_client_coro_ce_ptr, ZEND_STRL("connected"), 0, ZEND_ACC_PUBLIC);
zend_declare_class_constant_long(swoole_client_coro_ce_ptr, ZEND_STRL("MSG_OOB"), MSG_OOB);
zend_declare_class_constant_long(swoole_client_coro_ce_ptr, ZEND_STRL("MSG_PEEK"), MSG_PEEK);
zend_declare_class_constant_long(swoole_client_coro_ce_ptr, ZEND_STRL("MSG_DONTWAIT"), MSG_DONTWAIT);
zend_declare_class_constant_long(swoole_client_coro_ce_ptr, ZEND_STRL("MSG_WAITALL"), MSG_WAITALL);
}
static sw_inline Socket* client_get_ptr(zval *zobject, bool silent = false)
{
Socket *cli = (Socket *) swoole_get_object(zobject);
if (cli && cli->socket && cli->socket->active == 1)
{
return cli;
}
else
{
if (!silent)
{
SwooleG.error = SW_ERROR_CLIENT_NO_CONNECTION;
zend_update_property_long(swoole_client_coro_ce_ptr, zobject, ZEND_STRL("errCode"), SwooleG.error);
swoole_php_error(E_WARNING, "client is not connected to server.");
}
return nullptr;
}
}
static Socket* client_coro_new(zval *zobject, int port)
{
zval *ztype = sw_zend_read_property(Z_OBJCE_P(zobject), zobject, ZEND_STRL("type"), 0);
zend_long type = zval_get_long(ztype);
if ((type == SW_SOCK_TCP || type == SW_SOCK_TCP6) && (port <= 0 || port > SW_CLIENT_MAX_PORT))
{
swoole_php_fatal_error(E_WARNING, "The port is invalid.");
return NULL;
}
Socket *cli = new Socket((enum swSocket_type) type);
if (unlikely(cli->socket == nullptr))
{
swoole_php_fatal_error(E_WARNING, "new Socket() failed. Error: %s [%d]", strerror(errno), errno);
zend_update_property_long(Z_OBJCE_P(zobject), zobject, ZEND_STRL("errCode"), errno);
delete cli;
return NULL;
}
zend_update_property_long(Z_OBJCE_P(zobject), zobject, ZEND_STRL("sock"), cli->socket->fd);
#ifdef SW_USE_OPENSSL
if (type & SW_SOCK_SSL)
{
cli->open_ssl = true;
}
#endif
swoole_set_object(zobject, cli);
return cli;
}
static bool client_coro_close(zval *zobject)
{
Socket *cli = (Socket *) swoole_get_object(zobject);
if (cli)
{
zend_update_property_bool(Z_OBJCE_P(zobject), zobject, ZEND_STRL("connected"), 0);
if (!cli->get_bound_cid())
{
#ifdef SWOOLE_SOCKETS_SUPPORT
zval *zsocket = (zval *) swoole_get_property(zobject, client_property_socket);
if (zsocket)
{
sw_zval_free(zsocket);
swoole_set_property(zobject, client_property_socket, NULL);
}
#endif
swoole_set_object(zobject, NULL);
}
return php_swoole_client_coro_socket_free(cli);
}
return false;
}
bool php_swoole_client_coro_socket_free(Socket *cli)
{
//FIXME: move to Socket method, we should not manage it externally
if (!cli->has_bound())
{
if (cli->socks5_proxy)
{
if (cli->socks5_proxy->host)
{
efree(cli->socks5_proxy->host);
cli->socks5_proxy->host = nullptr;
}
if (cli->socks5_proxy->username)
{
efree(cli->socks5_proxy->username);
cli->socks5_proxy->username = nullptr;
}
if (cli->socks5_proxy->password)
{
efree(cli->socks5_proxy->password);
cli->socks5_proxy->password = nullptr;
}
efree(cli->socks5_proxy);
cli->socks5_proxy = nullptr;
}
if (cli->http_proxy)
{
if (cli->http_proxy->proxy_host)
{
efree(cli->http_proxy->proxy_host);
cli->http_proxy->proxy_host = nullptr;
}
if (cli->http_proxy->user)
{
efree(cli->http_proxy->user);
cli->http_proxy->user = nullptr;
}
if (cli->http_proxy->password)
{
efree(cli->http_proxy->password);
cli->http_proxy->password = nullptr;
}
efree(cli->http_proxy);
cli->http_proxy = nullptr;
}
if (cli->protocol.private_data)
{
zval *zcallback = (zval *) cli->protocol.private_data;
sw_zval_free(zcallback);
cli->protocol.private_data = nullptr;
}
}
return cli->close();
}
void sw_coro_socket_set(Socket *cli, zval *zset)
{
HashTable *vht;
zval *v;
int value = 1;
vht = Z_ARRVAL_P(zset);
//buffer: eof check
if (php_swoole_array_get_value(vht, "open_eof_check", v))
{
cli->open_eof_check = zval_is_true(v);
}
//buffer: split package with eof
if (php_swoole_array_get_value(vht, "open_eof_split", v))
{
cli->protocol.split_by_eof = zval_is_true(v);
if (cli->protocol.split_by_eof)
{
cli->open_eof_check = 1;
}
}
//package eof
if (php_swoole_array_get_value(vht, "package_eof", v))
{
zend::string str_v(v);
cli->protocol.package_eof_len = str_v.len();
if (cli->protocol.package_eof_len == 0)
{
swoole_php_fatal_error(E_ERROR, "pacakge_eof cannot be an empty string");
return;
}
else if (cli->protocol.package_eof_len > SW_DATA_EOF_MAXLEN)
{
swoole_php_fatal_error(E_ERROR, "pacakge_eof max length is %d", SW_DATA_EOF_MAXLEN);
return;
}
bzero(cli->protocol.package_eof, SW_DATA_EOF_MAXLEN);
memcpy(cli->protocol.package_eof, str_v.val(), str_v.len());
}
//open mqtt protocol
if (php_swoole_array_get_value(vht, "open_mqtt_protocol", v))
{
cli->open_length_check = zval_is_true(v);
cli->protocol.get_package_length = swMqtt_get_package_length;
}
//open length check
if (php_swoole_array_get_value(vht, "open_length_check", v))
{
cli->open_length_check = zval_is_true(v);
cli->protocol.get_package_length = swProtocol_get_package_length;
}
//package length size
if (php_swoole_array_get_value(vht, "package_length_type", v))
{
zend::string str_v(v);
cli->protocol.package_length_type = str_v.val()[0];
cli->protocol.package_length_size = swoole_type_size(cli->protocol.package_length_type);
if (cli->protocol.package_length_size == 0)
{
swoole_php_fatal_error(E_ERROR, "Unknown package_length_type name '%c', see pack(). Link: http://php.net/pack", cli->protocol.package_length_type);
return;
}
}
//package length offset
if (php_swoole_array_get_value(vht, "package_length_offset", v))
{
cli->protocol.package_length_offset = (int) zval_get_long(v);
}
//package body start
if (php_swoole_array_get_value(vht, "package_body_offset", v))
{
cli->protocol.package_body_offset = (int) zval_get_long(v);
}
//length function
if (php_swoole_array_get_value(vht, "package_length_func", v))
{
while(1)
{
if (Z_TYPE_P(v) == IS_STRING)
{
swProtocol_length_function func = (swProtocol_length_function) swoole_get_function(Z_STRVAL_P(v),
Z_STRLEN_P(v));
if (func != NULL)
{
cli->protocol.get_package_length = func;
break;
}
}
char *func_name = NULL;
if (!sw_zend_is_callable(v, 0, &func_name))
{
swoole_php_fatal_error(E_ERROR, "function '%s' is not callable", func_name);
return;
}
efree(func_name);
cli->protocol.get_package_length = php_swoole_length_func;
if (cli->protocol.private_data)
{
zval_ptr_dtor((zval *)cli->protocol.private_data);
efree(cli->protocol.private_data);
}
Z_TRY_ADDREF_P(v);
cli->protocol.private_data = sw_zval_dup(v);
break;
}
cli->protocol.package_length_size = 0;
cli->protocol.package_length_type = '\0';
cli->protocol.package_length_offset = SW_IPC_BUFFER_SIZE;
}
/**
* package max length
*/
if (php_swoole_array_get_value(vht, "package_max_length", v))
{
cli->protocol.package_max_length = (int) zval_get_long(v);
}
else
{
cli->protocol.package_max_length = SW_BUFFER_INPUT_SIZE;
}
/**
* socket send/recv buffer size
*/
if (php_swoole_array_get_value(vht, "socket_buffer_size", v))
{
value = (int) zval_get_long(v);
if (value <= 0)
{
value = INT_MAX;
}
swSocket_set_buffer_size(cli->socket->fd, value);
cli->socket->buffer_size = value;
}
/**
* bind port
*/
if (php_swoole_array_get_value(vht, "bind_port", v))
{
int bind_port = (int) zval_get_long(v);
/**
* bind address
*/
if (php_swoole_array_get_value(vht, "bind_address", v))
{
zend::string str_v(v);
swSocket_bind(cli->socket->fd, cli->type, str_v.val(), &bind_port);
}
}
/**
* client: tcp_nodelay
*/
if (php_swoole_array_get_value(vht, "open_tcp_nodelay", v))
{
cli->set_tcp_nodelay(zval_is_true(v));
}
else
{
cli->set_tcp_nodelay(1);
}
/**
* socks5 proxy
*/
if (php_swoole_array_get_value(vht, "socks5_host", v))
{
zend::string host(v);
if (php_swoole_array_get_value(vht, "socks5_port", v))
{
cli->socks5_proxy = (struct _swSocks5 *) ecalloc(1, sizeof(swSocks5));
cli->socks5_proxy->host = estrdup(host.val());
cli->socks5_proxy->port = zval_get_long(v);
cli->socks5_proxy->dns_tunnel = 1;
if (php_swoole_array_get_value(vht, "socks5_username", v))
{
zend::string username(v);
if (php_swoole_array_get_value(vht, "socks5_password", v))
{
zend::string password(v);
cli->socks5_proxy->method = 0x02;
cli->socks5_proxy->username = username.val();
cli->socks5_proxy->l_username = username.len();
cli->socks5_proxy->password = password.val();
cli->socks5_proxy->l_password = password.len();
}
else
{
swoole_php_fatal_error(E_WARNING, "socks5_password should not be null.");
}
}
}
else
{
swoole_php_fatal_error(E_WARNING, "socks5_port should not be null.");
}
}
/**
* http proxy
*/
else if (php_swoole_array_get_value(vht, "http_proxy_host", v))
{
zend::string host(v);
if (php_swoole_array_get_value(vht, "http_proxy_port", v))
{
cli->http_proxy = (struct _http_proxy*) ecalloc(1, sizeof(struct _http_proxy));
cli->http_proxy->proxy_host = estrdup(host.val());
cli->http_proxy->proxy_port = zval_get_long(v);
if (php_swoole_array_get_value(vht, "http_proxy_username", v) || php_swoole_array_get_value(vht, "http_proxy_user", v))
{
zend::string username(v);
if (php_swoole_array_get_value(vht, "http_proxy_password", v))
{
zend::string password(v);
cli->http_proxy->user = estrdup(username.val());
cli->http_proxy->l_user = username.len();
cli->http_proxy->password = estrdup(password.val());
cli->http_proxy->l_password = password.len();
}
else
{
swoole_php_fatal_error(E_WARNING, "http_proxy_password should not be null.");
}
}
}
else
{
swoole_php_fatal_error(E_WARNING, "http_proxy_port should not be null.");
}
}
/**
* ssl
*/
#ifdef SW_USE_OPENSSL
if (cli->open_ssl)
{
sw_coro_socket_set_ssl(cli, zset);
}
#endif
}
#ifdef SW_USE_OPENSSL
static void sw_coro_socket_set_ssl(Socket *cli, zval *zset)
{
HashTable *vht = Z_ARRVAL_P(zset);
zval *v;
if (php_swoole_array_get_value(vht, "ssl_method", v))
{
cli->ssl_option.method = (int) zval_get_long(v);
}
if (php_swoole_array_get_value(vht, "ssl_compress", v))
{
cli->ssl_option.disable_compress = !zval_is_true(v);
}
if (php_swoole_array_get_value(vht, "ssl_cert_file", v))
{
zend::string str_v(v);
cli->ssl_option.cert_file = sw_strndup(str_v.val(), str_v.len());
if (access(cli->ssl_option.cert_file, R_OK) < 0)
{
swoole_php_fatal_error(E_ERROR, "ssl cert file[%s] not found.", cli->ssl_option.cert_file);
return;
}
}
if (php_swoole_array_get_value(vht, "ssl_key_file", v))
{
zend::string str_v(v);
cli->ssl_option.key_file = sw_strndup(str_v.val(), str_v.len());
if (access(cli->ssl_option.key_file, R_OK) < 0)
{
swoole_php_fatal_error(E_ERROR, "ssl key file[%s] not found.", cli->ssl_option.key_file);
return;
}
}
if (php_swoole_array_get_value(vht, "ssl_passphrase", v))
{
zend::string str_v(v);
cli->ssl_option.passphrase = sw_strndup(str_v.val(), str_v.len());
}
#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
if (php_swoole_array_get_value(vht, "ssl_host_name", v))
{
zend::string str_v(v);
cli->ssl_option.tls_host_name = sw_strndup(str_v.val(), str_v.len());
}
#endif
if (php_swoole_array_get_value(vht, "ssl_verify_peer", v))
{
cli->ssl_option.verify_peer = zval_is_true(v);
}
if (php_swoole_array_get_value(vht, "ssl_allow_self_signed", v))
{
cli->ssl_option.allow_self_signed = zval_is_true(v);
}
if (php_swoole_array_get_value(vht, "ssl_cafile", v))
{
zend::string str_v(v);
cli->ssl_option.cafile = sw_strndup(str_v.val(), str_v.len());
}
if (php_swoole_array_get_value(vht, "ssl_capath", v))
{
zend::string str_v(v);
cli->ssl_option.capath = sw_strndup(str_v.val(), str_v.len());
}
if (php_swoole_array_get_value(vht, "ssl_verify_depth", v))
{
cli->ssl_option.verify_depth = (int) zval_get_long(v);
}
if (cli->ssl_option.cert_file && !cli->ssl_option.key_file)
{
swoole_php_fatal_error(E_ERROR, "ssl require key file.");
return;
}
}
#endif
static PHP_METHOD(swoole_client_coro, __construct)
{
zend_long type = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|ls", &type) == FAILURE)
{
swoole_php_fatal_error(E_ERROR, "socket type param is required.");
RETURN_FALSE;
}
int client_type = php_swoole_socktype(type);
if (client_type < SW_SOCK_TCP || client_type > SW_SOCK_UNIX_STREAM)
{
swoole_php_fatal_error(E_ERROR, "Unknown client type '%d'.", client_type);
}
php_swoole_check_reactor();
zend_update_property_long(swoole_client_coro_ce_ptr, getThis(), ZEND_STRL("type"), type);
//init
swoole_set_object(getThis(), NULL);
swoole_set_property(getThis(), client_property_callback, NULL);
#ifdef SWOOLE_SOCKETS_SUPPORT
swoole_set_property(getThis(), client_property_socket, NULL);
#endif
RETURN_TRUE;
}
static PHP_METHOD(swoole_client_coro, __destruct)
{
SW_PREVENT_USER_DESTRUCT;
client_coro_close(getThis());
}
static PHP_METHOD(swoole_client_coro, set)
{
Socket *cli = client_get_ptr(getThis(), true);
zval *zset, *zsetting;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(zset)
ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE);
zsetting = sw_zend_read_property_array(swoole_client_coro_ce_ptr, getThis(), ZEND_STRL("setting"), 1);
php_array_merge(Z_ARRVAL_P(zsetting), Z_ARRVAL_P(zset));
if (cli)
{
sw_coro_socket_set(cli, zset);
}
RETURN_TRUE;
}
static PHP_METHOD(swoole_client_coro, connect)
{
char *host;
size_t host_len;
zend_long port = 0;
double timeout = 0;
zend_long sock_flag = 0;
ZEND_PARSE_PARAMETERS_START(1, 4)
Z_PARAM_STRING(host, host_len)
Z_PARAM_OPTIONAL
Z_PARAM_LONG(port)
Z_PARAM_DOUBLE(timeout)
Z_PARAM_LONG(sock_flag)
ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE);
if (host_len == 0)
{
swoole_php_fatal_error(E_WARNING, "The host is empty.");
RETURN_FALSE;
}
Socket *cli = (Socket *) swoole_get_object(getThis());
if (cli)
{
swoole_php_error(E_WARNING, "connection to the server has already been established.");
RETURN_FALSE;
}
cli = client_coro_new(getThis(), (int) port);
if (cli == NULL)
{
RETURN_FALSE;
}
zval *zset = sw_zend_read_property(swoole_client_coro_ce_ptr, getThis(), ZEND_STRL("setting"), 1);
if (zset && ZVAL_IS_ARRAY(zset))
{
sw_coro_socket_set(cli, zset);
}
PHPCoroutine::check_bind("client", cli->get_bound_cid());
cli->set_timeout(timeout == 0 ? PHPCoroutine::socket_connect_timeout : timeout);
if (!cli->connect(host, port, sock_flag))
{
swoole_php_error(E_WARNING, "connect to server[%s:%d] failed. Error: %s[%d]", host, (int )port, cli->errMsg, cli->errCode);
zend_update_property_long(swoole_client_coro_ce_ptr, getThis(), ZEND_STRL("errCode"), cli->errCode);
client_coro_close(getThis());
RETURN_FALSE;
}
else
{
cli->set_timeout(timeout == 0 ? PHPCoroutine::socket_timeout : timeout);
zend_update_property_bool(swoole_client_coro_ce_ptr, getThis(), ZEND_STRL("connected"), 1);
RETURN_TRUE;
}
}
static PHP_METHOD(swoole_client_coro, send)
{
char *data;
size_t data_len;
double timeout = 0;
ZEND_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_STRING(data, data_len)
Z_PARAM_OPTIONAL
Z_PARAM_DOUBLE(timeout)
ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE);
if (data_len == 0)
{
swoole_php_fatal_error(E_WARNING, "data to send is empty.");
RETURN_FALSE;
}
Socket *cli = client_get_ptr(getThis());
if (!cli)
{
RETURN_FALSE;
}
//clear errno
SwooleG.error = 0;
PHPCoroutine::check_bind("client", cli->get_bound_cid(SW_EVENT_WRITE));
double persistent_timeout = cli->get_timeout();
cli->set_timeout(timeout);
ssize_t ret = cli->send_all(data, data_len);
cli->set_timeout(persistent_timeout);
if (ret < 0)
{
swoole_php_sys_error(E_WARNING, "failed to send %zu bytes to fd#%d.", data_len, cli->socket->fd);
zend_update_property_long(swoole_client_coro_ce_ptr, getThis(), ZEND_STRL("errCode"), (SwooleG.error = cli->errCode));
RETVAL_FALSE;
}
else
{
if ((ret < 0 || (size_t) ret < data_len) && cli->errCode)
{
swoole_php_sys_error(E_WARNING, "expected sent %zu bytes to fd #%d but actually %zu bytes.", data_len, cli->socket->fd, ret);
zend_update_property_long(swoole_client_coro_ce_ptr, getThis(), ZEND_STRL("errCode"), (SwooleG.error = cli->errCode));
}
RETURN_LONG(ret);
}
}
static PHP_METHOD(swoole_client_coro, sendto)
{
char* ip;
size_t ip_len;
long port;
char *data;
size_t len;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "sls", &ip, &ip_len, &port, &data, &len) == FAILURE)
{
RETURN_FALSE;
}
if (len == 0)
{
swoole_php_error(E_WARNING, "data to send is empty.");
RETURN_FALSE;
}
Socket *cli = (Socket *) swoole_get_object(getThis());
if (!cli)
{
cli = client_coro_new(getThis(), (int) port);
if (cli == NULL)
{
RETURN_FALSE;
}
cli->socket->active = 1;
}
PHPCoroutine::check_bind("client", cli->get_bound_cid(SW_EVENT_WRITE));
SW_CHECK_RETURN(cli->sendto(ip, port, data, len));
}
static PHP_METHOD(swoole_client_coro, recvfrom)
{
zend_long length;
zval *address, *port;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "lz/|z/", &length, &address, &port) == FAILURE)
{
RETURN_FALSE;
}
if (length <= 0)
{
swoole_php_error(E_WARNING, "invalid length.");
RETURN_FALSE;
}
Socket *cli = (Socket *) swoole_get_object(getThis());
if (!cli)
{
cli = client_coro_new(getThis());
if (cli == NULL)
{
RETURN_FALSE;
}
cli->socket->active = 1;
}
zend_string *retval = zend_string_alloc(length + 1, 0);
PHPCoroutine::check_bind("client", cli->get_bound_cid(SW_EVENT_READ));
// cli->set_timeout(timeout, true); TODO
ssize_t n_bytes = cli->recvfrom(ZSTR_VAL(retval), length);
if (n_bytes < 0)
{
zend_string_free(retval);
RETURN_FALSE;
}
else
{
ZSTR_LEN(retval) = n_bytes;
ZSTR_VAL(retval)[ZSTR_LEN(retval)] = '\0';
ZVAL_STRING(address, swConnection_get_ip(cli->socket));
if (port)
{
ZVAL_LONG(port, swConnection_get_port(cli->socket));
}
RETURN_STR(retval);
}
}
static PHP_METHOD(swoole_client_coro, sendfile)
{
char *file;
size_t file_len;
zend_long offset = 0;
zend_long length = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|ll", &file, &file_len, &offset, &length) == FAILURE)
{
RETURN_FALSE;
}
if (file_len == 0)
{
swoole_php_fatal_error(E_WARNING, "file to send is empty.");
RETURN_FALSE;
}
Socket *cli = client_get_ptr(getThis());
if (!cli)
{
RETURN_FALSE;
}
//only stream socket can sendfile
if (!(cli->type == SW_SOCK_TCP || cli->type == SW_SOCK_TCP6 || cli->type == SW_SOCK_UNIX_STREAM))
{
swoole_php_error(E_WARNING, "dgram socket cannot use sendfile.");
RETURN_FALSE;
}
//clear errno
SwooleG.error = 0;
PHPCoroutine::check_bind("client", cli->get_bound_cid(SW_EVENT_WRITE));
int ret = cli->sendfile(file, offset, length);
if (ret < 0)
{
swoole_php_error(E_WARNING, "sendfile() failed. Error: %s [%d]", cli->errMsg, (SwooleG.error = cli->errCode));
zend_update_property_long(swoole_client_coro_ce_ptr, getThis(), ZEND_STRL("errCode"), cli->errCode);
RETVAL_FALSE;
}
else
{
RETVAL_TRUE;
}
}
static PHP_METHOD(swoole_client_coro, recv)
{
double timeout = 0;
ZEND_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_DOUBLE(timeout)
ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE);
Socket *cli = client_get_ptr(getThis());
if (!cli)
{
RETURN_FALSE;
}
PHPCoroutine::check_bind("client", cli->get_bound_cid(SW_EVENT_READ));
ssize_t retval ;
if (cli->open_length_check || cli->open_eof_check)
{
retval = cli->recv_packet(timeout);
if (retval > 0)
{
RETVAL_STRINGL(cli->read_buffer->str, retval);
}
}
else
{
zend_string *result = zend_string_alloc(SW_PHP_CLIENT_BUFFER_SIZE - sizeof(zend_string), 0);
double persistent_timeout = cli->get_timeout();
cli->set_timeout(timeout);
retval = cli->recv(ZSTR_VAL(result), SW_PHP_CLIENT_BUFFER_SIZE - sizeof(zend_string));
cli->set_timeout(persistent_timeout);
if (retval > 0)
{
ZSTR_VAL(result)[retval] = '\0';
ZSTR_LEN(result) = retval;
RETURN_STR(result);
}
else
{
zend_string_free(result);
}
}
if (retval < 0)
{
swoole_php_error(E_WARNING, "recv() failed. Error: %s [%d]", cli->errMsg, (SwooleG.error = cli->errCode));
zend_update_property_long(swoole_client_coro_ce_ptr, getThis(), ZEND_STRL("errCode"), cli->errCode);
RETURN_FALSE;
}
else if (retval == 0)
{
RETURN_EMPTY_STRING();
}
}
static PHP_METHOD(swoole_client_coro, peek)
{
zend_long buf_len = SW_PHP_CLIENT_BUFFER_SIZE;
int ret;
char *buf = NULL;
ZEND_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_LONG(buf_len)
ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE);
Socket *cli = client_get_ptr(getThis());
if (!cli)
{
RETURN_FALSE;
}
SwooleG.error = 0;
buf = (char *) emalloc(buf_len + 1);
ret = cli->peek(buf, buf_len);
if (ret < 0)
{
swoole_php_error(E_WARNING, "peek() failed. Error: %s [%d]", cli->errMsg, (SwooleG.error = cli->errCode));
zend_update_property_long(swoole_client_coro_ce_ptr, getThis(), ZEND_STRL("errCode"), cli->errCode);
efree(buf);
RETURN_FALSE;
}
else
{
buf[ret] = 0;
RETVAL_STRINGL(buf, ret);
efree(buf);
}
}
static PHP_METHOD(swoole_client_coro, isConnected)
{
Socket *cli = (Socket *) swoole_get_object(getThis());
if (cli && cli->socket && cli->socket->active == 1)
{
RETURN_TRUE;
}
else
{
RETURN_FALSE;
}
}
static PHP_METHOD(swoole_client_coro, getsockname)
{
Socket *cli = client_get_ptr(getThis());
if (!cli)
{
RETURN_FALSE;
}
if (cli->type == SW_SOCK_UNIX_STREAM || cli->type == SW_SOCK_UNIX_DGRAM)
{
swoole_php_fatal_error(E_WARNING, "getsockname() only support AF_INET family socket.");
RETURN_FALSE;
}
cli->socket->info.len = sizeof(cli->socket->info.addr);
if (getsockname(cli->socket->fd, (struct sockaddr*) &cli->socket->info.addr, &cli->socket->info.len) < 0)
{
swoole_php_sys_error(E_WARNING, "getsockname() failed.");
RETURN_FALSE;
}
array_init(return_value);
if (cli->type == SW_SOCK_UDP6 || cli->type == SW_SOCK_TCP6)
{
add_assoc_long(return_value, "port", ntohs(cli->socket->info.addr.inet_v6.sin6_port));
char tmp[INET6_ADDRSTRLEN];
if (inet_ntop(AF_INET6, &cli->socket->info.addr.inet_v6.sin6_addr, tmp, sizeof(tmp)))
{
add_assoc_string(return_value, "host", tmp);
}
else
{
swoole_php_fatal_error(E_WARNING, "inet_ntop() failed.");
}
}
else
{
add_assoc_long(return_value, "port", ntohs(cli->socket->info.addr.inet_v4.sin_port));
add_assoc_string(return_value, "host", inet_ntoa(cli->socket->info.addr.inet_v4.sin_addr));
}
}
#ifdef SWOOLE_SOCKETS_SUPPORT
static PHP_METHOD(swoole_client_coro, getSocket)
{
zval *zsocket = (zval *) swoole_get_property(getThis(), client_property_socket);
if (zsocket)
{
RETURN_ZVAL(zsocket, 1, NULL);
}
Socket *cli = client_get_ptr(getThis());
if (!cli)
{
RETURN_FALSE;
}
php_socket *socket_object = swoole_convert_to_socket(cli->socket->fd);
if (!socket_object)
{
RETURN_FALSE;
}
SW_ZEND_REGISTER_RESOURCE(return_value, (void * ) socket_object, php_sockets_le_socket());
zsocket = sw_zval_dup(return_value);
Z_TRY_ADDREF_P(zsocket);
swoole_set_property(getThis(), client_property_socket, zsocket);
}
#endif
static PHP_METHOD(swoole_client_coro, getpeername)
{
Socket *cli = client_get_ptr(getThis());
if (!cli)
{
RETURN_FALSE;
}
if (cli->type == SW_SOCK_UDP)
{
array_init(return_value);
add_assoc_long(return_value, "port", ntohs(cli->socket->info.addr.inet_v4.sin_port));
add_assoc_string(return_value, "host", inet_ntoa(cli->socket->info.addr.inet_v4.sin_addr));
}
else if (cli->type == SW_SOCK_UDP6)
{
array_init(return_value);
add_assoc_long(return_value, "port", ntohs(cli->socket->info.addr.inet_v6.sin6_port));
char tmp[INET6_ADDRSTRLEN];
if (inet_ntop(AF_INET6, &cli->socket->info.addr.inet_v6.sin6_addr, tmp, sizeof(tmp)))
{
add_assoc_string(return_value, "host", tmp);
}
else
{
swoole_php_fatal_error(E_WARNING, "inet_ntop() failed.");
}
}
else
{
swoole_php_fatal_error(E_WARNING, "only supports SWOOLE_SOCK_UDP or SWOOLE_SOCK_UDP6.");
RETURN_FALSE;
}
}
static PHP_METHOD(swoole_client_coro, close)
{
RETURN_BOOL(client_coro_close(getThis()));
}
#ifdef SW_USE_OPENSSL
static PHP_METHOD(swoole_client_coro, enableSSL)
{
Socket *cli = client_get_ptr(getThis());
if (!cli)
{
RETURN_FALSE;
}
if (cli->type != SW_SOCK_TCP && cli->type != SW_SOCK_TCP6)
{
swoole_php_fatal_error(E_WARNING, "cannot use enableSSL.");
RETURN_FALSE;
}
if (cli->socket->ssl)
{
swoole_php_fatal_error(E_WARNING, "SSL has been enabled.");
RETURN_FALSE;
}
cli->open_ssl = true;
zval *zset = sw_zend_read_property(swoole_client_coro_ce_ptr, getThis(), ZEND_STRL("setting"), 0);
if (ZVAL_IS_ARRAY(zset))
{
sw_coro_socket_set_ssl(cli, zset);
}
PHPCoroutine::check_bind("client", cli->get_bound_cid());
if (cli->ssl_handshake() == false)
{
RETURN_FALSE;
}
RETURN_TRUE;
}
static PHP_METHOD(swoole_client_coro, getPeerCert)
{
Socket *cli = client_get_ptr(getThis());
if (!cli)
{
RETURN_FALSE;
}
if (!cli->socket->ssl)
{
swoole_php_fatal_error(E_WARNING, "SSL is not ready.");
RETURN_FALSE;
}
char buf[8192];
int n = swSSL_get_client_certificate(cli->socket->ssl, buf, sizeof(buf));
if (n < 0)
{
RETURN_FALSE;
}
RETURN_STRINGL(buf, n);
}
static PHP_METHOD(swoole_client_coro, verifyPeerCert)
{
Socket *cli = client_get_ptr(getThis());
if (!cli)
{
RETURN_FALSE;
}
if (!cli->socket->ssl)
{
swoole_php_fatal_error(E_WARNING, "SSL is not ready.");
RETURN_FALSE;
}
zend_bool allow_self_signed = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &allow_self_signed) == FAILURE)
{
RETURN_FALSE;
}
SW_CHECK_RETURN(cli->ssl_verify(allow_self_signed));
}
#endif
|
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/profiler/backends/cpu/traceme_recorder.h"
#include <stddef.h>
#include <algorithm>
#include <atomic>
#include <memory>
#include <new>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
namespace profiler {
namespace internal {
std::atomic<int> g_trace_level(TraceMeRecorder::kTracingDisabled);
// g_trace_level implementation must be lock-free for faster execution of the
// TraceMe API. This can be commented (if compilation is failing) but execution
// might be slow (even when tracing is disabled).
static_assert(ATOMIC_INT_LOCK_FREE == 2, "Assumed atomic<int> was lock free");
} // namespace internal
namespace {
// Track events created by ActivityStart and merge their data into events
// created by ActivityEnd. TraceMe records events in its destructor, so this
// results in complete events sorted by their end_time in the thread they ended.
// Within the same thread, the record created by ActivityStart must appear
// before the record created by ActivityEnd. Cross-thread events must be
// processed in a separate pass. A single map can be used because the
// activity_id is globally unique.
class SplitEventTracker {
public:
void AddStart(TraceMeRecorder::Event&& event) {
DCHECK(event.IsStart());
start_events_.emplace(event.ActivityId(), std::move(event));
}
void AddEnd(TraceMeRecorder::Event* event) {
DCHECK(event->IsEnd());
if (!FindStartAndMerge(event)) {
end_events_.push_back(event);
}
}
void HandleCrossThreadEvents() {
for (auto* event : end_events_) {
FindStartAndMerge(event);
}
}
private:
// Finds the start of the given event and merges data into it.
bool FindStartAndMerge(TraceMeRecorder::Event* event) {
auto iter = start_events_.find(event->ActivityId());
if (iter == start_events_.end()) return false;
auto& start_event = iter->second;
event->name = std::move(start_event.name);
event->start_time = start_event.start_time;
start_events_.erase(iter);
return true;
}
// Start events are collected from each ThreadLocalRecorder::Consume() call.
// Their data is merged into end_events.
absl::flat_hash_map<int64_t, TraceMeRecorder::Event> start_events_;
// End events are stored in the output of TraceMeRecorder::Consume().
std::vector<TraceMeRecorder::Event*> end_events_;
};
// A single-producer single-consumer queue of Events.
//
// Implemented as a linked-list of blocks containing numbered slots, with start
// and end pointers:
//
// [ events........ | next-]--> [ events......... | next ]
// ^start_block_ ^start_ ^end_block_ ^end_
//
// start_ is the first occupied slot, end_ is the first unoccupied slot.
//
// Push writes at end_, and then advances it, allocating a block if needed.
// Consume takes ownership of events in the range [start_, end_).
// Clear removes events in the range [start_, end_).
// The end_ pointer is atomic so Push and Consume can be concurrent.
//
// Push and Consume are lock free and each might be called from at most one
// thread. Push is only called by the owner thread. Consume is only called by
// the tracing control thread.
//
// Thus, Consume might race with Push, so Consume only removes events that were
// in the queue when it was invoked. If Push is called while Consume is active,
// the new event remains in the queue. Thus, the tracing control thread should
// call Consume when tracing stops to remove events created during tracing, and
// Clear when tracing starts again to remove any remaining events.
class EventQueue {
public:
EventQueue()
: start_block_(new Block{/*start=*/0, /*next=*/nullptr}),
start_(start_block_->start),
end_block_(start_block_),
end_(start_) {}
// Memory should be deallocated and trace events destroyed on destruction.
// This doesn't require global lock as this discards all the stored trace
// events and we assume of destruction of this instance only after the last
// Push() has been called.
~EventQueue() {
Clear();
DCHECK(Empty());
delete end_block_;
}
// Add a new event to the back of the queue. Fast and lock-free.
void Push(TraceMeRecorder::Event&& event) {
size_t end = end_.load(std::memory_order_relaxed);
new (&end_block_->events[end++ - end_block_->start].event)
TraceMeRecorder::Event(std::move(event));
if (TF_PREDICT_FALSE(end - end_block_->start == Block::kNumSlots)) {
auto* new_block = new Block{end, nullptr};
end_block_->next = new_block;
end_block_ = new_block;
}
end_.store(end, std::memory_order_release); // Write index after contents.
}
// Removes all events from the queue.
void Clear() {
size_t end = end_.load(std::memory_order_acquire);
while (start_ != end) {
Pop();
}
}
// Retrieve and remove all events in the queue at the time of invocation.
// If Push is called while Consume is active, the new event will not be
// removed from the queue.
// Consume is only called from ThreadLocalRecorder::Clear, which in turn is
// only called while holding TraceMeRecorder::Mutex, so Consume has a single
// caller at a time.
TF_MUST_USE_RESULT std::deque<TraceMeRecorder::Event> Consume(
SplitEventTracker* split_event_tracker) {
// Read index before contents.
size_t end = end_.load(std::memory_order_acquire);
std::deque<TraceMeRecorder::Event> result;
while (start_ != end) {
TraceMeRecorder::Event event = Pop();
// Copy data from start events to end events. TraceMe records events in
// its destructor, so this results in complete events sorted by their
// end_time in the thread they ended. Within the same thread, the start
// event must appear before the corresponding end event.
if (event.IsStart()) {
split_event_tracker->AddStart(std::move(event));
continue;
}
result.emplace_back(std::move(event));
if (result.back().IsEnd()) {
split_event_tracker->AddEnd(&result.back());
}
}
return result;
}
private:
// Returns true if the queue is empty at the time of invocation.
bool Empty() const {
return (start_ == end_.load(std::memory_order_acquire));
}
// Remove one event off the front of the queue and return it.
// REQUIRES: The queue must not be empty.
TraceMeRecorder::Event Pop() {
DCHECK(!Empty());
// Move the next event into the output.
auto& event = start_block_->events[start_++ - start_block_->start].event;
TraceMeRecorder::Event out = std::move(event);
event.~Event(); // Events must be individually destroyed.
// If we reach the end of a block, we own it and should delete it.
// The next block is present: end always points to something.
if (TF_PREDICT_FALSE(start_ - start_block_->start == Block::kNumSlots)) {
auto* next_block = start_block_->next;
delete start_block_;
start_block_ = next_block;
DCHECK_EQ(start_, start_block_->start);
}
return out;
}
struct Block {
// The number of slots in a block is chosen so the block fits in 64 KiB.
static constexpr size_t kSize = 1 << 16;
static constexpr size_t kNumSlots =
(kSize - (sizeof(size_t) + sizeof(Block*))) /
sizeof(TraceMeRecorder::Event);
size_t start; // The number of the first slot.
Block* next;
// Defer construction of Event until the data is available.
// Must also destroy manually, as the block may not fill entirely.
union MaybeEvent {
MaybeEvent() {}
~MaybeEvent() {}
TraceMeRecorder::Event event;
} events[kNumSlots];
};
static_assert(sizeof(Block) <= Block::kSize, "");
// Head of list for reading. Only accessed by consumer thread.
Block* start_block_;
size_t start_;
// Tail of list for writing. Accessed by producer thread.
Block* end_block_;
std::atomic<size_t> end_; // Atomic: also read by consumer thread.
};
} // namespace
// To avoid unnecessary synchronization between threads, each thread has a
// ThreadLocalRecorder that independently records its events.
class TraceMeRecorder::ThreadLocalRecorder {
public:
// The recorder is created the first time TraceMeRecorder::Record() is called
// on a thread.
ThreadLocalRecorder() {
auto* env = Env::Default();
info_.tid = env->GetCurrentThreadId();
env->GetCurrentThreadName(&info_.name);
}
uint32 ThreadId() const { return info_.tid; }
bool IsActive() const { return active_; }
void SetActive(bool active) { active_ = active; }
// Record is only called from the owner thread.
void Record(TraceMeRecorder::Event&& event) { queue_.Push(std::move(event)); }
// Clear is called from the control thread when tracing starts to remove any
// elements added due to Record racing with Consume.
void Clear() { queue_.Clear(); }
// Consume is called from the control thread when tracing stops.
TF_MUST_USE_RESULT TraceMeRecorder::ThreadEvents Consume(
SplitEventTracker* split_event_tracker) {
return {info_, queue_.Consume(split_event_tracker)};
}
private:
TraceMeRecorder::ThreadInfo info_;
EventQueue queue_;
bool active_ = true;
};
// An instance of this wrapper is allocated in thread_local storage.
// It creates the ThreadLocalRecorder and notifies TraceMeRecorder when the
// the first TraceMe on the thread is executed while tracing is active, or when
// the thread is destroyed.
class TraceMeRecorder::ThreadLocalRecorderWrapper {
public:
ThreadLocalRecorderWrapper()
: recorder_(std::make_shared<TraceMeRecorder::ThreadLocalRecorder>()) {
TraceMeRecorder::Get()->RegisterThread(recorder_->ThreadId(), recorder_);
}
void Record(TraceMeRecorder::Event&& event) {
recorder_->Record(std::move(event));
}
~ThreadLocalRecorderWrapper() {
recorder_->SetActive(false);
TraceMeRecorder::Get()->UnregisterThread(recorder_->ThreadId());
}
private:
// Ownership of ThreadLocalRecorder is shared with TraceMeRecorder.
// If a thread is destroyed during tracing, its ThreadLocalRecorder is kept
// alive until the end of tracing.
std::shared_ptr<TraceMeRecorder::ThreadLocalRecorder> recorder_;
};
/*static*/ TraceMeRecorder* TraceMeRecorder::Get() {
static TraceMeRecorder* singleton = new TraceMeRecorder;
return singleton;
}
void TraceMeRecorder::RegisterThread(
uint32 tid, std::shared_ptr<ThreadLocalRecorder> thread) {
mutex_lock lock(mutex_);
threads_.insert_or_assign(tid, std::move(thread));
}
void TraceMeRecorder::UnregisterThread(uint32 tid) {
// If tracing is active, keep the ThreadLocalRecorder alive.
if (Active()) return;
// If tracing is inactive, destroy the ThreadLocalRecorder.
mutex_lock lock(mutex_);
threads_.erase(tid);
}
// This method is performance critical and should be kept fast. It is called
// when tracing starts. The mutex is held, so no threads can be
// registered/unregistered. This ensures only the control thread calls
// ThreadLocalRecorder::Clear().
void TraceMeRecorder::Clear() {
for (auto& id_and_recorder : threads_) {
auto& recorder = id_and_recorder.second;
recorder->Clear();
// We should not have an inactive ThreadLocalRecorder here. If a thread is
// destroyed while tracing is inactive, its ThreadLocalRecorder is removed
// in UnregisterThread.
DCHECK(recorder->IsActive());
}
}
// This method is performance critical and should be kept fast. It is called
// when tracing stops. The mutex is held, so no threads can be
// registered/unregistered. This ensures only the control thread calls
// ThreadLocalRecorder::Consume().
TraceMeRecorder::Events TraceMeRecorder::Consume() {
TraceMeRecorder::Events result;
result.reserve(threads_.size());
SplitEventTracker split_event_tracker;
for (auto iter = threads_.begin(); iter != threads_.end();) {
auto& recorder = iter->second;
TraceMeRecorder::ThreadEvents events =
recorder->Consume(&split_event_tracker);
if (!events.events.empty()) {
result.push_back(std::move(events));
}
// We can have an active thread here. If a thread is destroyed while tracing
// is active, its ThreadLocalRecorder is kept alive in UnregisterThread.
if (!recorder->IsActive()) {
threads_.erase(iter++);
} else {
++iter;
}
}
split_event_tracker.HandleCrossThreadEvents();
return result;
}
bool TraceMeRecorder::StartRecording(int level) {
level = std::max(0, level);
mutex_lock lock(mutex_);
// Change trace_level_ while holding mutex_.
int expected = kTracingDisabled;
bool started = internal::g_trace_level.compare_exchange_strong(
expected, level, std::memory_order_acq_rel);
if (started) {
// We may have old events in buffers because Record() raced with Stop().
Clear();
}
return started;
}
void TraceMeRecorder::Record(Event&& event) {
static thread_local ThreadLocalRecorderWrapper thread_local_recorder;
thread_local_recorder.Record(std::move(event));
}
TraceMeRecorder::Events TraceMeRecorder::StopRecording() {
TraceMeRecorder::Events events;
mutex_lock lock(mutex_);
// Change trace_level_ while holding mutex_.
if (internal::g_trace_level.exchange(
kTracingDisabled, std::memory_order_acq_rel) != kTracingDisabled) {
events = Consume();
}
return events;
}
/*static*/ int64_t TraceMeRecorder::NewActivityId() {
// Activity IDs: To avoid contention over a counter, the top 32 bits identify
// the originating thread, the bottom 32 bits name the event within a thread.
// IDs may be reused after 4 billion events on one thread, or 2 billion
// threads.
static std::atomic<int32> thread_counter(1); // avoid kUntracedActivity
const thread_local static int32_t thread_id =
thread_counter.fetch_add(1, std::memory_order_relaxed);
thread_local static uint32 per_thread_activity_id = 0;
return static_cast<int64_t>(thread_id) << 32 | per_thread_activity_id++;
}
} // namespace profiler
} // namespace tensorflow
|
/*!
* Copyright (c) 2016 by Contributors
*/
#include "Debug.h"
namespace Halide {
namespace Internal {
int debug::debug_level() { return 0; }
} // namespace Internal
} // namespace Halide
|
#include <stdio.h>
#include <sys/time.h>
#include "pl_util.h"
#define FILE_MEMORY_STATUS "/proc/self/statm"
double now_us(void)
{
struct timeval tv;
double now = 0.0;
int rc = gettimeofday(&tv, 0);
if (rc == 0) {
now = 1000000.0 * tv.tv_sec + tv.tv_usec;
}
return now;
}
long total_memory_pages(void)
{
long pages = 0;
/*
* /proc/[pid]/statm
* Provides information about memory usage, measured in pages.
* size total program size
* (same as VmSize in /proc/[pid]/status)
* resident resident set size
* (same as VmRSS in /proc/[pid]/status)
* share shared pages (from shared mappings)
* text text (code)
* lib library (unused in Linux 2.6)
* data data + stack
* dirty dirty pages (unused in Linux 2.6)
*/
FILE* fp = 0;
do {
long size, resident, share, text, lib, data, dirty;
int nread;
fp = fopen(FILE_MEMORY_STATUS, "r");
if (!fp) {
/* silently ignore, some OSs do not have this file */
break;
}
nread = fscanf(fp, "%ld %ld %ld %ld %ld %ld %ld",
&size, &resident, &share, &text, &lib, &data, &dirty);
if (nread != 7) {
/* silently ignore, avoid noisy errors */
break;
}
pages = size;
} while (0);
if (fp) {
fclose(fp);
fp = 0;
}
return pages;
}
|
// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*-
//-----------------------------------------------------------------------------
// Copyright 2000-2022 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com)
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: Apache-2.0
//-----------------------------------------------------------------------------
/*---------------------------------------------------------------------------*/
/* CartesianMeshUniqueIdRenumbering.cc (C) 2000-2021 */
/* */
/* Renumérotation des uniqueId() pour les maillages cartésiens. */
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
#include "arcane/cartesianmesh/internal/CartesianMeshUniqueIdRenumbering.h"
#include "arcane/utils/PlatformUtils.h"
#include "arcane/cea/ICartesianMesh.h"
#include "arcane/cea/ICartesianMeshPatch.h"
#include "arcane/VariableTypes.h"
#include "arcane/IMesh.h"
#include "arcane/IItemFamily.h"
#include "arcane/ICartesianMeshGenerationInfo.h"
#include <array>
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
namespace Arcane
{
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
CartesianMeshUniqueIdRenumbering::
CartesianMeshUniqueIdRenumbering(ICartesianMesh* cmesh, ICartesianMeshGenerationInfo* gen_info)
: TraceAccessor(cmesh->traceMng())
, m_cartesian_mesh(cmesh)
, m_generation_info(gen_info)
{
if (platform::getEnvironmentVariable("ARCANE_DEBUG_AMR_RENUMBERING") == "1")
m_is_verbose = true;
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void CartesianMeshUniqueIdRenumbering::
renumber()
{
IMesh* mesh = m_cartesian_mesh->mesh();
Int64 cartesian_global_nb_cell = m_generation_info->globalNbCell();
info() << "Apply UniqueId renumbering to mesh '" << mesh->name() << "'"
<< " global_nb_cell=" << cartesian_global_nb_cell
<< " global_nb_cell_by_dim=" << m_generation_info->globalNbCells();
if (mesh->dimension() != 2)
ARCANE_THROW(NotImplementedException, "Renumbering is only implemented for 2D mesh");
VariableCellInt64 cells_new_uid(VariableBuildInfo(mesh, "ArcaneRenumberCellsNewUid"));
VariableNodeInt64 nodes_new_uid(VariableBuildInfo(mesh, "ArcaneRenumberNodesNewUid"));
VariableFaceInt64 faces_new_uid(VariableBuildInfo(mesh, "ArcaneRenumberFacesNewUid"));
cells_new_uid.fill(-1);
nodes_new_uid.fill(-1);
faces_new_uid.fill(-1);
// Marque les entités issues du maillage cartésien comme étant de niveau 0
// Elles ne seront pas renumérotées
ICartesianMeshPatch* patch0 = m_cartesian_mesh->patch(0);
ENUMERATE_ (Cell, icell, patch0->cells()) {
Cell c{ *icell };
cells_new_uid[icell] = c.uniqueId().asInt64();
for (Node n : c.nodes())
nodes_new_uid[n] = n.uniqueId();
for (Face f : c.faces())
faces_new_uid[f] = f.uniqueId();
}
// Pour chaque maille de niveau 0, calcule son indice (i,j) dans le maillage cartésien
// Pour cela, on suppose que le maillage a été créé avec le 'CartesianMeshGenerator'
// (ou un générateur qui a la même numérotation) et que le uniqueId() d'une maille est:
// Int64 cell_unique_id = i + j * all_nb_cell_x;
// avec:
// all_nb_cell_x = m_generation_info->globalNbCells()[MD_DirX];
Int64ConstArrayView global_nb_cells_by_direction = m_generation_info->globalNbCells();
Int64 nb_cell_x = global_nb_cells_by_direction[MD_DirX];
if (nb_cell_x <= 0)
ARCANE_FATAL("Bad value '{0}' for globalNbCells()[MD_DirX] (should be >0)", nb_cell_x);
Int64 nb_cell_y = global_nb_cells_by_direction[MD_DirY];
if (nb_cell_y <= 0)
ARCANE_FATAL("Bad value '{0}' for globalNbCells()[MD_DirY] (should be >0)", nb_cell_y);
ENUMERATE_ (Cell, icell, patch0->cells()) {
Cell cell{ *icell };
Int64 uid = cell.uniqueId();
Int64 coord_i = uid % nb_cell_x;
Int64 coord_j = uid / nb_cell_x;
if (m_is_verbose)
info() << "Renumbering: PARENT: cell_uid=" << cell.uniqueId() << " I=" << coord_i
<< " J=" << coord_j << " nb_cell_x=" << nb_cell_x;
_applyChildrenCell(cell, nodes_new_uid, faces_new_uid, cells_new_uid, coord_i, coord_j, nb_cell_x, nb_cell_y, 1);
}
// TODO: faire une classe pour cela.
//info() << "Change CellFamily";
//mesh->cellFamily()->notifyItemsUniqueIdChanged();
_applyFamilyRenumbering(mesh->cellFamily(), cells_new_uid);
_applyFamilyRenumbering(mesh->nodeFamily(), nodes_new_uid);
_applyFamilyRenumbering(mesh->faceFamily(), faces_new_uid);
mesh->checkValidMesh();
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void CartesianMeshUniqueIdRenumbering::
_applyFamilyRenumbering(IItemFamily* family, VariableItemInt64& items_new_uid)
{
info() << "Change uniqueId() for family=" << family->name();
items_new_uid.synchronize();
ENUMERATE_ (Item, iitem, family->allItems()) {
Item item{ *iitem };
Int64 current_uid = item.uniqueId();
Int64 new_uid = items_new_uid[iitem];
if (new_uid >= 0 && new_uid != current_uid) {
if (m_is_verbose)
info() << "Change ItemUID old=" << current_uid << " new=" << new_uid;
item.internal()->setUniqueId(new_uid);
}
}
family->notifyItemsUniqueIdChanged();
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void CartesianMeshUniqueIdRenumbering::
_applyChildrenCell(Cell cell, VariableNodeInt64& nodes_new_uid, VariableFaceInt64& faces_new_uid,
VariableCellInt64& cells_new_uid,
Int64 coord_i, Int64 coord_j,
Int64 nb_cell_x, Int64 nb_cell_y, Int32 level)
{
// TODO: pour pouvoir s'adapter à tous les raffinements, au lieu de 4,
// il faudrait prendre le max des nbHChildren()
// Suppose qu'on a un pattern 2x2
coord_i *= 2;
coord_j *= 2;
nb_cell_x *= 2;
nb_cell_y *= 2;
const Int64 nb_node_x = nb_cell_x + 1;
const Int64 nb_node_y = nb_cell_y + 1;
const Int64 cell_adder = nb_cell_x * nb_cell_y * level;
const Int64 nb_face_x = nb_cell_x + 1;
const Int64 node_adder = nb_node_x * nb_node_y * level;
const Int64 face_adder = node_adder * 2;
// Renumérote les noeuds de la maille courante.
// Suppose qu'on a 4 noeuds
// ATTENTION a priori on ne peut pas conserver facilement l'ordre
// des uniqueId() entre l'ancienne et la nouvelle numérotation.
// Cela invalide l'orientation des faces qu'il faudra refaire.
{
if (cell.nbNode() != 4)
ARCANE_FATAL("Invalid number of nodes N={0}, expected=4", cell.nbNode());
std::array<Int64, 4> new_uids;
new_uids[0] = (coord_i + 0) + ((coord_j + 0) * nb_node_x);
new_uids[1] = (coord_i + 1) + ((coord_j + 0) * nb_node_x);
new_uids[2] = (coord_i + 1) + ((coord_j + 1) * nb_node_x);
new_uids[3] = (coord_i + 0) + ((coord_j + 1) * nb_node_x);
for (Integer z = 0; z < 4; ++z) {
Node node = cell.node(z);
if (nodes_new_uid[node] < 0) {
new_uids[z] += node_adder;
if (m_is_verbose)
info() << "APPLY_NODE_CHILD: uid=" << node.uniqueId() << " parent_cell=" << cell.uniqueId()
<< " I=" << z << " new_uid=" << new_uids[z];
nodes_new_uid[node] = new_uids[z];
}
}
}
// Renumérote les faces
// TODO: Vérifier la validité de cette méthode.
{
if (cell.nbFace() != 4)
ARCANE_FATAL("Invalid number of faces N={0}, expected=4", cell.nbFace());
std::array<Int64, 4> new_uids;
new_uids[0] = (coord_i + 0) + ((coord_j + 0) * nb_face_x);
new_uids[1] = (coord_i + 1) + ((coord_j + 0) * nb_face_x);
new_uids[2] = (coord_i + 1) + ((coord_j + 1) * nb_face_x);
new_uids[3] = (coord_i + 0) + ((coord_j + 1) * nb_face_x);
for (Integer z = 0; z < 4; ++z) {
Face face = cell.face(z);
if (faces_new_uid[face] < 0) {
new_uids[z] += face_adder;
if (m_is_verbose)
info() << "APPLY_FACE_CHILD: uid=" << face.uniqueId() << " parent_cell=" << cell.uniqueId()
<< " I=" << z << " new_uid=" << new_uids[z];
faces_new_uid[face] = new_uids[z];
}
}
}
// Renumérote les sous-mailles
// Suppose qu'on a 4 mailles enfants comme suit par mailles
// -------
// | 2| 3|
// -------
// | 0| 1|
// -------
Int32 nb_child = cell.nbHChildren();
for (Int32 icell = 0; icell < nb_child; ++icell) {
Cell sub_cell = cell.hChild(icell);
Int64 my_coord_i = coord_i + icell % 2;
Int64 my_coord_j = coord_j + icell / 2;
Int64 new_uid = (my_coord_i + my_coord_j * nb_cell_x) + cell_adder;
if (m_is_verbose)
info() << "APPLY_CELL_CHILD: uid=" << sub_cell.uniqueId() << " I=" << my_coord_i << " J=" << my_coord_j
<< " level=" << level << " new_uid=" << new_uid << " NodeAdder=" << node_adder;
_applyChildrenCell(sub_cell, nodes_new_uid, faces_new_uid, cells_new_uid, my_coord_i, my_coord_j,
nb_cell_x, nb_cell_y, level + 1);
if (cells_new_uid[sub_cell] < 0)
cells_new_uid[sub_cell] = new_uid;
}
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
} // End namespace Arcane
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
|
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size() <= 1) return 0;
int res = 0;
for (int i = 1; i < prices.size(); i++)
if (prices[i] > prices[i - 1])
res += (prices[i] - prices[i - 1]);
return res;
}
};
|
#include "gtest/gtest.h"
#include "inc.h"
#include "stl_headers.h"
#include <list>
NS_BEGIN(elloop);
using namespace std;
//********************************** new case **********************************
RUN_GTEST(ListTest, Example, @);
auto printList = [](const list<int> &l, const string &info="") {
p(info);
for (auto &i : l) {
p(i); p(" ");
}
cr;
};
list<int> list1, list2;
for (int i=0; i<6; ++i) {
list1.push_back(i);
list2.push_front(i);
}
printList(list1, "after push, list1: ");
printList(list2, "after push, list2: ");
// 把list1全部移到list2中,位置是list2中第一个等于3的元素之前
list2.splice(find(begin(list2), end(list2), 3), list1);
printList(list1, "list1, after splice: "); // empty
printList(list2, "list2, after splice: ");
// 把list2的第一个元素移到其末尾
list2.splice(end(list2), list2, begin(list2));
printList(list2, "list2, move begin to end: ");
list2.sort();
list1 = list2;
list2.unique();
printList(list1, "list1, after assign: ");
printList(list2, "list2, after sort & unique: ");
list1.merge(list2);
printList(list1, "list1, after merge: ");
printList(list2, "list2, after merge: ");
END_TEST;
NS_END(elloop);
|
#include "add_activity_dialog.h"
#include "ui_add_activity_dialog.h"
#include "add_activity_info_dialog.h"
#include "add_field_dialog.h"
#include "application_state.h"
#include "error_macros.h"
#include <QMessageBox>
#include <QLineEdit>
#include <QDebug>
#include <QLabel>
AddActivityDialog::AddActivityDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::AddActivityDialog)
{
ui->setupUi(this);
g_app.database()->loadActivityCategories();
QList<ActivityCategory*> categories = g_app.database()->activityCategories();
if (categories.count() == 0)
{
QMessageBox::critical(this, "Error", "No categories are present.");
close();
return;
}
for (ActivityCategory* category : categories)
{
ui->activityInfoComboBox->addItem(category->name, QVariant::fromValue(reinterpret_cast<void*>(category)));
}
ui->activityInfoComboBox->setCurrentIndex(0);
ui->scrollArea->setEnabled(false);
setActivityCategory(categories[0]);
}
AddActivityDialog::~AddActivityDialog()
{
delete ui;
}
void AddActivityDialog::setActivityCategory(ActivityCategory * category)
{
ERR_VERIFY_NULL(category);
if (m_currentActivityInfo)
{
for (auto widget : m_activityInfoWidgets)
{
delete widget;
}
m_activityInfoWidgets.clear();
m_activityInfoFieldWidgets.clear();
}
m_currentActivityInfo = category;
ui->scrollArea->setEnabled(true);
}
void AddActivityDialog::on_addFieldButton_clicked()
{
AddFieldDialog* dialog = new AddFieldDialog(m_currentActivityInfo, this);
connect(dialog, &AddFieldDialog::fieldAdded,
this, &AddActivityDialog::addFieldDialogFieldAdded);
connect(dialog, &AddFieldDialog::finished,
this, &AddActivityDialog::addFieldDialogFinished);
dialog->exec();
}
void AddActivityDialog::addFieldDialogFieldAdded()
{
QObject* sender = QObject::sender();
AddFieldDialog* dialog = qobject_cast<AddFieldDialog*>(sender);
ERR_VERIFY_NULL(dialog);
setActivityCategory(m_currentActivityInfo);
}
void AddActivityDialog::addFieldDialogFinished(int result)
{
Q_UNUSED(result)
QObject* sender = QObject::sender();
AddFieldDialog* dialog = qobject_cast<AddFieldDialog*>(sender);
ERR_VERIFY_NULL(dialog);
dialog->deleteLater();
}
void AddActivityDialog::on_activityInfoComboBox_currentIndexChanged(int index)
{
auto activityInfo = reinterpret_cast<ActivityCategory*>(ui->activityInfoComboBox->itemData(index, Qt::UserRole).value<void*>());
ERR_VERIFY_NULL(activityInfo);
setActivityCategory(activityInfo);
}
Activity* AddActivityDialog::constructActivity()
{
ERR_VERIFY_V(!m_activityWasConstructed, nullptr); // call this thing only once
if (!m_currentActivityInfo)
return nullptr;
if (m_activityWasConstructed)
return nullptr;
Activity* activity = g_app.m_activityAllocator.allocate();
ERR_VERIFY_NULL_V(activity, nullptr);
activity->id = -1;
activity->category = m_currentActivityInfo;
activity->startTime = getCurrentDateTimeUtc();
activity->endTime = activity->startTime;
// activity->fieldValues.reserve(m_activityInfoFieldWidgets.size());
// for (const QWidget* fieldWidget : m_activityInfoFieldWidgets)
// {
// const QLineEdit* lineEdit = qobject_cast<const QLineEdit*>(fieldWidget);
// if (!lineEdit) {
// g_app.m_activityAllocator.deallocate(activity);
// ERR_VERIFY_NULL_V(lineEdit, nullptr);
// }
// activity->fieldValues.append(lineEdit->text());
// }
g_app.database()->saveActivity(activity);
m_activityWasConstructed = true;
return activity;
}
void AddActivityDialog::on_AddActivityDialog_finished(int result)
{
Q_UNUSED(result)
}
void AddActivityDialog::on_buttonBox_accepted()
{
this->accept();
}
void AddActivityDialog::on_buttonBox_rejected()
{
this->reject();
}
void AddActivityDialog::on_addActivityInfo_clicked()
{
AddActivityInfoDialog* dialog = new AddActivityInfoDialog();
connect(dialog, &AddActivityInfoDialog::finished,
this, &AddActivityDialog::addActivityInfoDialogFinished);
connect(dialog, &AddActivityInfoDialog::infoAdded,
this, &AddActivityDialog::addActivityInfoDialogInfoAdded);
dialog->exec();
}
void AddActivityDialog::addActivityInfoDialogInfoAdded()
{
QObject* sender = QObject::sender();
AddActivityInfoDialog* dialog = qobject_cast<AddActivityInfoDialog*>(sender);
ERR_VERIFY(dialog);
ActivityCategory* info = dialog->constructActivityInfo();
ERR_VERIFY(info);
ui->activityInfoComboBox->addItem(info->name, QVariant::fromValue(reinterpret_cast<void*>(info)));
ui->activityInfoComboBox->setCurrentIndex(ui->activityInfoComboBox->children().count() - 1);
}
void AddActivityDialog::addActivityInfoDialogFinished(int result)
{
Q_UNUSED(result)
QObject* sender = QObject::sender();
AddActivityInfoDialog* dialog = qobject_cast<AddActivityInfoDialog*>(sender);
ERR_VERIFY(dialog);
dialog->deleteLater();
}
|
/*++
Copyright (C) 2004 - 2005 Microsoft Corporation
All rights reserved.
Module Name:
PrintSystemUtil.cpp
Abstract:
Utility help classes.
Author:
Ali Naqvi (alinaqvi) Feb 4, 2005
Revision History:
--*/
#include "win32inc.hpp"
using namespace System;
using namespace System::IO;
using namespace System::Collections;
using namespace System::Reflection;
#ifndef __PRINTSYSTEMUTIL_HPP__
#include <PrintSystemUtil.hpp>
#endif
using namespace System::Printing;
/*-----------------------------------------------------------------------------------------------
InternalExceptionResourceManager Implementation
-------------------------------------------------------------------------------------------------*/
InternalExceptionResourceManager::
InternalExceptionResourceManager(
void
) : ResourceManager("System.Printing",
Assembly::GetExecutingAssembly())
{
}
|
/**
* @file Tests.cpp
*
* @brief Test routines for Zerocoin.
*
* @author Ian Miers, Christina Garman and Matthew Green
* @date June 2013
*
* @copyright Copyright 2013 Ian Miers, Christina Garman and Matthew Green
* @license This project is released under the MIT license.
**/
// Copyright (c) 2017-2018 The PIVX developers
// Copyright (c) 2021-2022 The FunCoin developers
#include <boost/test/unit_test.hpp>
#include <string>
#include <iostream>
#include <fstream>
#include <cmath>
// #include <curses.h>
#include <exception>
#include "streams.h"
#include "libzerocoin/ParamGeneration.h"
#include "libzerocoin/Denominations.h"
#include "libzerocoin/Coin.h"
#include "libzerocoin/CoinSpend.h"
#include "libzerocoin/Accumulator.h"
using namespace std;
using namespace libzerocoin;
#define COLOR_STR_GREEN "\033[32m"
#define COLOR_STR_NORMAL "\033[0m"
#define COLOR_STR_RED "\033[31m"
#define TESTS_COINS_TO_ACCUMULATE 10
#define NON_PRIME_TESTS 100
// Global test counters
uint32_t gNumTests = 0;
uint32_t gSuccessfulTests = 0;
// Proof size
uint32_t gProofSize = 0;
uint32_t gCoinSize = 0;
uint32_t gSerialNumberSize = 0;
// Global coin array
PrivateCoin *gCoins[TESTS_COINS_TO_ACCUMULATE];
// Global params
ZerocoinParams *g_Params;
//////////
// Utility routines
//////////
void
LogTestResult(string testName, bool (*testPtr)())
{
string colorGreen(COLOR_STR_GREEN);
string colorNormal(COLOR_STR_NORMAL);
string colorRed(COLOR_STR_RED);
cout << "Testing if " << testName << "..." << endl;
bool testResult = testPtr();
if (testResult == true) {
cout << "\t" << colorGreen << "[PASS]" << colorNormal << endl;
gSuccessfulTests++;
} else {
cout << colorRed << "\t[FAIL]" << colorNormal << endl;
}
gNumTests++;
}
CBigNum
GetTestModulus()
{
static CBigNum testModulus(0);
// TODO: should use a hard-coded RSA modulus for testing
if (!testModulus) {
CBigNum p, q;
// Note: we are NOT using safe primes for testing because
// they take too long to generate. Don't do this in real
// usage. See the paramgen utility for better code.
p = CBigNum::generatePrime(1024, false);
q = CBigNum::generatePrime(1024, false);
testModulus = p * q;
}
return testModulus;
}
//////////
// Test routines
//////////
bool
Test_GenRSAModulus()
{
CBigNum result = GetTestModulus();
if (!result) {
return false;
}
else {
return true;
}
}
bool
Test_CalcParamSizes()
{
bool result = true;
#if 0
uint32_t pLen, qLen;
try {
calculateGroupParamLengths(4000, 80, &pLen, &qLen);
if (pLen < 1024 || qLen < 256) {
result = false;
}
calculateGroupParamLengths(4000, 96, &pLen, &qLen);
if (pLen < 2048 || qLen < 256) {
result = false;
}
calculateGroupParamLengths(4000, 112, &pLen, &qLen);
if (pLen < 3072 || qLen < 320) {
result = false;
}
calculateGroupParamLengths(4000, 120, &pLen, &qLen);
if (pLen < 3072 || qLen < 320) {
result = false;
}
calculateGroupParamLengths(4000, 128, &pLen, &qLen);
if (pLen < 3072 || qLen < 320) {
result = false;
}
} catch (exception &e) {
result = false;
}
#endif
return result;
}
bool
Test_GenerateGroupParams()
{
uint32_t pLen = 1024, qLen = 256, count;
IntegerGroupParams group;
for (count = 0; count < 1; count++) {
try {
group = deriveIntegerGroupParams(calculateSeed(GetTestModulus(), "test", ZEROCOIN_DEFAULT_SECURITYLEVEL, "TEST GROUP"), pLen, qLen);
} catch (std::runtime_error e) {
cout << "Caught exception " << e.what() << endl;
return false;
}
// Now perform some simple tests on the resulting parameters
if ((uint32_t)group.groupOrder.bitSize() < qLen || (uint32_t)group.modulus.bitSize() < pLen) {
return false;
}
CBigNum c = group.g.pow_mod(group.groupOrder, group.modulus);
//cout << "g^q mod p = " << c << endl;
if (!(c.isOne())) return false;
// Try at multiple parameter sizes
pLen = pLen * 1.5;
qLen = qLen * 1.5;
}
return true;
}
bool
Test_ParamGen()
{
bool result = true;
try {
// Instantiating testParams runs the parameter generation code
ZerocoinParams testParams(GetTestModulus(),ZEROCOIN_DEFAULT_SECURITYLEVEL);
} catch (runtime_error e) {
cout << e.what() << endl;
result = false;
}
return result;
}
bool
Test_Accumulator()
{
// This test assumes a list of coins were generated during
// the Test_MintCoin() test.
if (gCoins[0] == NULL) {
return false;
}
try {
// Accumulate the coin list from first to last into one accumulator
Accumulator accOne(&g_Params->accumulatorParams, CoinDenomination::ZQ_ONE);
Accumulator accTwo(&g_Params->accumulatorParams,CoinDenomination::ZQ_ONE);
Accumulator accThree(&g_Params->accumulatorParams,CoinDenomination::ZQ_ONE);
Accumulator accFour(&g_Params->accumulatorParams,CoinDenomination::ZQ_ONE);
AccumulatorWitness wThree(g_Params, accThree, gCoins[0]->getPublicCoin());
for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) {
accOne += gCoins[i]->getPublicCoin();
accTwo += gCoins[TESTS_COINS_TO_ACCUMULATE - (i+1)]->getPublicCoin();
accThree += gCoins[i]->getPublicCoin();
wThree += gCoins[i]->getPublicCoin();
if(i != 0) {
accFour += gCoins[i]->getPublicCoin();
}
}
// Compare the accumulated results
if (accOne.getValue() != accTwo.getValue() || accOne.getValue() != accThree.getValue()) {
cout << "Accumulators don't match" << endl;
return false;
}
if(accFour.getValue() != wThree.getValue()) {
cout << "Witness math not working," << endl;
return false;
}
// Verify that the witness is correct
if (!wThree.VerifyWitness(accThree, gCoins[0]->getPublicCoin()) ) {
cout << "Witness not valid" << endl;
return false;
}
// Serialization test: see if we can serialize the accumulator
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << accOne;
// Deserialize it into a new object
Accumulator newAcc(g_Params, ss);
// Compare the results
if (accOne.getValue() != newAcc.getValue()) {
return false;
}
} catch (runtime_error e) {
return false;
}
return true;
}
bool
Test_EqualityPoK()
{
// Run this test 10 times
for (uint32_t i = 0; i < 10; i++) {
try {
// Generate a random integer "val"
CBigNum val = CBigNum::randBignum(g_Params->coinCommitmentGroup.groupOrder);
// Manufacture two commitments to "val", both
// under different sets of parameters
Commitment one(&g_Params->accumulatorParams.accumulatorPoKCommitmentGroup, val);
Commitment two(&g_Params->serialNumberSoKCommitmentGroup, val);
// Now generate a proof of knowledge that "one" and "two" are
// both commitments to the same value
CommitmentProofOfKnowledge pok(&g_Params->accumulatorParams.accumulatorPoKCommitmentGroup,
&g_Params->serialNumberSoKCommitmentGroup,
one, two);
// Serialize the proof into a stream
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << pok;
// Deserialize back into a PoK object
CommitmentProofOfKnowledge newPok(&g_Params->accumulatorParams.accumulatorPoKCommitmentGroup,
&g_Params->serialNumberSoKCommitmentGroup,
ss);
if (newPok.Verify(one.getCommitmentValue(), two.getCommitmentValue()) != true) {
return false;
}
// Just for fun, deserialize the proof a second time
CDataStream ss2(SER_NETWORK, PROTOCOL_VERSION);
ss2 << pok;
// This time tamper with it, then deserialize it back into a PoK
ss2[15] = 0;
CommitmentProofOfKnowledge newPok2(&g_Params->accumulatorParams.accumulatorPoKCommitmentGroup,
&g_Params->serialNumberSoKCommitmentGroup,
ss2);
// If the tampered proof verifies, that's a failure!
if (newPok2.Verify(one.getCommitmentValue(), two.getCommitmentValue()) == true) {
return false;
}
} catch (runtime_error &e) {
return false;
}
}
return true;
}
bool
Test_MintCoin()
{
gCoinSize = 0;
try {
// Generate a list of coins
for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) {
gCoins[i] = new PrivateCoin(g_Params,libzerocoin::CoinDenomination::ZQ_ONE);
PublicCoin pc = gCoins[i]->getPublicCoin();
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << pc;
gCoinSize += ss.size();
}
gCoinSize /= TESTS_COINS_TO_ACCUMULATE;
} catch (exception &e) {
return false;
}
return true;
}
bool Test_InvalidCoin()
{
CBigNum coinValue;
try {
// Pick a random non-prime CBigNum
for (uint32_t i = 0; i < NON_PRIME_TESTS; i++) {
coinValue = CBigNum::randBignum(g_Params->coinCommitmentGroup.modulus);
coinValue = coinValue * 2;
if (!coinValue.isPrime()) break;
}
PublicCoin pubCoin(g_Params);
if (pubCoin.validate()) {
// A blank coin should not be valid!
return false;
}
PublicCoin pubCoin2(g_Params, coinValue, ZQ_ONE);
if (pubCoin2.validate()) {
// A non-prime coin should not be valid!
return false;
}
PublicCoin pubCoin3 = pubCoin2;
if (pubCoin2.validate()) {
// A copy of a non-prime coin should not be valid!
return false;
}
// Serialize and deserialize the coin
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << pubCoin;
PublicCoin pubCoin4(g_Params, ss);
if (pubCoin4.validate()) {
// A deserialized copy of a non-prime coin should not be valid!
return false;
}
} catch (runtime_error &e) {
cout << "Caught exception: " << e.what() << endl;
return false;
}
return true;
}
bool
Test_MintAndSpend()
{
try {
// This test assumes a list of coins were generated in Test_MintCoin()
if (gCoins[0] == NULL)
{
// No coins: mint some.
Test_MintCoin();
if (gCoins[0] == NULL) {
return false;
}
}
// Accumulate the list of generated coins into a fresh accumulator.
// The first one gets marked as accumulated for a witness, the
// others just get accumulated normally.
Accumulator acc(&g_Params->accumulatorParams,CoinDenomination::ZQ_ONE);
AccumulatorWitness wAcc(g_Params, acc, gCoins[0]->getPublicCoin());
for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) {
acc += gCoins[i]->getPublicCoin();
wAcc +=gCoins[i]->getPublicCoin();
}
// Now spend the coin
//SpendMetaData m(1,1);
CDataStream cc(SER_NETWORK, PROTOCOL_VERSION);
cc << *gCoins[0];
PrivateCoin myCoin(g_Params,cc);
CoinSpend spend(g_Params, g_Params, myCoin, acc, 0, wAcc, 0, SpendType::SPEND);
spend.Verify(acc);
// Serialize the proof and deserialize into newSpend
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << spend;
gProofSize = ss.size();
CoinSpend newSpend(g_Params, g_Params, ss);
// See if we can verify the deserialized proof (return our result)
bool ret = newSpend.Verify(acc);
// Extract the serial number
CBigNum serialNumber = newSpend.getCoinSerialNumber();
gSerialNumberSize = ceil((double)serialNumber.bitSize() / 8.0);
return ret;
} catch (runtime_error &e) {
cout << e.what() << endl;
return false;
}
return false;
}
void
Test_RunAllTests()
{
// Make a new set of parameters from a random RSA modulus
g_Params = new ZerocoinParams(GetTestModulus());
gNumTests = gSuccessfulTests = gProofSize = 0;
for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) {
gCoins[i] = NULL;
}
// Run through all of the Zerocoin tests
LogTestResult("an RSA modulus can be generated", Test_GenRSAModulus);
LogTestResult("parameter sizes are correct", Test_CalcParamSizes);
LogTestResult("group/field parameters can be generated", Test_GenerateGroupParams);
LogTestResult("parameter generation is correct", Test_ParamGen);
LogTestResult("coins can be minted", Test_MintCoin);
LogTestResult("invalid coins will be rejected", Test_InvalidCoin);
LogTestResult("the accumulator works", Test_Accumulator);
LogTestResult("the commitment equality PoK works", Test_EqualityPoK);
LogTestResult("a minted coin can be spent", Test_MintAndSpend);
cout << endl << "Average coin size is " << gCoinSize << " bytes." << endl;
cout << "Serial number size is " << gSerialNumberSize << " bytes." << endl;
cout << "Spend proof size is " << gProofSize << " bytes." << endl;
// Summarize test results
if (gSuccessfulTests < gNumTests) {
cout << endl << "ERROR: SOME TESTS FAILED" << endl;
}
// Clear any generated coins
for (uint32_t i = 0; i < TESTS_COINS_TO_ACCUMULATE; i++) {
delete gCoins[i];
}
cout << endl << gSuccessfulTests << " out of " << gNumTests << " tests passed." << endl << endl;
delete g_Params;
}
BOOST_AUTO_TEST_SUITE(libzerocoin)
BOOST_AUTO_TEST_CASE(libzerocoin_tests)
{
cout << "libzerocoin v" << ZEROCOIN_VERSION_STRING << " test utility." << endl << endl;
Test_RunAllTests();
}
BOOST_AUTO_TEST_SUITE_END()
|
#include "stdafx.h"
#include <tc.common/byte_buffer.hpp>
TEST( byte_buffer , ctor_other_block_type ) {
tc::buffer::byte_buffer<tc::buffer::simple_block> block(24);
int val = 1000;
ASSERT_EQ(block.write(&val, sizeof(int)), sizeof(int));
ASSERT_EQ(block.length(), sizeof(int));
tc::buffer::byte_buffer<tc::buffer::rc_block> block2(block);
ASSERT_EQ(block2.length(), sizeof(int));
int val2 = 0;
ASSERT_EQ(block2.read(&val2, sizeof(int)), sizeof(int));
ASSERT_EQ(val, val2);
}
TEST(byte_buffer, rc_block_refs) {
tc::buffer::byte_buffer< tc::buffer::rc_block > buffer(24);
tc::buffer::byte_buffer< tc::buffer::rc_block > buffer2(buffer);
ASSERT_EQ(buffer.rd_ptr(), buffer2.rd_ptr());
buffer2.reserve(buffer2.capacity());
ASSERT_NE(buffer.rd_ptr(), buffer2.rd_ptr());
}
TEST(byte_buffer, external) {
char buf1[128];
char buf2[128];
tc::buffer::byte_buffer< tc::buffer::external_block > buffer1((u8*)buf1, 128);
tc::buffer::byte_buffer< tc::buffer::external_block > buffer2((u8*)buf2, 128);
for (int i = 0; i < 128; ++i) {
buffer1.write(&i, sizeof(char));
}
memcpy(buffer2.wr_ptr(), buffer1.rd_ptr(), buffer1.length());
buffer2.wr_ptr(buffer1.length());
ASSERT_EQ(buffer1.length(), buffer2.length());
ASSERT_EQ(buffer1.length(), 128);
ASSERT_EQ(0, std::memcmp(buf1, buf2, 128));
}
TEST(byte_buffer, fit) {
tc::buffer::byte_buffer< tc::buffer::rc_block > buffer1(256);
for (int i = 0; i < 128; ++i) {
buffer1.write(&i, sizeof(char));
}
for (int i = 0; i < 128; ++i) {
char val;
buffer1.read(&val, sizeof(char));
ASSERT_EQ(val, (char)i);
ASSERT_EQ(buffer1.space(), 256 - (128 - i));
buffer1.fit();
}
}
|
//
// TreeLevelOrderTraversal.cpp
// HackerRank
//
// Created by Fabrizio Duroni on 14/12/2016.
//
// https://www.hackerrank.com/challenges/tree-level-order-traversal
#include <queue>
#include <iostream>
using namespace std;
struct node {
int data;
node* left;
node* right;
};
/*
Breadth first search visit method.
@param root the current root level of the tree.
*/
void LevelOrder(node * root) {
queue<node*> q;
q.push(root);
node* currentNode;
while (!q.empty()) {
currentNode = q.front();
q.pop();
cout << currentNode->data << " ";
if (currentNode->left) {
q.push(currentNode->left);
}
if (currentNode->right) {
q.push(currentNode->right);
}
}
}
|
// The MIT License (MIT)
// Copyright (c) 2013 lailongwei<lailongwei@126.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "core/file/TestCase_Core_File_Directory.h"
int TestCase_Core_File_Directory::Run(int argc, char *argv[])
{
std::cout <<"core/file/Directory test:" <<std::endl;
bool allTested = false;
do
{
if (CurDirTest() != LLBC_OK)
break;
if (ExistsTest() != LLBC_OK)
break;
if (CreateRemoveTest() != LLBC_OK)
break;
if (AbsPathTest() != LLBC_OK)
break;
if (JoinTest() != LLBC_OK)
break;
if (SplitExtTest() != LLBC_OK)
break;
if (GetFilesTest() != LLBC_OK)
break;
if (GetDirectoriesTest() != LLBC_OK)
break;
if (ModuleFileTest() != LLBC_OK)
break;
if (DirNameBaseNameTest() != LLBC_OK)
break;
if (MiscTest() != LLBC_OK)
break;
allTested = true;
} while(0);
std::cout <<"All test done, press any key to exit..." <<std::endl;
getchar();
return allTested ? LLBC_OK : LLBC_FAILED;
}
int TestCase_Core_File_Directory::CurDirTest()
{
LLBC_PrintLine("CurDir/SetCurDir test:");
#if LLBC_TARGET_PLATFORM_WIN32
const LLBC_String toPath = "C:\\";
#else
const LLBC_String toPath = "/";
#endif
const LLBC_String curDir = LLBC_Directory::CurDir();
LLBC_PrintLine("Current directory: %s", curDir.c_str());
LLBC_PrintLine("Set current directory To <%s>: ", toPath.c_str());
if (LLBC_Directory::SetCurDir(toPath) != LLBC_OK)
{
LLBC_PrintLine("Set current directory to <%s> failed, error: %s", toPath.c_str(), LLBC_FormatLastError());
return LLBC_FAILED;
}
LLBC_PrintLine("After set, current directory: %s", LLBC_Directory::CurDir().c_str());
LLBC_Directory::SetCurDir(curDir);
LLBC_PrintLine("");
return LLBC_OK;
}
int TestCase_Core_File_Directory::ExistsTest()
{
LLBC_PrintLine("Exists test:");
LLBC_String path = ".";
LLBC_PrintLine("%s exists? %d", path.c_str(), LLBC_Directory::Exists(path));
path = "~~~~~~~~";
LLBC_PrintLine("%s exists? %d", path.c_str(), LLBC_Directory::Exists(path));
path = LLBC_Directory::ModuleFileName();
LLBC_PrintLine("%s exists? %d", path.c_str(), LLBC_Directory::Exists(path));
LLBC_PrintLine("");
return LLBC_OK;
}
int TestCase_Core_File_Directory::CreateRemoveTest()
{
LLBC_PrintLine("Create/Remove test:");
LLBC_PrintLine("Create directory: a");
if (LLBC_Directory::Create("a") != LLBC_OK)
{
LLBC_PrintLine("Create directory a failed, error: %s", LLBC_FormatLastError());
return LLBC_FAILED;
}
for (int i = 0; i < 10; ++i)
{
const LLBC_String path = LLBC_String().format("a/b_%d", i);
LLBC_PrintLine("Create directory: %s", path.c_str());
if (LLBC_Directory::Create(path) != LLBC_OK)
{
LLBC_PrintLine("Create directory %s failed, error: %s", path.c_str(), LLBC_FormatLastError());
return LLBC_FAILED;
}
}
LLBC_PrintLine("Remove directory: a");
if (LLBC_Directory::Remove("a") != LLBC_OK)
{
LLBC_PrintLine("Remove directory a failed, error: %s", LLBC_FormatLastError());
return LLBC_FAILED;
}
// Complex path create/remove test.
const LLBC_String complexPath = "a/b/c__d/d/add";
LLBC_PrintLine("Create directory: %s", complexPath.c_str());
if (LLBC_Directory::Create(complexPath) != LLBC_OK)
{
LLBC_PrintLine("Create directory %s faiiled, error: %s", complexPath.c_str(), LLBC_FormatLastError());
return LLBC_FAILED;
}
LLBC_PrintLine("Remove directory: %s", complexPath.c_str());
if (LLBC_Directory::Remove(complexPath) != LLBC_OK)
{
LLBC_PrintLine("Remove directory %s failed, error: %s", complexPath.c_str(), LLBC_FormatLastError());
return LLBC_FAILED;
}
LLBC_PrintLine("");
return LLBC_OK;
}
int TestCase_Core_File_Directory::AbsPathTest()
{
LLBC_PrintLine("AbsPath test:");
LLBC_String path = "";
LLBC_PrintLine("%s abspath: %s", path.c_str(), LLBC_Directory::AbsPath(path).c_str());
path = ".";
LLBC_PrintLine("%s abspath: %s", path.c_str(), LLBC_Directory::AbsPath(path).c_str());
path = "/";
LLBC_PrintLine("%s abspath: %s", path.c_str(), LLBC_Directory::AbsPath(path).c_str());
#if LLBC_TARGET_PLATFORM_WIN32
path = "a/b\\c/..\\";
#else
path = "a/b/c/../";
#endif
LLBC_PrintLine("%s abspath: %s", path.c_str(), LLBC_Directory::AbsPath(path).c_str());
#if LLBC_TARGET_PLATFORM_WIN32
path = "c:\\";
LLBC_PrintLine("%s abspath: %s", path.c_str(), LLBC_Directory::AbsPath(path).c_str());
path = "c:\\windows\\.\\.\\..\\windows/././";
LLBC_PrintLine("%s abspath: %s", path.c_str(), LLBC_Directory::AbsPath(path).c_str());
#endif
LLBC_PrintLine("");
return LLBC_OK;
}
int TestCase_Core_File_Directory::JoinTest()
{
LLBC_PrintLine("Join test:");
LLBC_Strings parts;
parts.push_back("a"), parts.push_back("b"), parts.push_back("c"), JoinTest(parts);
parts.clear(), parts.push_back("a/"), parts.push_back("b"), JoinTest(parts);
parts.clear(), parts.push_back("a"), parts.push_back("/b"), JoinTest(parts);
parts.clear(), parts.push_back("a/"), parts.push_back("/b/"), JoinTest(parts);
#if LLBC_TARGET_PLATFORM_WIN32
parts.clear(), parts.push_back("c:\\"), parts.push_back("/b"), JoinTest(parts);
#endif
return LLBC_OK;
}
int TestCase_Core_File_Directory::SplitExtTest()
{
LLBC_PrintLine("SplitExt test:");
LLBC_String path("a/b");
LLBC_Strings parts = LLBC_Directory::SplitExt(path);
LLBC_PrintLine("Split %s: part1: [%s], part2: [%s]", path.c_str(), parts[0].c_str(), parts[1].c_str());
path = ("a.exe/b");
parts = LLBC_Directory::SplitExt(path);
LLBC_PrintLine("Split %s: part1: [%s], part2: [%s]", path.c_str(), parts[0].c_str(), parts[1].c_str());
path = ("a.exe/b.exe");
parts = LLBC_Directory::SplitExt(path);
LLBC_PrintLine("Split %s: part1: [%s], part2: [%s]", path.c_str(), parts[0].c_str(), parts[1].c_str());
path = ("a.exe/b.exe.bk");
parts = LLBC_Directory::SplitExt(path);
LLBC_PrintLine("Split %s: part1: [%s], part2: [%s]", path.c_str(), parts[0].c_str(), parts[1].c_str());
LLBC_PrintLine("");
return LLBC_OK;
}
int TestCase_Core_File_Directory::GetFilesTest()
{
LLBC_PrintLine("GetFiles test:");
LLBC_PrintLine("Create some directories and files for test:");
LLBC_Directory::Create("a/b");
LLBC_Directory::Create("a/c");
LLBC_Directory::Create("a/d");
LLBC_File::TouchFile("a/z");
LLBC_File::TouchFile("a/b/bb");
LLBC_File::TouchFile("a/c/cc");
LLBC_File::TouchFile("a/d/dd");
LLBC_Directory::Create("a/b/zz");
LLBC_PrintLine("Get files from directory a(recursive = false)");
if (GetFilesTest("a", false) != LLBC_OK)
{
LLBC_Directory::Remove("a");
return LLBC_FAILED;
}
LLBC_PrintLine("Get files from directory a(recursive = true)");
if (GetFilesTest("a", true) != LLBC_OK)
{
LLBC_Directory::Remove("a");
return LLBC_FAILED;
}
LLBC_Directory::Remove("a");
LLBC_PrintLine("");
return LLBC_OK;
}
int TestCase_Core_File_Directory::GetDirectoriesTest()
{
LLBC_PrintLine("GetDirectories test:");
LLBC_PrintLine("Create some directories and files for test:");
LLBC_Directory::Create("a/b");
LLBC_Directory::Create("a/c");
LLBC_Directory::Create("a/d");
LLBC_File::TouchFile("a/z");
LLBC_File::TouchFile("a/b/bb");
LLBC_File::TouchFile("a/c/cc");
LLBC_File::TouchFile("a/d/dd");
LLBC_Directory::Create("a/b/zz");
LLBC_PrintLine("Get directories from directory a(recursive = false)");
if (GetDirectoriesTest("a", false) != LLBC_OK)
{
LLBC_Directory::Remove("a");
return LLBC_FAILED;
}
LLBC_PrintLine("Get directories from directory a(recursive = true)");
if (GetDirectoriesTest("a", true) != LLBC_OK)
{
LLBC_Directory::Remove("a");
return LLBC_FAILED;
}
LLBC_Directory::Remove("a");
LLBC_PrintLine("");
return LLBC_OK;
return LLBC_OK;
}
int TestCase_Core_File_Directory::ModuleFileTest()
{
LLBC_PrintLine("ModuleFile test:");
LLBC_PrintLine("Module file name: %s", LLBC_Directory::ModuleFileName().c_str());
LLBC_PrintLine("Module file directory: %s", LLBC_Directory::ModuleFileDir().c_str());
LLBC_PrintLine("");
return LLBC_OK;
}
int TestCase_Core_File_Directory::DirNameBaseNameTest()
{
LLBC_PrintLine("DirName/BaseName test:");
LLBC_String path = "a/b";
LLBC_PrintLine("path %s dirName: %s, baseName: %s",
path.c_str(), LLBC_Directory::DirName(path).c_str(), LLBC_Directory::BaseName(path).c_str());
path = "/a/b.exe";
LLBC_PrintLine("path %s dirName: %s, baseName: %s",
path.c_str(), LLBC_Directory::DirName(path).c_str(), LLBC_Directory::BaseName(path).c_str());
path = "a/b.exe/";
LLBC_PrintLine("path %s dirName: %s, baseName: %s",
path.c_str(), LLBC_Directory::DirName(path).c_str(), LLBC_Directory::BaseName(path).c_str());
LLBC_PrintLine("");
return LLBC_OK;
}
int TestCase_Core_File_Directory::MiscTest()
{
LLBC_PrintLine("Misc test:");
LLBC_PrintLine("Document directory: %s", LLBC_Directory::DocDir().c_str());
LLBC_PrintLine("Home directory: %s", LLBC_Directory::HomeDir().c_str());
LLBC_PrintLine("Temporary directory: %s", LLBC_Directory::TempDir().c_str());
LLBC_PrintLine("Cache directory: %s", LLBC_Directory::CacheDir().c_str());
LLBC_PrintLine("");
return LLBC_OK;
}
int TestCase_Core_File_Directory::JoinTest(const LLBC_Strings &pathParts)
{
LLBC_Print("Join [");
for (size_t i = 0; i < pathParts.size(); ++i)
{
LLBC_Print("%s", pathParts[i].c_str());
if (i != pathParts.size() - 1)
LLBC_Print(", ");
}
LLBC_Print("], ");
const LLBC_String &joined = LLBC_Directory::Join(pathParts);
LLBC_PrintLine("Done, Result: %s", joined.c_str());
return LLBC_OK;
}
int TestCase_Core_File_Directory::GetFilesTest(const LLBC_String &path, bool recursive)
{
LLBC_PrintLine("Get files from directory: %s, recursive: %d", path.c_str(), recursive);
LLBC_Strings files;
if (LLBC_Directory::GetFiles(path, files, recursive) != LLBC_OK)
{
LLBC_PrintLine("Failed, error: %s", LLBC_FormatLastError());
return LLBC_FAILED;
}
LLBC_Print("Directory %s files(count: %ld): ", path.c_str(), files.size());
for (size_t i = 0; i < files.size(); ++i)
{
LLBC_Print("%s", files[i].c_str());
if (i != files.size() - 1)
LLBC_Print(", ");
}
LLBC_PrintLine("");
return LLBC_OK;
}
int TestCase_Core_File_Directory::GetDirectoriesTest(const LLBC_String &path, bool recursive)
{
LLBC_PrintLine("Get directories from directory: %s, recursive: %d", path.c_str(), recursive);
LLBC_Strings directories;
if (LLBC_Directory::GetDirectories(path, directories, recursive) != LLBC_OK)
{
LLBC_PrintLine("Failed, error: %s", LLBC_FormatLastError());
return LLBC_FAILED;
}
LLBC_Print("Directory %s subdirectories(count: %ld): ", path.c_str(), directories.size());
for (size_t i = 0; i < directories.size(); ++i)
{
LLBC_Print("%s", directories[i].c_str());
if (i != directories.size() - 1)
LLBC_Print(", ");
}
LLBC_PrintLine("");
return LLBC_OK;
}
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtWidgets module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qglobal.h>
#include "qstylesheetstyle_p.h"
#if QT_CONFIG(style_stylesheet)
#include "private/qcssutil_p.h"
#include <qdebug.h>
#include <qapplication.h>
#if QT_CONFIG(menu)
#include <qmenu.h>
#endif
#if QT_CONFIG(menubar)
#include <qmenubar.h>
#endif
#include <qpainter.h>
#include <qstyleoption.h>
#if QT_CONFIG(lineedit)
#include <qlineedit.h>
#endif
#include <private/qwindowsstyle_p.h>
#if QT_CONFIG(combobox)
#include <qcombobox.h>
#endif
#include "private/qcssparser_p.h"
#include "private/qmath_p.h"
#include <qabstractscrollarea.h>
#include "private/qabstractscrollarea_p.h"
#include <qtooltip.h>
#include <qshareddata.h>
#if QT_CONFIG(toolbutton)
#include <qtoolbutton.h>
#endif
#if QT_CONFIG(scrollbar)
#include <qscrollbar.h>
#endif
#if QT_CONFIG(abstractslider)
#include <qabstractslider.h>
#endif
#include <qstring.h>
#include <qfile.h>
#if QT_CONFIG(checkbox)
#include <qcheckbox.h>
#endif
#if QT_CONFIG(itemviews)
#include <qheaderview.h>
#endif
#include <private/qwindowsstyle_p_p.h>
#include <private/qstyleanimation_p.h>
#if QT_CONFIG(tabbar)
#include <qtabbar.h>
#endif
#include <QMetaProperty>
#if QT_CONFIG(mainwindow)
#include <qmainwindow.h>
#endif
#if QT_CONFIG(dockwidget)
#include <qdockwidget.h>
#endif
#if QT_CONFIG(mdiarea)
#include <qmdisubwindow.h>
#endif
#if QT_CONFIG(dialog)
#include <qdialog.h>
#endif
#include <private/qwidget_p.h>
#if QT_CONFIG(spinbox)
#include <QAbstractSpinBox>
#endif
#if QT_CONFIG(label)
#include <QLabel>
#endif
#include "qdrawutil.h"
#include <limits.h>
#include <QtWidgets/qtoolbar.h>
QT_BEGIN_NAMESPACE
using namespace QCss;
class QStyleSheetStylePrivate : public QWindowsStylePrivate
{
Q_DECLARE_PUBLIC(QStyleSheetStyle)
public:
QStyleSheetStylePrivate() { }
};
static QStyleSheetStyleCaches *styleSheetCaches = 0;
/* RECURSION_GUARD:
* the QStyleSheetStyle is a proxy. If used with others proxy style, we may end up with something like:
* QStyleSheetStyle -> ProxyStyle -> QStyleSheetStyle -> OriginalStyle
* Recursion may happen if the style call the widget()->style() again.
* Not to mention the performence penalty of having two lookup of rules.
*
* The first instance of QStyleSheetStyle will set globalStyleSheetStyle to itself. The second one
* will notice the globalStyleSheetStyle is not istelf and call its base style directly.
*/
static const QStyleSheetStyle *globalStyleSheetStyle = 0;
class QStyleSheetStyleRecursionGuard
{
public:
QStyleSheetStyleRecursionGuard(const QStyleSheetStyle *that)
: guarded(globalStyleSheetStyle == 0)
{
if (guarded) globalStyleSheetStyle = that;
}
~QStyleSheetStyleRecursionGuard() { if (guarded) globalStyleSheetStyle = 0; }
bool guarded;
};
#define RECURSION_GUARD(RETURN) \
if (globalStyleSheetStyle != 0 && globalStyleSheetStyle != this) { RETURN; } \
QStyleSheetStyleRecursionGuard recursion_guard(this);
#define ceil(x) ((int)(x) + ((x) > 0 && (x) != (int)(x)))
enum PseudoElement {
PseudoElement_None,
PseudoElement_DownArrow,
PseudoElement_UpArrow,
PseudoElement_LeftArrow,
PseudoElement_RightArrow,
PseudoElement_Indicator,
PseudoElement_ExclusiveIndicator,
PseudoElement_PushButtonMenuIndicator,
PseudoElement_ComboBoxDropDown,
PseudoElement_ComboBoxArrow,
PseudoElement_Item,
PseudoElement_SpinBoxUpButton,
PseudoElement_SpinBoxUpArrow,
PseudoElement_SpinBoxDownButton,
PseudoElement_SpinBoxDownArrow,
PseudoElement_GroupBoxTitle,
PseudoElement_GroupBoxIndicator,
PseudoElement_ToolButtonMenu,
PseudoElement_ToolButtonMenuArrow,
PseudoElement_ToolButtonDownArrow,
PseudoElement_ToolBoxTab,
PseudoElement_ScrollBarSlider,
PseudoElement_ScrollBarAddPage,
PseudoElement_ScrollBarSubPage,
PseudoElement_ScrollBarAddLine,
PseudoElement_ScrollBarSubLine,
PseudoElement_ScrollBarFirst,
PseudoElement_ScrollBarLast,
PseudoElement_ScrollBarUpArrow,
PseudoElement_ScrollBarDownArrow,
PseudoElement_ScrollBarLeftArrow,
PseudoElement_ScrollBarRightArrow,
PseudoElement_SplitterHandle,
PseudoElement_ToolBarHandle,
PseudoElement_ToolBarSeparator,
PseudoElement_MenuScroller,
PseudoElement_MenuTearoff,
PseudoElement_MenuCheckMark,
PseudoElement_MenuSeparator,
PseudoElement_MenuIcon,
PseudoElement_MenuRightArrow,
PseudoElement_TreeViewBranch,
PseudoElement_HeaderViewSection,
PseudoElement_HeaderViewUpArrow,
PseudoElement_HeaderViewDownArrow,
PseudoElement_ProgressBarChunk,
PseudoElement_TabBarTab,
PseudoElement_TabBarScroller,
PseudoElement_TabBarTear,
PseudoElement_SliderGroove,
PseudoElement_SliderHandle,
PseudoElement_SliderAddPage,
PseudoElement_SliderSubPage,
PseudoElement_SliderTickmark,
PseudoElement_TabWidgetPane,
PseudoElement_TabWidgetTabBar,
PseudoElement_TabWidgetLeftCorner,
PseudoElement_TabWidgetRightCorner,
PseudoElement_DockWidgetTitle,
PseudoElement_DockWidgetCloseButton,
PseudoElement_DockWidgetFloatButton,
PseudoElement_DockWidgetSeparator,
PseudoElement_MdiCloseButton,
PseudoElement_MdiMinButton,
PseudoElement_MdiNormalButton,
PseudoElement_TitleBar,
PseudoElement_TitleBarCloseButton,
PseudoElement_TitleBarMinButton,
PseudoElement_TitleBarMaxButton,
PseudoElement_TitleBarShadeButton,
PseudoElement_TitleBarUnshadeButton,
PseudoElement_TitleBarNormalButton,
PseudoElement_TitleBarContextHelpButton,
PseudoElement_TitleBarSysMenu,
PseudoElement_ViewItem,
PseudoElement_ViewItemIcon,
PseudoElement_ViewItemText,
PseudoElement_ViewItemIndicator,
PseudoElement_ScrollAreaCorner,
PseudoElement_TabBarTabCloseButton,
NumPseudoElements
};
struct PseudoElementInfo {
QStyle::SubControl subControl;
const char name[19];
};
static const PseudoElementInfo knownPseudoElements[NumPseudoElements] = {
{ QStyle::SC_None, "" },
{ QStyle::SC_None, "down-arrow" },
{ QStyle::SC_None, "up-arrow" },
{ QStyle::SC_None, "left-arrow" },
{ QStyle::SC_None, "right-arrow" },
{ QStyle::SC_None, "indicator" },
{ QStyle::SC_None, "indicator" },
{ QStyle::SC_None, "menu-indicator" },
{ QStyle::SC_ComboBoxArrow, "drop-down" },
{ QStyle::SC_ComboBoxArrow, "down-arrow" },
{ QStyle::SC_None, "item" },
{ QStyle::SC_SpinBoxUp, "up-button" },
{ QStyle::SC_SpinBoxUp, "up-arrow" },
{ QStyle::SC_SpinBoxDown, "down-button" },
{ QStyle::SC_SpinBoxDown, "down-arrow" },
{ QStyle::SC_GroupBoxLabel, "title" },
{ QStyle::SC_GroupBoxCheckBox, "indicator" },
{ QStyle::SC_ToolButtonMenu, "menu-button" },
{ QStyle::SC_ToolButtonMenu, "menu-arrow" },
{ QStyle::SC_None, "menu-indicator" },
{ QStyle::SC_None, "tab" },
{ QStyle::SC_ScrollBarSlider, "handle" },
{ QStyle::SC_ScrollBarAddPage, "add-page" },
{ QStyle::SC_ScrollBarSubPage, "sub-page" },
{ QStyle::SC_ScrollBarAddLine, "add-line" },
{ QStyle::SC_ScrollBarSubLine, "sub-line" },
{ QStyle::SC_ScrollBarFirst, "first" },
{ QStyle::SC_ScrollBarLast, "last" },
{ QStyle::SC_ScrollBarSubLine, "up-arrow" },
{ QStyle::SC_ScrollBarAddLine, "down-arrow" },
{ QStyle::SC_ScrollBarSubLine, "left-arrow" },
{ QStyle::SC_ScrollBarAddLine, "right-arrow" },
{ QStyle::SC_None, "handle" },
{ QStyle::SC_None, "handle" },
{ QStyle::SC_None, "separator" },
{ QStyle::SC_None, "scroller" },
{ QStyle::SC_None, "tearoff" },
{ QStyle::SC_None, "indicator" },
{ QStyle::SC_None, "separator" },
{ QStyle::SC_None, "icon" },
{ QStyle::SC_None, "right-arrow" },
{ QStyle::SC_None, "branch" },
{ QStyle::SC_None, "section" },
{ QStyle::SC_None, "down-arrow" },
{ QStyle::SC_None, "up-arrow" },
{ QStyle::SC_None, "chunk" },
{ QStyle::SC_None, "tab" },
{ QStyle::SC_None, "scroller" },
{ QStyle::SC_None, "tear" },
{ QStyle::SC_SliderGroove, "groove" },
{ QStyle::SC_SliderHandle, "handle" },
{ QStyle::SC_None, "add-page" },
{ QStyle::SC_None, "sub-page"},
{ QStyle::SC_SliderTickmarks, "tick-mark" },
{ QStyle::SC_None, "pane" },
{ QStyle::SC_None, "tab-bar" },
{ QStyle::SC_None, "left-corner" },
{ QStyle::SC_None, "right-corner" },
{ QStyle::SC_None, "title" },
{ QStyle::SC_None, "close-button" },
{ QStyle::SC_None, "float-button" },
{ QStyle::SC_None, "separator" },
{ QStyle::SC_MdiCloseButton, "close-button" },
{ QStyle::SC_MdiMinButton, "minimize-button" },
{ QStyle::SC_MdiNormalButton, "normal-button" },
{ QStyle::SC_TitleBarLabel, "title" },
{ QStyle::SC_TitleBarCloseButton, "close-button" },
{ QStyle::SC_TitleBarMinButton, "minimize-button" },
{ QStyle::SC_TitleBarMaxButton, "maximize-button" },
{ QStyle::SC_TitleBarShadeButton, "shade-button" },
{ QStyle::SC_TitleBarUnshadeButton, "unshade-button" },
{ QStyle::SC_TitleBarNormalButton, "normal-button" },
{ QStyle::SC_TitleBarContextHelpButton, "contexthelp-button" },
{ QStyle::SC_TitleBarSysMenu, "sys-menu" },
{ QStyle::SC_None, "item" },
{ QStyle::SC_None, "icon" },
{ QStyle::SC_None, "text" },
{ QStyle::SC_None, "indicator" },
{ QStyle::SC_None, "corner" },
{ QStyle::SC_None, "close-button" },
};
struct QStyleSheetBorderImageData : public QSharedData
{
QStyleSheetBorderImageData()
: horizStretch(QCss::TileMode_Unknown), vertStretch(QCss::TileMode_Unknown)
{
for (int i = 0; i < 4; i++)
cuts[i] = -1;
}
int cuts[4];
QPixmap pixmap;
QImage image;
QCss::TileMode horizStretch, vertStretch;
};
struct QStyleSheetBackgroundData : public QSharedData
{
QStyleSheetBackgroundData(const QBrush& b, const QPixmap& p, QCss::Repeat r,
Qt::Alignment a, QCss::Origin o, Attachment t, QCss::Origin c)
: brush(b), pixmap(p), repeat(r), position(a), origin(o), attachment(t), clip(c) { }
bool isTransparent() const {
if (brush.style() != Qt::NoBrush)
return !brush.isOpaque();
return pixmap.isNull() ? false : pixmap.hasAlpha();
}
QBrush brush;
QPixmap pixmap;
QCss::Repeat repeat;
Qt::Alignment position;
QCss::Origin origin;
QCss::Attachment attachment;
QCss::Origin clip;
};
struct QStyleSheetBorderData : public QSharedData
{
QStyleSheetBorderData() : bi(0)
{
for (int i = 0; i < 4; i++) {
borders[i] = 0;
styles[i] = QCss::BorderStyle_None;
}
}
QStyleSheetBorderData(int *b, QBrush *c, QCss::BorderStyle *s, QSize *r) : bi(0)
{
for (int i = 0; i < 4; i++) {
borders[i] = b[i];
styles[i] = s[i];
colors[i] = c[i];
radii[i] = r[i];
}
}
int borders[4];
QBrush colors[4];
QCss::BorderStyle styles[4];
QSize radii[4]; // topleft, topright, bottomleft, bottomright
const QStyleSheetBorderImageData *borderImage() const
{ return bi; }
bool hasBorderImage() const { return bi!=0; }
QSharedDataPointer<QStyleSheetBorderImageData> bi;
bool isOpaque() const
{
for (int i = 0; i < 4; i++) {
if (styles[i] == QCss::BorderStyle_Native || styles[i] == QCss::BorderStyle_None)
continue;
if (styles[i] >= QCss::BorderStyle_Dotted && styles[i] <= QCss::BorderStyle_DotDotDash
&& styles[i] != BorderStyle_Solid)
return false;
if (!colors[i].isOpaque())
return false;
if (!radii[i].isEmpty())
return false;
}
if (bi != 0 && bi->pixmap.hasAlpha())
return false;
return true;
}
};
struct QStyleSheetOutlineData : public QStyleSheetBorderData
{
QStyleSheetOutlineData()
{
for (int i = 0; i < 4; i++) {
offsets[i] = 0;
}
}
QStyleSheetOutlineData(int *b, QBrush *c, QCss::BorderStyle *s, QSize *r, int *o)
: QStyleSheetBorderData(b, c, s, r)
{
for (int i = 0; i < 4; i++) {
offsets[i] = o[i];
}
}
int offsets[4];
};
struct QStyleSheetBoxData : public QSharedData
{
QStyleSheetBoxData(int *m, int *p, int s) : spacing(s)
{
for (int i = 0; i < 4; i++) {
margins[i] = m[i];
paddings[i] = p[i];
}
}
int margins[4];
int paddings[4];
int spacing;
};
struct QStyleSheetPaletteData : public QSharedData
{
QStyleSheetPaletteData(const QBrush &fg, const QBrush &sfg, const QBrush &sbg,
const QBrush &abg)
: foreground(fg), selectionForeground(sfg), selectionBackground(sbg),
alternateBackground(abg) { }
QBrush foreground;
QBrush selectionForeground;
QBrush selectionBackground;
QBrush alternateBackground;
};
struct QStyleSheetGeometryData : public QSharedData
{
QStyleSheetGeometryData(int w, int h, int minw, int minh, int maxw, int maxh)
: minWidth(minw), minHeight(minh), width(w), height(h), maxWidth(maxw), maxHeight(maxh) { }
int minWidth, minHeight, width, height, maxWidth, maxHeight;
};
struct QStyleSheetPositionData : public QSharedData
{
QStyleSheetPositionData(int l, int t, int r, int b, Origin o, Qt::Alignment p, QCss::PositionMode m, Qt::Alignment a = 0)
: left(l), top(t), bottom(b), right(r), origin(o), position(p), mode(m), textAlignment(a) { }
int left, top, bottom, right;
Origin origin;
Qt::Alignment position;
QCss::PositionMode mode;
Qt::Alignment textAlignment;
};
struct QStyleSheetImageData : public QSharedData
{
QStyleSheetImageData(const QIcon &i, Qt::Alignment a, const QSize &sz)
: icon(i), alignment(a), size(sz) { }
QIcon icon;
Qt::Alignment alignment;
QSize size;
};
class QRenderRule
{
public:
QRenderRule() : features(0), hasFont(false), pal(0), b(0), bg(0), bd(0), ou(0), geo(0), p(0), img(0), clipset(0) { }
QRenderRule(const QVector<QCss::Declaration> &, const QObject *);
QRect borderRect(const QRect &r) const;
QRect outlineRect(const QRect &r) const;
QRect paddingRect(const QRect &r) const;
QRect contentsRect(const QRect &r) const;
enum { Margin = 1, Border = 2, Padding = 4, All=Margin|Border|Padding };
QRect boxRect(const QRect &r, int flags = All) const;
QSize boxSize(const QSize &s, int flags = All) const;
QRect originRect(const QRect &rect, Origin origin) const;
QPainterPath borderClip(QRect rect);
void drawBorder(QPainter *, const QRect&);
void drawOutline(QPainter *, const QRect&);
void drawBorderImage(QPainter *, const QRect&);
void drawBackground(QPainter *, const QRect&, const QPoint& = QPoint(0, 0));
void drawBackgroundImage(QPainter *, const QRect&, QPoint = QPoint(0, 0));
void drawFrame(QPainter *, const QRect&);
void drawImage(QPainter *p, const QRect &rect);
void drawRule(QPainter *, const QRect&);
void configurePalette(QPalette *, QPalette::ColorGroup, const QWidget *, bool);
void configurePalette(QPalette *p, QPalette::ColorRole fr, QPalette::ColorRole br);
const QStyleSheetPaletteData *palette() const { return pal; }
const QStyleSheetBoxData *box() const { return b; }
const QStyleSheetBackgroundData *background() const { return bg; }
const QStyleSheetBorderData *border() const { return bd; }
const QStyleSheetOutlineData *outline() const { return ou; }
const QStyleSheetGeometryData *geometry() const { return geo; }
const QStyleSheetPositionData *position() const { return p; }
bool hasPalette() const { return pal != 0; }
bool hasBackground() const { return bg != 0 && (!bg->pixmap.isNull() || bg->brush.style() != Qt::NoBrush); }
bool hasGradientBackground() const { return bg && bg->brush.style() >= Qt::LinearGradientPattern
&& bg->brush.style() <= Qt::ConicalGradientPattern; }
bool hasNativeBorder() const {
return bd == 0
|| (!bd->hasBorderImage() && bd->styles[0] == BorderStyle_Native);
}
bool hasNativeOutline() const {
return (ou == 0
|| (!ou->hasBorderImage() && ou->styles[0] == BorderStyle_Native));
}
bool baseStyleCanDraw() const {
if (!hasBackground() || (background()->brush.style() == Qt::NoBrush && bg->pixmap.isNull()))
return true;
if (bg && !bg->pixmap.isNull())
return false;
if (hasGradientBackground())
return features & StyleFeature_BackgroundGradient;
return features & StyleFeature_BackgroundColor;
}
bool hasBox() const { return b != 0; }
bool hasBorder() const { return bd != 0; }
bool hasOutline() const { return ou != 0; }
bool hasPosition() const { return p != 0; }
bool hasGeometry() const { return geo != 0; }
bool hasDrawable() const { return !hasNativeBorder() || hasBackground() || hasImage(); }
bool hasImage() const { return img != 0; }
QSize minimumContentsSize() const
{ return geo ? QSize(geo->minWidth, geo->minHeight) : QSize(0, 0); }
QSize minimumSize() const
{ return boxSize(minimumContentsSize()); }
QSize contentsSize() const
{ return geo ? QSize(geo->width, geo->height)
: ((img && img->size.isValid()) ? img->size : QSize()); }
QSize contentsSize(const QSize &sz) const
{
QSize csz = contentsSize();
if (csz.width() == -1) csz.setWidth(sz.width());
if (csz.height() == -1) csz.setHeight(sz.height());
return csz;
}
bool hasContentsSize() const
{ return (geo && (geo->width != -1 || geo->height != -1)) || (img && img->size.isValid()); }
QSize size() const { return boxSize(contentsSize()); }
QSize size(const QSize &sz) const { return boxSize(contentsSize(sz)); }
QSize adjustSize(const QSize &sz)
{
if (!geo)
return sz;
QSize csz = contentsSize();
if (csz.width() == -1) csz.setWidth(sz.width());
if (csz.height() == -1) csz.setHeight(sz.height());
if (geo->maxWidth != -1 && csz.width() > geo->maxWidth) csz.setWidth(geo->maxWidth);
if (geo->maxHeight != -1 && csz.height() > geo->maxHeight) csz.setHeight(geo->maxHeight);
csz=csz.expandedTo(QSize(geo->minWidth, geo->minHeight));
return csz;
}
bool hasStyleHint(const QString &sh) const { return styleHints.contains(sh); }
QVariant styleHint(const QString &sh) const { return styleHints.value(sh); }
void fixupBorder(int);
// Shouldn't be here
void setClip(QPainter *p, const QRect &rect);
void unsetClip(QPainter *);
public:
int features;
QBrush defaultBackground;
QFont font;
bool hasFont;
QHash<QString, QVariant> styleHints;
QSharedDataPointer<QStyleSheetPaletteData> pal;
QSharedDataPointer<QStyleSheetBoxData> b;
QSharedDataPointer<QStyleSheetBackgroundData> bg;
QSharedDataPointer<QStyleSheetBorderData> bd;
QSharedDataPointer<QStyleSheetOutlineData> ou;
QSharedDataPointer<QStyleSheetGeometryData> geo;
QSharedDataPointer<QStyleSheetPositionData> p;
QSharedDataPointer<QStyleSheetImageData> img;
int clipset;
QPainterPath clipPath;
};
Q_DECLARE_TYPEINFO(QRenderRule, Q_MOVABLE_TYPE);
///////////////////////////////////////////////////////////////////////////////////////////
static const char knownStyleHints[][45] = {
"activate-on-singleclick",
"alignment",
"arrow-keys-navigate-into-children",
"backward-icon",
"button-layout",
"cd-icon",
"combobox-list-mousetracking",
"combobox-popup",
"computer-icon",
"desktop-icon",
"dialog-apply-icon",
"dialog-cancel-icon",
"dialog-close-icon",
"dialog-discard-icon",
"dialog-help-icon",
"dialog-no-icon",
"dialog-ok-icon",
"dialog-open-icon",
"dialog-reset-icon",
"dialog-save-icon",
"dialog-yes-icon",
"dialogbuttonbox-buttons-have-icons",
"directory-closed-icon",
"directory-icon",
"directory-link-icon",
"directory-open-icon",
"dither-disable-text",
"dockwidget-close-icon",
"downarrow-icon",
"dvd-icon",
"etch-disabled-text",
"file-icon",
"file-link-icon",
"filedialog-backward-icon", // unused
"filedialog-contentsview-icon",
"filedialog-detailedview-icon",
"filedialog-end-icon",
"filedialog-infoview-icon",
"filedialog-listview-icon",
"filedialog-new-directory-icon",
"filedialog-parent-directory-icon",
"filedialog-start-icon",
"floppy-icon",
"forward-icon",
"gridline-color",
"harddisk-icon",
"home-icon",
"icon-size",
"leftarrow-icon",
"lineedit-password-character",
"lineedit-password-mask-delay",
"mdi-fill-space-on-maximize",
"menu-scrollable",
"menubar-altkey-navigation",
"menubar-separator",
"messagebox-critical-icon",
"messagebox-information-icon",
"messagebox-question-icon",
"messagebox-text-interaction-flags",
"messagebox-warning-icon",
"mouse-tracking",
"network-icon",
"opacity",
"paint-alternating-row-colors-for-empty-area",
"rightarrow-icon",
"scrollbar-contextmenu",
"scrollbar-leftclick-absolute-position",
"scrollbar-middleclick-absolute-position",
"scrollbar-roll-between-buttons",
"scrollbar-scroll-when-pointer-leaves-control",
"scrollview-frame-around-contents",
"show-decoration-selected",
"spinbox-click-autorepeat-rate",
"spincontrol-disable-on-bounds",
"tabbar-elide-mode",
"tabbar-prefer-no-arrows",
"titlebar-close-icon",
"titlebar-contexthelp-icon",
"titlebar-maximize-icon",
"titlebar-menu-icon",
"titlebar-minimize-icon",
"titlebar-normal-icon",
"titlebar-shade-icon",
"titlebar-unshade-icon",
"toolbutton-popup-delay",
"trash-icon",
"uparrow-icon"
};
static const int numKnownStyleHints = sizeof(knownStyleHints)/sizeof(knownStyleHints[0]);
static QList<QVariant> subControlLayout(const QString& layout)
{
QList<QVariant> buttons;
for (int i = 0; i < layout.count(); i++) {
int button = layout[i].toLatin1();
switch (button) {
case 'm':
buttons.append(PseudoElement_MdiMinButton);
buttons.append(PseudoElement_TitleBarMinButton);
break;
case 'M':
buttons.append(PseudoElement_TitleBarMaxButton);
break;
case 'X':
buttons.append(PseudoElement_MdiCloseButton);
buttons.append(PseudoElement_TitleBarCloseButton);
break;
case 'N':
buttons.append(PseudoElement_MdiNormalButton);
buttons.append(PseudoElement_TitleBarNormalButton);
break;
case 'I':
buttons.append(PseudoElement_TitleBarSysMenu);
break;
case 'T':
buttons.append(PseudoElement_TitleBar);
break;
case 'H':
buttons.append(PseudoElement_TitleBarContextHelpButton);
break;
case 'S':
buttons.append(PseudoElement_TitleBarShadeButton);
break;
default:
buttons.append(button);
break;
}
}
return buttons;
}
namespace {
struct ButtonInfo {
QRenderRule rule;
int element;
int offset;
int where;
int width;
};
}
template <> class QTypeInfo<ButtonInfo> : public QTypeInfoMerger<ButtonInfo, QRenderRule, int> {};
QHash<QStyle::SubControl, QRect> QStyleSheetStyle::titleBarLayout(const QWidget *w, const QStyleOptionTitleBar *tb) const
{
QHash<QStyle::SubControl, QRect> layoutRects;
const bool isMinimized = tb->titleBarState & Qt::WindowMinimized;
const bool isMaximized = tb->titleBarState & Qt::WindowMaximized;
QRenderRule subRule = renderRule(w, tb);
QRect cr = subRule.contentsRect(tb->rect);
QList<QVariant> layout = subRule.styleHint(QLatin1String("button-layout")).toList();
if (layout.isEmpty())
layout = subControlLayout(QLatin1String("I(T)HSmMX"));
int offsets[3] = { 0, 0, 0 };
enum Where { Left, Right, Center, NoWhere } where = Left;
QVector<ButtonInfo> infos;
const int numLayouts = layout.size();
infos.reserve(numLayouts);
for (int i = 0; i < numLayouts; i++) {
const int element = layout[i].toInt();
if (element == '(') {
where = Center;
} else if (element == ')') {
where = Right;
} else {
ButtonInfo info;
info.element = element;
switch (element) {
case PseudoElement_TitleBar:
if (!(tb->titleBarFlags & (Qt::WindowTitleHint | Qt::WindowSystemMenuHint)))
continue;
break;
case PseudoElement_TitleBarContextHelpButton:
if (!(tb->titleBarFlags & Qt::WindowContextHelpButtonHint))
continue;
break;
case PseudoElement_TitleBarMinButton:
if (!(tb->titleBarFlags & Qt::WindowMinimizeButtonHint))
continue;
if (isMinimized)
info.element = PseudoElement_TitleBarNormalButton;
break;
case PseudoElement_TitleBarMaxButton:
if (!(tb->titleBarFlags & Qt::WindowMaximizeButtonHint))
continue;
if (isMaximized)
info.element = PseudoElement_TitleBarNormalButton;
break;
case PseudoElement_TitleBarShadeButton:
if (!(tb->titleBarFlags & Qt::WindowShadeButtonHint))
continue;
if (isMinimized)
info.element = PseudoElement_TitleBarUnshadeButton;
break;
case PseudoElement_TitleBarCloseButton:
case PseudoElement_TitleBarSysMenu:
if (!(tb->titleBarFlags & Qt::WindowSystemMenuHint))
continue;
break;
default:
continue;
}
if (info.element == PseudoElement_TitleBar) {
info.width = tb->fontMetrics.width(tb->text) + 6;
subRule.geo = new QStyleSheetGeometryData(info.width, tb->fontMetrics.height(), -1, -1, -1, -1);
} else {
subRule = renderRule(w, tb, info.element);
info.width = subRule.size().width();
}
info.rule = subRule;
info.offset = offsets[where];
info.where = where;
infos.append(qMove(info));
offsets[where] += info.width;
}
}
for (int i = 0; i < infos.size(); i++) {
const ButtonInfo &info = infos[i];
QRect lr = cr;
switch (info.where) {
case Center: {
lr.setLeft(cr.left() + offsets[Left]);
lr.setRight(cr.right() - offsets[Right]);
QRect r(0, 0, offsets[Center], lr.height());
r.moveCenter(lr.center());
r.setLeft(r.left()+info.offset);
r.setWidth(info.width);
lr = r;
break; }
case Left:
lr.translate(info.offset, 0);
lr.setWidth(info.width);
break;
case Right:
lr.moveLeft(cr.right() + 1 - offsets[Right] + info.offset);
lr.setWidth(info.width);
break;
default:
break;
}
QStyle::SubControl control = knownPseudoElements[info.element].subControl;
layoutRects[control] = positionRect(w, info.rule, info.element, lr, tb->direction);
}
return layoutRects;
}
static QStyle::StandardPixmap subControlIcon(int pe)
{
switch (pe) {
case PseudoElement_MdiCloseButton: return QStyle::SP_TitleBarCloseButton;
case PseudoElement_MdiMinButton: return QStyle::SP_TitleBarMinButton;
case PseudoElement_MdiNormalButton: return QStyle::SP_TitleBarNormalButton;
case PseudoElement_TitleBarCloseButton: return QStyle::SP_TitleBarCloseButton;
case PseudoElement_TitleBarMinButton: return QStyle::SP_TitleBarMinButton;
case PseudoElement_TitleBarMaxButton: return QStyle::SP_TitleBarMaxButton;
case PseudoElement_TitleBarShadeButton: return QStyle::SP_TitleBarShadeButton;
case PseudoElement_TitleBarUnshadeButton: return QStyle::SP_TitleBarUnshadeButton;
case PseudoElement_TitleBarNormalButton: return QStyle::SP_TitleBarNormalButton;
case PseudoElement_TitleBarContextHelpButton: return QStyle::SP_TitleBarContextHelpButton;
default: break;
}
return QStyle::SP_CustomBase;
}
QRenderRule::QRenderRule(const QVector<Declaration> &declarations, const QObject *object)
: features(0), hasFont(false), pal(0), b(0), bg(0), bd(0), ou(0), geo(0), p(0), img(0), clipset(0)
{
QPalette palette = QApplication::palette(); // ###: ideally widget's palette
ValueExtractor v(declarations, palette);
features = v.extractStyleFeatures();
int w = -1, h = -1, minw = -1, minh = -1, maxw = -1, maxh = -1;
if (v.extractGeometry(&w, &h, &minw, &minh, &maxw, &maxh))
geo = new QStyleSheetGeometryData(w, h, minw, minh, maxw, maxh);
int left = 0, top = 0, right = 0, bottom = 0;
Origin origin = Origin_Unknown;
Qt::Alignment position = 0;
QCss::PositionMode mode = PositionMode_Unknown;
Qt::Alignment textAlignment = 0;
if (v.extractPosition(&left, &top, &right, &bottom, &origin, &position, &mode, &textAlignment))
p = new QStyleSheetPositionData(left, top, right, bottom, origin, position, mode, textAlignment);
int margins[4], paddings[4], spacing = -1;
for (int i = 0; i < 4; i++)
margins[i] = paddings[i] = 0;
if (v.extractBox(margins, paddings, &spacing))
b = new QStyleSheetBoxData(margins, paddings, spacing);
int borders[4];
QBrush colors[4];
QCss::BorderStyle styles[4];
QSize radii[4];
for (int i = 0; i < 4; i++) {
borders[i] = 0;
styles[i] = BorderStyle_None;
}
if (v.extractBorder(borders, colors, styles, radii))
bd = new QStyleSheetBorderData(borders, colors, styles, radii);
int offsets[4];
for (int i = 0; i < 4; i++) {
borders[i] = offsets[i] = 0;
styles[i] = BorderStyle_None;
}
if (v.extractOutline(borders, colors, styles, radii, offsets))
ou = new QStyleSheetOutlineData(borders, colors, styles, radii, offsets);
QBrush brush;
QString uri;
Repeat repeat = Repeat_XY;
Qt::Alignment alignment = Qt::AlignTop | Qt::AlignLeft;
Attachment attachment = Attachment_Scroll;
origin = Origin_Padding;
Origin clip = Origin_Border;
if (v.extractBackground(&brush, &uri, &repeat, &alignment, &origin, &attachment, &clip))
bg = new QStyleSheetBackgroundData(brush, QPixmap(uri), repeat, alignment, origin, attachment, clip);
QBrush sfg, fg;
QBrush sbg, abg;
if (v.extractPalette(&fg, &sfg, &sbg, &abg))
pal = new QStyleSheetPaletteData(fg, sfg, sbg, abg);
QIcon icon;
alignment = Qt::AlignCenter;
QSize size;
if (v.extractImage(&icon, &alignment, &size))
img = new QStyleSheetImageData(icon, alignment, size);
int adj = -255;
hasFont = v.extractFont(&font, &adj);
#ifndef QT_NO_TOOLTIP
if (object && qstrcmp(object->metaObject()->className(), "QTipLabel") == 0)
palette = QToolTip::palette();
#endif
for (int i = 0; i < declarations.count(); i++) {
const Declaration& decl = declarations.at(i);
if (decl.d->propertyId == BorderImage) {
QString uri;
QCss::TileMode horizStretch, vertStretch;
int cuts[4];
decl.borderImageValue(&uri, cuts, &horizStretch, &vertStretch);
if (uri.isEmpty() || uri == QLatin1String("none")) {
if (bd && bd->bi)
bd->bi->pixmap = QPixmap();
} else {
if (!bd)
bd = new QStyleSheetBorderData;
if (!bd->bi)
bd->bi = new QStyleSheetBorderImageData;
QStyleSheetBorderImageData *bi = bd->bi;
bi->pixmap = QPixmap(uri);
for (int i = 0; i < 4; i++)
bi->cuts[i] = cuts[i];
bi->horizStretch = horizStretch;
bi->vertStretch = vertStretch;
}
} else if (decl.d->propertyId == QtBackgroundRole) {
if (bg && bg->brush.style() != Qt::NoBrush)
continue;
int role = decl.d->values.at(0).variant.toInt();
if (role >= Value_FirstColorRole && role <= Value_LastColorRole)
defaultBackground = palette.color((QPalette::ColorRole)(role-Value_FirstColorRole));
} else if (decl.d->property.startsWith(QLatin1String("qproperty-"), Qt::CaseInsensitive)) {
// intentionally left blank...
} else if (decl.d->propertyId == UnknownProperty) {
bool knownStyleHint = false;
for (int i = 0; i < numKnownStyleHints; i++) {
QLatin1String styleHint(knownStyleHints[i]);
if (decl.d->property.compare(styleHint) == 0) {
QString hintName = QString(styleHint);
QVariant hintValue;
if (hintName.endsWith(QLatin1String("alignment"))) {
hintValue = (int) decl.alignmentValue();
} else if (hintName.endsWith(QLatin1String("color"))) {
hintValue = (int) decl.colorValue().rgba();
} else if (hintName.endsWith(QLatin1String("size"))) {
hintValue = decl.sizeValue();
} else if (hintName.endsWith(QLatin1String("icon"))) {
hintValue = decl.iconValue();
} else if (hintName == QLatin1String("button-layout")
&& decl.d->values.count() != 0 && decl.d->values.at(0).type == Value::String) {
hintValue = subControlLayout(decl.d->values.at(0).variant.toString());
} else {
int integer;
decl.intValue(&integer);
hintValue = integer;
}
styleHints[decl.d->property] = hintValue;
knownStyleHint = true;
break;
}
}
if (!knownStyleHint)
qDebug("Unknown property %s", qPrintable(decl.d->property));
}
}
if (hasBorder()) {
if (const QWidget *widget = qobject_cast<const QWidget *>(object)) {
QStyleSheetStyle *style = const_cast<QStyleSheetStyle *>(globalStyleSheetStyle);
if (!style)
style = qobject_cast<QStyleSheetStyle *>(widget->style());
if (style)
fixupBorder(style->nativeFrameWidth(widget));
}
if (border()->hasBorderImage())
defaultBackground = QBrush();
}
}
QRect QRenderRule::borderRect(const QRect& r) const
{
if (!hasBox())
return r;
const int* m = box()->margins;
return r.adjusted(m[LeftEdge], m[TopEdge], -m[RightEdge], -m[BottomEdge]);
}
QRect QRenderRule::outlineRect(const QRect& r) const
{
QRect br = borderRect(r);
if (!hasOutline())
return br;
const int *b = outline()->borders;
return r.adjusted(b[LeftEdge], b[TopEdge], -b[RightEdge], -b[BottomEdge]);
}
QRect QRenderRule::paddingRect(const QRect& r) const
{
QRect br = borderRect(r);
if (!hasBorder())
return br;
const int *b = border()->borders;
return br.adjusted(b[LeftEdge], b[TopEdge], -b[RightEdge], -b[BottomEdge]);
}
QRect QRenderRule::contentsRect(const QRect& r) const
{
QRect pr = paddingRect(r);
if (!hasBox())
return pr;
const int *p = box()->paddings;
return pr.adjusted(p[LeftEdge], p[TopEdge], -p[RightEdge], -p[BottomEdge]);
}
QRect QRenderRule::boxRect(const QRect& cr, int flags) const
{
QRect r = cr;
if (hasBox()) {
if (flags & Margin) {
const int *m = box()->margins;
r.adjust(-m[LeftEdge], -m[TopEdge], m[RightEdge], m[BottomEdge]);
}
if (flags & Padding) {
const int *p = box()->paddings;
r.adjust(-p[LeftEdge], -p[TopEdge], p[RightEdge], p[BottomEdge]);
}
}
if (hasBorder() && (flags & Border)) {
const int *b = border()->borders;
r.adjust(-b[LeftEdge], -b[TopEdge], b[RightEdge], b[BottomEdge]);
}
return r;
}
QSize QRenderRule::boxSize(const QSize &cs, int flags) const
{
QSize bs = boxRect(QRect(QPoint(0, 0), cs), flags).size();
if (cs.width() < 0) bs.setWidth(-1);
if (cs.height() < 0) bs.setHeight(-1);
return bs;
}
void QRenderRule::fixupBorder(int nativeWidth)
{
if (bd == 0)
return;
if (!bd->hasBorderImage() || bd->bi->pixmap.isNull()) {
bd->bi = 0;
// ignore the color, border of edges that have none border-style
QBrush color = pal ? pal->foreground : QBrush();
const bool hasRadius = bd->radii[0].isValid() || bd->radii[1].isValid()
|| bd->radii[2].isValid() || bd->radii[3].isValid();
for (int i = 0; i < 4; i++) {
if ((bd->styles[i] == BorderStyle_Native) && hasRadius)
bd->styles[i] = BorderStyle_None;
switch (bd->styles[i]) {
case BorderStyle_None:
// border-style: none forces width to be 0
bd->colors[i] = QBrush();
bd->borders[i] = 0;
break;
case BorderStyle_Native:
if (bd->borders[i] == 0)
bd->borders[i] = nativeWidth;
Q_FALLTHROUGH();
default:
if (bd->colors[i].style() == Qt::NoBrush) // auto-acquire 'color'
bd->colors[i] = color;
break;
}
}
return;
}
// inspect the border image
QStyleSheetBorderImageData *bi = bd->bi;
if (bi->cuts[0] == -1) {
for (int i = 0; i < 4; i++) // assume, cut = border
bi->cuts[i] = int(border()->borders[i]);
}
}
void QRenderRule::drawBorderImage(QPainter *p, const QRect& rect)
{
setClip(p, rect);
static const Qt::TileRule tileMode2TileRule[] = {
Qt::StretchTile, Qt::RoundTile, Qt::StretchTile, Qt::RepeatTile, Qt::StretchTile };
const QStyleSheetBorderImageData *borderImageData = border()->borderImage();
const int *targetBorders = border()->borders;
const int *sourceBorders = borderImageData->cuts;
QMargins sourceMargins(sourceBorders[LeftEdge], sourceBorders[TopEdge],
sourceBorders[RightEdge], sourceBorders[BottomEdge]);
QMargins targetMargins(targetBorders[LeftEdge], targetBorders[TopEdge],
targetBorders[RightEdge], targetBorders[BottomEdge]);
bool wasSmoothPixmapTransform = p->renderHints() & QPainter::SmoothPixmapTransform;
p->setRenderHint(QPainter::SmoothPixmapTransform);
qDrawBorderPixmap(p, rect, targetMargins, borderImageData->pixmap,
QRect(QPoint(), borderImageData->pixmap.size()), sourceMargins,
QTileRules(tileMode2TileRule[borderImageData->horizStretch], tileMode2TileRule[borderImageData->vertStretch]));
p->setRenderHint(QPainter::SmoothPixmapTransform, wasSmoothPixmapTransform);
unsetClip(p);
}
QRect QRenderRule::originRect(const QRect &rect, Origin origin) const
{
switch (origin) {
case Origin_Padding:
return paddingRect(rect);
case Origin_Border:
return borderRect(rect);
case Origin_Content:
return contentsRect(rect);
case Origin_Margin:
default:
return rect;
}
}
void QRenderRule::drawBackgroundImage(QPainter *p, const QRect &rect, QPoint off)
{
if (!hasBackground())
return;
const QPixmap& bgp = background()->pixmap;
if (bgp.isNull())
return;
setClip(p, borderRect(rect));
if (background()->origin != background()->clip) {
p->save();
p->setClipRect(originRect(rect, background()->clip), Qt::IntersectClip);
}
if (background()->attachment == Attachment_Fixed)
off = QPoint(0, 0);
QRect r = originRect(rect, background()->origin);
QRect aligned = QStyle::alignedRect(Qt::LeftToRight, background()->position, bgp.size(), r);
QRect inter = aligned.translated(-off).intersected(r);
switch (background()->repeat) {
case Repeat_Y:
p->drawTiledPixmap(inter.x(), r.y(), inter.width(), r.height(), bgp,
inter.x() - aligned.x() + off.x(),
bgp.height() - int(aligned.y() - r.y()) % bgp.height() + off.y());
break;
case Repeat_X:
p->drawTiledPixmap(r.x(), inter.y(), r.width(), inter.height(), bgp,
bgp.width() - int(aligned.x() - r.x())%bgp.width() + off.x(),
inter.y() - aligned.y() + off.y());
break;
case Repeat_XY:
p->drawTiledPixmap(r, bgp,
QPoint(bgp.width() - int(aligned.x() - r.x())% bgp.width() + off.x(),
bgp.height() - int(aligned.y() - r.y())%bgp.height() + off.y()));
break;
case Repeat_None:
default:
p->drawPixmap(inter.x(), inter.y(), bgp, inter.x() - aligned.x() + off.x(),
inter.y() - aligned.y() + off.y(), inter.width(), inter.height());
break;
}
if (background()->origin != background()->clip)
p->restore();
unsetClip(p);
}
void QRenderRule::drawOutline(QPainter *p, const QRect &rect)
{
if (!hasOutline())
return;
bool wasAntialiased = p->renderHints() & QPainter::Antialiasing;
p->setRenderHint(QPainter::Antialiasing);
qDrawBorder(p, rect, ou->styles, ou->borders, ou->colors, ou->radii);
p->setRenderHint(QPainter::Antialiasing, wasAntialiased);
}
void QRenderRule::drawBorder(QPainter *p, const QRect& rect)
{
if (!hasBorder())
return;
if (border()->hasBorderImage()) {
drawBorderImage(p, rect);
return;
}
bool wasAntialiased = p->renderHints() & QPainter::Antialiasing;
p->setRenderHint(QPainter::Antialiasing);
qDrawBorder(p, rect, bd->styles, bd->borders, bd->colors, bd->radii);
p->setRenderHint(QPainter::Antialiasing, wasAntialiased);
}
QPainterPath QRenderRule::borderClip(QRect r)
{
if (!hasBorder())
return QPainterPath();
QSize tlr, trr, blr, brr;
qNormalizeRadii(r, bd->radii, &tlr, &trr, &blr, &brr);
if (tlr.isNull() && trr.isNull() && blr.isNull() && brr.isNull())
return QPainterPath();
const QRectF rect(r);
const int *borders = border()->borders;
QPainterPath path;
qreal curY = rect.y() + borders[TopEdge]/2.0;
path.moveTo(rect.x() + tlr.width(), curY);
path.lineTo(rect.right() - trr.width(), curY);
qreal curX = rect.right() - borders[RightEdge]/2.0;
path.arcTo(curX - 2*trr.width() + borders[RightEdge], curY,
trr.width()*2 - borders[RightEdge], trr.height()*2 - borders[TopEdge], 90, -90);
path.lineTo(curX, rect.bottom() - brr.height());
curY = rect.bottom() - borders[BottomEdge]/2.0;
path.arcTo(curX - 2*brr.width() + borders[RightEdge], curY - 2*brr.height() + borders[BottomEdge],
brr.width()*2 - borders[RightEdge], brr.height()*2 - borders[BottomEdge], 0, -90);
path.lineTo(rect.x() + blr.width(), curY);
curX = rect.left() + borders[LeftEdge]/2.0;
path.arcTo(curX, rect.bottom() - 2*blr.height() + borders[BottomEdge]/2,
blr.width()*2 - borders[LeftEdge], blr.height()*2 - borders[BottomEdge], 270, -90);
path.lineTo(curX, rect.top() + tlr.height());
path.arcTo(curX, rect.top() + borders[TopEdge]/2,
tlr.width()*2 - borders[LeftEdge], tlr.height()*2 - borders[TopEdge], 180, -90);
path.closeSubpath();
return path;
}
/*! \internal
Clip the painter to the border (in case we are using radius border)
*/
void QRenderRule::setClip(QPainter *p, const QRect &rect)
{
if (clipset++)
return;
clipPath = borderClip(rect);
if (!clipPath.isEmpty()) {
p->save();
p->setClipPath(clipPath, Qt::IntersectClip);
}
}
void QRenderRule::unsetClip(QPainter *p)
{
if (--clipset)
return;
if (!clipPath.isEmpty())
p->restore();
}
void QRenderRule::drawBackground(QPainter *p, const QRect& rect, const QPoint& off)
{
QBrush brush = hasBackground() ? background()->brush : QBrush();
if (brush.style() == Qt::NoBrush)
brush = defaultBackground;
if (brush.style() != Qt::NoBrush) {
Origin origin = hasBackground() ? background()->clip : Origin_Border;
// ### fix for gradients
const QPainterPath &borderPath = borderClip(originRect(rect, origin));
if (!borderPath.isEmpty()) {
// Drawn intead of being used as clipping path for better visual quality
bool wasAntialiased = p->renderHints() & QPainter::Antialiasing;
p->setRenderHint(QPainter::Antialiasing);
p->fillPath(borderPath, brush);
p->setRenderHint(QPainter::Antialiasing, wasAntialiased);
} else {
p->fillRect(originRect(rect, origin), brush);
}
}
drawBackgroundImage(p, rect, off);
}
void QRenderRule::drawFrame(QPainter *p, const QRect& rect)
{
drawBackground(p, rect);
if (hasBorder())
drawBorder(p, borderRect(rect));
}
void QRenderRule::drawImage(QPainter *p, const QRect &rect)
{
if (!hasImage())
return;
img->icon.paint(p, rect, img->alignment);
}
void QRenderRule::drawRule(QPainter *p, const QRect& rect)
{
drawFrame(p, rect);
drawImage(p, contentsRect(rect));
}
// *shudder* , *horror*, *whoa* <-- what you might feel when you see the functions below
void QRenderRule::configurePalette(QPalette *p, QPalette::ColorRole fr, QPalette::ColorRole br)
{
if (bg && bg->brush.style() != Qt::NoBrush) {
if (br != QPalette::NoRole)
p->setBrush(br, bg->brush);
p->setBrush(QPalette::Window, bg->brush);
if (bg->brush.style() == Qt::SolidPattern) {
p->setBrush(QPalette::Light, bg->brush.color().lighter(115));
p->setBrush(QPalette::Midlight, bg->brush.color().lighter(107));
p->setBrush(QPalette::Dark, bg->brush.color().darker(150));
p->setBrush(QPalette::Shadow, bg->brush.color().darker(300));
}
}
if (!hasPalette())
return;
if (pal->foreground.style() != Qt::NoBrush) {
if (fr != QPalette::NoRole)
p->setBrush(fr, pal->foreground);
p->setBrush(QPalette::WindowText, pal->foreground);
p->setBrush(QPalette::Text, pal->foreground);
}
if (pal->selectionBackground.style() != Qt::NoBrush)
p->setBrush(QPalette::Highlight, pal->selectionBackground);
if (pal->selectionForeground.style() != Qt::NoBrush)
p->setBrush(QPalette::HighlightedText, pal->selectionForeground);
if (pal->alternateBackground.style() != Qt::NoBrush)
p->setBrush(QPalette::AlternateBase, pal->alternateBackground);
}
void QRenderRule::configurePalette(QPalette *p, QPalette::ColorGroup cg, const QWidget *w, bool embedded)
{
if (bg && bg->brush.style() != Qt::NoBrush) {
p->setBrush(cg, QPalette::Base, bg->brush); // for windows, windowxp
p->setBrush(cg, QPalette::Button, bg->brush); // for plastique
p->setBrush(cg, w->backgroundRole(), bg->brush);
p->setBrush(cg, QPalette::Window, bg->brush);
}
if (embedded) {
/* For embedded widgets (ComboBox, SpinBox and ScrollArea) we want the embedded widget
* to be transparent when we have a transparent background or border image */
if ((hasBackground() && background()->isTransparent())
|| (hasBorder() && border()->hasBorderImage() && !border()->borderImage()->pixmap.isNull()))
p->setBrush(cg, w->backgroundRole(), Qt::NoBrush);
}
if (!hasPalette())
return;
if (pal->foreground.style() != Qt::NoBrush) {
p->setBrush(cg, QPalette::ButtonText, pal->foreground);
p->setBrush(cg, w->foregroundRole(), pal->foreground);
p->setBrush(cg, QPalette::WindowText, pal->foreground);
p->setBrush(cg, QPalette::Text, pal->foreground);
}
if (pal->selectionBackground.style() != Qt::NoBrush)
p->setBrush(cg, QPalette::Highlight, pal->selectionBackground);
if (pal->selectionForeground.style() != Qt::NoBrush)
p->setBrush(cg, QPalette::HighlightedText, pal->selectionForeground);
if (pal->alternateBackground.style() != Qt::NoBrush)
p->setBrush(cg, QPalette::AlternateBase, pal->alternateBackground);
}
///////////////////////////////////////////////////////////////////////////////
// Style rules
#define OBJECT_PTR(x) (static_cast<QObject *>(x.ptr))
static inline QObject *parentObject(const QObject *obj)
{
#if QT_CONFIG(tooltip)
if (qobject_cast<const QLabel *>(obj) && qstrcmp(obj->metaObject()->className(), "QTipLabel") == 0) {
QObject *p = qvariant_cast<QObject *>(obj->property("_q_stylesheet_parent"));
if (p)
return p;
}
#endif
return obj->parent();
}
class QStyleSheetStyleSelector : public StyleSelector
{
public:
QStyleSheetStyleSelector() { }
QStringList nodeNames(NodePtr node) const Q_DECL_OVERRIDE
{
if (isNullNode(node))
return QStringList();
const QMetaObject *metaObject = OBJECT_PTR(node)->metaObject();
#ifndef QT_NO_TOOLTIP
if (qstrcmp(metaObject->className(), "QTipLabel") == 0)
return QStringList(QLatin1String("QToolTip"));
#endif
QStringList result;
do {
result += QString::fromLatin1(metaObject->className()).replace(QLatin1Char(':'), QLatin1Char('-'));
metaObject = metaObject->superClass();
} while (metaObject != 0);
return result;
}
QString attribute(NodePtr node, const QString& name) const Q_DECL_OVERRIDE
{
if (isNullNode(node))
return QString();
QHash<QString, QString> &cache = m_attributeCache[OBJECT_PTR(node)];
QHash<QString, QString>::const_iterator cacheIt = cache.constFind(name);
if (cacheIt != cache.constEnd())
return cacheIt.value();
QObject *obj = OBJECT_PTR(node);
QVariant value = obj->property(name.toLatin1());
if (!value.isValid()) {
if (name == QLatin1String("class")) {
QString className = QString::fromLatin1(obj->metaObject()->className());
if (className.contains(QLatin1Char(':')))
className.replace(QLatin1Char(':'), QLatin1Char('-'));
cache[name] = className;
return className;
} else if (name == QLatin1String("style")) {
QWidget *w = qobject_cast<QWidget *>(obj);
QStyleSheetStyle *proxy = w ? qobject_cast<QStyleSheetStyle *>(w->style()) : 0;
if (proxy) {
QString styleName = QString::fromLatin1(proxy->baseStyle()->metaObject()->className());
cache[name] = styleName;
return styleName;
}
}
}
QString valueStr;
if(value.type() == QVariant::StringList || value.type() == QVariant::List)
valueStr = value.toStringList().join(QLatin1Char(' '));
else
valueStr = value.toString();
cache[name] = valueStr;
return valueStr;
}
bool nodeNameEquals(NodePtr node, const QString& nodeName) const Q_DECL_OVERRIDE
{
if (isNullNode(node))
return false;
const QMetaObject *metaObject = OBJECT_PTR(node)->metaObject();
#ifndef QT_NO_TOOLTIP
if (qstrcmp(metaObject->className(), "QTipLabel") == 0)
return nodeName == QLatin1String("QToolTip");
#endif
do {
const ushort *uc = (const ushort *)nodeName.constData();
const ushort *e = uc + nodeName.length();
const uchar *c = (const uchar *)metaObject->className();
while (*c && uc != e && (*uc == *c || (*c == ':' && *uc == '-'))) {
++uc;
++c;
}
if (uc == e && !*c)
return true;
metaObject = metaObject->superClass();
} while (metaObject != 0);
return false;
}
bool hasAttributes(NodePtr) const Q_DECL_OVERRIDE
{ return true; }
QStringList nodeIds(NodePtr node) const Q_DECL_OVERRIDE
{ return isNullNode(node) ? QStringList() : QStringList(OBJECT_PTR(node)->objectName()); }
bool isNullNode(NodePtr node) const Q_DECL_OVERRIDE
{ return node.ptr == 0; }
NodePtr parentNode(NodePtr node) const Q_DECL_OVERRIDE
{ NodePtr n; n.ptr = isNullNode(node) ? 0 : parentObject(OBJECT_PTR(node)); return n; }
NodePtr previousSiblingNode(NodePtr) const Q_DECL_OVERRIDE
{ NodePtr n; n.ptr = 0; return n; }
NodePtr duplicateNode(NodePtr node) const Q_DECL_OVERRIDE
{ return node; }
void freeNode(NodePtr) const Q_DECL_OVERRIDE
{ }
private:
mutable QHash<const QObject *, QHash<QString, QString> > m_attributeCache;
};
QVector<QCss::StyleRule> QStyleSheetStyle::styleRules(const QObject *obj) const
{
QHash<const QObject *, QVector<StyleRule> >::const_iterator cacheIt = styleSheetCaches->styleRulesCache.constFind(obj);
if (cacheIt != styleSheetCaches->styleRulesCache.constEnd())
return cacheIt.value();
if (!initObject(obj)) {
return QVector<StyleRule>();
}
QStyleSheetStyleSelector styleSelector;
StyleSheet defaultSs;
QHash<const void *, StyleSheet>::const_iterator defaultCacheIt = styleSheetCaches->styleSheetCache.constFind(baseStyle());
if (defaultCacheIt == styleSheetCaches->styleSheetCache.constEnd()) {
defaultSs = getDefaultStyleSheet();
QStyle *bs = baseStyle();
styleSheetCaches->styleSheetCache.insert(bs, defaultSs);
QObject::connect(bs, SIGNAL(destroyed(QObject*)), styleSheetCaches, SLOT(styleDestroyed(QObject*)), Qt::UniqueConnection);
} else {
defaultSs = defaultCacheIt.value();
}
styleSelector.styleSheets += defaultSs;
if (!qApp->styleSheet().isEmpty()) {
StyleSheet appSs;
QHash<const void *, StyleSheet>::const_iterator appCacheIt = styleSheetCaches->styleSheetCache.constFind(qApp);
if (appCacheIt == styleSheetCaches->styleSheetCache.constEnd()) {
QString ss = qApp->styleSheet();
if (ss.startsWith(QLatin1String("file:///")))
ss.remove(0, 8);
parser.init(ss, qApp->styleSheet() != ss);
if (Q_UNLIKELY(!parser.parse(&appSs)))
qWarning("Could not parse application stylesheet");
appSs.origin = StyleSheetOrigin_Inline;
appSs.depth = 1;
styleSheetCaches->styleSheetCache.insert(qApp, appSs);
} else {
appSs = appCacheIt.value();
}
styleSelector.styleSheets += appSs;
}
QVector<QCss::StyleSheet> objectSs;
for (const QObject *o = obj; o; o = parentObject(o)) {
QString styleSheet = o->property("styleSheet").toString();
if (styleSheet.isEmpty())
continue;
StyleSheet ss;
QHash<const void *, StyleSheet>::const_iterator objCacheIt = styleSheetCaches->styleSheetCache.constFind(o);
if (objCacheIt == styleSheetCaches->styleSheetCache.constEnd()) {
parser.init(styleSheet);
if (!parser.parse(&ss)) {
parser.init(QLatin1String("* {") + styleSheet + QLatin1Char('}'));
if (Q_UNLIKELY(!parser.parse(&ss)))
qWarning("Could not parse stylesheet of object %p", o);
}
ss.origin = StyleSheetOrigin_Inline;
styleSheetCaches->styleSheetCache.insert(o, ss);
} else {
ss = objCacheIt.value();
}
objectSs.append(ss);
}
for (int i = 0; i < objectSs.count(); i++)
objectSs[i].depth = objectSs.count() - i + 2;
styleSelector.styleSheets += objectSs;
StyleSelector::NodePtr n;
n.ptr = const_cast<QObject *>(obj);
QVector<QCss::StyleRule> rules = styleSelector.styleRulesForNode(n);
styleSheetCaches->styleRulesCache.insert(obj, rules);
return rules;
}
/////////////////////////////////////////////////////////////////////////////////////////
// Rendering rules
static QVector<Declaration> declarations(const QVector<StyleRule> &styleRules, const QString &part, quint64 pseudoClass = PseudoClass_Unspecified)
{
QVector<Declaration> decls;
for (int i = 0; i < styleRules.count(); i++) {
const Selector& selector = styleRules.at(i).selectors.at(0);
// Rules with pseudo elements don't cascade. This is an intentional
// diversion for CSS
if (part.compare(selector.pseudoElement(), Qt::CaseInsensitive) != 0)
continue;
quint64 negated = 0;
quint64 cssClass = selector.pseudoClass(&negated);
if ((pseudoClass == PseudoClass_Any) || (cssClass == PseudoClass_Unspecified)
|| ((((cssClass & pseudoClass) == cssClass)) && ((negated & pseudoClass) == 0)))
decls += styleRules.at(i).declarations;
}
return decls;
}
int QStyleSheetStyle::nativeFrameWidth(const QWidget *w)
{
QStyle *base = baseStyle();
#if QT_CONFIG(spinbox)
if (qobject_cast<const QAbstractSpinBox *>(w))
return base->pixelMetric(QStyle::PM_SpinBoxFrameWidth, 0, w);
#endif
#if QT_CONFIG(combobox)
if (qobject_cast<const QComboBox *>(w))
return base->pixelMetric(QStyle::PM_ComboBoxFrameWidth, 0, w);
#endif
#if QT_CONFIG(menu)
if (qobject_cast<const QMenu *>(w))
return base->pixelMetric(QStyle::PM_MenuPanelWidth, 0, w);
#endif
#if QT_CONFIG(menubar)
if (qobject_cast<const QMenuBar *>(w))
return base->pixelMetric(QStyle::PM_MenuBarPanelWidth, 0, w);
#endif
#ifndef QT_NO_FRAME
if (const QFrame *frame = qobject_cast<const QFrame *>(w)) {
if (frame->frameShape() == QFrame::NoFrame)
return 0;
}
#endif
if (qstrcmp(w->metaObject()->className(), "QTipLabel") == 0)
return base->pixelMetric(QStyle::PM_ToolTipLabelFrameWidth, 0, w);
return base->pixelMetric(QStyle::PM_DefaultFrameWidth, 0, w);
}
static quint64 pseudoClass(QStyle::State state)
{
quint64 pc = 0;
if (state & QStyle::State_Enabled) {
pc |= PseudoClass_Enabled;
if (state & QStyle::State_MouseOver)
pc |= PseudoClass_Hover;
} else {
pc |= PseudoClass_Disabled;
}
if (state & QStyle::State_Active)
pc |= PseudoClass_Active;
if (state & QStyle::State_Window)
pc |= PseudoClass_Window;
if (state & QStyle::State_Sunken)
pc |= PseudoClass_Pressed;
if (state & QStyle::State_HasFocus)
pc |= PseudoClass_Focus;
if (state & QStyle::State_On)
pc |= (PseudoClass_On | PseudoClass_Checked);
if (state & QStyle::State_Off)
pc |= (PseudoClass_Off | PseudoClass_Unchecked);
if (state & QStyle::State_NoChange)
pc |= PseudoClass_Indeterminate;
if (state & QStyle::State_Selected)
pc |= PseudoClass_Selected;
if (state & QStyle::State_Horizontal)
pc |= PseudoClass_Horizontal;
else
pc |= PseudoClass_Vertical;
if (state & (QStyle::State_Open | QStyle::State_On | QStyle::State_Sunken))
pc |= PseudoClass_Open;
else
pc |= PseudoClass_Closed;
if (state & QStyle::State_Children)
pc |= PseudoClass_Children;
if (state & QStyle::State_Sibling)
pc |= PseudoClass_Sibling;
if (state & QStyle::State_ReadOnly)
pc |= PseudoClass_ReadOnly;
if (state & QStyle::State_Item)
pc |= PseudoClass_Item;
#ifdef QT_KEYPAD_NAVIGATION
if (state & QStyle::State_HasEditFocus)
pc |= PseudoClass_EditFocus;
#endif
return pc;
}
static void qt_check_if_internal_object(const QObject **obj, int *element)
{
#if !QT_CONFIG(dockwidget)
Q_UNUSED(obj);
Q_UNUSED(element);
#else
if (*obj && qstrcmp((*obj)->metaObject()->className(), "QDockWidgetTitleButton") == 0) {
if ((*obj)->objectName() == QLatin1String("qt_dockwidget_closebutton")) {
*element = PseudoElement_DockWidgetCloseButton;
} else if ((*obj)->objectName() == QLatin1String("qt_dockwidget_floatbutton")) {
*element = PseudoElement_DockWidgetFloatButton;
}
*obj = (*obj)->parent();
}
#endif
}
QRenderRule QStyleSheetStyle::renderRule(const QObject *obj, int element, quint64 state) const
{
qt_check_if_internal_object(&obj, &element);
QHash<quint64, QRenderRule> &cache = styleSheetCaches->renderRulesCache[obj][element];
QHash<quint64, QRenderRule>::const_iterator cacheIt = cache.constFind(state);
if (cacheIt != cache.constEnd())
return cacheIt.value();
if (!initObject(obj))
return QRenderRule();
quint64 stateMask = 0;
const QVector<StyleRule> rules = styleRules(obj);
for (int i = 0; i < rules.count(); i++) {
const Selector& selector = rules.at(i).selectors.at(0);
quint64 negated = 0;
stateMask |= selector.pseudoClass(&negated);
stateMask |= negated;
}
cacheIt = cache.constFind(state & stateMask);
if (cacheIt != cache.constEnd()) {
const QRenderRule &newRule = cacheIt.value();
cache[state] = newRule;
return newRule;
}
const QString part = QLatin1String(knownPseudoElements[element].name);
QVector<Declaration> decls = declarations(rules, part, state);
QRenderRule newRule(decls, obj);
cache[state] = newRule;
if ((state & stateMask) != state)
cache[state&stateMask] = newRule;
return newRule;
}
QRenderRule QStyleSheetStyle::renderRule(const QObject *obj, const QStyleOption *opt, int pseudoElement) const
{
quint64 extraClass = 0;
QStyle::State state = opt ? opt->state : QStyle::State(QStyle::State_None);
if (const QStyleOptionComplex *complex = qstyleoption_cast<const QStyleOptionComplex *>(opt)) {
if (pseudoElement != PseudoElement_None) {
// if not an active subcontrol, just pass enabled/disabled
QStyle::SubControl subControl = knownPseudoElements[pseudoElement].subControl;
if (!(complex->activeSubControls & subControl))
state &= (QStyle::State_Enabled | QStyle::State_Horizontal | QStyle::State_HasFocus);
}
switch (pseudoElement) {
case PseudoElement_ComboBoxDropDown:
case PseudoElement_ComboBoxArrow:
state |= (complex->state & (QStyle::State_On|QStyle::State_ReadOnly));
break;
case PseudoElement_SpinBoxUpButton:
case PseudoElement_SpinBoxDownButton:
case PseudoElement_SpinBoxUpArrow:
case PseudoElement_SpinBoxDownArrow:
#if QT_CONFIG(spinbox)
if (const QStyleOptionSpinBox *sb = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
bool on = false;
bool up = pseudoElement == PseudoElement_SpinBoxUpButton
|| pseudoElement == PseudoElement_SpinBoxUpArrow;
if ((sb->stepEnabled & QAbstractSpinBox::StepUpEnabled) && up)
on = true;
else if ((sb->stepEnabled & QAbstractSpinBox::StepDownEnabled) && !up)
on = true;
state |= (on ? QStyle::State_On : QStyle::State_Off);
}
#endif // QT_CONFIG(spinbox)
break;
case PseudoElement_GroupBoxTitle:
state |= (complex->state & (QStyle::State_MouseOver | QStyle::State_Sunken));
break;
case PseudoElement_ToolButtonMenu:
case PseudoElement_ToolButtonMenuArrow:
case PseudoElement_ToolButtonDownArrow:
state |= complex->state & QStyle::State_MouseOver;
if (complex->state & QStyle::State_Sunken ||
complex->activeSubControls & QStyle::SC_ToolButtonMenu)
state |= QStyle::State_Sunken;
break;
case PseudoElement_SliderGroove:
state |= complex->state & QStyle::State_MouseOver;
break;
default:
break;
}
if (const QStyleOptionComboBox *combo = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
// QStyle::State_On is set when the popup is being shown
// Propagate EditField Pressed state
if (pseudoElement == PseudoElement_None
&& (complex->activeSubControls & QStyle::SC_ComboBoxEditField)
&& (!(state & QStyle::State_MouseOver))) {
state |= QStyle::State_Sunken;
}
if (!combo->frame)
extraClass |= PseudoClass_Frameless;
if (!combo->editable)
extraClass |= PseudoClass_ReadOnly;
else
extraClass |= PseudoClass_Editable;
#if QT_CONFIG(spinbox)
} else if (const QStyleOptionSpinBox *spin = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
if (!spin->frame)
extraClass |= PseudoClass_Frameless;
#endif // QT_CONFIG(spinbox)
} else if (const QStyleOptionGroupBox *gb = qstyleoption_cast<const QStyleOptionGroupBox *>(opt)) {
if (gb->features & QStyleOptionFrame::Flat)
extraClass |= PseudoClass_Flat;
if (gb->lineWidth == 0)
extraClass |= PseudoClass_Frameless;
} else if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
if (tb->titleBarState & Qt::WindowMinimized) {
extraClass |= PseudoClass_Minimized;
}
else if (tb->titleBarState & Qt::WindowMaximized)
extraClass |= PseudoClass_Maximized;
}
} else {
// handle simple style options
if (const QStyleOptionMenuItem *mi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
if (mi->menuItemType == QStyleOptionMenuItem::DefaultItem)
extraClass |= PseudoClass_Default;
if (mi->checkType == QStyleOptionMenuItem::Exclusive)
extraClass |= PseudoClass_Exclusive;
else if (mi->checkType == QStyleOptionMenuItem::NonExclusive)
extraClass |= PseudoClass_NonExclusive;
if (mi->checkType != QStyleOptionMenuItem::NotCheckable)
extraClass |= (mi->checked) ? (PseudoClass_On|PseudoClass_Checked)
: (PseudoClass_Off|PseudoClass_Unchecked);
} else if (const QStyleOptionHeader *hdr = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
if (hdr->position == QStyleOptionHeader::OnlyOneSection)
extraClass |= PseudoClass_OnlyOne;
else if (hdr->position == QStyleOptionHeader::Beginning)
extraClass |= PseudoClass_First;
else if (hdr->position == QStyleOptionHeader::End)
extraClass |= PseudoClass_Last;
else if (hdr->position == QStyleOptionHeader::Middle)
extraClass |= PseudoClass_Middle;
if (hdr->selectedPosition == QStyleOptionHeader::NextAndPreviousAreSelected)
extraClass |= (PseudoClass_NextSelected | PseudoClass_PreviousSelected);
else if (hdr->selectedPosition == QStyleOptionHeader::NextIsSelected)
extraClass |= PseudoClass_NextSelected;
else if (hdr->selectedPosition == QStyleOptionHeader::PreviousIsSelected)
extraClass |= PseudoClass_PreviousSelected;
#if QT_CONFIG(tabwidget)
} else if (const QStyleOptionTabWidgetFrame *tab = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
switch (tab->shape) {
case QTabBar::RoundedNorth:
case QTabBar::TriangularNorth:
extraClass |= PseudoClass_Top;
break;
case QTabBar::RoundedSouth:
case QTabBar::TriangularSouth:
extraClass |= PseudoClass_Bottom;
break;
case QTabBar::RoundedEast:
case QTabBar::TriangularEast:
extraClass |= PseudoClass_Left;
break;
case QTabBar::RoundedWest:
case QTabBar::TriangularWest:
extraClass |= PseudoClass_Right;
break;
default:
break;
}
#endif
#if QT_CONFIG(tabbar)
} else if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
if (tab->position == QStyleOptionTab::OnlyOneTab)
extraClass |= PseudoClass_OnlyOne;
else if (tab->position == QStyleOptionTab::Beginning)
extraClass |= PseudoClass_First;
else if (tab->position == QStyleOptionTab::End)
extraClass |= PseudoClass_Last;
else if (tab->position == QStyleOptionTab::Middle)
extraClass |= PseudoClass_Middle;
if (tab->selectedPosition == QStyleOptionTab::NextIsSelected)
extraClass |= PseudoClass_NextSelected;
else if (tab->selectedPosition == QStyleOptionTab::PreviousIsSelected)
extraClass |= PseudoClass_PreviousSelected;
switch (tab->shape) {
case QTabBar::RoundedNorth:
case QTabBar::TriangularNorth:
extraClass |= PseudoClass_Top;
break;
case QTabBar::RoundedSouth:
case QTabBar::TriangularSouth:
extraClass |= PseudoClass_Bottom;
break;
case QTabBar::RoundedEast:
case QTabBar::TriangularEast:
extraClass |= PseudoClass_Left;
break;
case QTabBar::RoundedWest:
case QTabBar::TriangularWest:
extraClass |= PseudoClass_Right;
break;
default:
break;
}
#endif // QT_CONFIG(tabbar)
} else if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
if (btn->features & QStyleOptionButton::Flat)
extraClass |= PseudoClass_Flat;
if (btn->features & QStyleOptionButton::DefaultButton)
extraClass |= PseudoClass_Default;
} else if (const QStyleOptionFrame *frm = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
if (frm->lineWidth == 0)
extraClass |= PseudoClass_Frameless;
if (frm->features & QStyleOptionFrame::Flat)
extraClass |= PseudoClass_Flat;
}
#ifndef QT_NO_TOOLBAR
else if (const QStyleOptionToolBar *tb = qstyleoption_cast<const QStyleOptionToolBar *>(opt)) {
if (tb->toolBarArea == Qt::LeftToolBarArea)
extraClass |= PseudoClass_Left;
else if (tb->toolBarArea == Qt::RightToolBarArea)
extraClass |= PseudoClass_Right;
else if (tb->toolBarArea == Qt::TopToolBarArea)
extraClass |= PseudoClass_Top;
else if (tb->toolBarArea == Qt::BottomToolBarArea)
extraClass |= PseudoClass_Bottom;
if (tb->positionWithinLine == QStyleOptionToolBar::Beginning)
extraClass |= PseudoClass_First;
else if (tb->positionWithinLine == QStyleOptionToolBar::Middle)
extraClass |= PseudoClass_Middle;
else if (tb->positionWithinLine == QStyleOptionToolBar::End)
extraClass |= PseudoClass_Last;
else if (tb->positionWithinLine == QStyleOptionToolBar::OnlyOne)
extraClass |= PseudoClass_OnlyOne;
}
#endif // QT_NO_TOOLBAR
#if QT_CONFIG(toolbox)
else if (const QStyleOptionToolBox *tb = qstyleoption_cast<const QStyleOptionToolBox *>(opt)) {
if (tb->position == QStyleOptionToolBox::OnlyOneTab)
extraClass |= PseudoClass_OnlyOne;
else if (tb->position == QStyleOptionToolBox::Beginning)
extraClass |= PseudoClass_First;
else if (tb->position == QStyleOptionToolBox::End)
extraClass |= PseudoClass_Last;
else if (tb->position == QStyleOptionToolBox::Middle)
extraClass |= PseudoClass_Middle;
if (tb->selectedPosition == QStyleOptionToolBox::NextIsSelected)
extraClass |= PseudoClass_NextSelected;
else if (tb->selectedPosition == QStyleOptionToolBox::PreviousIsSelected)
extraClass |= PseudoClass_PreviousSelected;
}
#endif // QT_CONFIG(toolbox)
#if QT_CONFIG(dockwidget)
else if (const QStyleOptionDockWidget *dw = qstyleoption_cast<const QStyleOptionDockWidget *>(opt)) {
if (dw->verticalTitleBar)
extraClass |= PseudoClass_Vertical;
else
extraClass |= PseudoClass_Horizontal;
if (dw->closable)
extraClass |= PseudoClass_Closable;
if (dw->floatable)
extraClass |= PseudoClass_Floatable;
if (dw->movable)
extraClass |= PseudoClass_Movable;
}
#endif // QT_CONFIG(dockwidget)
#if QT_CONFIG(itemviews)
else if (const QStyleOptionViewItem *vopt = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
if (vopt->features & QStyleOptionViewItem::Alternate)
extraClass |= PseudoClass_Alternate;
if (vopt->viewItemPosition == QStyleOptionViewItem::OnlyOne)
extraClass |= PseudoClass_OnlyOne;
else if (vopt->viewItemPosition == QStyleOptionViewItem::Beginning)
extraClass |= PseudoClass_First;
else if (vopt->viewItemPosition == QStyleOptionViewItem::End)
extraClass |= PseudoClass_Last;
else if (vopt->viewItemPosition == QStyleOptionViewItem::Middle)
extraClass |= PseudoClass_Middle;
}
#endif
#if QT_CONFIG(lineedit)
// LineEdit sets Sunken flag to indicate Sunken frame (argh)
if (const QLineEdit *lineEdit = qobject_cast<const QLineEdit *>(obj)) {
state &= ~QStyle::State_Sunken;
if (lineEdit->hasFrame()) {
extraClass &= ~PseudoClass_Frameless;
} else {
extraClass |= PseudoClass_Frameless;
}
} else
#endif
if (const QFrame *frm = qobject_cast<const QFrame *>(obj)) {
if (frm->lineWidth() == 0)
extraClass |= PseudoClass_Frameless;
}
}
return renderRule(obj, pseudoElement, pseudoClass(state) | extraClass);
}
bool QStyleSheetStyle::hasStyleRule(const QObject *obj, int part) const
{
QHash<int, bool> &cache = styleSheetCaches->hasStyleRuleCache[obj];
QHash<int, bool>::const_iterator cacheIt = cache.constFind(part);
if (cacheIt != cache.constEnd())
return cacheIt.value();
if (!initObject(obj))
return false;
const QVector<StyleRule> &rules = styleRules(obj);
if (part == PseudoElement_None) {
bool result = obj && !rules.isEmpty();
cache[part] = result;
return result;
}
QString pseudoElement = QLatin1String(knownPseudoElements[part].name);
for (int i = 0; i < rules.count(); i++) {
const Selector& selector = rules.at(i).selectors.at(0);
if (pseudoElement.compare(selector.pseudoElement(), Qt::CaseInsensitive) == 0) {
cache[part] = true;
return true;
}
}
cache[part] = false;
return false;
}
static Origin defaultOrigin(int pe)
{
switch (pe) {
case PseudoElement_ScrollBarAddPage:
case PseudoElement_ScrollBarSubPage:
case PseudoElement_ScrollBarAddLine:
case PseudoElement_ScrollBarSubLine:
case PseudoElement_ScrollBarFirst:
case PseudoElement_ScrollBarLast:
case PseudoElement_GroupBoxTitle:
case PseudoElement_GroupBoxIndicator: // never used
case PseudoElement_ToolButtonMenu:
case PseudoElement_SliderAddPage:
case PseudoElement_SliderSubPage:
return Origin_Border;
case PseudoElement_SpinBoxUpButton:
case PseudoElement_SpinBoxDownButton:
case PseudoElement_PushButtonMenuIndicator:
case PseudoElement_ComboBoxDropDown:
case PseudoElement_ToolButtonDownArrow:
case PseudoElement_MenuCheckMark:
case PseudoElement_MenuIcon:
case PseudoElement_MenuRightArrow:
return Origin_Padding;
case PseudoElement_Indicator:
case PseudoElement_ExclusiveIndicator:
case PseudoElement_ComboBoxArrow:
case PseudoElement_ScrollBarSlider:
case PseudoElement_ScrollBarUpArrow:
case PseudoElement_ScrollBarDownArrow:
case PseudoElement_ScrollBarLeftArrow:
case PseudoElement_ScrollBarRightArrow:
case PseudoElement_SpinBoxUpArrow:
case PseudoElement_SpinBoxDownArrow:
case PseudoElement_ToolButtonMenuArrow:
case PseudoElement_HeaderViewUpArrow:
case PseudoElement_HeaderViewDownArrow:
case PseudoElement_SliderGroove:
case PseudoElement_SliderHandle:
return Origin_Content;
default:
return Origin_Margin;
}
}
static Qt::Alignment defaultPosition(int pe)
{
switch (pe) {
case PseudoElement_Indicator:
case PseudoElement_ExclusiveIndicator:
case PseudoElement_MenuCheckMark:
case PseudoElement_MenuIcon:
return Qt::AlignLeft | Qt::AlignVCenter;
case PseudoElement_ScrollBarAddLine:
case PseudoElement_ScrollBarLast:
case PseudoElement_SpinBoxDownButton:
case PseudoElement_PushButtonMenuIndicator:
case PseudoElement_ToolButtonDownArrow:
return Qt::AlignRight | Qt::AlignBottom;
case PseudoElement_ScrollBarSubLine:
case PseudoElement_ScrollBarFirst:
case PseudoElement_SpinBoxUpButton:
case PseudoElement_ComboBoxDropDown:
case PseudoElement_ToolButtonMenu:
case PseudoElement_DockWidgetCloseButton:
case PseudoElement_DockWidgetFloatButton:
return Qt::AlignRight | Qt::AlignTop;
case PseudoElement_ScrollBarUpArrow:
case PseudoElement_ScrollBarDownArrow:
case PseudoElement_ScrollBarLeftArrow:
case PseudoElement_ScrollBarRightArrow:
case PseudoElement_SpinBoxUpArrow:
case PseudoElement_SpinBoxDownArrow:
case PseudoElement_ComboBoxArrow:
case PseudoElement_DownArrow:
case PseudoElement_ToolButtonMenuArrow:
case PseudoElement_SliderGroove:
return Qt::AlignCenter;
case PseudoElement_GroupBoxTitle:
case PseudoElement_GroupBoxIndicator: // never used
return Qt::AlignLeft | Qt::AlignTop;
case PseudoElement_HeaderViewUpArrow:
case PseudoElement_HeaderViewDownArrow:
case PseudoElement_MenuRightArrow:
return Qt::AlignRight | Qt::AlignVCenter;
default:
return 0;
}
}
QSize QStyleSheetStyle::defaultSize(const QWidget *w, QSize sz, const QRect& rect, int pe) const
{
QStyle *base = baseStyle();
switch (pe) {
case PseudoElement_Indicator:
case PseudoElement_MenuCheckMark:
if (sz.width() == -1)
sz.setWidth(base->pixelMetric(PM_IndicatorWidth, 0, w));
if (sz.height() == -1)
sz.setHeight(base->pixelMetric(PM_IndicatorHeight, 0, w));
break;
case PseudoElement_ExclusiveIndicator:
case PseudoElement_GroupBoxIndicator:
if (sz.width() == -1)
sz.setWidth(base->pixelMetric(PM_ExclusiveIndicatorWidth, 0, w));
if (sz.height() == -1)
sz.setHeight(base->pixelMetric(PM_ExclusiveIndicatorHeight, 0, w));
break;
case PseudoElement_PushButtonMenuIndicator: {
int pm = base->pixelMetric(PM_MenuButtonIndicator, 0, w);
if (sz.width() == -1)
sz.setWidth(pm);
if (sz.height() == -1)
sz.setHeight(pm);
}
break;
case PseudoElement_ComboBoxDropDown:
if (sz.width() == -1)
sz.setWidth(16);
break;
case PseudoElement_ComboBoxArrow:
case PseudoElement_DownArrow:
case PseudoElement_ToolButtonMenuArrow:
case PseudoElement_ToolButtonDownArrow:
case PseudoElement_MenuRightArrow:
if (sz.width() == -1)
sz.setWidth(13);
if (sz.height() == -1)
sz.setHeight(13);
break;
case PseudoElement_SpinBoxUpButton:
case PseudoElement_SpinBoxDownButton:
if (sz.width() == -1)
sz.setWidth(16);
if (sz.height() == -1)
sz.setHeight(rect.height()/2);
break;
case PseudoElement_ToolButtonMenu:
if (sz.width() == -1)
sz.setWidth(base->pixelMetric(PM_MenuButtonIndicator, 0, w));
break;
case PseudoElement_HeaderViewUpArrow:
case PseudoElement_HeaderViewDownArrow: {
int pm = base->pixelMetric(PM_HeaderMargin, 0, w);
if (sz.width() == -1)
sz.setWidth(pm);
if (sz.height() == 1)
sz.setHeight(pm);
break;
}
case PseudoElement_ScrollBarFirst:
case PseudoElement_ScrollBarLast:
case PseudoElement_ScrollBarAddLine:
case PseudoElement_ScrollBarSubLine:
case PseudoElement_ScrollBarSlider: {
int pm = pixelMetric(QStyle::PM_ScrollBarExtent, 0, w);
if (sz.width() == -1)
sz.setWidth(pm);
if (sz.height() == -1)
sz.setHeight(pm);
break;
}
case PseudoElement_DockWidgetCloseButton:
case PseudoElement_DockWidgetFloatButton: {
int iconSize = pixelMetric(PM_SmallIconSize, 0, w);
return QSize(iconSize, iconSize);
}
default:
break;
}
// expand to rectangle
if (sz.height() == -1)
sz.setHeight(rect.height());
if (sz.width() == -1)
sz.setWidth(rect.width());
return sz;
}
static PositionMode defaultPositionMode(int pe)
{
switch (pe) {
case PseudoElement_ScrollBarFirst:
case PseudoElement_ScrollBarLast:
case PseudoElement_ScrollBarAddLine:
case PseudoElement_ScrollBarSubLine:
case PseudoElement_ScrollBarAddPage:
case PseudoElement_ScrollBarSubPage:
case PseudoElement_ScrollBarSlider:
case PseudoElement_SliderGroove:
case PseudoElement_SliderHandle:
case PseudoElement_TabWidgetPane:
return PositionMode_Absolute;
default:
return PositionMode_Static;
}
}
QRect QStyleSheetStyle::positionRect(const QWidget *w, const QRenderRule &rule2, int pe,
const QRect &originRect, Qt::LayoutDirection dir) const
{
const QStyleSheetPositionData *p = rule2.position();
PositionMode mode = (p && p->mode != PositionMode_Unknown) ? p->mode : defaultPositionMode(pe);
Qt::Alignment position = (p && p->position != 0) ? p->position : defaultPosition(pe);
QRect r;
if (mode != PositionMode_Absolute) {
QSize sz = defaultSize(w, rule2.size(), originRect, pe);
sz = sz.expandedTo(rule2.minimumContentsSize());
r = QStyle::alignedRect(dir, position, sz, originRect);
if (p) {
int left = p->left ? p->left : -p->right;
int top = p->top ? p->top : -p->bottom;
r.translate(dir == Qt::LeftToRight ? left : -left, top);
}
} else {
r = p ? originRect.adjusted(dir == Qt::LeftToRight ? p->left : p->right, p->top,
dir == Qt::LeftToRight ? -p->right : -p->left, -p->bottom)
: originRect;
if (rule2.hasContentsSize()) {
QSize sz = rule2.size().expandedTo(rule2.minimumContentsSize());
if (sz.width() == -1) sz.setWidth(r.width());
if (sz.height() == -1) sz.setHeight(r.height());
r = QStyle::alignedRect(dir, position, sz, r);
}
}
return r;
}
QRect QStyleSheetStyle::positionRect(const QWidget *w, const QRenderRule& rule1, const QRenderRule& rule2, int pe,
const QRect& rect, Qt::LayoutDirection dir) const
{
const QStyleSheetPositionData *p = rule2.position();
Origin origin = (p && p->origin != Origin_Unknown) ? p->origin : defaultOrigin(pe);
QRect originRect = rule1.originRect(rect, origin);
return positionRect(w, rule2, pe, originRect, dir);
}
/** \internal
For widget that have an embedded widget (such as combobox) return that embedded widget.
otherwise return the widget itself
*/
static QWidget *embeddedWidget(QWidget *w)
{
#if QT_CONFIG(combobox)
if (QComboBox *cmb = qobject_cast<QComboBox *>(w)) {
if (cmb->isEditable())
return cmb->lineEdit();
else
return cmb;
}
#endif
#if QT_CONFIG(spinbox)
if (QAbstractSpinBox *sb = qobject_cast<QAbstractSpinBox *>(w))
return sb->findChild<QLineEdit *>();
#endif
#if QT_CONFIG(scrollarea)
if (QAbstractScrollArea *sa = qobject_cast<QAbstractScrollArea *>(w))
return sa->viewport();
#endif
return w;
}
/** \internal
in case w is an embedded widget, return the container widget
(i.e, the widget for which the rules actualy apply)
(exemple, if w is a lineedit embedded in a combobox, return the combobox)
if w is not embedded, return w itself
*/
static QWidget *containerWidget(const QWidget *w)
{
#if QT_CONFIG(lineedit)
if (qobject_cast<const QLineEdit *>(w)) {
//if the QLineEdit is an embeddedWidget, we need the rule of the real widget
#if QT_CONFIG(combobox)
if (qobject_cast<const QComboBox *>(w->parentWidget()))
return w->parentWidget();
#endif
#if QT_CONFIG(spinbox)
if (qobject_cast<const QAbstractSpinBox *>(w->parentWidget()))
return w->parentWidget();
#endif
}
#endif // QT_CONFIG(lineedit)
#if QT_CONFIG(scrollarea)
if (const QAbstractScrollArea *sa = qobject_cast<const QAbstractScrollArea *>(w->parentWidget())) {
if (sa->viewport() == w)
return w->parentWidget();
}
#endif
return const_cast<QWidget *>(w);
}
/** \internal
returns \c true if the widget can NOT be styled directly
*/
static bool unstylable(const QWidget *w)
{
if (w->windowType() == Qt::Desktop)
return true;
if (!w->styleSheet().isEmpty())
return false;
if (containerWidget(w) != w)
return true;
#ifndef QT_NO_FRAME
// detect QComboBoxPrivateContainer
else if (qobject_cast<const QFrame *>(w)) {
if (0
#if QT_CONFIG(combobox)
|| qobject_cast<const QComboBox *>(w->parentWidget())
#endif
)
return true;
}
#endif
#if QT_CONFIG(tabbar)
if (w->metaObject() == &QWidget::staticMetaObject
&& qobject_cast<const QTabBar*>(w->parentWidget()))
return true; // The moving tab of a QTabBar
#endif
return false;
}
static quint64 extendedPseudoClass(const QWidget *w)
{
quint64 pc = w->isWindow() ? quint64(PseudoClass_Window) : 0;
#if QT_CONFIG(abstractslider)
if (const QAbstractSlider *slider = qobject_cast<const QAbstractSlider *>(w)) {
pc |= ((slider->orientation() == Qt::Vertical) ? PseudoClass_Vertical : PseudoClass_Horizontal);
} else
#endif
#if QT_CONFIG(combobox)
if (const QComboBox *combo = qobject_cast<const QComboBox *>(w)) {
if (combo->isEditable())
pc |= (combo->isEditable() ? PseudoClass_Editable : PseudoClass_ReadOnly);
} else
#endif
#if QT_CONFIG(lineedit)
if (const QLineEdit *edit = qobject_cast<const QLineEdit *>(w)) {
pc |= (edit->isReadOnly() ? PseudoClass_ReadOnly : PseudoClass_Editable);
} else
#endif
{ } // required for the above ifdef'ery to work
return pc;
}
// sets up the geometry of the widget. We set a dynamic property when
// we modify the min/max size of the widget. The min/max size is restored
// to their original value when a new stylesheet that does not contain
// the CSS properties is set and when the widget has this dynamic property set.
// This way we don't trample on users who had setup a min/max size in code and
// don't use stylesheets at all.
void QStyleSheetStyle::setGeometry(QWidget *w)
{
QRenderRule rule = renderRule(w, PseudoElement_None, PseudoClass_Enabled | extendedPseudoClass(w));
const QStyleSheetGeometryData *geo = rule.geometry();
if (w->property("_q_stylesheet_minw").toBool()
&& ((!rule.hasGeometry() || geo->minWidth == -1))) {
w->setMinimumWidth(0);
w->setProperty("_q_stylesheet_minw", QVariant());
}
if (w->property("_q_stylesheet_minh").toBool()
&& ((!rule.hasGeometry() || geo->minHeight == -1))) {
w->setMinimumHeight(0);
w->setProperty("_q_stylesheet_minh", QVariant());
}
if (w->property("_q_stylesheet_maxw").toBool()
&& ((!rule.hasGeometry() || geo->maxWidth == -1))) {
w->setMaximumWidth(QWIDGETSIZE_MAX);
w->setProperty("_q_stylesheet_maxw", QVariant());
}
if (w->property("_q_stylesheet_maxh").toBool()
&& ((!rule.hasGeometry() || geo->maxHeight == -1))) {
w->setMaximumHeight(QWIDGETSIZE_MAX);
w->setProperty("_q_stylesheet_maxh", QVariant());
}
if (rule.hasGeometry()) {
if (geo->minWidth != -1) {
w->setProperty("_q_stylesheet_minw", true);
w->setMinimumWidth(rule.boxSize(QSize(qMax(geo->width, geo->minWidth), 0)).width());
}
if (geo->minHeight != -1) {
w->setProperty("_q_stylesheet_minh", true);
w->setMinimumHeight(rule.boxSize(QSize(0, qMax(geo->height, geo->minHeight))).height());
}
if (geo->maxWidth != -1) {
w->setProperty("_q_stylesheet_maxw", true);
w->setMaximumWidth(rule.boxSize(QSize(qMin(geo->width == -1 ? QWIDGETSIZE_MAX : geo->width,
geo->maxWidth == -1 ? QWIDGETSIZE_MAX : geo->maxWidth), 0)).width());
}
if (geo->maxHeight != -1) {
w->setProperty("_q_stylesheet_maxh", true);
w->setMaximumHeight(rule.boxSize(QSize(0, qMin(geo->height == -1 ? QWIDGETSIZE_MAX : geo->height,
geo->maxHeight == -1 ? QWIDGETSIZE_MAX : geo->maxHeight))).height());
}
}
}
void QStyleSheetStyle::setProperties(QWidget *w)
{
// The final occurrence of each property is authoritative.
// Set value for each property in the order of property final occurrence
// since properties interact.
const QVector<Declaration> decls = declarations(styleRules(w), QString());
QVector<int> finals; // indices in reverse order of each property's final occurrence
{
// scan decls for final occurrence of each "qproperty"
QSet<const QString> propertySet;
for (int i = decls.count() - 1; i >= 0; --i) {
const QString property = decls.at(i).d->property;
if (!property.startsWith(QLatin1String("qproperty-"), Qt::CaseInsensitive))
continue;
if (!propertySet.contains(property)) {
propertySet.insert(property);
finals.append(i);
}
}
}
for (int i = finals.count() - 1; i >= 0; --i) {
const Declaration &decl = decls.at(finals[i]);
QString property = decl.d->property;
property.remove(0, 10); // strip "qproperty-"
const QMetaObject *metaObject = w->metaObject();
int index = metaObject->indexOfProperty(property.toLatin1());
if (Q_UNLIKELY(index == -1)) {
qWarning() << w << " does not have a property named " << property;
continue;
}
const QMetaProperty metaProperty = metaObject->property(index);
if (Q_UNLIKELY(!metaProperty.isWritable() || !metaProperty.isDesignable())) {
qWarning() << w << " cannot design property named " << property;
continue;
}
QVariant v;
const QVariant value = w->property(property.toLatin1());
switch (value.type()) {
case QVariant::Icon: v = decl.iconValue(); break;
case QVariant::Image: v = QImage(decl.uriValue()); break;
case QVariant::Pixmap: v = QPixmap(decl.uriValue()); break;
case QVariant::Rect: v = decl.rectValue(); break;
case QVariant::Size: v = decl.sizeValue(); break;
case QVariant::Color: v = decl.colorValue(); break;
case QVariant::Brush: v = decl.brushValue(); break;
#ifndef QT_NO_SHORTCUT
case QVariant::KeySequence: v = QKeySequence(decl.d->values.at(0).variant.toString()); break;
#endif
default: v = decl.d->values.at(0).variant; break;
}
w->setProperty(property.toLatin1(), v);
}
}
void QStyleSheetStyle::setPalette(QWidget *w)
{
struct RuleRoleMap {
int state;
QPalette::ColorGroup group;
} map[3] = {
{ int(PseudoClass_Active | PseudoClass_Enabled), QPalette::Active },
{ PseudoClass_Disabled, QPalette::Disabled },
{ PseudoClass_Enabled, QPalette::Inactive }
};
const bool useStyleSheetPropagationInWidgetStyles =
QCoreApplication::testAttribute(Qt::AA_UseStyleSheetPropagationInWidgetStyles);
QPalette p;
if (!useStyleSheetPropagationInWidgetStyles)
p = w->palette();
QWidget *ew = embeddedWidget(w);
for (int i = 0; i < 3; i++) {
QRenderRule rule = renderRule(w, PseudoElement_None, map[i].state | extendedPseudoClass(w));
if (i == 0) {
if (!w->property("_q_styleSheetWidgetFont").isValid()) {
saveWidgetFont(w, w->font());
}
updateStyleSheetFont(w);
if (ew != w)
updateStyleSheetFont(ew);
}
rule.configurePalette(&p, map[i].group, ew, ew != w);
}
if (!useStyleSheetPropagationInWidgetStyles || p.resolve() != 0) {
QPalette wp = w->palette();
styleSheetCaches->customPaletteWidgets.insert(w, {wp, p.resolve()});
if (useStyleSheetPropagationInWidgetStyles) {
p = p.resolve(wp);
p.resolve(p.resolve() | wp.resolve());
}
w->setPalette(p);
if (ew != w)
ew->setPalette(p);
}
}
void QStyleSheetStyle::unsetPalette(QWidget *w)
{
const bool useStyleSheetPropagationInWidgetStyles =
QCoreApplication::testAttribute(Qt::AA_UseStyleSheetPropagationInWidgetStyles);
const auto it = styleSheetCaches->customPaletteWidgets.find(w);
if (it != styleSheetCaches->customPaletteWidgets.end()) {
auto customizedPalette = std::move(*it);
styleSheetCaches->customPaletteWidgets.erase(it);
QPalette original;
if (useStyleSheetPropagationInWidgetStyles)
original = std::move(customizedPalette).reverted(w->palette());
else
original = customizedPalette.oldWidgetValue;
w->setPalette(original);
QWidget *ew = embeddedWidget(w);
if (ew != w)
ew->setPalette(original);
}
if (useStyleSheetPropagationInWidgetStyles) {
unsetStyleSheetFont(w);
QWidget *ew = embeddedWidget(w);
if (ew != w)
unsetStyleSheetFont(ew);
} else {
QVariant oldFont = w->property("_q_styleSheetWidgetFont");
if (oldFont.isValid()) {
w->setFont(qvariant_cast<QFont>(oldFont));
}
}
if (styleSheetCaches->autoFillDisabledWidgets.contains(w)) {
embeddedWidget(w)->setAutoFillBackground(true);
styleSheetCaches->autoFillDisabledWidgets.remove(w);
}
}
void QStyleSheetStyle::unsetStyleSheetFont(QWidget *w) const
{
const auto it = styleSheetCaches->customFontWidgets.find(w);
if (it != styleSheetCaches->customFontWidgets.end()) {
auto customizedFont = std::move(*it);
styleSheetCaches->customFontWidgets.erase(it);
w->setFont(std::move(customizedFont).reverted(w->font()));
}
}
static void updateObjects(const QList<const QObject *>& objects)
{
if (!styleSheetCaches->styleRulesCache.isEmpty() || !styleSheetCaches->hasStyleRuleCache.isEmpty() || !styleSheetCaches->renderRulesCache.isEmpty()) {
for (int i = 0; i < objects.size(); ++i) {
const QObject *object = objects.at(i);
styleSheetCaches->styleRulesCache.remove(object);
styleSheetCaches->hasStyleRuleCache.remove(object);
styleSheetCaches->renderRulesCache.remove(object);
}
}
QWidgetList widgets;
foreach (const QObject *object, objects) {
if (QWidget *w = qobject_cast<QWidget*>(const_cast<QObject*>(object)))
widgets << w;
}
QEvent event(QEvent::StyleChange);
foreach (QWidget *widget, widgets) {
widget->style()->polish(widget);
QApplication::sendEvent(widget, &event);
}
}
/////////////////////////////////////////////////////////////////////////////////////////
// The stylesheet style
int QStyleSheetStyle::numinstances = 0;
QStyleSheetStyle::QStyleSheetStyle(QStyle *base)
: QWindowsStyle(*new QStyleSheetStylePrivate), base(base), refcount(1)
{
++numinstances;
if (numinstances == 1) {
styleSheetCaches = new QStyleSheetStyleCaches;
}
}
QStyleSheetStyle::~QStyleSheetStyle()
{
--numinstances;
if (numinstances == 0) {
delete styleSheetCaches;
}
}
QStyle *QStyleSheetStyle::baseStyle() const
{
if (base)
return base;
if (QStyleSheetStyle *me = qobject_cast<QStyleSheetStyle *>(QApplication::style()))
return me->base;
return QApplication::style();
}
void QStyleSheetStyleCaches::objectDestroyed(QObject *o)
{
styleRulesCache.remove(o);
hasStyleRuleCache.remove(o);
renderRulesCache.remove(o);
customPaletteWidgets.remove((const QWidget *)o);
customFontWidgets.remove(static_cast<QWidget *>(o));
styleSheetCache.remove(o);
autoFillDisabledWidgets.remove((const QWidget *)o);
}
void QStyleSheetStyleCaches::styleDestroyed(QObject *o)
{
styleSheetCache.remove(o);
}
/*!
* Make sure that the cache will be clean by connecting destroyed if needed.
* return false if the widget is not stylable;
*/
bool QStyleSheetStyle::initObject(const QObject *obj) const
{
if (!obj)
return false;
if (const QWidget *w = qobject_cast<const QWidget*>(obj)) {
if (w->testAttribute(Qt::WA_StyleSheet))
return true;
if (unstylable(w))
return false;
const_cast<QWidget *>(w)->setAttribute(Qt::WA_StyleSheet, true);
}
QObject::connect(obj, SIGNAL(destroyed(QObject*)), styleSheetCaches, SLOT(objectDestroyed(QObject*)), Qt::UniqueConnection);
return true;
}
void QStyleSheetStyle::polish(QWidget *w)
{
baseStyle()->polish(w);
RECURSION_GUARD(return)
if (!initObject(w))
return;
if (styleSheetCaches->styleRulesCache.contains(w)) {
// the widget accessed its style pointer before polish (or repolish)
// (exemple: the QAbstractSpinBox constructor ask for the stylehint)
styleSheetCaches->styleRulesCache.remove(w);
styleSheetCaches->hasStyleRuleCache.remove(w);
styleSheetCaches->renderRulesCache.remove(w);
styleSheetCaches->styleSheetCache.remove(w);
}
setGeometry(w);
setProperties(w);
unsetPalette(w);
setPalette(w);
//set the WA_Hover attribute if one of the selector depends of the hover state
QVector<StyleRule> rules = styleRules(w);
for (int i = 0; i < rules.count(); i++) {
const Selector& selector = rules.at(i).selectors.at(0);
quint64 negated = 0;
quint64 cssClass = selector.pseudoClass(&negated);
if ( cssClass & PseudoClass_Hover || negated & PseudoClass_Hover) {
w->setAttribute(Qt::WA_Hover);
embeddedWidget(w)->setAttribute(Qt::WA_Hover);
}
}
#if QT_CONFIG(scrollarea)
if (QAbstractScrollArea *sa = qobject_cast<QAbstractScrollArea *>(w)) {
QRenderRule rule = renderRule(sa, PseudoElement_None, PseudoClass_Enabled);
if ((rule.hasBorder() && rule.border()->hasBorderImage())
|| (rule.hasBackground() && !rule.background()->pixmap.isNull())) {
QObject::connect(sa->horizontalScrollBar(), SIGNAL(valueChanged(int)),
sa, SLOT(update()), Qt::UniqueConnection);
QObject::connect(sa->verticalScrollBar(), SIGNAL(valueChanged(int)),
sa, SLOT(update()), Qt::UniqueConnection);
}
}
#endif
QRenderRule rule = renderRule(w, PseudoElement_None, PseudoClass_Any);
if (rule.hasDrawable() || rule.hasBox()) {
if (w->metaObject() == &QWidget::staticMetaObject
#if QT_CONFIG(itemviews)
|| qobject_cast<QHeaderView *>(w)
#endif
#if QT_CONFIG(tabbar)
|| qobject_cast<QTabBar *>(w)
#endif
#ifndef QT_NO_FRAME
|| qobject_cast<QFrame *>(w)
#endif
#if QT_CONFIG(mainwindow)
|| qobject_cast<QMainWindow *>(w)
#endif
#if QT_CONFIG(mdiarea)
|| qobject_cast<QMdiSubWindow *>(w)
#endif
#if QT_CONFIG(menubar)
|| qobject_cast<QMenuBar *>(w)
#endif
#if QT_CONFIG(dialog)
|| qobject_cast<QDialog *>(w)
#endif
) {
w->setAttribute(Qt::WA_StyledBackground, true);
}
QWidget *ew = embeddedWidget(w);
if (ew->autoFillBackground()) {
ew->setAutoFillBackground(false);
styleSheetCaches->autoFillDisabledWidgets.insert(w);
if (ew != w) { //eg. viewport of a scrollarea
//(in order to draw the background anyway in case we don't.)
ew->setAttribute(Qt::WA_StyledBackground, true);
}
}
if (!rule.hasBackground() || rule.background()->isTransparent() || rule.hasBox()
|| (!rule.hasNativeBorder() && !rule.border()->isOpaque()))
w->setAttribute(Qt::WA_OpaquePaintEvent, false);
}
}
void QStyleSheetStyle::polish(QApplication *app)
{
baseStyle()->polish(app);
}
void QStyleSheetStyle::polish(QPalette &pal)
{
baseStyle()->polish(pal);
}
void QStyleSheetStyle::repolish(QWidget *w)
{
QList<const QObject *> children = w->findChildren<const QObject *>(QString());
children.append(w);
styleSheetCaches->styleSheetCache.remove(w);
updateObjects(children);
}
void QStyleSheetStyle::repolish(QApplication *app)
{
Q_UNUSED(app);
const QList<const QObject*> allObjects = styleSheetCaches->styleRulesCache.keys();
styleSheetCaches->styleSheetCache.remove(qApp);
styleSheetCaches->styleRulesCache.clear();
styleSheetCaches->hasStyleRuleCache.clear();
styleSheetCaches->renderRulesCache.clear();
updateObjects(allObjects);
}
void QStyleSheetStyle::unpolish(QWidget *w)
{
if (!w || !w->testAttribute(Qt::WA_StyleSheet)) {
baseStyle()->unpolish(w);
return;
}
styleSheetCaches->styleRulesCache.remove(w);
styleSheetCaches->hasStyleRuleCache.remove(w);
styleSheetCaches->renderRulesCache.remove(w);
styleSheetCaches->styleSheetCache.remove(w);
unsetPalette(w);
w->setProperty("_q_stylesheet_minw", QVariant());
w->setProperty("_q_stylesheet_minh", QVariant());
w->setProperty("_q_stylesheet_maxw", QVariant());
w->setProperty("_q_stylesheet_maxh", QVariant());
w->setAttribute(Qt::WA_StyleSheet, false);
QObject::disconnect(w, 0, this, 0);
#if QT_CONFIG(scrollarea)
if (QAbstractScrollArea *sa = qobject_cast<QAbstractScrollArea *>(w)) {
QObject::disconnect(sa->horizontalScrollBar(), SIGNAL(valueChanged(int)),
sa, SLOT(update()));
QObject::disconnect(sa->verticalScrollBar(), SIGNAL(valueChanged(int)),
sa, SLOT(update()));
}
#endif
baseStyle()->unpolish(w);
}
void QStyleSheetStyle::unpolish(QApplication *app)
{
baseStyle()->unpolish(app);
RECURSION_GUARD(return)
styleSheetCaches->styleRulesCache.clear();
styleSheetCaches->hasStyleRuleCache.clear();
styleSheetCaches->renderRulesCache.clear();
styleSheetCaches->styleSheetCache.remove(qApp);
}
#if QT_CONFIG(tabbar)
inline static bool verticalTabs(QTabBar::Shape shape)
{
return shape == QTabBar::RoundedWest
|| shape == QTabBar::RoundedEast
|| shape == QTabBar::TriangularWest
|| shape == QTabBar::TriangularEast;
}
#endif // QT_CONFIG(tabbar)
void QStyleSheetStyle::drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p,
const QWidget *w) const
{
RECURSION_GUARD(baseStyle()->drawComplexControl(cc, opt, p, w); return)
QRenderRule rule = renderRule(w, opt);
switch (cc) {
case CC_ComboBox:
if (const QStyleOptionComboBox *cmb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
QStyleOptionComboBox cmbOpt(*cmb);
cmbOpt.rect = rule.borderRect(opt->rect);
if (rule.hasNativeBorder()) {
rule.drawBackgroundImage(p, cmbOpt.rect);
rule.configurePalette(&cmbOpt.palette, QPalette::ButtonText, QPalette::Button);
bool customDropDown = (opt->subControls & QStyle::SC_ComboBoxArrow)
&& (hasStyleRule(w, PseudoElement_ComboBoxDropDown) || hasStyleRule(w, PseudoElement_ComboBoxArrow));
if (customDropDown)
cmbOpt.subControls &= ~QStyle::SC_ComboBoxArrow;
if (rule.baseStyleCanDraw()) {
baseStyle()->drawComplexControl(cc, &cmbOpt, p, w);
} else {
QWindowsStyle::drawComplexControl(cc, &cmbOpt, p, w);
}
if (!customDropDown)
return;
} else {
rule.drawRule(p, opt->rect);
}
if (opt->subControls & QStyle::SC_ComboBoxArrow) {
QRenderRule subRule = renderRule(w, opt, PseudoElement_ComboBoxDropDown);
if (subRule.hasDrawable()) {
QRect r = subControlRect(CC_ComboBox, opt, SC_ComboBoxArrow, w);
subRule.drawRule(p, r);
QRenderRule subRule2 = renderRule(w, opt, PseudoElement_ComboBoxArrow);
r = positionRect(w, subRule, subRule2, PseudoElement_ComboBoxArrow, r, opt->direction);
subRule2.drawRule(p, r);
} else {
cmbOpt.subControls = QStyle::SC_ComboBoxArrow;
QWindowsStyle::drawComplexControl(cc, &cmbOpt, p, w);
}
}
return;
}
break;
#if QT_CONFIG(spinbox)
case CC_SpinBox:
if (const QStyleOptionSpinBox *spin = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
QStyleOptionSpinBox spinOpt(*spin);
rule.configurePalette(&spinOpt.palette, QPalette::ButtonText, QPalette::Button);
rule.configurePalette(&spinOpt.palette, QPalette::Text, QPalette::Base);
spinOpt.rect = rule.borderRect(opt->rect);
bool customUp = true, customDown = true;
QRenderRule upRule = renderRule(w, opt, PseudoElement_SpinBoxUpButton);
QRenderRule downRule = renderRule(w, opt, PseudoElement_SpinBoxDownButton);
bool upRuleMatch = upRule.hasGeometry() || upRule.hasPosition();
bool downRuleMatch = downRule.hasGeometry() || downRule.hasPosition();
if (rule.hasNativeBorder() && !upRuleMatch && !downRuleMatch) {
rule.drawBackgroundImage(p, spinOpt.rect);
customUp = (opt->subControls & QStyle::SC_SpinBoxUp)
&& (hasStyleRule(w, PseudoElement_SpinBoxUpButton) || hasStyleRule(w, PseudoElement_UpArrow));
if (customUp)
spinOpt.subControls &= ~QStyle::SC_SpinBoxUp;
customDown = (opt->subControls & QStyle::SC_SpinBoxDown)
&& (hasStyleRule(w, PseudoElement_SpinBoxDownButton) || hasStyleRule(w, PseudoElement_DownArrow));
if (customDown)
spinOpt.subControls &= ~QStyle::SC_SpinBoxDown;
if (rule.baseStyleCanDraw()) {
baseStyle()->drawComplexControl(cc, &spinOpt, p, w);
} else {
QWindowsStyle::drawComplexControl(cc, &spinOpt, p, w);
}
if (!customUp && !customDown)
return;
} else {
rule.drawRule(p, opt->rect);
}
if ((opt->subControls & QStyle::SC_SpinBoxUp) && customUp) {
QRenderRule subRule = renderRule(w, opt, PseudoElement_SpinBoxUpButton);
if (subRule.hasDrawable()) {
QRect r = subControlRect(CC_SpinBox, opt, SC_SpinBoxUp, w);
subRule.drawRule(p, r);
QRenderRule subRule2 = renderRule(w, opt, PseudoElement_SpinBoxUpArrow);
r = positionRect(w, subRule, subRule2, PseudoElement_SpinBoxUpArrow, r, opt->direction);
subRule2.drawRule(p, r);
} else {
spinOpt.subControls = QStyle::SC_SpinBoxUp;
QWindowsStyle::drawComplexControl(cc, &spinOpt, p, w);
}
}
if ((opt->subControls & QStyle::SC_SpinBoxDown) && customDown) {
QRenderRule subRule = renderRule(w, opt, PseudoElement_SpinBoxDownButton);
if (subRule.hasDrawable()) {
QRect r = subControlRect(CC_SpinBox, opt, SC_SpinBoxDown, w);
subRule.drawRule(p, r);
QRenderRule subRule2 = renderRule(w, opt, PseudoElement_SpinBoxDownArrow);
r = positionRect(w, subRule, subRule2, PseudoElement_SpinBoxDownArrow, r, opt->direction);
subRule2.drawRule(p, r);
} else {
spinOpt.subControls = QStyle::SC_SpinBoxDown;
QWindowsStyle::drawComplexControl(cc, &spinOpt, p, w);
}
}
return;
}
break;
#endif // QT_CONFIG(spinbox)
case CC_GroupBox:
if (const QStyleOptionGroupBox *gb = qstyleoption_cast<const QStyleOptionGroupBox *>(opt)) {
QRect labelRect, checkBoxRect, titleRect, frameRect;
bool hasTitle = (gb->subControls & QStyle::SC_GroupBoxCheckBox) || !gb->text.isEmpty();
if (!rule.hasDrawable() && (!hasTitle || !hasStyleRule(w, PseudoElement_GroupBoxTitle))
&& !hasStyleRule(w, PseudoElement_Indicator) && !rule.hasBox() && !rule.hasFont && !rule.hasPalette()) {
// let the native style draw the combobox if there is no style for it.
break;
}
rule.drawBackground(p, opt->rect);
QRenderRule titleRule = renderRule(w, opt, PseudoElement_GroupBoxTitle);
bool clipSet = false;
if (hasTitle) {
labelRect = subControlRect(CC_GroupBox, opt, SC_GroupBoxLabel, w);
//Some native style (such as mac) may return a too small rectangle (because they use smaller fonts), so we may need to expand it a little bit.
labelRect.setSize(labelRect.size().expandedTo(ParentStyle::subControlRect(CC_GroupBox, opt, SC_GroupBoxLabel, w).size()));
if (gb->subControls & QStyle::SC_GroupBoxCheckBox) {
checkBoxRect = subControlRect(CC_GroupBox, opt, SC_GroupBoxCheckBox, w);
titleRect = titleRule.boxRect(checkBoxRect.united(labelRect));
} else {
titleRect = titleRule.boxRect(labelRect);
}
if (!titleRule.hasBackground() || !titleRule.background()->isTransparent()) {
clipSet = true;
p->save();
p->setClipRegion(QRegion(opt->rect) - titleRect);
}
}
frameRect = subControlRect(CC_GroupBox, opt, SC_GroupBoxFrame, w);
QStyleOptionFrame frame;
frame.QStyleOption::operator=(*gb);
frame.features = gb->features;
frame.lineWidth = gb->lineWidth;
frame.midLineWidth = gb->midLineWidth;
frame.rect = frameRect;
drawPrimitive(PE_FrameGroupBox, &frame, p, w);
if (clipSet)
p->restore();
// draw background and frame of the title
if (hasTitle)
titleRule.drawRule(p, titleRect);
// draw the indicator
if (gb->subControls & QStyle::SC_GroupBoxCheckBox) {
QStyleOptionButton box;
box.QStyleOption::operator=(*gb);
box.rect = checkBoxRect;
drawPrimitive(PE_IndicatorCheckBox, &box, p, w);
}
// draw the text
if (!gb->text.isEmpty()) {
int alignment = int(Qt::AlignCenter | Qt::TextShowMnemonic);
if (!styleHint(QStyle::SH_UnderlineShortcut, opt, w)) {
alignment |= Qt::TextHideMnemonic;
}
QPalette pal = gb->palette;
if (gb->textColor.isValid())
pal.setColor(QPalette::WindowText, gb->textColor);
titleRule.configurePalette(&pal, QPalette::WindowText, QPalette::Window);
drawItemText(p, labelRect, alignment, pal, gb->state & State_Enabled,
gb->text, QPalette::WindowText);
if (gb->state & State_HasFocus) {
QStyleOptionFocusRect fropt;
fropt.QStyleOption::operator=(*gb);
fropt.rect = labelRect;
drawPrimitive(PE_FrameFocusRect, &fropt, p, w);
}
}
return;
}
break;
case CC_ToolButton:
if (const QStyleOptionToolButton *tool = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) {
QStyleOptionToolButton toolOpt(*tool);
rule.configurePalette(&toolOpt.palette, QPalette::ButtonText, QPalette::Button);
toolOpt.font = rule.font.resolve(toolOpt.font);
toolOpt.rect = rule.borderRect(opt->rect);
bool customArrow = (tool->features & (QStyleOptionToolButton::HasMenu | QStyleOptionToolButton::MenuButtonPopup));
bool customDropDown = tool->features & QStyleOptionToolButton::MenuButtonPopup;
if (rule.hasNativeBorder()) {
if (tool->subControls & SC_ToolButton) {
//in some case (eg. the button is "auto raised") the style doesn't draw the background
//so we need to draw the background.
// use the same condition as in QCommonStyle
State bflags = tool->state & ~State_Sunken;
if (bflags & State_AutoRaise && (!(bflags & State_MouseOver) || !(bflags & State_Enabled)))
bflags &= ~State_Raised;
if (tool->state & State_Sunken && tool->activeSubControls & SC_ToolButton)
bflags |= State_Sunken;
if (!(bflags & (State_Sunken | State_On | State_Raised)))
rule.drawBackground(p, toolOpt.rect);
}
customArrow = customArrow && hasStyleRule(w, PseudoElement_ToolButtonDownArrow);
if (customArrow)
toolOpt.features &= ~QStyleOptionToolButton::HasMenu;
customDropDown = customDropDown && hasStyleRule(w, PseudoElement_ToolButtonMenu);
if (customDropDown)
toolOpt.subControls &= ~QStyle::SC_ToolButtonMenu;
if (rule.baseStyleCanDraw() && !(tool->features & QStyleOptionToolButton::Arrow)) {
baseStyle()->drawComplexControl(cc, &toolOpt, p, w);
} else {
QWindowsStyle::drawComplexControl(cc, &toolOpt, p, w);
}
if (!customArrow && !customDropDown)
return;
} else {
rule.drawRule(p, opt->rect);
toolOpt.rect = rule.contentsRect(opt->rect);
if (rule.hasFont)
toolOpt.font = rule.font;
drawControl(CE_ToolButtonLabel, &toolOpt, p, w);
}
QRenderRule subRule = renderRule(w, opt, PseudoElement_ToolButtonMenu);
QRect r = subControlRect(CC_ToolButton, opt, QStyle::SC_ToolButtonMenu, w);
if (customDropDown) {
if (opt->subControls & QStyle::SC_ToolButtonMenu) {
if (subRule.hasDrawable()) {
subRule.drawRule(p, r);
} else {
toolOpt.rect = r;
baseStyle()->drawPrimitive(PE_IndicatorButtonDropDown, &toolOpt, p, w);
}
}
}
if (customArrow) {
QRenderRule subRule2 = customDropDown ? renderRule(w, opt, PseudoElement_ToolButtonMenuArrow)
: renderRule(w, opt, PseudoElement_ToolButtonDownArrow);
QRect r2 = customDropDown
? positionRect(w, subRule, subRule2, PseudoElement_ToolButtonMenuArrow, r, opt->direction)
: positionRect(w, rule, subRule2, PseudoElement_ToolButtonDownArrow, opt->rect, opt->direction);
if (subRule2.hasDrawable()) {
subRule2.drawRule(p, r2);
} else {
toolOpt.rect = r2;
baseStyle()->drawPrimitive(QStyle::PE_IndicatorArrowDown, &toolOpt, p, w);
}
}
return;
}
break;
#if QT_CONFIG(scrollbar)
case CC_ScrollBar:
if (const QStyleOptionSlider *sb = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
QStyleOptionSlider sbOpt(*sb);
if (!rule.hasDrawable()) {
sbOpt.rect = rule.borderRect(opt->rect);
rule.drawBackgroundImage(p, opt->rect);
baseStyle()->drawComplexControl(cc, &sbOpt, p, w);
} else {
rule.drawRule(p, opt->rect);
QWindowsStyle::drawComplexControl(cc, opt, p, w);
}
return;
}
break;
#endif // QT_CONFIG(scrollbar)
#if QT_CONFIG(slider)
case CC_Slider:
if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
rule.drawRule(p, opt->rect);
QRenderRule grooveSubRule = renderRule(w, opt, PseudoElement_SliderGroove);
QRenderRule handleSubRule = renderRule(w, opt, PseudoElement_SliderHandle);
if (!grooveSubRule.hasDrawable()) {
QStyleOptionSlider slOpt(*slider);
bool handleHasRule = handleSubRule.hasDrawable();
// If the style specifies a different handler rule, draw the groove without the handler.
if (handleHasRule)
slOpt.subControls &= ~SC_SliderHandle;
baseStyle()->drawComplexControl(cc, &slOpt, p, w);
if (!handleHasRule)
return;
}
QRect gr = subControlRect(cc, opt, SC_SliderGroove, w);
if (slider->subControls & SC_SliderGroove) {
grooveSubRule.drawRule(p, gr);
}
if (slider->subControls & SC_SliderHandle) {
QRect hr = subControlRect(cc, opt, SC_SliderHandle, w);
QRenderRule subRule1 = renderRule(w, opt, PseudoElement_SliderSubPage);
if (subRule1.hasDrawable()) {
QRect r(gr.topLeft(),
slider->orientation == Qt::Horizontal
? QPoint(hr.x()+hr.width()/2, gr.y()+gr.height() - 1)
: QPoint(gr.x()+gr.width() - 1, hr.y()+hr.height()/2));
subRule1.drawRule(p, r);
}
QRenderRule subRule2 = renderRule(w, opt, PseudoElement_SliderAddPage);
if (subRule2.hasDrawable()) {
QRect r(slider->orientation == Qt::Horizontal
? QPoint(hr.x()+hr.width()/2+1, gr.y())
: QPoint(gr.x(), hr.y()+hr.height()/2+1),
gr.bottomRight());
subRule2.drawRule(p, r);
}
handleSubRule.drawRule(p, handleSubRule.boxRect(hr, Margin));
}
if (slider->subControls & SC_SliderTickmarks) {
// TODO...
}
return;
}
break;
#endif // QT_CONFIG(slider)
case CC_MdiControls:
if (hasStyleRule(w, PseudoElement_MdiCloseButton)
|| hasStyleRule(w, PseudoElement_MdiNormalButton)
|| hasStyleRule(w, PseudoElement_MdiMinButton)) {
QList<QVariant> layout = rule.styleHint(QLatin1String("button-layout")).toList();
if (layout.isEmpty())
layout = subControlLayout(QLatin1String("mNX"));
QStyleOptionComplex optCopy(*opt);
optCopy.subControls = 0;
for (int i = 0; i < layout.count(); i++) {
int layoutButton = layout[i].toInt();
if (layoutButton < PseudoElement_MdiCloseButton
|| layoutButton > PseudoElement_MdiNormalButton)
continue;
QStyle::SubControl control = knownPseudoElements[layoutButton].subControl;
if (!(opt->subControls & control))
continue;
QRenderRule subRule = renderRule(w, opt, layoutButton);
if (subRule.hasDrawable()) {
QRect rect = subRule.boxRect(subControlRect(CC_MdiControls, opt, control, w), Margin);
subRule.drawRule(p, rect);
QIcon icon = standardIcon(subControlIcon(layoutButton), opt);
icon.paint(p, subRule.contentsRect(rect), Qt::AlignCenter);
} else {
optCopy.subControls |= control;
}
}
if (optCopy.subControls)
baseStyle()->drawComplexControl(CC_MdiControls, &optCopy, p, w);
return;
}
break;
case CC_TitleBar:
if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
QRenderRule subRule = renderRule(w, opt, PseudoElement_TitleBar);
if (!subRule.hasDrawable() && !subRule.hasBox() && !subRule.hasBorder())
break;
subRule.drawRule(p, opt->rect);
QHash<QStyle::SubControl, QRect> layout = titleBarLayout(w, tb);
QRect ir;
ir = layout[SC_TitleBarLabel];
if (ir.isValid()) {
if (subRule.hasPalette())
p->setPen(subRule.palette()->foreground.color());
p->fillRect(ir, Qt::white);
p->drawText(ir.x(), ir.y(), ir.width(), ir.height(), Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine, tb->text);
}
QPixmap pm;
ir = layout[SC_TitleBarSysMenu];
if (ir.isValid()) {
QRenderRule subSubRule = renderRule(w, opt, PseudoElement_TitleBarSysMenu);
subSubRule.drawRule(p, ir);
ir = subSubRule.contentsRect(ir);
if (!tb->icon.isNull()) {
tb->icon.paint(p, ir);
} else {
int iconSize = pixelMetric(PM_SmallIconSize, tb, w);
pm = standardIcon(SP_TitleBarMenuButton, 0, w).pixmap(iconSize, iconSize);
drawItemPixmap(p, ir, Qt::AlignCenter, pm);
}
}
ir = layout[SC_TitleBarCloseButton];
if (ir.isValid()) {
QRenderRule subSubRule = renderRule(w, opt, PseudoElement_TitleBarCloseButton);
subSubRule.drawRule(p, ir);
QSize sz = subSubRule.contentsRect(ir).size();
if ((tb->titleBarFlags & Qt::WindowType_Mask) == Qt::Tool)
pm = standardIcon(SP_DockWidgetCloseButton, 0, w).pixmap(sz);
else
pm = standardIcon(SP_TitleBarCloseButton, 0, w).pixmap(sz);
drawItemPixmap(p, ir, Qt::AlignCenter, pm);
}
int pes[] = {
PseudoElement_TitleBarMaxButton,
PseudoElement_TitleBarMinButton,
PseudoElement_TitleBarNormalButton,
PseudoElement_TitleBarShadeButton,
PseudoElement_TitleBarUnshadeButton,
PseudoElement_TitleBarContextHelpButton
};
for (unsigned int i = 0; i < sizeof(pes)/sizeof(int); i++) {
int pe = pes[i];
QStyle::SubControl sc = knownPseudoElements[pe].subControl;
ir = layout[sc];
if (!ir.isValid())
continue;
QRenderRule subSubRule = renderRule(w, opt, pe);
subSubRule.drawRule(p, ir);
pm = standardIcon(subControlIcon(pe), 0, w).pixmap(subSubRule.contentsRect(ir).size());
drawItemPixmap(p, ir, Qt::AlignCenter, pm);
}
return;
}
break;
default:
break;
}
baseStyle()->drawComplexControl(cc, opt, p, w);
}
void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPainter *p,
const QWidget *w) const
{
RECURSION_GUARD(baseStyle()->drawControl(ce, opt, p, w); return)
QRenderRule rule = renderRule(w, opt);
int pe1 = PseudoElement_None, pe2 = PseudoElement_None;
bool fallback = false;
switch (ce) {
case CE_ToolButtonLabel:
if (const QStyleOptionToolButton *btn = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) {
if (rule.hasBox() || btn->features & QStyleOptionToolButton::Arrow) {
QCommonStyle::drawControl(ce, opt, p, w);
} else {
QStyleOptionToolButton butOpt(*btn);
rule.configurePalette(&butOpt.palette, QPalette::ButtonText, QPalette::Button);
baseStyle()->drawControl(ce, &butOpt, p, w);
}
return;
}
break;
case CE_FocusFrame:
if (!rule.hasNativeBorder()) {
rule.drawBorder(p, opt->rect);
return;
}
break;
case CE_PushButton:
if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
if (rule.hasDrawable() || rule.hasBox() || rule.hasPosition() || rule.hasPalette() ||
((btn->features & QStyleOptionButton::HasMenu) && hasStyleRule(w, PseudoElement_PushButtonMenuIndicator))) {
ParentStyle::drawControl(ce, opt, p, w);
return;
}
}
break;
case CE_PushButtonBevel:
if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
QStyleOptionButton btnOpt(*btn);
btnOpt.rect = rule.borderRect(opt->rect);
if (rule.hasNativeBorder()) {
rule.drawBackgroundImage(p, btnOpt.rect);
rule.configurePalette(&btnOpt.palette, QPalette::ButtonText, QPalette::Button);
bool customMenu = (btn->features & QStyleOptionButton::HasMenu
&& hasStyleRule(w, PseudoElement_PushButtonMenuIndicator));
if (customMenu)
btnOpt.features &= ~QStyleOptionButton::HasMenu;
if (rule.baseStyleCanDraw()) {
baseStyle()->drawControl(ce, &btnOpt, p, w);
} else {
QWindowsStyle::drawControl(ce, &btnOpt, p, w);
}
if (!customMenu)
return;
} else {
rule.drawRule(p, opt->rect);
}
if (btn->features & QStyleOptionButton::HasMenu) {
QRenderRule subRule = renderRule(w, opt, PseudoElement_PushButtonMenuIndicator);
QRect ir = positionRect(w, rule, subRule, PseudoElement_PushButtonMenuIndicator, opt->rect, opt->direction);
if (subRule.hasDrawable()) {
subRule.drawRule(p, ir);
} else {
btnOpt.rect = ir;
baseStyle()->drawPrimitive(PE_IndicatorArrowDown, &btnOpt, p, w);
}
}
}
return;
case CE_PushButtonLabel:
if (const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
QStyleOptionButton butOpt(*button);
rule.configurePalette(&butOpt.palette, QPalette::ButtonText, QPalette::Button);
const QFont oldFont = p->font();
if (rule.hasFont)
p->setFont(rule.font);
if (rule.hasPosition() && rule.position()->textAlignment != 0) {
Qt::Alignment textAlignment = rule.position()->textAlignment;
QRect textRect = button->rect;
uint tf = Qt::TextShowMnemonic;
const uint verticalAlignMask = Qt::AlignVCenter | Qt::AlignTop | Qt::AlignLeft;
tf |= (textAlignment & verticalAlignMask) ? (textAlignment & verticalAlignMask) : Qt::AlignVCenter;
if (!styleHint(SH_UnderlineShortcut, button, w))
tf |= Qt::TextHideMnemonic;
if (!button->icon.isNull()) {
//Group both icon and text
QRect iconRect;
QIcon::Mode mode = button->state & State_Enabled ? QIcon::Normal : QIcon::Disabled;
if (mode == QIcon::Normal && button->state & State_HasFocus)
mode = QIcon::Active;
QIcon::State state = QIcon::Off;
if (button->state & State_On)
state = QIcon::On;
QPixmap pixmap = button->icon.pixmap(button->iconSize, mode, state);
int pixmapWidth = pixmap.width() / pixmap.devicePixelRatio();
int pixmapHeight = pixmap.height() / pixmap.devicePixelRatio();
int labelWidth = pixmapWidth;
int labelHeight = pixmapHeight;
int iconSpacing = 4;//### 4 is currently hardcoded in QPushButton::sizeHint()
int textWidth = button->fontMetrics.boundingRect(opt->rect, tf, button->text).width();
if (!button->text.isEmpty())
labelWidth += (textWidth + iconSpacing);
//Determine label alignment:
if (textAlignment & Qt::AlignLeft) { /*left*/
iconRect = QRect(textRect.x(), textRect.y() + (textRect.height() - labelHeight) / 2,
pixmapWidth, pixmapHeight);
} else if (textAlignment & Qt::AlignHCenter) { /* center */
iconRect = QRect(textRect.x() + (textRect.width() - labelWidth) / 2,
textRect.y() + (textRect.height() - labelHeight) / 2,
pixmapWidth, pixmapHeight);
} else { /*right*/
iconRect = QRect(textRect.x() + textRect.width() - labelWidth,
textRect.y() + (textRect.height() - labelHeight) / 2,
pixmapWidth, pixmapHeight);
}
iconRect = visualRect(button->direction, textRect, iconRect);
tf |= Qt::AlignLeft; //left align, we adjust the text-rect instead
if (button->direction == Qt::RightToLeft)
textRect.setRight(iconRect.left() - iconSpacing);
else
textRect.setLeft(iconRect.left() + iconRect.width() + iconSpacing);
if (button->state & (State_On | State_Sunken))
iconRect.translate(pixelMetric(PM_ButtonShiftHorizontal, opt, w),
pixelMetric(PM_ButtonShiftVertical, opt, w));
p->drawPixmap(iconRect, pixmap);
} else {
tf |= textAlignment;
}
if (button->state & (State_On | State_Sunken))
textRect.translate(pixelMetric(PM_ButtonShiftHorizontal, opt, w),
pixelMetric(PM_ButtonShiftVertical, opt, w));
if (button->features & QStyleOptionButton::HasMenu) {
int indicatorSize = pixelMetric(PM_MenuButtonIndicator, button, w);
if (button->direction == Qt::LeftToRight)
textRect = textRect.adjusted(0, 0, -indicatorSize, 0);
else
textRect = textRect.adjusted(indicatorSize, 0, 0, 0);
}
drawItemText(p, textRect, tf, butOpt.palette, (button->state & State_Enabled),
button->text, QPalette::ButtonText);
} else {
ParentStyle::drawControl(ce, &butOpt, p, w);
}
if (rule.hasFont)
p->setFont(oldFont);
}
return;
case CE_RadioButton:
case CE_CheckBox:
if (rule.hasBox() || !rule.hasNativeBorder() || rule.hasDrawable() || hasStyleRule(w, PseudoElement_Indicator)) {
rule.drawRule(p, opt->rect);
ParentStyle::drawControl(ce, opt, p, w);
return;
} else if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
QStyleOptionButton butOpt(*btn);
rule.configurePalette(&butOpt.palette, QPalette::ButtonText, QPalette::Button);
baseStyle()->drawControl(ce, &butOpt, p, w);
return;
}
break;
case CE_RadioButtonLabel:
case CE_CheckBoxLabel:
if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
QStyleOptionButton butOpt(*btn);
rule.configurePalette(&butOpt.palette, QPalette::ButtonText, QPalette::Button);
ParentStyle::drawControl(ce, &butOpt, p, w);
}
return;
case CE_Splitter:
pe1 = PseudoElement_SplitterHandle;
break;
case CE_ToolBar:
if (rule.hasBackground()) {
rule.drawBackground(p, opt->rect);
}
if (rule.hasBorder()) {
rule.drawBorder(p, rule.borderRect(opt->rect));
} else {
#ifndef QT_NO_TOOLBAR
if (const QStyleOptionToolBar *tb = qstyleoption_cast<const QStyleOptionToolBar *>(opt)) {
QStyleOptionToolBar newTb(*tb);
newTb.rect = rule.borderRect(opt->rect);
baseStyle()->drawControl(ce, &newTb, p, w);
}
#endif // QT_NO_TOOLBAR
}
return;
case CE_MenuEmptyArea:
case CE_MenuBarEmptyArea:
if (rule.hasDrawable()) {
// Drawn by PE_Widget
return;
}
break;
case CE_MenuTearoff:
case CE_MenuScroller:
if (const QStyleOptionMenuItem *m = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
QStyleOptionMenuItem mi(*m);
int pe = ce == CE_MenuTearoff ? PseudoElement_MenuTearoff : PseudoElement_MenuScroller;
QRenderRule subRule = renderRule(w, opt, pe);
mi.rect = subRule.contentsRect(opt->rect);
rule.configurePalette(&mi.palette, QPalette::ButtonText, QPalette::Button);
subRule.configurePalette(&mi.palette, QPalette::ButtonText, QPalette::Button);
if (subRule.hasDrawable()) {
subRule.drawRule(p, opt->rect);
} else {
baseStyle()->drawControl(ce, &mi, p, w);
}
}
return;
case CE_MenuItem:
if (const QStyleOptionMenuItem *m = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
QStyleOptionMenuItem mi(*m);
int pseudo = (mi.menuItemType == QStyleOptionMenuItem::Separator) ? PseudoElement_MenuSeparator : PseudoElement_Item;
QRenderRule subRule = renderRule(w, opt, pseudo);
mi.rect = subRule.contentsRect(opt->rect);
rule.configurePalette(&mi.palette, QPalette::ButtonText, QPalette::Button);
rule.configurePalette(&mi.palette, QPalette::HighlightedText, QPalette::Highlight);
subRule.configurePalette(&mi.palette, QPalette::ButtonText, QPalette::Button);
subRule.configurePalette(&mi.palette, QPalette::HighlightedText, QPalette::Highlight);
QFont oldFont = p->font();
if (subRule.hasFont)
p->setFont(subRule.font.resolve(p->font()));
else
p->setFont(mi.font);
// We fall back to drawing with the style sheet code whenever at least one of the
// items are styled in an incompatible way, such as having a background image.
QRenderRule allRules = renderRule(w, PseudoElement_Item, PseudoClass_Any);
if ((pseudo == PseudoElement_MenuSeparator) && subRule.hasDrawable()) {
subRule.drawRule(p, opt->rect);
} else if ((pseudo == PseudoElement_Item)
&& (allRules.hasBox() || allRules.hasBorder() || subRule.hasFont
|| (allRules.background() && !allRules.background()->pixmap.isNull()))) {
subRule.drawRule(p, opt->rect);
if (subRule.hasBackground()) {
mi.palette.setBrush(QPalette::Highlight, Qt::NoBrush);
mi.palette.setBrush(QPalette::Button, Qt::NoBrush);
} else {
mi.palette.setBrush(QPalette::Highlight, mi.palette.brush(QPalette::Button));
}
mi.palette.setBrush(QPalette::HighlightedText, mi.palette.brush(QPalette::ButtonText));
bool checkable = mi.checkType != QStyleOptionMenuItem::NotCheckable;
bool checked = checkable ? mi.checked : false;
bool dis = !(opt->state & QStyle::State_Enabled),
act = opt->state & QStyle::State_Selected;
if (!mi.icon.isNull()) {
QIcon::Mode mode = dis ? QIcon::Disabled : QIcon::Normal;
if (act && !dis)
mode = QIcon::Active;
QPixmap pixmap;
if (checked)
pixmap = mi.icon.pixmap(pixelMetric(PM_SmallIconSize), mode, QIcon::On);
else
pixmap = mi.icon.pixmap(pixelMetric(PM_SmallIconSize), mode);
const int pixw = pixmap.width() / pixmap.devicePixelRatio();
const int pixh = pixmap.height() / pixmap.devicePixelRatio();
QRenderRule iconRule = renderRule(w, opt, PseudoElement_MenuIcon);
if (!iconRule.hasGeometry()) {
iconRule.geo = new QStyleSheetGeometryData(pixw, pixh, pixw, pixh, -1, -1);
} else {
iconRule.geo->width = pixw;
iconRule.geo->height = pixh;
}
QRect iconRect = positionRect(w, subRule, iconRule, PseudoElement_MenuIcon, opt->rect, opt->direction);
iconRule.drawRule(p, iconRect);
QRect pmr(0, 0, pixw, pixh);
pmr.moveCenter(iconRect.center());
p->drawPixmap(pmr.topLeft(), pixmap);
} else if (checkable) {
QRenderRule subSubRule = renderRule(w, opt, PseudoElement_MenuCheckMark);
if (subSubRule.hasDrawable() || checked) {
QStyleOptionMenuItem newMi = mi;
newMi.rect = positionRect(w, subRule, subSubRule, PseudoElement_MenuCheckMark, opt->rect, opt->direction);
drawPrimitive(PE_IndicatorMenuCheckMark, &newMi, p, w);
}
}
QRect textRect = subRule.contentsRect(opt->rect);
textRect.setWidth(textRect.width() - mi.tabWidth);
QStringRef s(&mi.text);
p->setPen(mi.palette.buttonText().color());
if (!s.isEmpty()) {
int text_flags = Qt::AlignLeft | Qt::AlignVCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
if (!styleHint(SH_UnderlineShortcut, &mi, w))
text_flags |= Qt::TextHideMnemonic;
int t = s.indexOf(QLatin1Char('\t'));
if (t >= 0) {
QRect vShortcutRect = visualRect(opt->direction, mi.rect,
QRect(textRect.topRight(), QPoint(mi.rect.right(), textRect.bottom())));
p->drawText(vShortcutRect, text_flags, s.mid(t + 1).toString());
s = s.left(t);
}
p->drawText(textRect, text_flags, s.left(t).toString());
}
if (mi.menuItemType == QStyleOptionMenuItem::SubMenu) {// draw sub menu arrow
PrimitiveElement arrow = (opt->direction == Qt::RightToLeft) ? PE_IndicatorArrowLeft : PE_IndicatorArrowRight;
QRenderRule subRule2 = renderRule(w, opt, PseudoElement_MenuRightArrow);
mi.rect = positionRect(w, subRule, subRule2, PseudoElement_MenuRightArrow, opt->rect, mi.direction);
drawPrimitive(arrow, &mi, p, w);
}
} else if (hasStyleRule(w, PseudoElement_MenuCheckMark) || hasStyleRule(w, PseudoElement_MenuRightArrow)) {
QWindowsStyle::drawControl(ce, &mi, p, w);
if (mi.checkType != QStyleOptionMenuItem::NotCheckable && !mi.checked) {
// We have a style defined, but QWindowsStyle won't draw anything if not checked.
// So we mimick what QWindowsStyle would do.
int checkcol = qMax<int>(mi.maxIconWidth, QWindowsStylePrivate::windowsCheckMarkWidth);
QRect vCheckRect = visualRect(opt->direction, mi.rect, QRect(mi.rect.x(), mi.rect.y(), checkcol, mi.rect.height()));
if (mi.state.testFlag(State_Enabled) && mi.state.testFlag(State_Selected)) {
qDrawShadePanel(p, vCheckRect, mi.palette, true, 1, &mi.palette.brush(QPalette::Button));
} else {
QBrush fill(mi.palette.light().color(), Qt::Dense4Pattern);
qDrawShadePanel(p, vCheckRect, mi.palette, true, 1, &fill);
}
QRenderRule subSubRule = renderRule(w, opt, PseudoElement_MenuCheckMark);
if (subSubRule.hasDrawable()) {
QStyleOptionMenuItem newMi(mi);
newMi.rect = visualRect(opt->direction, mi.rect, QRect(mi.rect.x() + QWindowsStylePrivate::windowsItemFrame,
mi.rect.y() + QWindowsStylePrivate::windowsItemFrame,
checkcol - 2 * QWindowsStylePrivate::windowsItemFrame,
mi.rect.height() - 2 * QWindowsStylePrivate::windowsItemFrame));
drawPrimitive(PE_IndicatorMenuCheckMark, &newMi, p, w);
}
}
} else {
if (rule.hasDrawable() && !subRule.hasDrawable() && !(opt->state & QStyle::State_Selected)) {
mi.palette.setColor(QPalette::Window, Qt::transparent);
mi.palette.setColor(QPalette::Button, Qt::transparent);
}
if (rule.baseStyleCanDraw() && subRule.baseStyleCanDraw()) {
baseStyle()->drawControl(ce, &mi, p, w);
} else {
ParentStyle::drawControl(ce, &mi, p, w);
}
}
p->setFont(oldFont);
return;
}
return;
case CE_MenuBarItem:
if (const QStyleOptionMenuItem *m = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
QStyleOptionMenuItem mi(*m);
QRenderRule subRule = renderRule(w, opt, PseudoElement_Item);
mi.rect = subRule.contentsRect(opt->rect);
rule.configurePalette(&mi.palette, QPalette::ButtonText, QPalette::Button);
subRule.configurePalette(&mi.palette, QPalette::ButtonText, QPalette::Button);
if (subRule.hasDrawable()) {
subRule.drawRule(p, opt->rect);
QCommonStyle::drawControl(ce, &mi, p, w);
} else {
if (rule.hasDrawable() && !(opt->state & QStyle::State_Selected)) {
// So that the menu bar background is not hidden by the items
mi.palette.setColor(QPalette::Window, Qt::transparent);
mi.palette.setColor(QPalette::Button, Qt::transparent);
}
baseStyle()->drawControl(ce, &mi, p, w);
}
}
return;
#if QT_CONFIG(combobox)
case CE_ComboBoxLabel:
if (!rule.hasBox())
break;
if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
QRect editRect = subControlRect(CC_ComboBox, cb, SC_ComboBoxEditField, w);
p->save();
p->setClipRect(editRect);
if (!cb->currentIcon.isNull()) {
int spacing = rule.hasBox() ? rule.box()->spacing : -1;
if (spacing == -1)
spacing = 6;
QIcon::Mode mode = cb->state & State_Enabled ? QIcon::Normal : QIcon::Disabled;
QPixmap pixmap = cb->currentIcon.pixmap(cb->iconSize, mode);
QRect iconRect(editRect);
iconRect.setWidth(cb->iconSize.width());
iconRect = alignedRect(cb->direction,
Qt::AlignLeft | Qt::AlignVCenter,
iconRect.size(), editRect);
drawItemPixmap(p, iconRect, Qt::AlignCenter, pixmap);
if (cb->direction == Qt::RightToLeft)
editRect.translate(-spacing - cb->iconSize.width(), 0);
else
editRect.translate(cb->iconSize.width() + spacing, 0);
}
if (!cb->currentText.isEmpty() && !cb->editable) {
QPalette styledPalette(cb->palette);
rule.configurePalette(&styledPalette, QPalette::Text, QPalette::Base);
drawItemText(p, editRect.adjusted(0, 0, 0, 0), Qt::AlignLeft | Qt::AlignVCenter, styledPalette,
cb->state & State_Enabled, cb->currentText, QPalette::Text);
}
p->restore();
return;
}
break;
#endif // QT_CONFIG(combobox)
case CE_Header:
if (hasStyleRule(w, PseudoElement_HeaderViewUpArrow)
|| hasStyleRule(w, PseudoElement_HeaderViewDownArrow)) {
ParentStyle::drawControl(ce, opt, p, w);
return;
}
if(hasStyleRule(w, PseudoElement_HeaderViewSection)) {
QRenderRule subRule = renderRule(w, opt, PseudoElement_HeaderViewSection);
if (!subRule.hasNativeBorder() || !subRule.baseStyleCanDraw()
|| subRule.hasBackground() || subRule.hasPalette()) {
ParentStyle::drawControl(ce, opt, p, w);
return;
}
if (subRule.hasFont) {
const QFont oldFont = p->font();
p->setFont(subRule.font.resolve(p->font()));
baseStyle()->drawControl(ce, opt, p, w);
p->setFont(oldFont);
return;
}
}
break;
case CE_HeaderSection:
if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
QRenderRule subRule = renderRule(w, opt, PseudoElement_HeaderViewSection);
if (subRule.hasNativeBorder()) {
QStyleOptionHeader hdr(*header);
subRule.configurePalette(&hdr.palette, QPalette::ButtonText, QPalette::Button);
if (subRule.baseStyleCanDraw()) {
baseStyle()->drawControl(CE_HeaderSection, &hdr, p, w);
} else {
QWindowsStyle::drawControl(CE_HeaderSection, &hdr, p, w);
}
} else {
subRule.drawRule(p, opt->rect);
}
return;
}
break;
case CE_HeaderLabel:
if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
QStyleOptionHeader hdr(*header);
QRenderRule subRule = renderRule(w, opt, PseudoElement_HeaderViewSection);
subRule.configurePalette(&hdr.palette, QPalette::ButtonText, QPalette::Button);
QFont oldFont = p->font();
if (subRule.hasFont)
p->setFont(subRule.font.resolve(p->font()));
baseStyle()->drawControl(ce, &hdr, p, w);
if (subRule.hasFont)
p->setFont(oldFont);
return;
}
break;
case CE_HeaderEmptyArea:
if (rule.hasDrawable()) {
return;
}
break;
case CE_ProgressBar:
QWindowsStyle::drawControl(ce, opt, p, w);
return;
case CE_ProgressBarGroove:
if (!rule.hasNativeBorder()) {
rule.drawRule(p, rule.boxRect(opt->rect, Margin));
return;
}
break;
case CE_ProgressBarContents: {
QRenderRule subRule = renderRule(w, opt, PseudoElement_ProgressBarChunk);
if (subRule.hasDrawable()) {
if (const QStyleOptionProgressBar *pb = qstyleoption_cast<const QStyleOptionProgressBar *>(opt)) {
p->save();
p->setClipRect(pb->rect);
qint64 minimum = qint64(pb->minimum);
qint64 maximum = qint64(pb->maximum);
qint64 progress = qint64(pb->progress);
bool vertical = (pb->orientation == Qt::Vertical);
bool inverted = pb->invertedAppearance;
QTransform m;
QRect rect = pb->rect;
if (vertical) {
rect = QRect(rect.y(), rect.x(), rect.height(), rect.width());
m.rotate(90);
m.translate(0, -(rect.height() + rect.y()*2));
}
bool reverse = ((!vertical && (pb->direction == Qt::RightToLeft)) || vertical);
if (inverted)
reverse = !reverse;
const bool indeterminate = pb->minimum == pb->maximum;
const auto fillRatio = indeterminate ? 0.50 : double(progress - minimum) / (maximum - minimum);
const auto fillWidth = static_cast<int>(rect.width() * fillRatio);
int chunkWidth = fillWidth;
if (subRule.hasContentsSize()) {
QSize sz = subRule.size();
chunkWidth = (opt->state & QStyle::State_Horizontal) ? sz.width() : sz.height();
}
QRect r = rect;
#if QT_CONFIG(animation)
Q_D(const QWindowsStyle);
#endif
if (pb->minimum == 0 && pb->maximum == 0) {
int chunkCount = fillWidth/chunkWidth;
int offset = 0;
#if QT_CONFIG(animation)
if (QProgressStyleAnimation *animation = qobject_cast<QProgressStyleAnimation*>(d->animation(opt->styleObject)))
offset = animation->animationStep() * 8 % rect.width();
else
d->startAnimation(new QProgressStyleAnimation(d->animationFps, opt->styleObject));
#endif
int x = reverse ? r.left() + r.width() - offset - chunkWidth : r.x() + offset;
while (chunkCount > 0) {
r.setRect(x, rect.y(), chunkWidth, rect.height());
r = m.mapRect(QRectF(r)).toRect();
subRule.drawRule(p, r);
x += reverse ? -chunkWidth : chunkWidth;
if (reverse ? x < rect.left() : x > rect.right())
break;
--chunkCount;
}
r = rect;
x = reverse ? r.right() - (r.left() - x - chunkWidth)
: r.left() + (x - r.right() - chunkWidth);
while (chunkCount > 0) {
r.setRect(x, rect.y(), chunkWidth, rect.height());
r = m.mapRect(QRectF(r)).toRect();
subRule.drawRule(p, r);
x += reverse ? -chunkWidth : chunkWidth;
--chunkCount;
};
} else if (chunkWidth > 0) {
const int chunkCount = ceil(qreal(fillWidth)/chunkWidth);
int x = reverse ? r.left() + r.width() - chunkWidth : r.x();
for (int i = 0; i < chunkCount; ++i) {
r.setRect(x, rect.y(), chunkWidth, rect.height());
r = m.mapRect(QRectF(r)).toRect();
subRule.drawRule(p, r);
x += reverse ? -chunkWidth : chunkWidth;
}
#if QT_CONFIG(animation)
d->stopAnimation(opt->styleObject);
#endif
}
p->restore();
return;
}
}
}
break;
case CE_ProgressBarLabel:
if (const QStyleOptionProgressBar *pb = qstyleoption_cast<const QStyleOptionProgressBar *>(opt)) {
if (rule.hasBox() || rule.hasBorder() || hasStyleRule(w, PseudoElement_ProgressBarChunk)) {
drawItemText(p, pb->rect, pb->textAlignment | Qt::TextSingleLine, pb->palette,
pb->state & State_Enabled, pb->text, QPalette::Text);
} else {
QStyleOptionProgressBar pbCopy(*pb);
rule.configurePalette(&pbCopy.palette, QPalette::HighlightedText, QPalette::Highlight);
baseStyle()->drawControl(ce, &pbCopy, p, w);
}
return;
}
break;
case CE_SizeGrip:
if (const QStyleOptionSizeGrip *sgOpt = qstyleoption_cast<const QStyleOptionSizeGrip *>(opt)) {
if (rule.hasDrawable()) {
rule.drawFrame(p, opt->rect);
p->save();
switch (sgOpt->corner) {
case Qt::BottomRightCorner: break;
case Qt::BottomLeftCorner: p->rotate(90); break;
case Qt::TopLeftCorner: p->rotate(180); break;
case Qt::TopRightCorner: p->rotate(270); break;
default: break;
}
rule.drawImage(p, opt->rect);
p->restore();
} else {
QStyleOptionSizeGrip sg(*sgOpt);
sg.rect = rule.contentsRect(opt->rect);
baseStyle()->drawControl(CE_SizeGrip, &sg, p, w);
}
return;
}
break;
case CE_ToolBoxTab:
QWindowsStyle::drawControl(ce, opt, p, w);
return;
case CE_ToolBoxTabShape: {
QRenderRule subRule = renderRule(w, opt, PseudoElement_ToolBoxTab);
if (subRule.hasDrawable()) {
subRule.drawRule(p, opt->rect);
return;
}
}
break;
case CE_ToolBoxTabLabel:
if (const QStyleOptionToolBox *box = qstyleoption_cast<const QStyleOptionToolBox *>(opt)) {
QStyleOptionToolBox boxCopy(*box);
QRenderRule subRule = renderRule(w, opt, PseudoElement_ToolBoxTab);
subRule.configurePalette(&boxCopy.palette, QPalette::ButtonText, QPalette::Button);
QFont oldFont = p->font();
if (subRule.hasFont)
p->setFont(subRule.font);
boxCopy.rect = subRule.contentsRect(opt->rect);
QWindowsStyle::drawControl(ce, &boxCopy, p , w);
if (subRule.hasFont)
p->setFont(oldFont);
return;
}
break;
case CE_ScrollBarAddPage:
pe1 = PseudoElement_ScrollBarAddPage;
break;
case CE_ScrollBarSubPage:
pe1 = PseudoElement_ScrollBarSubPage;
break;
case CE_ScrollBarAddLine:
pe1 = PseudoElement_ScrollBarAddLine;
pe2 = (opt->state & QStyle::State_Horizontal) ? PseudoElement_ScrollBarRightArrow : PseudoElement_ScrollBarDownArrow;
fallback = true;
break;
case CE_ScrollBarSubLine:
pe1 = PseudoElement_ScrollBarSubLine;
pe2 = (opt->state & QStyle::State_Horizontal) ? PseudoElement_ScrollBarLeftArrow : PseudoElement_ScrollBarUpArrow;
fallback = true;
break;
case CE_ScrollBarFirst:
pe1 = PseudoElement_ScrollBarFirst;
break;
case CE_ScrollBarLast:
pe1 = PseudoElement_ScrollBarLast;
break;
case CE_ScrollBarSlider:
pe1 = PseudoElement_ScrollBarSlider;
fallback = true;
break;
#if QT_CONFIG(itemviews)
case CE_ItemViewItem:
if (const QStyleOptionViewItem *vopt = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
QRenderRule subRule = renderRule(w, opt, PseudoElement_ViewItem);
if (subRule.hasDrawable() || hasStyleRule(w, PseudoElement_Indicator)) {
QStyleOptionViewItem optCopy(*vopt);
subRule.configurePalette(&optCopy.palette, vopt->state & QStyle::State_Selected ? QPalette::HighlightedText : QPalette::Text,
vopt->state & QStyle::State_Selected ? QPalette::Highlight : QPalette::Base);
QWindowsStyle::drawControl(ce, &optCopy, p, w);
} else {
QStyleOptionViewItem voptCopy(*vopt);
subRule.configurePalette(&voptCopy.palette, QPalette::Text, QPalette::NoRole);
baseStyle()->drawControl(ce, &voptCopy, p, w);
}
return;
}
break;
#endif // QT_CONFIG(itemviews)
#if QT_CONFIG(tabbar)
case CE_TabBarTab:
if (hasStyleRule(w, PseudoElement_TabBarTab)) {
QWindowsStyle::drawControl(ce, opt, p, w);
return;
}
break;
case CE_TabBarTabLabel:
case CE_TabBarTabShape:
if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
QRenderRule subRule = renderRule(w, opt, PseudoElement_TabBarTab);
QRect r = positionRect(w, subRule, PseudoElement_TabBarTab, opt->rect, opt->direction);
if (ce == CE_TabBarTabShape && subRule.hasDrawable()) {
subRule.drawRule(p, r);
return;
}
QStyleOptionTab tabCopy(*tab);
subRule.configurePalette(&tabCopy.palette, QPalette::WindowText, QPalette::Window);
QFont oldFont = p->font();
if (subRule.hasFont)
p->setFont(subRule.font);
if (subRule.hasBox() || !subRule.hasNativeBorder()) {
tabCopy.rect = ce == CE_TabBarTabShape ? subRule.borderRect(r)
: subRule.contentsRect(r);
QWindowsStyle::drawControl(ce, &tabCopy, p, w);
} else {
baseStyle()->drawControl(ce, &tabCopy, p, w);
}
if (subRule.hasFont)
p->setFont(oldFont);
return;
}
break;
#endif // QT_CONFIG(tabbar)
case CE_ColumnViewGrip:
if (rule.hasDrawable()) {
rule.drawRule(p, opt->rect);
return;
}
break;
case CE_DockWidgetTitle:
if (const QStyleOptionDockWidget *dwOpt = qstyleoption_cast<const QStyleOptionDockWidget *>(opt)) {
QRenderRule subRule = renderRule(w, opt, PseudoElement_DockWidgetTitle);
if (!subRule.hasDrawable() && !subRule.hasPosition())
break;
if (subRule.hasDrawable()) {
subRule.drawRule(p, opt->rect);
} else {
QStyleOptionDockWidget dwCopy(*dwOpt);
dwCopy.title = QString();
baseStyle()->drawControl(ce, &dwCopy, p, w);
}
if (!dwOpt->title.isEmpty()) {
QRect r = subElementRect(SE_DockWidgetTitleBarText, opt, w);
if (dwOpt->verticalTitleBar) {
r = r.transposed();
p->save();
p->translate(r.left(), r.top() + r.width());
p->rotate(-90);
p->translate(-r.left(), -r.top());
}
r = subRule.contentsRect(r);
Qt::Alignment alignment = 0;
if (subRule.hasPosition())
alignment = subRule.position()->textAlignment;
if (alignment == 0)
alignment = Qt::AlignLeft;
QString titleText = p->fontMetrics().elidedText(dwOpt->title, Qt::ElideRight, r.width());
drawItemText(p, r,
alignment | Qt::TextShowMnemonic, dwOpt->palette,
dwOpt->state & State_Enabled, titleText,
QPalette::WindowText);
if (dwOpt->verticalTitleBar)
p->restore();
}
return;
}
break;
case CE_ShapedFrame:
if (const QStyleOptionFrame *frm = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
if (rule.hasNativeBorder()) {
QStyleOptionFrame frmOpt(*frm);
rule.configurePalette(&frmOpt.palette, QPalette::Text, QPalette::Base);
frmOpt.rect = rule.borderRect(frmOpt.rect);
baseStyle()->drawControl(ce, &frmOpt, p, w);
}
// else, borders are already drawn in PE_Widget
}
return;
default:
break;
}
if (pe1 != PseudoElement_None) {
QRenderRule subRule = renderRule(w, opt, pe1);
if (subRule.bg != 0 || subRule.hasDrawable()) {
//We test subRule.bg directly because hasBackground() would return false for background:none.
//But we still don't want the default drawning in that case (example for QScrollBar::add-page) (task 198926)
subRule.drawRule(p, opt->rect);
} else if (fallback) {
QWindowsStyle::drawControl(ce, opt, p, w);
pe2 = PseudoElement_None;
} else {
baseStyle()->drawControl(ce, opt, p, w);
}
if (pe2 != PseudoElement_None) {
QRenderRule subSubRule = renderRule(w, opt, pe2);
QRect r = positionRect(w, subRule, subSubRule, pe2, opt->rect, opt->direction);
subSubRule.drawRule(p, r);
}
return;
}
baseStyle()->drawControl(ce, opt, p, w);
}
void QStyleSheetStyle::drawItemPixmap(QPainter *p, const QRect &rect, int alignment, const
QPixmap &pixmap) const
{
baseStyle()->drawItemPixmap(p, rect, alignment, pixmap);
}
void QStyleSheetStyle::drawItemText(QPainter *painter, const QRect& rect, int alignment, const QPalette &pal,
bool enabled, const QString& text, QPalette::ColorRole textRole) const
{
baseStyle()->drawItemText(painter, rect, alignment, pal, enabled, text, textRole);
}
void QStyleSheetStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p,
const QWidget *w) const
{
RECURSION_GUARD(baseStyle()->drawPrimitive(pe, opt, p, w); return)
int pseudoElement = PseudoElement_None;
QRenderRule rule = renderRule(w, opt);
QRect rect = opt->rect;
switch (pe) {
case PE_FrameStatusBar: {
QRenderRule subRule = renderRule(w ? w->parentWidget() : Q_NULLPTR, opt, PseudoElement_Item);
if (subRule.hasDrawable()) {
subRule.drawRule(p, opt->rect);
return;
}
break;
}
case PE_IndicatorArrowDown:
pseudoElement = PseudoElement_DownArrow;
break;
case PE_IndicatorArrowUp:
pseudoElement = PseudoElement_UpArrow;
break;
case PE_IndicatorRadioButton:
pseudoElement = PseudoElement_ExclusiveIndicator;
break;
case PE_IndicatorViewItemCheck:
pseudoElement = PseudoElement_ViewItemIndicator;
break;
case PE_IndicatorCheckBox:
pseudoElement = PseudoElement_Indicator;
break;
case PE_IndicatorHeaderArrow:
if (const QStyleOptionHeader *hdr = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
pseudoElement = hdr->sortIndicator == QStyleOptionHeader::SortUp
? PseudoElement_HeaderViewUpArrow
: PseudoElement_HeaderViewDownArrow;
}
break;
case PE_PanelButtonTool:
case PE_PanelButtonCommand:
#if QT_CONFIG(abstractbutton)
if (qobject_cast<const QAbstractButton *>(w) && rule.hasBackground() && rule.hasNativeBorder()) {
//the window style will draw the borders
ParentStyle::drawPrimitive(pe, opt, p, w);
if (!rule.background()->pixmap.isNull() || rule.hasImage()) {
rule.drawRule(p, rule.boxRect(opt->rect, QRenderRule::Margin).adjusted(1,1,-1,-1));
}
return;
}
#endif
if (!rule.hasNativeBorder()) {
rule.drawRule(p, rule.boxRect(opt->rect, QRenderRule::Margin));
return;
}
break;
case PE_IndicatorButtonDropDown: {
QRenderRule subRule = renderRule(w, opt, PseudoElement_ToolButtonMenu);
if (!subRule.hasNativeBorder()) {
rule.drawBorder(p, opt->rect);
return;
}
break;
}
case PE_FrameDefaultButton:
if (rule.hasNativeBorder()) {
if (rule.baseStyleCanDraw())
break;
QWindowsStyle::drawPrimitive(pe, opt, p, w);
}
return;
case PE_FrameWindow:
case PE_FrameDockWidget:
case PE_Frame:
if (const QStyleOptionFrame *frm = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
if (rule.hasNativeBorder()) {
QStyleOptionFrame frmOpt(*frm);
rule.configurePalette(&frmOpt.palette, QPalette::Text, QPalette::Base);
baseStyle()->drawPrimitive(pe, &frmOpt, p, w);
} else {
rule.drawBorder(p, rule.borderRect(opt->rect));
}
}
return;
case PE_PanelLineEdit:
if (const QStyleOptionFrame *frm = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
#if QT_CONFIG(spinbox)
if (w && qobject_cast<const QAbstractSpinBox *>(w->parentWidget())) {
QRenderRule spinboxRule = renderRule(w->parentWidget(), opt);
if (!spinboxRule.hasNativeBorder() || !spinboxRule.baseStyleCanDraw())
return;
rule = spinboxRule;
}
#endif
if (rule.hasNativeBorder()) {
QStyleOptionFrame frmOpt(*frm);
rule.configurePalette(&frmOpt.palette, QPalette::Text, QPalette::Base);
frmOpt.rect = rule.borderRect(frmOpt.rect);
if (rule.baseStyleCanDraw()) {
rule.drawBackgroundImage(p, opt->rect);
baseStyle()->drawPrimitive(pe, &frmOpt, p, w);
} else {
rule.drawBackground(p, opt->rect);
if (frmOpt.lineWidth > 0)
baseStyle()->drawPrimitive(PE_FrameLineEdit, &frmOpt, p, w);
}
} else {
rule.drawRule(p, opt->rect);
}
}
return;
case PE_Widget:
if (w && !rule.hasDrawable()) {
QWidget *container = containerWidget(w);
if (styleSheetCaches->autoFillDisabledWidgets.contains(container)
&& (container == w || !renderRule(container, opt).hasBackground())) {
//we do not have a background, but we disabled the autofillbackground anyway. so fill the background now.
// (this may happen if we have rules like :focus)
p->fillRect(opt->rect, opt->palette.brush(w->backgroundRole()));
}
break;
}
#if QT_CONFIG(scrollarea)
if (const QAbstractScrollArea *sa = qobject_cast<const QAbstractScrollArea *>(w)) {
const QAbstractScrollAreaPrivate *sap = sa->d_func();
rule.drawBackground(p, opt->rect, sap->contentsOffset());
if (rule.hasBorder()) {
QRect brect = rule.borderRect(opt->rect);
if (styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents, opt, w)) {
QRect r = brect.adjusted(0, 0, sa->verticalScrollBar()->isVisible() ? -sa->verticalScrollBar()->width() : 0,
sa->horizontalScrollBar()->isVisible() ? -sa->horizontalScrollBar()->height() : 0);
brect = QStyle::visualRect(opt->direction, brect, r);
}
rule.drawBorder(p, brect);
}
break;
}
#endif
Q_FALLTHROUGH();
case PE_PanelMenu:
case PE_PanelStatusBar:
if(rule.hasDrawable()) {
rule.drawRule(p, opt->rect);
return;
}
break;
case PE_FrameMenu:
if (rule.hasDrawable()) {
// Drawn by PE_PanelMenu
return;
}
break;
case PE_PanelMenuBar:
if (rule.hasDrawable()) {
// Drawn by PE_Widget
return;
}
break;
case PE_IndicatorToolBarSeparator:
case PE_IndicatorToolBarHandle: {
PseudoElement ps = pe == PE_IndicatorToolBarHandle ? PseudoElement_ToolBarHandle : PseudoElement_ToolBarSeparator;
QRenderRule subRule = renderRule(w, opt, ps);
if (subRule.hasDrawable()) {
subRule.drawRule(p, opt->rect);
return;
}
}
break;
case PE_IndicatorMenuCheckMark:
pseudoElement = PseudoElement_MenuCheckMark;
break;
case PE_IndicatorArrowLeft:
pseudoElement = PseudoElement_LeftArrow;
break;
case PE_IndicatorArrowRight:
pseudoElement = PseudoElement_RightArrow;
break;
case PE_IndicatorColumnViewArrow:
#if QT_CONFIG(itemviews)
if (const QStyleOptionViewItem *viewOpt = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
bool reverse = (viewOpt->direction == Qt::RightToLeft);
pseudoElement = reverse ? PseudoElement_LeftArrow : PseudoElement_RightArrow;
} else
#endif
{
pseudoElement = PseudoElement_RightArrow;
}
break;
#if QT_CONFIG(itemviews)
case PE_IndicatorBranch:
if (const QStyleOptionViewItem *vopt = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
QRenderRule subRule = renderRule(w, opt, PseudoElement_TreeViewBranch);
if (subRule.hasDrawable()) {
if ((vopt->state & QStyle::State_Selected) && vopt->showDecorationSelected)
p->fillRect(vopt->rect, vopt->palette.highlight());
else if (vopt->features & QStyleOptionViewItem::Alternate)
p->fillRect(vopt->rect, vopt->palette.alternateBase());
subRule.drawRule(p, opt->rect);
} else {
baseStyle()->drawPrimitive(pe, vopt, p, w);
}
}
return;
#endif // QT_CONFIG(itemviews)
case PE_PanelTipLabel:
if (!rule.hasDrawable())
break;
if (const QStyleOptionFrame *frmOpt = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
if (rule.hasNativeBorder()) {
rule.drawBackground(p, opt->rect);
QStyleOptionFrame optCopy(*frmOpt);
optCopy.rect = rule.borderRect(opt->rect);
optCopy.palette.setBrush(QPalette::Window, Qt::NoBrush); // oh dear
baseStyle()->drawPrimitive(pe, &optCopy, p, w);
} else {
rule.drawRule(p, opt->rect);
}
}
return;
case PE_FrameGroupBox:
if (rule.hasNativeBorder())
break;
rule.drawBorder(p, opt->rect);
return;
#if QT_CONFIG(tabwidget)
case PE_FrameTabWidget:
if (const QStyleOptionTabWidgetFrame *frm = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
QRenderRule subRule = renderRule(w, opt, PseudoElement_TabWidgetPane);
if (subRule.hasNativeBorder()) {
subRule.drawBackground(p, opt->rect);
QStyleOptionTabWidgetFrame frmCopy(*frm);
subRule.configurePalette(&frmCopy.palette, QPalette::WindowText, QPalette::Window);
baseStyle()->drawPrimitive(pe, &frmCopy, p, w);
} else {
subRule.drawRule(p, opt->rect);
}
return;
}
break;
#endif // QT_CONFIG(tabwidget)
case PE_IndicatorProgressChunk:
pseudoElement = PseudoElement_ProgressBarChunk;
break;
case PE_IndicatorTabTear:
pseudoElement = PseudoElement_TabBarTear;
break;
case PE_FrameFocusRect:
if (!rule.hasNativeOutline()) {
rule.drawOutline(p, opt->rect);
return;
}
break;
case PE_IndicatorDockWidgetResizeHandle:
pseudoElement = PseudoElement_DockWidgetSeparator;
break;
case PE_PanelItemViewItem:
pseudoElement = PseudoElement_ViewItem;
break;
case PE_PanelScrollAreaCorner:
pseudoElement = PseudoElement_ScrollAreaCorner;
break;
case PE_IndicatorSpinDown:
case PE_IndicatorSpinMinus:
pseudoElement = PseudoElement_SpinBoxDownArrow;
break;
case PE_IndicatorSpinUp:
case PE_IndicatorSpinPlus:
pseudoElement = PseudoElement_SpinBoxUpArrow;
break;
#if QT_CONFIG(tabbar)
case PE_IndicatorTabClose:
if (w)
w = w->parentWidget(); //match on the QTabBar instead of the CloseButton
pseudoElement = PseudoElement_TabBarTabCloseButton;
#endif
default:
break;
}
if (pseudoElement != PseudoElement_None) {
QRenderRule subRule = renderRule(w, opt, pseudoElement);
if (subRule.hasDrawable()) {
subRule.drawRule(p, rect);
} else {
baseStyle()->drawPrimitive(pe, opt, p, w);
}
} else {
baseStyle()->drawPrimitive(pe, opt, p, w);
}
}
QPixmap QStyleSheetStyle::generatedIconPixmap(QIcon::Mode iconMode, const QPixmap& pixmap,
const QStyleOption *option) const
{
return baseStyle()->generatedIconPixmap(iconMode, pixmap, option);
}
QStyle::SubControl QStyleSheetStyle::hitTestComplexControl(ComplexControl cc, const QStyleOptionComplex *opt,
const QPoint &pt, const QWidget *w) const
{
RECURSION_GUARD(return baseStyle()->hitTestComplexControl(cc, opt, pt, w))
switch (cc) {
case CC_TitleBar:
if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
QRenderRule rule = renderRule(w, opt, PseudoElement_TitleBar);
if (rule.hasDrawable() || rule.hasBox() || rule.hasBorder()) {
QHash<QStyle::SubControl, QRect> layout = titleBarLayout(w, tb);
QRect r;
QStyle::SubControl sc = QStyle::SC_None;
uint ctrl = SC_TitleBarSysMenu;
while (ctrl <= SC_TitleBarLabel) {
r = layout[QStyle::SubControl(ctrl)];
if (r.isValid() && r.contains(pt)) {
sc = QStyle::SubControl(ctrl);
break;
}
ctrl <<= 1;
}
return sc;
}
}
break;
case CC_MdiControls:
if (hasStyleRule(w, PseudoElement_MdiCloseButton)
|| hasStyleRule(w, PseudoElement_MdiNormalButton)
|| hasStyleRule(w, PseudoElement_MdiMinButton))
return QWindowsStyle::hitTestComplexControl(cc, opt, pt, w);
break;
case CC_ScrollBar: {
QRenderRule rule = renderRule(w, opt);
if (!rule.hasDrawable() && !rule.hasBox())
break;
}
// intentionally falls through
case CC_SpinBox:
case CC_GroupBox:
case CC_ComboBox:
case CC_Slider:
case CC_ToolButton:
return QWindowsStyle::hitTestComplexControl(cc, opt, pt, w);
default:
break;
}
return baseStyle()->hitTestComplexControl(cc, opt, pt, w);
}
QRect QStyleSheetStyle::itemPixmapRect(const QRect &rect, int alignment, const QPixmap &pixmap) const
{
return baseStyle()->itemPixmapRect(rect, alignment, pixmap);
}
QRect QStyleSheetStyle::itemTextRect(const QFontMetrics &metrics, const QRect& rect, int alignment,
bool enabled, const QString& text) const
{
return baseStyle()->itemTextRect(metrics, rect, alignment, enabled, text);
}
int QStyleSheetStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWidget *w) const
{
RECURSION_GUARD(return baseStyle()->pixelMetric(m, opt, w))
QRenderRule rule = renderRule(w, opt);
QRenderRule subRule;
switch (m) {
case PM_MenuButtonIndicator:
#if QT_CONFIG(toolbutton)
// QToolButton adds this directly to the width
if (qobject_cast<const QToolButton *>(w) && (rule.hasBox() || !rule.hasNativeBorder()))
return 0;
#endif
subRule = renderRule(w, opt, PseudoElement_PushButtonMenuIndicator);
if (subRule.hasContentsSize())
return subRule.size().width();
break;
case PM_ButtonShiftHorizontal:
case PM_ButtonShiftVertical:
case PM_ButtonMargin:
case PM_ButtonDefaultIndicator:
if (rule.hasBox())
return 0;
break;
case PM_DefaultFrameWidth:
if (!rule.hasNativeBorder())
return rule.border()->borders[LeftEdge];
break;
case PM_ExclusiveIndicatorWidth:
case PM_IndicatorWidth:
case PM_ExclusiveIndicatorHeight:
case PM_IndicatorHeight:
subRule = renderRule(w, opt, PseudoElement_Indicator);
if (subRule.hasContentsSize()) {
return (m == PM_ExclusiveIndicatorWidth) || (m == PM_IndicatorWidth)
? subRule.size().width() : subRule.size().height();
}
break;
case PM_DockWidgetFrameWidth:
case PM_ToolTipLabelFrameWidth: // border + margin + padding (support only one width)
if (!rule.hasDrawable())
break;
return (rule.border() ? rule.border()->borders[LeftEdge] : 0)
+ (rule.hasBox() ? rule.box()->margins[LeftEdge] + rule.box()->paddings[LeftEdge]: 0);
case PM_ToolBarFrameWidth:
if (rule.hasBorder() || rule.hasBox())
return (rule.border() ? rule.border()->borders[LeftEdge] : 0)
+ (rule.hasBox() ? rule.box()->paddings[LeftEdge]: 0);
break;
case PM_MenuPanelWidth:
case PM_MenuBarPanelWidth:
if (rule.hasBorder() || rule.hasBox())
return (rule.border() ? rule.border()->borders[LeftEdge] : 0)
+ (rule.hasBox() ? rule.box()->margins[LeftEdge]: 0);
break;
case PM_MenuHMargin:
case PM_MenuBarHMargin:
if (rule.hasBox())
return rule.box()->paddings[LeftEdge];
break;
case PM_MenuVMargin:
case PM_MenuBarVMargin:
if (rule.hasBox())
return rule.box()->paddings[TopEdge];
break;
case PM_DockWidgetTitleBarButtonMargin:
case PM_ToolBarItemMargin:
if (rule.hasBox())
return rule.box()->margins[TopEdge];
break;
case PM_ToolBarItemSpacing:
case PM_MenuBarItemSpacing:
if (rule.hasBox() && rule.box()->spacing != -1)
return rule.box()->spacing;
break;
case PM_MenuTearoffHeight:
case PM_MenuScrollerHeight: {
PseudoElement ps = m == PM_MenuTearoffHeight ? PseudoElement_MenuTearoff : PseudoElement_MenuScroller;
subRule = renderRule(w, opt, ps);
if (subRule.hasContentsSize())
return subRule.size().height();
break;
}
case PM_ToolBarExtensionExtent:
break;
case PM_SplitterWidth:
case PM_ToolBarSeparatorExtent:
case PM_ToolBarHandleExtent: {
PseudoElement ps;
if (m == PM_ToolBarHandleExtent) ps = PseudoElement_ToolBarHandle;
else if (m == PM_SplitterWidth) ps = PseudoElement_SplitterHandle;
else ps = PseudoElement_ToolBarSeparator;
subRule = renderRule(w, opt, ps);
if (subRule.hasContentsSize()) {
QSize sz = subRule.size();
return (opt && opt->state & QStyle::State_Horizontal) ? sz.width() : sz.height();
}
break;
}
case PM_RadioButtonLabelSpacing:
if (rule.hasBox() && rule.box()->spacing != -1)
return rule.box()->spacing;
break;
case PM_CheckBoxLabelSpacing:
#if QT_CONFIG(checkbox)
if (qobject_cast<const QCheckBox *>(w)) {
if (rule.hasBox() && rule.box()->spacing != -1)
return rule.box()->spacing;
}
#endif
// assume group box
subRule = renderRule(w, opt, PseudoElement_GroupBoxTitle);
if (subRule.hasBox() && subRule.box()->spacing != -1)
return subRule.box()->spacing;
break;
#if QT_CONFIG(scrollbar)
case PM_ScrollBarExtent:
if (rule.hasContentsSize()) {
QSize sz = rule.size();
if (const QStyleOptionSlider *sb = qstyleoption_cast<const QStyleOptionSlider *>(opt))
return sb->orientation == Qt::Horizontal ? sz.height() : sz.width();
return sz.width() == -1 ? sz.height() : sz.width();
}
break;
case PM_ScrollBarSliderMin:
if (hasStyleRule(w, PseudoElement_ScrollBarSlider)) {
subRule = renderRule(w, opt, PseudoElement_ScrollBarSlider);
QSize msz = subRule.minimumSize();
if (const QStyleOptionSlider *sb = qstyleoption_cast<const QStyleOptionSlider *>(opt))
return sb->orientation == Qt::Horizontal ? msz.width() : msz.height();
return msz.width() == -1 ? msz.height() : msz.width();
}
break;
case PM_ScrollView_ScrollBarSpacing:
if(!rule.hasNativeBorder() || rule.hasBox())
return 0;
break;
#endif // QT_CONFIG(scrollbar)
case PM_ProgressBarChunkWidth:
subRule = renderRule(w, opt, PseudoElement_ProgressBarChunk);
if (subRule.hasContentsSize()) {
QSize sz = subRule.size();
return (opt->state & QStyle::State_Horizontal)
? sz.width() : sz.height();
}
break;
#if QT_CONFIG(tabwidget)
case PM_TabBarTabHSpace:
case PM_TabBarTabVSpace:
subRule = renderRule(w, opt, PseudoElement_TabBarTab);
if (subRule.hasBox() || subRule.hasBorder())
return 0;
break;
case PM_TabBarScrollButtonWidth: {
subRule = renderRule(w, opt, PseudoElement_TabBarScroller);
if (subRule.hasContentsSize()) {
QSize sz = subRule.size();
return sz.width() != -1 ? sz.width() : sz.height();
}
}
break;
case PM_TabBarTabShiftHorizontal:
case PM_TabBarTabShiftVertical:
subRule = renderRule(w, opt, PseudoElement_TabBarTab);
if (subRule.hasBox())
return 0;
break;
case PM_TabBarBaseOverlap: {
const QWidget *tabWidget = qobject_cast<const QTabWidget *>(w);
if (!tabWidget && w)
tabWidget = w->parentWidget();
if (hasStyleRule(tabWidget, PseudoElement_TabWidgetPane)) {
return 0;
}
break;
}
#endif // QT_CONFIG(tabwidget)
case PM_SliderThickness: // horizontal slider's height (sizeHint)
case PM_SliderLength: // minimum length of slider
if (rule.hasContentsSize()) {
bool horizontal = opt->state & QStyle::State_Horizontal;
if (m == PM_SliderThickness) {
QSize sz = rule.size();
return horizontal ? sz.height() : sz.width();
} else {
QSize msz = rule.minimumContentsSize();
return horizontal ? msz.width() : msz.height();
}
}
break;
case PM_SliderControlThickness: {
QRenderRule subRule = renderRule(w, opt, PseudoElement_SliderHandle);
if (!subRule.hasContentsSize())
break;
QSize size = subRule.size();
return (opt->state & QStyle::State_Horizontal) ? size.height() : size.width();
}
case PM_ToolBarIconSize:
case PM_ListViewIconSize:
case PM_IconViewIconSize:
case PM_TabBarIconSize:
case PM_MessageBoxIconSize:
case PM_ButtonIconSize:
case PM_SmallIconSize:
if (rule.hasStyleHint(QLatin1String("icon-size"))) {
return rule.styleHint(QLatin1String("icon-size")).toSize().width();
}
break;
case PM_DockWidgetTitleMargin: {
QRenderRule subRule = renderRule(w, opt, PseudoElement_DockWidgetTitle);
if (!subRule.hasBox())
break;
return (subRule.border() ? subRule.border()->borders[TopEdge] : 0)
+ (subRule.hasBox() ? subRule.box()->margins[TopEdge] + subRule.box()->paddings[TopEdge]: 0);
}
case PM_DockWidgetSeparatorExtent: {
QRenderRule subRule = renderRule(w, opt, PseudoElement_DockWidgetSeparator);
if (!subRule.hasContentsSize())
break;
QSize sz = subRule.size();
return qMax(sz.width(), sz.height());
}
case PM_TitleBarHeight: {
QRenderRule subRule = renderRule(w, opt, PseudoElement_TitleBar);
if (subRule.hasContentsSize())
return subRule.size().height();
else if (subRule.hasBox() || subRule.hasBorder()) {
QFontMetrics fm = opt ? opt->fontMetrics : w->fontMetrics();
return subRule.size(QSize(0, fm.height())).height();
}
break;
}
case PM_MdiSubWindowFrameWidth:
if (rule.hasBox() || rule.hasBorder()) {
return (rule.border() ? rule.border()->borders[LeftEdge] : 0)
+ (rule.hasBox() ? rule.box()->paddings[LeftEdge]+rule.box()->margins[LeftEdge]: 0);
}
break;
case PM_MdiSubWindowMinimizedWidth: {
QRenderRule subRule = renderRule(w, PseudoElement_None, PseudoClass_Minimized);
int width = subRule.size().width();
if (width != -1)
return width;
break;
}
default:
break;
}
return baseStyle()->pixelMetric(m, opt, w);
}
QSize QStyleSheetStyle::sizeFromContents(ContentsType ct, const QStyleOption *opt,
const QSize &csz, const QWidget *w) const
{
RECURSION_GUARD(return baseStyle()->sizeFromContents(ct, opt, csz, w))
QRenderRule rule = renderRule(w, opt);
QSize sz = rule.adjustSize(csz);
switch (ct) {
#if QT_CONFIG(spinbox)
case CT_SpinBox: // ### hopelessly broken QAbstractSpinBox (part 1)
if (const QStyleOptionSpinBox *spinbox = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
// Add some space for the up/down buttons
QRenderRule subRule = renderRule(w, opt, PseudoElement_SpinBoxUpButton);
if (subRule.hasDrawable()) {
QRect r = positionRect(w, rule, subRule, PseudoElement_SpinBoxUpButton,
opt->rect, opt->direction);
sz += QSize(r.width(), 0);
} else {
QSize defaultUpSize = defaultSize(w, subRule.size(), spinbox->rect, PseudoElement_SpinBoxUpButton);
sz += QSize(defaultUpSize.width(), 0);
}
if (rule.hasBox() || rule.hasBorder() || !rule.hasNativeBorder())
sz = rule.boxSize(sz);
return sz;
}
break;
#endif // QT_CONFIG(spinbox)
case CT_ToolButton:
if (rule.hasBox() || !rule.hasNativeBorder() || !rule.baseStyleCanDraw())
sz += QSize(3, 3); // ### broken QToolButton
Q_FALLTHROUGH();
case CT_ComboBox:
case CT_PushButton:
if (rule.hasBox() || !rule.hasNativeBorder()) {
if(ct == CT_ComboBox) {
//add some space for the drop down.
QRenderRule subRule = renderRule(w, opt, PseudoElement_ComboBoxDropDown);
QRect comboRect = positionRect(w, rule, subRule, PseudoElement_ComboBoxDropDown, opt->rect, opt->direction);
//+2 because there is hardcoded margins in QCommonStyle::drawControl(CE_ComboBoxLabel)
sz += QSize(comboRect.width() + 2, 0);
}
return rule.boxSize(sz);
}
sz = rule.baseStyleCanDraw() ? baseStyle()->sizeFromContents(ct, opt, sz, w)
: QWindowsStyle::sizeFromContents(ct, opt, sz, w);
return rule.boxSize(sz, Margin);
case CT_HeaderSection: {
if (const QStyleOptionHeader *hdr = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
QRenderRule subRule = renderRule(w, opt, PseudoElement_HeaderViewSection);
if (subRule.hasGeometry() || subRule.hasBox() || !subRule.hasNativeBorder() || subRule.hasFont) {
sz = subRule.adjustSize(csz);
if (!subRule.hasGeometry()) {
QSize nativeContentsSize;
bool nullIcon = hdr->icon.isNull();
int iconSize = nullIcon ? 0 : pixelMetric(QStyle::PM_SmallIconSize, hdr, w);
const QSize txt = subRule.hasFont ? QFontMetrics(subRule.font).size(0, hdr->text)
: hdr->fontMetrics.size(0, hdr->text);
nativeContentsSize.setHeight(qMax(iconSize, txt.height()));
nativeContentsSize.setWidth(iconSize + txt.width());
sz = sz.expandedTo(nativeContentsSize);
}
return subRule.size(sz);
}
return subRule.baseStyleCanDraw() ? baseStyle()->sizeFromContents(ct, opt, sz, w)
: QWindowsStyle::sizeFromContents(ct, opt, sz, w);
}
}
break;
case CT_GroupBox:
case CT_LineEdit:
#if QT_CONFIG(spinbox)
if (qobject_cast<QAbstractSpinBox *>(w ? w->parentWidget() : 0))
return csz; // we only care about the size hint of the line edit
#endif
if (rule.hasBox() || !rule.hasNativeBorder()) {
return rule.boxSize(sz);
}
break;
case CT_CheckBox:
case CT_RadioButton:
if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
if (rule.hasBox() || rule.hasBorder() || hasStyleRule(w, PseudoElement_Indicator)) {
bool isRadio = (ct == CT_RadioButton);
int iw = pixelMetric(isRadio ? PM_ExclusiveIndicatorWidth
: PM_IndicatorWidth, btn, w);
int ih = pixelMetric(isRadio ? PM_ExclusiveIndicatorHeight
: PM_IndicatorHeight, btn, w);
int spacing = pixelMetric(isRadio ? PM_RadioButtonLabelSpacing
: PM_CheckBoxLabelSpacing, btn, w);
sz.setWidth(sz.width() + iw + spacing);
sz.setHeight(qMax(sz.height(), ih));
return rule.boxSize(sz);
}
}
break;
case CT_Menu:
case CT_MenuBar: // already has everything!
case CT_ScrollBar:
if (rule.hasBox() || rule.hasBorder())
return sz;
break;
case CT_MenuItem:
if (const QStyleOptionMenuItem *mi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
PseudoElement pe = (mi->menuItemType == QStyleOptionMenuItem::Separator)
? PseudoElement_MenuSeparator : PseudoElement_Item;
QRenderRule subRule = renderRule(w, opt, pe);
if ((pe == PseudoElement_MenuSeparator) && subRule.hasContentsSize()) {
return QSize(sz.width(), subRule.size().height());
} else if ((pe == PseudoElement_Item) && (subRule.hasBox() || subRule.hasBorder())) {
int width = csz.width();
if (mi->text.contains(QLatin1Char('\t')))
width += 12; //as in QCommonStyle
return subRule.boxSize(subRule.adjustSize(QSize(width, csz.height())));
}
}
break;
case CT_Splitter:
case CT_MenuBarItem: {
PseudoElement pe = (ct == CT_Splitter) ? PseudoElement_SplitterHandle : PseudoElement_Item;
QRenderRule subRule = renderRule(w, opt, pe);
if (subRule.hasBox() || subRule.hasBorder())
return subRule.boxSize(sz);
break;
}
case CT_ProgressBar:
case CT_SizeGrip:
return (rule.hasContentsSize())
? rule.size(sz)
: rule.boxSize(baseStyle()->sizeFromContents(ct, opt, sz, w));
break;
case CT_Slider:
if (rule.hasBorder() || rule.hasBox() || rule.hasGeometry())
return rule.boxSize(sz);
break;
#if QT_CONFIG(tabbar)
case CT_TabBarTab: {
QRenderRule subRule = renderRule(w, opt, PseudoElement_TabBarTab);
if (subRule.hasBox() || !subRule.hasNativeBorder()) {
int spaceForIcon = 0;
bool vertical = false;
if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
if (!tab->icon.isNull())
spaceForIcon = 6 /* icon offset */ + 4 /* spacing */ + 2 /* magic */; // ###: hardcoded to match with common style
vertical = verticalTabs(tab->shape);
}
sz = csz + QSize(vertical ? 0 : spaceForIcon, vertical ? spaceForIcon : 0);
return subRule.boxSize(subRule.adjustSize(sz));
}
#if 0 // Used to be included in Qt4 for Q_WS_MAC
if (baseStyle()->inherits("QMacStyle")) {
//adjust the size after the call to the style because the mac style ignore the size arguments anyway.
//this might cause the (max-){width,height} property to include the native style border while they should not.
return subRule.adjustSize(baseStyle()->sizeFromContents(ct, opt, csz, w));
}
#endif
sz = subRule.adjustSize(csz);
break;
}
#endif // QT_CONFIG(tabbar)
case CT_MdiControls:
if (const QStyleOptionComplex *ccOpt = qstyleoption_cast<const QStyleOptionComplex *>(opt)) {
if (!hasStyleRule(w, PseudoElement_MdiCloseButton)
&& !hasStyleRule(w, PseudoElement_MdiNormalButton)
&& !hasStyleRule(w, PseudoElement_MdiMinButton))
break;
QList<QVariant> layout = rule.styleHint(QLatin1String("button-layout")).toList();
if (layout.isEmpty())
layout = subControlLayout(QLatin1String("mNX"));
int width = 0, height = 0;
for (int i = 0; i < layout.count(); i++) {
int layoutButton = layout[i].toInt();
if (layoutButton < PseudoElement_MdiCloseButton
|| layoutButton > PseudoElement_MdiNormalButton)
continue;
QStyle::SubControl sc = knownPseudoElements[layoutButton].subControl;
if (!(ccOpt->subControls & sc))
continue;
QRenderRule subRule = renderRule(w, opt, layoutButton);
QSize sz = subRule.size();
width += sz.width();
height = qMax(height, sz.height());
}
return QSize(width, height);
}
break;
#if QT_CONFIG(itemviews)
case CT_ItemViewItem: {
QRenderRule subRule = renderRule(w, opt, PseudoElement_ViewItem);
sz = baseStyle()->sizeFromContents(ct, opt, csz, w);
sz = subRule.adjustSize(sz);
if (subRule.hasBox() || subRule.hasBorder())
sz = subRule.boxSize(sz);
return sz;
}
#endif // QT_CONFIG(itemviews)
default:
break;
}
return baseStyle()->sizeFromContents(ct, opt, sz, w);
}
/*!
\internal
*/
static QLatin1String propertyNameForStandardPixmap(QStyle::StandardPixmap sp)
{
switch (sp) {
case QStyle::SP_TitleBarMenuButton: return QLatin1String("titlebar-menu-icon");
case QStyle::SP_TitleBarMinButton: return QLatin1String("titlebar-minimize-icon");
case QStyle::SP_TitleBarMaxButton: return QLatin1String("titlebar-maximize-icon");
case QStyle::SP_TitleBarCloseButton: return QLatin1String("titlebar-close-icon");
case QStyle::SP_TitleBarNormalButton: return QLatin1String("titlebar-normal-icon");
case QStyle::SP_TitleBarShadeButton: return QLatin1String("titlebar-shade-icon");
case QStyle::SP_TitleBarUnshadeButton: return QLatin1String("titlebar-unshade-icon");
case QStyle::SP_TitleBarContextHelpButton: return QLatin1String("titlebar-contexthelp-icon");
case QStyle::SP_DockWidgetCloseButton: return QLatin1String("dockwidget-close-icon");
case QStyle::SP_MessageBoxInformation: return QLatin1String("messagebox-information-icon");
case QStyle::SP_MessageBoxWarning: return QLatin1String("messagebox-warning-icon");
case QStyle::SP_MessageBoxCritical: return QLatin1String("messagebox-critical-icon");
case QStyle::SP_MessageBoxQuestion: return QLatin1String("messagebox-question-icon");
case QStyle::SP_DesktopIcon: return QLatin1String("desktop-icon");
case QStyle::SP_TrashIcon: return QLatin1String("trash-icon");
case QStyle::SP_ComputerIcon: return QLatin1String("computer-icon");
case QStyle::SP_DriveFDIcon: return QLatin1String("floppy-icon");
case QStyle::SP_DriveHDIcon: return QLatin1String("harddisk-icon");
case QStyle::SP_DriveCDIcon: return QLatin1String("cd-icon");
case QStyle::SP_DriveDVDIcon: return QLatin1String("dvd-icon");
case QStyle::SP_DriveNetIcon: return QLatin1String("network-icon");
case QStyle::SP_DirOpenIcon: return QLatin1String("directory-open-icon");
case QStyle::SP_DirClosedIcon: return QLatin1String("directory-closed-icon");
case QStyle::SP_DirLinkIcon: return QLatin1String("directory-link-icon");
case QStyle::SP_FileIcon: return QLatin1String("file-icon");
case QStyle::SP_FileLinkIcon: return QLatin1String("file-link-icon");
case QStyle::SP_FileDialogStart: return QLatin1String("filedialog-start-icon");
case QStyle::SP_FileDialogEnd: return QLatin1String("filedialog-end-icon");
case QStyle::SP_FileDialogToParent: return QLatin1String("filedialog-parent-directory-icon");
case QStyle::SP_FileDialogNewFolder: return QLatin1String("filedialog-new-directory-icon");
case QStyle::SP_FileDialogDetailedView: return QLatin1String("filedialog-detailedview-icon");
case QStyle::SP_FileDialogInfoView: return QLatin1String("filedialog-infoview-icon");
case QStyle::SP_FileDialogContentsView: return QLatin1String("filedialog-contentsview-icon");
case QStyle::SP_FileDialogListView: return QLatin1String("filedialog-listview-icon");
case QStyle::SP_FileDialogBack: return QLatin1String("filedialog-backward-icon");
case QStyle::SP_DirIcon: return QLatin1String("directory-icon");
case QStyle::SP_DialogOkButton: return QLatin1String("dialog-ok-icon");
case QStyle::SP_DialogCancelButton: return QLatin1String("dialog-cancel-icon");
case QStyle::SP_DialogHelpButton: return QLatin1String("dialog-help-icon");
case QStyle::SP_DialogOpenButton: return QLatin1String("dialog-open-icon");
case QStyle::SP_DialogSaveButton: return QLatin1String("dialog-save-icon");
case QStyle::SP_DialogCloseButton: return QLatin1String("dialog-close-icon");
case QStyle::SP_DialogApplyButton: return QLatin1String("dialog-apply-icon");
case QStyle::SP_DialogResetButton: return QLatin1String("dialog-reset-icon");
case QStyle::SP_DialogDiscardButton: return QLatin1String("discard-icon");
case QStyle::SP_DialogYesButton: return QLatin1String("dialog-yes-icon");
case QStyle::SP_DialogNoButton: return QLatin1String("dialog-no-icon");
case QStyle::SP_ArrowUp: return QLatin1String("uparrow-icon");
case QStyle::SP_ArrowDown: return QLatin1String("downarrow-icon");
case QStyle::SP_ArrowLeft: return QLatin1String("leftarrow-icon");
case QStyle::SP_ArrowRight: return QLatin1String("rightarrow-icon");
case QStyle::SP_ArrowBack: return QLatin1String("backward-icon");
case QStyle::SP_ArrowForward: return QLatin1String("forward-icon");
case QStyle::SP_DirHomeIcon: return QLatin1String("home-icon");
default: return QLatin1String("");
}
}
QIcon QStyleSheetStyle::standardIcon(StandardPixmap standardIcon, const QStyleOption *opt,
const QWidget *w) const
{
RECURSION_GUARD(return baseStyle()->standardIcon(standardIcon, opt, w))
QString s = propertyNameForStandardPixmap(standardIcon);
if (!s.isEmpty()) {
QRenderRule rule = renderRule(w, opt);
if (rule.hasStyleHint(s))
return qvariant_cast<QIcon>(rule.styleHint(s));
}
return baseStyle()->standardIcon(standardIcon, opt, w);
}
QPalette QStyleSheetStyle::standardPalette() const
{
return baseStyle()->standardPalette();
}
QPixmap QStyleSheetStyle::standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt,
const QWidget *w) const
{
RECURSION_GUARD(return baseStyle()->standardPixmap(standardPixmap, opt, w))
QString s = propertyNameForStandardPixmap(standardPixmap);
if (!s.isEmpty()) {
QRenderRule rule = renderRule(w, opt);
if (rule.hasStyleHint(s)) {
QIcon icon = qvariant_cast<QIcon>(rule.styleHint(s));
return icon.pixmap(16, 16); // ###: unhard-code this if someone complains
}
}
return baseStyle()->standardPixmap(standardPixmap, opt, w);
}
int QStyleSheetStyle::layoutSpacing(QSizePolicy::ControlType control1, QSizePolicy::ControlType control2,
Qt::Orientation orientation, const QStyleOption *option,
const QWidget *widget) const
{
return baseStyle()->layoutSpacing(control1, control2, orientation, option, widget);
}
int QStyleSheetStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWidget *w,
QStyleHintReturn *shret) const
{
RECURSION_GUARD(return baseStyle()->styleHint(sh, opt, w, shret))
// Prevent endless loop if somebody use isActiveWindow property as selector.
// QWidget::isActiveWindow uses this styleHint to determine if the window is active or not
if (sh == SH_Widget_ShareActivation)
return baseStyle()->styleHint(sh, opt, w, shret);
QRenderRule rule = renderRule(w, opt);
QString s;
switch (sh) {
case SH_LineEdit_PasswordCharacter: s = QLatin1String("lineedit-password-character"); break;
case SH_LineEdit_PasswordMaskDelay: s = QLatin1String("lineedit-password-mask-delay"); break;
case SH_DitherDisabledText: s = QLatin1String("dither-disabled-text"); break;
case SH_EtchDisabledText: s = QLatin1String("etch-disabled-text"); break;
case SH_ItemView_ActivateItemOnSingleClick: s = QLatin1String("activate-on-singleclick"); break;
case SH_ItemView_ShowDecorationSelected: s = QLatin1String("show-decoration-selected"); break;
case SH_Table_GridLineColor: s = QLatin1String("gridline-color"); break;
case SH_DialogButtonLayout: s = QLatin1String("button-layout"); break;
case SH_ToolTipLabel_Opacity: s = QLatin1String("opacity"); break;
case SH_ComboBox_Popup: s = QLatin1String("combobox-popup"); break;
case SH_ComboBox_ListMouseTracking: s = QLatin1String("combobox-list-mousetracking"); break;
case SH_MenuBar_AltKeyNavigation: s = QLatin1String("menubar-altkey-navigation"); break;
case SH_Menu_Scrollable: s = QLatin1String("menu-scrollable"); break;
case SH_DrawMenuBarSeparator: s = QLatin1String("menubar-separator"); break;
case SH_MenuBar_MouseTracking: s = QLatin1String("mouse-tracking"); break;
case SH_SpinBox_ClickAutoRepeatRate: s = QLatin1String("spinbox-click-autorepeat-rate"); break;
case SH_SpinControls_DisableOnBounds: s = QLatin1String("spincontrol-disable-on-bounds"); break;
case SH_MessageBox_TextInteractionFlags: s = QLatin1String("messagebox-text-interaction-flags"); break;
case SH_ToolButton_PopupDelay: s = QLatin1String("toolbutton-popup-delay"); break;
case SH_ToolBox_SelectedPageTitleBold:
if (renderRule(w, opt, PseudoElement_ToolBoxTab).hasFont)
return 0;
break;
case SH_GroupBox_TextLabelColor:
if (rule.hasPalette() && rule.palette()->foreground.style() != Qt::NoBrush)
return rule.palette()->foreground.color().rgba();
break;
case SH_ScrollView_FrameOnlyAroundContents: s = QLatin1String("scrollview-frame-around-contents"); break;
case SH_ScrollBar_ContextMenu: s = QLatin1String("scrollbar-contextmenu"); break;
case SH_ScrollBar_LeftClickAbsolutePosition: s = QLatin1String("scrollbar-leftclick-absolute-position"); break;
case SH_ScrollBar_MiddleClickAbsolutePosition: s = QLatin1String("scrollbar-middleclick-absolute-position"); break;
case SH_ScrollBar_RollBetweenButtons: s = QLatin1String("scrollbar-roll-between-buttons"); break;
case SH_ScrollBar_ScrollWhenPointerLeavesControl: s = QLatin1String("scrollbar-scroll-when-pointer-leaves-control"); break;
case SH_TabBar_Alignment:
#if QT_CONFIG(tabwidget)
if (qobject_cast<const QTabWidget *>(w)) {
rule = renderRule(w, opt, PseudoElement_TabWidgetTabBar);
if (rule.hasPosition())
return rule.position()->position;
}
#endif // QT_CONFIG(tabwidget)
s = QLatin1String("alignment");
break;
#if QT_CONFIG(tabbar)
case SH_TabBar_CloseButtonPosition:
rule = renderRule(w, opt, PseudoElement_TabBarTabCloseButton);
if (rule.hasPosition()) {
Qt::Alignment align = rule.position()->position;
if (align & Qt::AlignLeft || align & Qt::AlignTop)
return QTabBar::LeftSide;
if (align & Qt::AlignRight || align & Qt::AlignBottom)
return QTabBar::RightSide;
}
break;
#endif
case SH_TabBar_ElideMode: s = QLatin1String("tabbar-elide-mode"); break;
case SH_TabBar_PreferNoArrows: s = QLatin1String("tabbar-prefer-no-arrows"); break;
case SH_ComboBox_PopupFrameStyle:
#if QT_CONFIG(combobox)
if (qobject_cast<const QComboBox *>(w)) {
QAbstractItemView *view = w->findChild<QAbstractItemView *>();
if (view) {
view->ensurePolished();
QRenderRule subRule = renderRule(view, PseudoElement_None);
if (subRule.hasBox() || !subRule.hasNativeBorder())
return QFrame::NoFrame;
}
}
#endif // QT_CONFIG(combobox)
break;
case SH_DialogButtonBox_ButtonsHaveIcons: s = QLatin1String("dialogbuttonbox-buttons-have-icons"); break;
case SH_Workspace_FillSpaceOnMaximize: s = QLatin1String("mdi-fill-space-on-maximize"); break;
case SH_TitleBar_NoBorder:
if (rule.hasBorder())
return !rule.border()->borders[LeftEdge];
break;
case SH_TitleBar_AutoRaise: { // plain absurd
QRenderRule subRule = renderRule(w, opt, PseudoElement_TitleBar);
if (subRule.hasDrawable())
return 1;
break;
}
case SH_ItemView_ArrowKeysNavigateIntoChildren: s = QLatin1String("arrow-keys-navigate-into-children"); break;
case SH_ItemView_PaintAlternatingRowColorsForEmptyArea: s = QLatin1String("paint-alternating-row-colors-for-empty-area"); break;
default: break;
}
if (!s.isEmpty() && rule.hasStyleHint(s)) {
return rule.styleHint(s).toInt();
}
return baseStyle()->styleHint(sh, opt, w, shret);
}
QRect QStyleSheetStyle::subControlRect(ComplexControl cc, const QStyleOptionComplex *opt, SubControl sc,
const QWidget *w) const
{
RECURSION_GUARD(return baseStyle()->subControlRect(cc, opt, sc, w))
QRenderRule rule = renderRule(w, opt);
switch (cc) {
case CC_ComboBox:
if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
if (rule.hasBox() || !rule.hasNativeBorder()) {
switch (sc) {
case SC_ComboBoxFrame: return rule.borderRect(opt->rect);
case SC_ComboBoxEditField:
{
QRenderRule subRule = renderRule(w, opt, PseudoElement_ComboBoxDropDown);
QRect r = rule.contentsRect(opt->rect);
QRect r2 = positionRect(w, rule, subRule, PseudoElement_ComboBoxDropDown,
opt->rect, opt->direction);
if (subRule.hasPosition() && subRule.position()->position & Qt::AlignLeft) {
return visualRect(opt->direction, r, r.adjusted(r2.width(),0,0,0));
} else {
return visualRect(opt->direction, r, r.adjusted(0,0,-r2.width(),0));
}
}
case SC_ComboBoxArrow: {
QRenderRule subRule = renderRule(w, opt, PseudoElement_ComboBoxDropDown);
return positionRect(w, rule, subRule, PseudoElement_ComboBoxDropDown, opt->rect, opt->direction);
}
case SC_ComboBoxListBoxPopup:
default:
return baseStyle()->subControlRect(cc, opt, sc, w);
}
}
QStyleOptionComboBox comboBox(*cb);
comboBox.rect = rule.borderRect(opt->rect);
return rule.baseStyleCanDraw() ? baseStyle()->subControlRect(cc, &comboBox, sc, w)
: QWindowsStyle::subControlRect(cc, &comboBox, sc, w);
}
break;
#if QT_CONFIG(spinbox)
case CC_SpinBox:
if (const QStyleOptionSpinBox *spin = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
QRenderRule upRule = renderRule(w, opt, PseudoElement_SpinBoxUpButton);
QRenderRule downRule = renderRule(w, opt, PseudoElement_SpinBoxDownButton);
bool ruleMatch = rule.hasBox() || !rule.hasNativeBorder();
bool upRuleMatch = upRule.hasGeometry() || upRule.hasPosition();
bool downRuleMatch = downRule.hasGeometry() || downRule.hasPosition();
if (ruleMatch || upRuleMatch || downRuleMatch) {
switch (sc) {
case SC_SpinBoxFrame:
return rule.borderRect(opt->rect);
case SC_SpinBoxEditField:
{
QRect r = rule.contentsRect(opt->rect);
// Use the widest button on each side to determine edit field size.
Qt::Alignment upAlign, downAlign;
upAlign = upRule.hasPosition() ? upRule.position()->position
: Qt::Alignment(Qt::AlignRight);
upAlign = resolveAlignment(opt->direction, upAlign);
downAlign = downRule.hasPosition() ? downRule.position()->position
: Qt::Alignment(Qt::AlignRight);
downAlign = resolveAlignment(opt->direction, downAlign);
int upSize = subControlRect(CC_SpinBox, opt, SC_SpinBoxUp, w).width();
int downSize = subControlRect(CC_SpinBox, opt, SC_SpinBoxDown, w).width();
int widestL = qMax((upAlign & Qt::AlignLeft) ? upSize : 0,
(downAlign & Qt::AlignLeft) ? downSize : 0);
int widestR = qMax((upAlign & Qt::AlignRight) ? upSize : 0,
(downAlign & Qt::AlignRight) ? downSize : 0);
r.setRight(r.right() - widestR);
r.setLeft(r.left() + widestL);
return r;
}
case SC_SpinBoxDown:
if (downRuleMatch)
return positionRect(w, rule, downRule, PseudoElement_SpinBoxDownButton,
opt->rect, opt->direction);
break;
case SC_SpinBoxUp:
if (upRuleMatch)
return positionRect(w, rule, upRule, PseudoElement_SpinBoxUpButton,
opt->rect, opt->direction);
break;
default:
break;
}
return baseStyle()->subControlRect(cc, opt, sc, w);
}
QStyleOptionSpinBox spinBox(*spin);
spinBox.rect = rule.borderRect(opt->rect);
return rule.baseStyleCanDraw() ? baseStyle()->subControlRect(cc, &spinBox, sc, w)
: QWindowsStyle::subControlRect(cc, &spinBox, sc, w);
}
break;
#endif // QT_CONFIG(spinbox)
case CC_GroupBox:
if (const QStyleOptionGroupBox *gb = qstyleoption_cast<const QStyleOptionGroupBox *>(opt)) {
switch (sc) {
case SC_GroupBoxFrame:
case SC_GroupBoxContents: {
if (rule.hasBox() || !rule.hasNativeBorder()) {
return sc == SC_GroupBoxFrame ? rule.borderRect(opt->rect)
: rule.contentsRect(opt->rect);
}
QStyleOptionGroupBox groupBox(*gb);
groupBox.rect = rule.borderRect(opt->rect);
return baseStyle()->subControlRect(cc, &groupBox, sc, w);
}
default:
case SC_GroupBoxLabel:
case SC_GroupBoxCheckBox: {
QRenderRule indRule = renderRule(w, opt, PseudoElement_GroupBoxIndicator);
QRenderRule labelRule = renderRule(w, opt, PseudoElement_GroupBoxTitle);
if (!labelRule.hasPosition() && !labelRule.hasGeometry() && !labelRule.hasBox()
&& !labelRule.hasBorder() && !indRule.hasContentsSize()) {
QStyleOptionGroupBox groupBox(*gb);
groupBox.rect = rule.borderRect(opt->rect);
return baseStyle()->subControlRect(cc, &groupBox, sc, w);
}
int tw = opt->fontMetrics.width(gb->text);
int th = opt->fontMetrics.height();
int spacing = pixelMetric(QStyle::PM_CheckBoxLabelSpacing, opt, w);
int iw = pixelMetric(QStyle::PM_IndicatorWidth, opt, w);
int ih = pixelMetric(QStyle::PM_IndicatorHeight, opt, w);
if (gb->subControls & QStyle::SC_GroupBoxCheckBox) {
tw = tw + iw + spacing;
th = qMax(th, ih);
}
if (!labelRule.hasGeometry()) {
labelRule.geo = new QStyleSheetGeometryData(tw, th, tw, th, -1, -1);
} else {
labelRule.geo->width = tw;
labelRule.geo->height = th;
}
if (!labelRule.hasPosition()) {
labelRule.p = new QStyleSheetPositionData(0, 0, 0, 0, defaultOrigin(PseudoElement_GroupBoxTitle),
gb->textAlignment, PositionMode_Static);
}
QRect r = positionRect(w, rule, labelRule, PseudoElement_GroupBoxTitle,
opt->rect, opt->direction);
if (gb->subControls & SC_GroupBoxCheckBox) {
r = labelRule.contentsRect(r);
if (sc == SC_GroupBoxLabel) {
r.setLeft(r.left() + iw + spacing);
r.setTop(r.center().y() - th/2);
} else {
r = QRect(r.left(), r.center().y() - ih/2, iw, ih);
}
return r;
} else {
return labelRule.contentsRect(r);
}
}
} // switch
}
break;
case CC_ToolButton:
if (const QStyleOptionToolButton *tb = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) {
if (rule.hasBox() || !rule.hasNativeBorder()) {
switch (sc) {
case SC_ToolButton: return rule.borderRect(opt->rect);
case SC_ToolButtonMenu: {
QRenderRule subRule = renderRule(w, opt, PseudoElement_ToolButtonMenu);
return positionRect(w, rule, subRule, PseudoElement_ToolButtonMenu, opt->rect, opt->direction);
}
default:
break;
}
}
QStyleOptionToolButton tool(*tb);
tool.rect = rule.borderRect(opt->rect);
return rule.baseStyleCanDraw() ? baseStyle()->subControlRect(cc, &tool, sc, w)
: QWindowsStyle::subControlRect(cc, &tool, sc, w);
}
break;
#if QT_CONFIG(scrollbar)
case CC_ScrollBar:
if (const QStyleOptionSlider *sb = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
QStyleOptionSlider styleOptionSlider(*sb);
styleOptionSlider.rect = rule.borderRect(opt->rect);
if (rule.hasDrawable() || rule.hasBox()) {
QRect grooveRect;
if (!rule.hasBox()) {
grooveRect = rule.baseStyleCanDraw() ? baseStyle()->subControlRect(cc, sb, SC_ScrollBarGroove, w)
: QWindowsStyle::subControlRect(cc, sb, SC_ScrollBarGroove, w);
} else {
grooveRect = rule.contentsRect(opt->rect);
}
PseudoElement pe = PseudoElement_None;
switch (sc) {
case SC_ScrollBarGroove:
return grooveRect;
case SC_ScrollBarAddPage:
case SC_ScrollBarSubPage:
case SC_ScrollBarSlider: {
QRect contentRect = grooveRect;
if (hasStyleRule(w, PseudoElement_ScrollBarSlider)) {
QRenderRule sliderRule = renderRule(w, opt, PseudoElement_ScrollBarSlider);
Origin origin = sliderRule.hasPosition() ? sliderRule.position()->origin : defaultOrigin(PseudoElement_ScrollBarSlider);
contentRect = rule.originRect(opt->rect, origin);
}
int maxlen = (styleOptionSlider.orientation == Qt::Horizontal) ? contentRect.width() : contentRect.height();
int sliderlen;
if (sb->maximum != sb->minimum) {
uint range = sb->maximum - sb->minimum;
sliderlen = (qint64(sb->pageStep) * maxlen) / (range + sb->pageStep);
int slidermin = pixelMetric(PM_ScrollBarSliderMin, sb, w);
if (sliderlen < slidermin || range > INT_MAX / 2)
sliderlen = slidermin;
if (sliderlen > maxlen)
sliderlen = maxlen;
} else {
sliderlen = maxlen;
}
const int sliderPosition = sb->orientation == Qt::Horizontal && sb->direction == Qt::RightToLeft ? sb->maximum - sb->sliderPosition + sb->minimum : sb->sliderPosition;
int sliderstart = (styleOptionSlider.orientation == Qt::Horizontal ? contentRect.left() : contentRect.top())
+ sliderPositionFromValue(sb->minimum, sb->maximum, sliderPosition,
maxlen - sliderlen, sb->upsideDown);
QRect sr = (sb->orientation == Qt::Horizontal)
? QRect(sliderstart, contentRect.top(), sliderlen, contentRect.height())
: QRect(contentRect.left(), sliderstart, contentRect.width(), sliderlen);
if (sc == SC_ScrollBarSlider) {
return sr;
} else if (sc == SC_ScrollBarSubPage) {
return QRect(contentRect.topLeft(), sb->orientation == Qt::Horizontal ? sr.bottomLeft() : sr.topRight());
} else { // SC_ScrollBarAddPage
return QRect(sb->orientation == Qt::Horizontal ? sr.topRight() : sr.bottomLeft(), contentRect.bottomRight());
}
break;
}
case SC_ScrollBarAddLine: pe = PseudoElement_ScrollBarAddLine; break;
case SC_ScrollBarSubLine: pe = PseudoElement_ScrollBarSubLine; break;
case SC_ScrollBarFirst: pe = PseudoElement_ScrollBarFirst; break;
case SC_ScrollBarLast: pe = PseudoElement_ScrollBarLast; break;
default: break;
}
if (hasStyleRule(w,pe)) {
QRenderRule subRule = renderRule(w, opt, pe);
if (subRule.hasPosition() || subRule.hasGeometry() || subRule.hasBox()) {
const QStyleSheetPositionData *pos = subRule.position();
QRect originRect = grooveRect;
if (rule.hasBox()) {
Origin origin = (pos && pos->origin != Origin_Unknown) ? pos->origin : defaultOrigin(pe);
originRect = rule.originRect(opt->rect, origin);
}
return positionRect(w, subRule, pe, originRect, styleOptionSlider.direction);
}
}
}
return rule.baseStyleCanDraw() ? baseStyle()->subControlRect(cc, &styleOptionSlider, sc, w)
: QWindowsStyle::subControlRect(cc, &styleOptionSlider, sc, w);
}
break;
#endif // QT_CONFIG(scrollbar)
#if QT_CONFIG(slider)
case CC_Slider:
if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
QRenderRule subRule = renderRule(w, opt, PseudoElement_SliderGroove);
if (!subRule.hasDrawable())
break;
subRule.img = 0;
QRect gr = positionRect(w, rule, subRule, PseudoElement_SliderGroove, opt->rect, opt->direction);
switch (sc) {
case SC_SliderGroove:
return gr;
case SC_SliderHandle: {
bool horizontal = slider->orientation & Qt::Horizontal;
QRect cr = subRule.contentsRect(gr);
QRenderRule subRule2 = renderRule(w, opt, PseudoElement_SliderHandle);
int len = horizontal ? subRule2.size().width() : subRule2.size().height();
subRule2.img = 0;
subRule2.geo = 0;
cr = positionRect(w, subRule2, PseudoElement_SliderHandle, cr, opt->direction);
int thickness = horizontal ? cr.height() : cr.width();
int sliderPos = sliderPositionFromValue(slider->minimum, slider->maximum, slider->sliderPosition,
(horizontal ? cr.width() : cr.height()) - len, slider->upsideDown);
cr = horizontal ? QRect(cr.x() + sliderPos, cr.y(), len, thickness)
: QRect(cr.x(), cr.y() + sliderPos, thickness, len);
return subRule2.borderRect(cr);
break; }
case SC_SliderTickmarks:
// TODO...
default:
break;
}
}
break;
#endif // QT_CONFIG(slider)
case CC_MdiControls:
if (hasStyleRule(w, PseudoElement_MdiCloseButton)
|| hasStyleRule(w, PseudoElement_MdiNormalButton)
|| hasStyleRule(w, PseudoElement_MdiMinButton)) {
QList<QVariant> layout = rule.styleHint(QLatin1String("button-layout")).toList();
if (layout.isEmpty())
layout = subControlLayout(QLatin1String("mNX"));
int x = 0, width = 0;
QRenderRule subRule;
for (int i = 0; i < layout.count(); i++) {
int layoutButton = layout[i].toInt();
if (layoutButton < PseudoElement_MdiCloseButton
|| layoutButton > PseudoElement_MdiNormalButton)
continue;
QStyle::SubControl control = knownPseudoElements[layoutButton].subControl;
if (!(opt->subControls & control))
continue;
subRule = renderRule(w, opt, layoutButton);
width = subRule.size().width();
if (sc == control)
break;
x += width;
}
return subRule.borderRect(QRect(x, opt->rect.top(), width, opt->rect.height()));
}
break;
case CC_TitleBar:
if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
QRenderRule subRule = renderRule(w, opt, PseudoElement_TitleBar);
if (!subRule.hasDrawable() && !subRule.hasBox() && !subRule.hasBorder())
break;
QHash<QStyle::SubControl, QRect> layoutRects = titleBarLayout(w, tb);
return layoutRects.value(sc);
}
break;
default:
break;
}
return baseStyle()->subControlRect(cc, opt, sc, w);
}
QRect QStyleSheetStyle::subElementRect(SubElement se, const QStyleOption *opt, const QWidget *w) const
{
RECURSION_GUARD(return baseStyle()->subElementRect(se, opt, w))
QRenderRule rule = renderRule(w, opt);
#if QT_CONFIG(tabbar)
int pe = PseudoElement_None;
#endif
switch (se) {
case SE_PushButtonContents:
case SE_PushButtonFocusRect:
if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
QStyleOptionButton btnOpt(*btn);
if (rule.hasBox() || !rule.hasNativeBorder())
return visualRect(opt->direction, opt->rect, rule.contentsRect(opt->rect));
return rule.baseStyleCanDraw() ? baseStyle()->subElementRect(se, &btnOpt, w)
: QWindowsStyle::subElementRect(se, &btnOpt, w);
}
break;
case SE_LineEditContents:
case SE_FrameContents:
case SE_ShapedFrameContents:
if (rule.hasBox() || !rule.hasNativeBorder()) {
return visualRect(opt->direction, opt->rect, rule.contentsRect(opt->rect));
}
break;
case SE_CheckBoxIndicator:
case SE_RadioButtonIndicator:
if (rule.hasBox() || rule.hasBorder() || hasStyleRule(w, PseudoElement_Indicator)) {
PseudoElement pe = se == SE_CheckBoxIndicator ? PseudoElement_Indicator : PseudoElement_ExclusiveIndicator;
QRenderRule subRule = renderRule(w, opt, pe);
return positionRect(w, rule, subRule, pe, opt->rect, opt->direction);
}
break;
case SE_CheckBoxContents:
case SE_RadioButtonContents:
if (rule.hasBox() || rule.hasBorder() || hasStyleRule(w, PseudoElement_Indicator)) {
bool isRadio = se == SE_RadioButtonContents;
QRect ir = subElementRect(isRadio ? SE_RadioButtonIndicator : SE_CheckBoxIndicator,
opt, w);
ir = visualRect(opt->direction, opt->rect, ir);
int spacing = pixelMetric(isRadio ? PM_RadioButtonLabelSpacing : PM_CheckBoxLabelSpacing, 0, w);
QRect cr = rule.contentsRect(opt->rect);
ir.setRect(ir.left() + ir.width() + spacing, cr.y(),
cr.width() - ir.width() - spacing, cr.height());
return visualRect(opt->direction, opt->rect, ir);
}
break;
case SE_ToolBoxTabContents:
if (w && hasStyleRule(w->parentWidget(), PseudoElement_ToolBoxTab)) {
QRenderRule subRule = renderRule(w->parentWidget(), opt, PseudoElement_ToolBoxTab);
return visualRect(opt->direction, opt->rect, subRule.contentsRect(opt->rect));
}
break;
case SE_RadioButtonFocusRect:
case SE_RadioButtonClickRect: // focusrect | indicator
if (rule.hasBox() || rule.hasBorder() || hasStyleRule(w, PseudoElement_Indicator)) {
return opt->rect;
}
break;
case SE_CheckBoxFocusRect:
case SE_CheckBoxClickRect: // relies on indicator and contents
return ParentStyle::subElementRect(se, opt, w);
#if QT_CONFIG(itemviews)
case SE_ViewItemCheckIndicator:
if (!qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
return subElementRect(SE_CheckBoxIndicator, opt, w);
}
// intentionally falls through
case SE_ItemViewItemText:
case SE_ItemViewItemDecoration:
case SE_ItemViewItemFocusRect:
if (const QStyleOptionViewItem *vopt = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
QRenderRule subRule = renderRule(w, opt, PseudoElement_ViewItem);
PseudoElement pe = PseudoElement_None;
if (se == SE_ItemViewItemText || se == SE_ItemViewItemFocusRect)
pe = PseudoElement_ViewItemText;
else if (se == SE_ItemViewItemDecoration && vopt->features & QStyleOptionViewItem::HasDecoration)
pe = PseudoElement_ViewItemIcon;
else if (se == SE_ItemViewItemCheckIndicator && vopt->features & QStyleOptionViewItem::HasCheckIndicator)
pe = PseudoElement_ViewItemIndicator;
else
break;
if (subRule.hasGeometry() || subRule.hasBox() || !subRule.hasNativeBorder() || hasStyleRule(w, pe)) {
QRenderRule subRule2 = renderRule(w, opt, pe);
QStyleOptionViewItem optCopy(*vopt);
optCopy.rect = subRule.contentsRect(vopt->rect);
QRect rect = ParentStyle::subElementRect(se, &optCopy, w);
return positionRect(w, subRule2, pe, rect, opt->direction);
}
}
break;
#endif // QT_CONFIG(itemviews)
case SE_HeaderArrow: {
QRenderRule subRule = renderRule(w, opt, PseudoElement_HeaderViewUpArrow);
if (subRule.hasPosition() || subRule.hasGeometry())
return positionRect(w, rule, subRule, PseudoElement_HeaderViewUpArrow, opt->rect, opt->direction);
}
break;
case SE_HeaderLabel: {
QRenderRule subRule = renderRule(w, opt, PseudoElement_HeaderViewSection);
if (subRule.hasBox() || !subRule.hasNativeBorder())
return subRule.contentsRect(opt->rect);
}
break;
case SE_ProgressBarGroove:
case SE_ProgressBarContents:
case SE_ProgressBarLabel:
if (const QStyleOptionProgressBar *pb = qstyleoption_cast<const QStyleOptionProgressBar *>(opt)) {
if (rule.hasBox() || !rule.hasNativeBorder() || rule.hasPosition() || hasStyleRule(w, PseudoElement_ProgressBarChunk)) {
if (se == SE_ProgressBarGroove)
return rule.borderRect(pb->rect);
else if (se == SE_ProgressBarContents)
return rule.contentsRect(pb->rect);
QSize sz = pb->fontMetrics.size(0, pb->text);
return QStyle::alignedRect(Qt::LeftToRight, rule.hasPosition() ? rule.position()->textAlignment : pb->textAlignment,
sz, pb->rect);
}
}
break;
#if QT_CONFIG(tabbar)
case SE_TabWidgetLeftCorner:
pe = PseudoElement_TabWidgetLeftCorner;
// intentionally falls through
case SE_TabWidgetRightCorner:
if (pe == PseudoElement_None)
pe = PseudoElement_TabWidgetRightCorner;
// intentionally falls through
case SE_TabWidgetTabBar:
if (pe == PseudoElement_None)
pe = PseudoElement_TabWidgetTabBar;
// intentionally falls through
case SE_TabWidgetTabPane:
case SE_TabWidgetTabContents:
if (pe == PseudoElement_None)
pe = PseudoElement_TabWidgetPane;
if (hasStyleRule(w, pe)) {
QRect r = QWindowsStyle::subElementRect(pe == PseudoElement_TabWidgetPane ? SE_TabWidgetTabPane : se, opt, w);
QRenderRule subRule = renderRule(w, opt, pe);
r = positionRect(w, subRule, pe, r, opt->direction);
if (pe == PseudoElement_TabWidgetTabBar) {
Q_ASSERT(opt);
r = opt->rect.intersected(r);
}
if (se == SE_TabWidgetTabContents)
r = subRule.contentsRect(r);
return r;
}
break;
case SE_TabBarTearIndicator: {
QRenderRule subRule = renderRule(w, opt, PseudoElement_TabBarTear);
if (subRule.hasContentsSize()) {
QRect r;
if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
switch (tab->shape) {
case QTabBar::RoundedNorth:
case QTabBar::TriangularNorth:
case QTabBar::RoundedSouth:
case QTabBar::TriangularSouth:
r.setRect(tab->rect.left(), tab->rect.top(), subRule.size().width(), opt->rect.height());
break;
case QTabBar::RoundedWest:
case QTabBar::TriangularWest:
case QTabBar::RoundedEast:
case QTabBar::TriangularEast:
r.setRect(tab->rect.left(), tab->rect.top(), opt->rect.width(), subRule.size().height());
break;
default:
break;
}
r = visualRect(opt->direction, opt->rect, r);
}
return r;
}
break;
}
case SE_TabBarTabText:
case SE_TabBarTabLeftButton:
case SE_TabBarTabRightButton: {
QRenderRule subRule = renderRule(w, opt, PseudoElement_TabBarTab);
if (subRule.hasBox() || !subRule.hasNativeBorder()) {
return ParentStyle::subElementRect(se, opt, w);
}
break;
}
#endif // QT_CONFIG(tabbar)
case SE_DockWidgetCloseButton:
case SE_DockWidgetFloatButton: {
PseudoElement pe = (se == SE_DockWidgetCloseButton) ? PseudoElement_DockWidgetCloseButton : PseudoElement_DockWidgetFloatButton;
QRenderRule subRule2 = renderRule(w, opt, pe);
if (!subRule2.hasPosition())
break;
QRenderRule subRule = renderRule(w, opt, PseudoElement_DockWidgetTitle);
return positionRect(w, subRule, subRule2, pe, opt->rect, opt->direction);
}
#ifndef QT_NO_TOOLBAR
case SE_ToolBarHandle:
if (hasStyleRule(w, PseudoElement_ToolBarHandle))
return ParentStyle::subElementRect(se, opt, w);
break;
#endif //QT_NO_TOOLBAR
// On mac we make pixel adjustments to layouts which are not
// desireable when you have custom style sheets on them
case SE_CheckBoxLayoutItem:
case SE_ComboBoxLayoutItem:
case SE_DateTimeEditLayoutItem:
case SE_LabelLayoutItem:
case SE_ProgressBarLayoutItem:
case SE_PushButtonLayoutItem:
case SE_RadioButtonLayoutItem:
case SE_SliderLayoutItem:
case SE_SpinBoxLayoutItem:
case SE_ToolButtonLayoutItem:
case SE_FrameLayoutItem:
case SE_GroupBoxLayoutItem:
case SE_TabWidgetLayoutItem:
if (!rule.hasNativeBorder())
return opt->rect;
break;
default:
break;
}
return baseStyle()->subElementRect(se, opt, w);
}
bool QStyleSheetStyle::event(QEvent *e)
{
return (baseStyle()->event(e) && e->isAccepted()) || ParentStyle::event(e);
}
void QStyleSheetStyle::updateStyleSheetFont(QWidget* w) const
{
// Qt's fontDialog relies on the font of the sample edit for its selection,
// we should never override it.
if (w->objectName() == QLatin1String("qt_fontDialog_sampleEdit"))
return;
QWidget *container = containerWidget(w);
QRenderRule rule = renderRule(container, PseudoElement_None,
PseudoClass_Active | PseudoClass_Enabled | extendedPseudoClass(container));
const bool useStyleSheetPropagationInWidgetStyles =
QCoreApplication::testAttribute(Qt::AA_UseStyleSheetPropagationInWidgetStyles);
if (useStyleSheetPropagationInWidgetStyles) {
unsetStyleSheetFont(w);
if (rule.font.resolve()) {
QFont wf = w->font();
styleSheetCaches->customFontWidgets.insert(w, {wf, rule.font.resolve()});
QFont font = rule.font.resolve(wf);
font.resolve(wf.resolve() | rule.font.resolve());
w->setFont(font);
}
} else {
QFont font = rule.font.resolve(w->font());
if ((!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))
&& isNaturalChild(w) && qobject_cast<QWidget *>(w->parent())) {
font = font.resolve(static_cast<QWidget *>(w->parent())->font());
}
if (w->data->fnt == font)
return;
w->data->fnt = font;
QEvent e(QEvent::FontChange);
QApplication::sendEvent(w, &e);
}
}
void QStyleSheetStyle::saveWidgetFont(QWidget* w, const QFont& font) const
{
w->setProperty("_q_styleSheetWidgetFont", font);
}
void QStyleSheetStyle::clearWidgetFont(QWidget* w) const
{
w->setProperty("_q_styleSheetWidgetFont", QVariant(QVariant::Invalid));
}
// Polish palette that should be used for a particular widget, with particular states
// (eg. :focus, :hover, ...)
// this is called by widgets that paint themself in their paint event
// Returns \c true if there is a new palette in pal.
bool QStyleSheetStyle::styleSheetPalette(const QWidget* w, const QStyleOption* opt, QPalette* pal)
{
if (!w || !opt || !pal)
return false;
RECURSION_GUARD(return false)
w = containerWidget(w);
QRenderRule rule = renderRule(w, PseudoElement_None, pseudoClass(opt->state) | extendedPseudoClass(w));
if (!rule.hasPalette())
return false;
rule.configurePalette(pal, QPalette::NoRole, QPalette::NoRole);
return true;
}
Qt::Alignment QStyleSheetStyle::resolveAlignment(Qt::LayoutDirection layDir, Qt::Alignment src)
{
if (layDir == Qt::LeftToRight || src & Qt::AlignAbsolute)
return src;
if (src & Qt::AlignLeft) {
src &= ~Qt::AlignLeft;
src |= Qt::AlignRight;
} else if (src & Qt::AlignRight) {
src &= ~Qt::AlignRight;
src |= Qt::AlignLeft;
}
src |= Qt::AlignAbsolute;
return src;
}
// Returns whether the given QWidget has a "natural" parent, meaning that
// the parent contains this child as part of its normal operation.
// An example is the QTabBar inside a QTabWidget.
// This does not mean that any QTabBar which is a child of QTabWidget will
// match, only the one that was created by the QTabWidget initialization
// (and hence has the correct object name).
bool QStyleSheetStyle::isNaturalChild(const QObject *obj)
{
if (obj->objectName().startsWith(QLatin1String("qt_")))
return true;
return false;
}
QT_END_NAMESPACE
#include "moc_qstylesheetstyle_p.cpp"
#endif // QT_CONFIG(style_stylesheet)
|
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include "../params.h"
#include "random.h"
using std::vector;
int main(int, char **argv) {
const long long seed = atoll(argv[1]);
// auto rng = Random(seed * 3 + 0);
const long long R = 0;
int D = -1;
long long N = -1;
switch (seed % 5) {
case 0: D = 0; N = 0; break;
case 1: D = 0; N = 1; break;
case 2: D = D_MAX; N = 0; break;
case 3: D = D_MAX; N = 1; break;
case 4: D = D_MAX; N = N_MAX; break;
default: assert(false);
}
printf("%lld %d %lld\n", R, D, N);
return 0;
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/network/network_sms_handler.h"
#include <algorithm>
#include <deque>
#include <string>
#include <vector>
#include "base/bind.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/shill_device_client.h"
#include "chromeos/dbus/shill_manager_client.h"
#include "chromeos/dbus/gsm_sms_client.h"
#include "chromeos/dbus/modem_messaging_client.h"
#include "chromeos/dbus/sms_client.h"
#include "dbus/object_path.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
// Not exposed/exported.
namespace {
const char kSmscKey[] = "smsc";
const char kValidityKey[] = "validity";
const char kClassKey[] = "class";
const char kIndexKey[] = "index";
// Keys from ModemManager1
const char kModemManager1NumberKey[] = "Number";
const char kModemManager1TextKey[] = "Text";
const char kModemManager1TimestampKey[] = "Timestamp";
} // namespace
namespace chromeos {
// static
const char NetworkSmsHandler::kNumberKey[] = "number";
const char NetworkSmsHandler::kTextKey[] = "text";
const char NetworkSmsHandler::kTimestampKey[] = "timestamp";
class NetworkSmsHandler::NetworkSmsDeviceHandler {
public:
NetworkSmsDeviceHandler() {}
virtual ~NetworkSmsDeviceHandler() {}
virtual void RequestUpdate() = 0;
};
class NetworkSmsHandler::ModemManagerNetworkSmsDeviceHandler
: public NetworkSmsHandler::NetworkSmsDeviceHandler {
public:
ModemManagerNetworkSmsDeviceHandler(NetworkSmsHandler* host,
std::string dbus_connection,
dbus::ObjectPath object_path);
virtual void RequestUpdate() OVERRIDE;
private:
void ListCallback(const base::ListValue& message_list);
void SmsReceivedCallback(uint32 index, bool complete);
void GetCallback(uint32 index, const base::DictionaryValue& dictionary);
void DeleteMessages();
void NotifyMessageReceived(const base::DictionaryValue& dictionary);
NetworkSmsHandler* host_;
std::string dbus_connection_;
dbus::ObjectPath object_path_;
bool deleting_messages_;
base::WeakPtrFactory<ModemManagerNetworkSmsDeviceHandler> weak_ptr_factory_;
std::vector<uint32> delete_queue_;
DISALLOW_COPY_AND_ASSIGN(ModemManagerNetworkSmsDeviceHandler);
};
NetworkSmsHandler::
ModemManagerNetworkSmsDeviceHandler::ModemManagerNetworkSmsDeviceHandler(
NetworkSmsHandler* host,
std::string dbus_connection,
dbus::ObjectPath object_path)
: host_(host),
dbus_connection_(dbus_connection),
object_path_(object_path),
deleting_messages_(false),
weak_ptr_factory_(this) {
// Set the handler for received Sms messaages.
DBusThreadManager::Get()->GetGsmSMSClient()->SetSmsReceivedHandler(
dbus_connection_, object_path_,
base::Bind(&ModemManagerNetworkSmsDeviceHandler::SmsReceivedCallback,
weak_ptr_factory_.GetWeakPtr()));
// List the existing messages.
DBusThreadManager::Get()->GetGsmSMSClient()->List(
dbus_connection_, object_path_,
base::Bind(&NetworkSmsHandler::
ModemManagerNetworkSmsDeviceHandler::ListCallback,
weak_ptr_factory_.GetWeakPtr()));
}
void NetworkSmsHandler::ModemManagerNetworkSmsDeviceHandler::RequestUpdate() {
DBusThreadManager::Get()->GetGsmSMSClient()->RequestUpdate(
dbus_connection_, object_path_);
}
void NetworkSmsHandler::ModemManagerNetworkSmsDeviceHandler::ListCallback(
const base::ListValue& message_list) {
// This receives all messages, so clear any pending deletes.
delete_queue_.clear();
for (base::ListValue::const_iterator iter = message_list.begin();
iter != message_list.end(); ++iter) {
base::DictionaryValue* message = NULL;
if (!(*iter)->GetAsDictionary(&message))
continue;
NotifyMessageReceived(*message);
double index = 0;
if (message->GetDoubleWithoutPathExpansion(kIndexKey, &index))
delete_queue_.push_back(static_cast<uint32>(index));
}
DeleteMessages();
}
// Messages must be deleted one at a time, since we can not guarantee
// the order the deletion will be executed in. Delete messages from
// the back of the list so that the indices are valid.
void NetworkSmsHandler::ModemManagerNetworkSmsDeviceHandler::DeleteMessages() {
if (delete_queue_.empty()) {
deleting_messages_ = false;
return;
}
deleting_messages_ = true;
uint32 index = delete_queue_.back();
delete_queue_.pop_back();
DBusThreadManager::Get()->GetGsmSMSClient()->Delete(
dbus_connection_, object_path_, index,
base::Bind(&NetworkSmsHandler::
ModemManagerNetworkSmsDeviceHandler::DeleteMessages,
weak_ptr_factory_.GetWeakPtr()));
}
void NetworkSmsHandler::
ModemManagerNetworkSmsDeviceHandler::SmsReceivedCallback(
uint32 index,
bool complete) {
// Only handle complete messages.
if (!complete)
return;
DBusThreadManager::Get()->GetGsmSMSClient()->Get(
dbus_connection_, object_path_, index,
base::Bind(&NetworkSmsHandler::
ModemManagerNetworkSmsDeviceHandler::GetCallback,
weak_ptr_factory_.GetWeakPtr(), index));
}
void NetworkSmsHandler::ModemManagerNetworkSmsDeviceHandler::GetCallback(
uint32 index,
const base::DictionaryValue& dictionary) {
NotifyMessageReceived(dictionary);
delete_queue_.push_back(index);
if (!deleting_messages_)
DeleteMessages();
}
void NetworkSmsHandler::
ModemManagerNetworkSmsDeviceHandler::NotifyMessageReceived(
const base::DictionaryValue& dictionary) {
// The keys of the ModemManager.Modem.Gsm.SMS interface match the
// exported keys, so the dictionary used as a notification argument
// unchanged.
host_->NotifyMessageReceived(dictionary);
}
class NetworkSmsHandler::ModemManager1NetworkSmsDeviceHandler
: public NetworkSmsHandler::NetworkSmsDeviceHandler {
public:
ModemManager1NetworkSmsDeviceHandler(NetworkSmsHandler* host,
std::string dbus_connection,
dbus::ObjectPath object_path);
virtual void RequestUpdate() OVERRIDE;
private:
void ListCallback(const std::vector<dbus::ObjectPath>& paths);
void SmsReceivedCallback(const dbus::ObjectPath& path, bool complete);
void GetCallback(const base::DictionaryValue& dictionary);
void DeleteMessages();
void GetMessages();
void NotifyMessageReceived(const base::DictionaryValue& dictionary);
NetworkSmsHandler* host_;
std::string dbus_connection_;
dbus::ObjectPath object_path_;
bool deleting_messages_;
bool retrieving_messages_;
base::WeakPtrFactory<ModemManager1NetworkSmsDeviceHandler> weak_ptr_factory_;
std::vector<dbus::ObjectPath> delete_queue_;
std::deque<dbus::ObjectPath> retrieval_queue_;
DISALLOW_COPY_AND_ASSIGN(ModemManager1NetworkSmsDeviceHandler);
};
NetworkSmsHandler::
ModemManager1NetworkSmsDeviceHandler::ModemManager1NetworkSmsDeviceHandler(
NetworkSmsHandler* host,
std::string dbus_connection,
dbus::ObjectPath object_path)
: host_(host),
dbus_connection_(dbus_connection),
object_path_(object_path),
deleting_messages_(false),
retrieving_messages_(false),
weak_ptr_factory_(this) {
// Set the handler for received Sms messaages.
DBusThreadManager::Get()->GetModemMessagingClient()->SetSmsReceivedHandler(
dbus_connection_, object_path_,
base::Bind(
&NetworkSmsHandler::
ModemManager1NetworkSmsDeviceHandler::SmsReceivedCallback,
weak_ptr_factory_.GetWeakPtr()));
// List the existing messages.
DBusThreadManager::Get()->GetModemMessagingClient()->List(
dbus_connection_, object_path_,
base::Bind(&NetworkSmsHandler::
ModemManager1NetworkSmsDeviceHandler::ListCallback,
weak_ptr_factory_.GetWeakPtr()));
}
void NetworkSmsHandler::ModemManager1NetworkSmsDeviceHandler::RequestUpdate() {
// Calling List using the service "AddSMS" causes the stub
// implementation to deliver new sms messages.
DBusThreadManager::Get()->GetModemMessagingClient()->List(
std::string("AddSMS"), dbus::ObjectPath("/"),
base::Bind(&NetworkSmsHandler::
ModemManager1NetworkSmsDeviceHandler::ListCallback,
weak_ptr_factory_.GetWeakPtr()));
}
void NetworkSmsHandler::ModemManager1NetworkSmsDeviceHandler::ListCallback(
const std::vector<dbus::ObjectPath>& paths) {
// This receives all messages, so clear any pending gets and deletes.
retrieval_queue_.clear();
delete_queue_.clear();
retrieval_queue_.resize(paths.size());
std::copy(paths.begin(), paths.end(), retrieval_queue_.begin());
if (!retrieving_messages_)
GetMessages();
}
// Messages must be deleted one at a time, since we can not guarantee
// the order the deletion will be executed in. Delete messages from
// the back of the list so that the indices are valid.
void NetworkSmsHandler::ModemManager1NetworkSmsDeviceHandler::DeleteMessages() {
if (delete_queue_.empty()) {
deleting_messages_ = false;
return;
}
deleting_messages_ = true;
dbus::ObjectPath sms_path = delete_queue_.back();
delete_queue_.pop_back();
DBusThreadManager::Get()->GetModemMessagingClient()->Delete(
dbus_connection_, object_path_, sms_path,
base::Bind(&NetworkSmsHandler::
ModemManager1NetworkSmsDeviceHandler::DeleteMessages,
weak_ptr_factory_.GetWeakPtr()));
}
// Messages must be fetched one at a time, so that we do not queue too
// many requests to a single threaded server.
void NetworkSmsHandler::ModemManager1NetworkSmsDeviceHandler::GetMessages() {
if (retrieval_queue_.empty()) {
retrieving_messages_ = false;
if (!deleting_messages_)
DeleteMessages();
return;
}
retrieving_messages_ = true;
dbus::ObjectPath sms_path = retrieval_queue_.front();
retrieval_queue_.pop_front();
DBusThreadManager::Get()->GetSMSClient()->GetAll(
dbus_connection_, sms_path,
base::Bind(&NetworkSmsHandler::
ModemManager1NetworkSmsDeviceHandler::GetCallback,
weak_ptr_factory_.GetWeakPtr()));
delete_queue_.push_back(sms_path);
}
void NetworkSmsHandler::
ModemManager1NetworkSmsDeviceHandler::SmsReceivedCallback(
const dbus::ObjectPath& sms_path,
bool complete) {
// Only handle complete messages.
if (!complete)
return;
retrieval_queue_.push_back(sms_path);
if (!retrieving_messages_)
GetMessages();
}
void NetworkSmsHandler::ModemManager1NetworkSmsDeviceHandler::GetCallback(
const base::DictionaryValue& dictionary) {
NotifyMessageReceived(dictionary);
GetMessages();
}
void NetworkSmsHandler::
ModemManager1NetworkSmsDeviceHandler::NotifyMessageReceived(
const base::DictionaryValue& dictionary) {
// The keys of the ModemManager1.SMS interface do not match the
// exported keys, so a new dictionary is created with the expected
// key namaes.
base::DictionaryValue new_dictionary;
std::string text, number, timestamp;
if (dictionary.GetStringWithoutPathExpansion(kModemManager1NumberKey,
&number))
new_dictionary.SetString(kNumberKey, number);
if (dictionary.GetStringWithoutPathExpansion(kModemManager1TextKey, &text))
new_dictionary.SetString(kTextKey, text);
// TODO(jglasgow): consider normalizing timestamp.
if (dictionary.GetStringWithoutPathExpansion(kModemManager1TimestampKey,
×tamp))
new_dictionary.SetString(kTimestampKey, timestamp);
host_->NotifyMessageReceived(new_dictionary);
}
///////////////////////////////////////////////////////////////////////////////
// NetworkSmsHandler
NetworkSmsHandler::NetworkSmsHandler()
: weak_ptr_factory_(this) {
}
NetworkSmsHandler::~NetworkSmsHandler() {
}
void NetworkSmsHandler::Init() {
// TODO(stevenjb): This code needs to monitor changes to Manager.Network
// so that devices added after Init() is called get added to device_handlers_.
// See: crbug.com/133416.
// Request network manager properties so that we can get the list of devices.
DBusThreadManager::Get()->GetShillManagerClient()->GetProperties(
base::Bind(&NetworkSmsHandler::ManagerPropertiesCallback,
weak_ptr_factory_.GetWeakPtr()));
}
void NetworkSmsHandler::RequestUpdate() {
for (ScopedVector<NetworkSmsDeviceHandler>::iterator iter =
device_handlers_.begin(); iter != device_handlers_.end(); ++iter) {
(*iter)->RequestUpdate();
}
}
void NetworkSmsHandler::AddObserver(Observer* observer) {
observers_.AddObserver(observer);
}
void NetworkSmsHandler::RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
void NetworkSmsHandler::NotifyMessageReceived(
const base::DictionaryValue& message) {
FOR_EACH_OBSERVER(Observer, observers_, MessageReceived(message));
}
void NetworkSmsHandler::ManagerPropertiesCallback(
DBusMethodCallStatus call_status,
const base::DictionaryValue& properties) {
if (call_status != DBUS_METHOD_CALL_SUCCESS) {
LOG(ERROR) << "NetworkSmsHandler: Failed to get manager properties.";
return;
}
const base::Value* value;
if (!properties.GetWithoutPathExpansion(flimflam::kDevicesProperty, &value) ||
value->GetType() != base::Value::TYPE_LIST) {
LOG(ERROR) << "NetworkSmsHandler: No list value for: "
<< flimflam::kDevicesProperty;
return;
}
const base::ListValue* devices = static_cast<const base::ListValue*>(value);
for (base::ListValue::const_iterator iter = devices->begin();
iter != devices->end(); ++iter) {
std::string device_path;
(*iter)->GetAsString(&device_path);
if (!device_path.empty()) {
// Request device properties.
VLOG(1) << "GetDeviceProperties: " << device_path;
DBusThreadManager::Get()->GetShillDeviceClient()->GetProperties(
dbus::ObjectPath(device_path),
base::Bind(&NetworkSmsHandler::DevicePropertiesCallback,
weak_ptr_factory_.GetWeakPtr(),
device_path));
}
}
}
void NetworkSmsHandler::DevicePropertiesCallback(
const std::string& device_path,
DBusMethodCallStatus call_status,
const base::DictionaryValue& properties) {
if (call_status != DBUS_METHOD_CALL_SUCCESS) {
LOG(ERROR) << "NetworkSmsHandler: ERROR: " << call_status
<< " For: " << device_path;
return;
}
std::string device_type;
if (!properties.GetStringWithoutPathExpansion(
flimflam::kTypeProperty, &device_type)) {
LOG(ERROR) << "NetworkSmsHandler: No type for: " << device_path;
return;
}
if (device_type != flimflam::kTypeCellular)
return;
std::string dbus_connection;
if (!properties.GetStringWithoutPathExpansion(
flimflam::kDBusConnectionProperty, &dbus_connection)) {
LOG(ERROR) << "Device has no DBusConnection Property: " << device_path;
return;
}
std::string object_path_string;
if (!properties.GetStringWithoutPathExpansion(
flimflam::kDBusObjectProperty, &object_path_string)) {
LOG(ERROR) << "Device has no DBusObject Property: " << device_path;
return;
}
dbus::ObjectPath object_path(object_path_string);
if (object_path_string.compare(
0, sizeof(modemmanager::kModemManager1ServicePath) - 1,
modemmanager::kModemManager1ServicePath) == 0) {
device_handlers_.push_back(
new ModemManager1NetworkSmsDeviceHandler(
this, dbus_connection, object_path));
} else {
device_handlers_.push_back(
new ModemManagerNetworkSmsDeviceHandler(
this, dbus_connection, object_path));
}
}
} // namespace chromeos
|
#include <bits/stdc++.h>
using namespace std;
const int MM = 1e6+2, SZ = MM*4;
struct ari_seg{
#define lc (rt<<1)
#define rc (rt<<1|1)
#define nm ((nl+nr)>>1)
int K[SZ], D[SZ], LK[SZ], LD[SZ], S[SZ];
void push_up(int rt){
S[rt] = S[lc] + S[rc];
}
void push_down(int nl, int nr, int rt){
if(LK[rt] == 0 && LD[rt] == 0)
return;
int sz = (nr-nl+1)/2;
K[lc] += LK[rt];
K[rc] += LK[rt]+LD[rt]*sz;
D[lc] += LD[rt];
D[rc] += LD[rt];
S[lc] += LK[rt]*sz + LD[rt]*sz*(sz-1)/2;
S[rc] += (LK[rt]+LD[rt]*sz)*sz + LD[rt]*sz*(sz-1)/2;
LK[lc] += LK[rt];
LK[rc] += LK[rt]+LD[rt]*sz;
LD[lc] += LD[rt];
LD[rc] += LD[rt];
LK[rt] = LD[rt] = 0;
}
int query(int l, int r, int nl = 1, int nr = MM-1, int rt = 1){
if(nl > r || nr < l)
return 0;
if(nl >= l && nr <= r)
return S[rt];
push_down(nl, nr, rt);
return query(l, r, nl, nm, lc) + query(l, r, nm + 1, nr, rc);
}
//add from l to r, first term = k, dif = d
void update(int l, int r, int k, int d, int nl = 1, int nr = MM-1, int rt = 1){
if(nl >= l && nr <= r){
K[rt] += k, D[rt] += d;
LK[rt] += k, LD[rt] += d;
int sz = (nr-nl+1);
S[rt] += k * sz + d * sz * (sz-1)/2;
return;
}
push_down(nl, nr, rt);
if(l <= nm) update(l, min(nm, r), k, d, nl, nm, lc);
if(r > nm) update(max(nm+1, l), r, k + d*max(nm-l+1, 0), d, nm+1, nr, rc);
push_up(rt);
}
#undef lc
#undef rc
#undef nm
} T;
int n, q;
int main(){
scanf("%d%d", &n, &q);
for(int i = 0,t,l,r,d; i < q; i++){
scanf("%d", &t);
if(t == 1){
scanf("%d%d%d", &l, &r, &d);
T.update(l,r,d,d);
}
else{
scanf("%d%d", &l, &r);
printf("%d\n", T.query(l,r));
}
}
}
|
#include <vector>
using namespace std;
// 12 ms, 9.9 MB. Greedy.
class Solution {
public:
bool canJump(vector<int>& nums) {
int farest = nums[0];
for (int i = 0; i < nums.size(); ++i) {
if (farest >= nums.size() - 1) {
return true;
}
if (i >= farest && nums[i] == 0) {
return false;
}
if (i + nums[i] > farest) {
farest = i + nums[i];
}
}
return false;
}
};
|
/*
* This file is part of the GROMACS molecular simulation package.
*
* Copyright (c) 2016,2018,2019,2020, by the GROMACS development team, led by
* Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
* and including many others, as listed in the AUTHORS file in the
* top-level source directory and at http://www.gromacs.org.
*
* GROMACS 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.
*
* GROMACS 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 GROMACS; if not, see
* http://www.gnu.org/licenses, or write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* If you want to redistribute modifications to GROMACS, please
* consider that scientific software is very special. Version
* control is crucial - bugs must be traceable. We will be happy to
* consider code for inclusion in the official distribution, but
* derived work must not be called official GROMACS. Details are found
* in the README & COPYING files - if they are missing, get the
* official version at http://www.gromacs.org.
*
* To help us fund GROMACS development, we humbly ask that you cite
* the research papers on the package. Check out http://www.gromacs.org.
*/
/*! \internal
* \file
* \brief
* Defines a driver routine for lmfit, and a callback for it to use.
*
* \author David van der Spoel <david.vanderspoel@icm.uu.se>
* \author Mark Abraham <mark.j.abraham@gmail.com>
* \ingroup module_correlationfunctions
*/
#include "gmxpre.h"
#include "gmx_lmcurve.h"
#include "config.h"
#include <cmath>
#if HAVE_LMFIT
# include <lmmin.h>
# include <lmstruct.h>
#endif
#include "gromacs/correlationfunctions/expfit.h"
#include "gromacs/math/functions.h"
#include "gromacs/utility/fatalerror.h"
#include "gromacs/utility/smalloc.h"
#if HAVE_LMFIT
typedef struct
{
const double* t;
const double* y;
const double* dy;
double (*f)(const double t, const double* par);
} lmcurve_data_struct;
//! Callback function used by lmmin
static void lmcurve_evaluate(const double* par, const int m_dat, const void* data, double* fvec, int* info)
{
const lmcurve_data_struct* D = reinterpret_cast<const lmcurve_data_struct*>(data);
for (int i = 0; i < m_dat; i++)
{
double dy = D->dy[i];
if (dy == 0)
{
dy = 1;
}
fvec[i] = (D->y[i] - D->f(D->t[i], par)) / dy;
}
*info = 0;
}
//! Calls lmmin with the given data, with callback function \c f.
static void gmx_lmcurve(const int n_par,
double* par,
const int m_dat,
const double* t,
const double* y,
const double* dy,
double (*f)(double t, const double* par),
const lm_control_struct* control,
lm_status_struct* status)
{
lmcurve_data_struct data = { t, y, dy, f };
lmmin(n_par, par, m_dat, nullptr, &data, lmcurve_evaluate, control, status);
}
#endif
bool lmfit_exp(int nfit,
const double x[],
const double y[],
const double dy[],
double parm[], // NOLINT(readability-non-const-parameter)
bool bVerbose,
int eFitFn,
int nfix)
{
if ((eFitFn < 0) || (eFitFn >= effnNR))
{
fprintf(stderr, "fitfn = %d, should be in the range 0..%d\n", eFitFn, effnNR - 1);
return false;
}
#if HAVE_LMFIT
double chisq, ochisq;
gmx_bool bCont;
int j;
int maxiter = 100;
lm_control_struct control;
lm_status_struct* status;
int nparam = effnNparams(eFitFn);
int p2;
gmx_bool bSkipLast;
/* Using default control structure for double precision fitting that
* comes with the lmfit package (i.e. from the include file).
*/
control = lm_control_double;
control.verbosity = (bVerbose ? 1 : 0);
control.n_maxpri = 0;
control.m_maxpri = 0;
snew(status, 1);
/* Initial params */
chisq = 1e12;
j = 0;
if (bVerbose)
{
printf("%4s %10s Parameters\n", "Step", "chi^2");
}
/* Check whether we have to skip some params */
if (nfix > 0)
{
do
{
p2 = 1 << (nparam - 1);
bSkipLast = ((p2 & nfix) == p2);
if (bSkipLast)
{
nparam--;
nfix -= p2;
}
} while ((nparam > 0) && (bSkipLast));
if (bVerbose)
{
printf("Using %d out of %d parameters\n", nparam, effnNparams(eFitFn));
}
}
do
{
ochisq = chisq;
gmx_lmcurve(nparam, parm, nfit, x, y, dy, lmcurves[eFitFn], &control, status);
chisq = gmx::square(status->fnorm);
if (bVerbose)
{
printf("status: fnorm = %g, nfev = %d, userbreak = %d\noutcome = %s\n",
status->fnorm,
status->nfev,
status->userbreak,
lm_infmsg[status->outcome]);
}
if (bVerbose)
{
int mmm;
printf("%4d %8g", j, chisq);
for (mmm = 0; (mmm < effnNparams(eFitFn)); mmm++)
{
printf(" %8g", parm[mmm]);
}
printf("\n");
}
j++;
bCont = (fabs(ochisq - chisq) > fabs(control.ftol * chisq));
} while (bCont && (j < maxiter));
sfree(status);
#else
gmx_fatal(FARGS,
"This build of GROMACS was not configured with support "
"for lmfit, so the requested fitting cannot be performed. "
"See the install guide for instructions on how to build "
"GROMACS with lmfit supported.");
GMX_UNUSED_VALUE(nfit);
GMX_UNUSED_VALUE(x);
GMX_UNUSED_VALUE(y);
GMX_UNUSED_VALUE(dy);
GMX_UNUSED_VALUE(parm);
GMX_UNUSED_VALUE(bVerbose);
GMX_UNUSED_VALUE(eFitFn);
GMX_UNUSED_VALUE(nfix);
#endif
return true;
}
|
#include <ctime>
#include "Citoyen.hpp"
#include "windowParam.hpp"
/**
* Constructeur d'Citoyen
*/
Citoyen::Citoyen(int hp, float speed){
m_texture.loadFromFile("img/sprite_electeur.png");
setTexture(m_texture);
setTextureRect(sf::IntRect(0,0,16,24));
setOrigin(((getTextureRect().width)/2),((getTextureRect().height)/2));
int posIni = rand()%4;
switch(posIni){
case 0:
setPosition(0, rand()%W_HEIGHT);
break;
case 1:
setPosition(W_WIDTH, rand()%W_HEIGHT);
break;
case 2:
setPosition(rand()%W_WIDTH, 0);
break;
case 3:
setPosition(rand()%W_WIDTH, 0);
break;
}
m_hp = hp;
setAlive(true);
m_speed = speed;
m_distance = 0;
m_dirX = 0;
m_dirY = 0;
}
/**
* Deplacement des Citoyens
*/
void Citoyen::deplacement(){
/* Définition de la rotation du personnage selon la direction de son déplacement */
int rotation[3][3] = {
{ -135, -90, -45 },
{ 180, 0, 0 },
{ 135, 90, 45}
};
if(m_distance <= 0)
{
m_distance = 500 + rand() % 300; // déplacement aléatoire durant 500 à 799 frames
// Direction aléatoire
m_dirX = rand()%3;
m_dirY = rand()%3;
}
else
{
setRotation(0);
m_distance --;
switch(m_dirY){
case 0:
goUp();
break;
case 1:
break;
case 2:
goDown();
break;
}
switch(m_dirX){
case 0:
goLeft();
break;
case 1:
break;
case 2:
goRight();
break;
}
}
setRotation(rotation[m_dirY][m_dirX]);
}
void Citoyen::animationDraw(){
static int i = 0;
// On déplace le sprite sur la texture pour obtenir la frame suivante de l'animation
setTextureRect(sf::IntRect(i*16,0,16,24));
i = (i+1) % 7;
}
|
/*------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2016 The Khronos Group Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief Synchronization tests utilities
*//*--------------------------------------------------------------------*/
#include "vktSynchronizationUtil.hpp"
#include "vkTypeUtil.hpp"
#include "vkCmdUtil.hpp"
#include "deStringUtil.hpp"
namespace vkt
{
namespace synchronization
{
using namespace vk;
Move<VkCommandBuffer> makeCommandBuffer (const DeviceInterface& vk, const VkDevice device, const VkCommandPool commandPool)
{
const VkCommandBufferAllocateInfo info =
{
VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
commandPool, // VkCommandPool commandPool;
VK_COMMAND_BUFFER_LEVEL_PRIMARY, // VkCommandBufferLevel level;
1u, // deUint32 commandBufferCount;
};
return allocateCommandBuffer(vk, device, &info);
}
Move<VkPipeline> makeComputePipeline (const DeviceInterface& vk,
const VkDevice device,
const VkPipelineLayout pipelineLayout,
const VkShaderModule shaderModule,
const VkSpecializationInfo* specInfo,
PipelineCacheData& pipelineCacheData)
{
const VkPipelineShaderStageCreateInfo shaderStageInfo =
{
VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkPipelineShaderStageCreateFlags)0, // VkPipelineShaderStageCreateFlags flags;
VK_SHADER_STAGE_COMPUTE_BIT, // VkShaderStageFlagBits stage;
shaderModule, // VkShaderModule module;
"main", // const char* pName;
specInfo, // const VkSpecializationInfo* pSpecializationInfo;
};
const VkComputePipelineCreateInfo pipelineInfo =
{
VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkPipelineCreateFlags)0, // VkPipelineCreateFlags flags;
shaderStageInfo, // VkPipelineShaderStageCreateInfo stage;
pipelineLayout, // VkPipelineLayout layout;
DE_NULL, // VkPipeline basePipelineHandle;
0, // deInt32 basePipelineIndex;
};
{
const vk::Unique<vk::VkPipelineCache> pipelineCache (pipelineCacheData.createPipelineCache(vk, device));
vk::Move<vk::VkPipeline> pipeline (createComputePipeline(vk, device, *pipelineCache, &pipelineInfo));
// Refresh data from cache
pipelineCacheData.setFromPipelineCache(vk, device, *pipelineCache);
return pipeline;
}
}
VkImageCreateInfo makeImageCreateInfo (const VkImageType imageType, const VkExtent3D& extent, const VkFormat format, const VkImageUsageFlags usage)
{
const VkImageCreateInfo imageInfo =
{
VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkImageCreateFlags)0, // VkImageCreateFlags flags;
imageType, // VkImageType imageType;
format, // VkFormat format;
extent, // VkExtent3D extent;
1u, // uint32_t mipLevels;
1u, // uint32_t arrayLayers;
VK_SAMPLE_COUNT_1_BIT, // VkSampleCountFlagBits samples;
VK_IMAGE_TILING_OPTIMAL, // VkImageTiling tiling;
usage, // VkImageUsageFlags usage;
VK_SHARING_MODE_EXCLUSIVE, // VkSharingMode sharingMode;
0u, // uint32_t queueFamilyIndexCount;
DE_NULL, // const uint32_t* pQueueFamilyIndices;
VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout initialLayout;
};
return imageInfo;
}
void beginRenderPassWithRasterizationDisabled (const DeviceInterface& vk,
const VkCommandBuffer commandBuffer,
const VkRenderPass renderPass,
const VkFramebuffer framebuffer)
{
const VkRect2D renderArea = {{ 0, 0 }, { 0, 0 }};
beginRenderPass(vk, commandBuffer, renderPass, framebuffer, renderArea);
}
GraphicsPipelineBuilder& GraphicsPipelineBuilder::setShader (const DeviceInterface& vk,
const VkDevice device,
const VkShaderStageFlagBits stage,
const ProgramBinary& binary,
const VkSpecializationInfo* specInfo)
{
VkShaderModule module;
switch (stage)
{
case (VK_SHADER_STAGE_VERTEX_BIT):
DE_ASSERT(m_vertexShaderModule.get() == DE_NULL);
m_vertexShaderModule = createShaderModule(vk, device, binary, (VkShaderModuleCreateFlags)0);
module = *m_vertexShaderModule;
break;
case (VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT):
DE_ASSERT(m_tessControlShaderModule.get() == DE_NULL);
m_tessControlShaderModule = createShaderModule(vk, device, binary, (VkShaderModuleCreateFlags)0);
module = *m_tessControlShaderModule;
break;
case (VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT):
DE_ASSERT(m_tessEvaluationShaderModule.get() == DE_NULL);
m_tessEvaluationShaderModule = createShaderModule(vk, device, binary, (VkShaderModuleCreateFlags)0);
module = *m_tessEvaluationShaderModule;
break;
case (VK_SHADER_STAGE_GEOMETRY_BIT):
DE_ASSERT(m_geometryShaderModule.get() == DE_NULL);
m_geometryShaderModule = createShaderModule(vk, device, binary, (VkShaderModuleCreateFlags)0);
module = *m_geometryShaderModule;
break;
case (VK_SHADER_STAGE_FRAGMENT_BIT):
DE_ASSERT(m_fragmentShaderModule.get() == DE_NULL);
m_fragmentShaderModule = createShaderModule(vk, device, binary, (VkShaderModuleCreateFlags)0);
module = *m_fragmentShaderModule;
break;
default:
DE_FATAL("Invalid shader stage");
return *this;
}
const VkPipelineShaderStageCreateInfo pipelineShaderStageInfo =
{
VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkPipelineShaderStageCreateFlags)0, // VkPipelineShaderStageCreateFlags flags;
stage, // VkShaderStageFlagBits stage;
module, // VkShaderModule module;
"main", // const char* pName;
specInfo, // const VkSpecializationInfo* pSpecializationInfo;
};
m_shaderStageFlags |= stage;
m_shaderStages.push_back(pipelineShaderStageInfo);
return *this;
}
GraphicsPipelineBuilder& GraphicsPipelineBuilder::setVertexInputSingleAttribute (const VkFormat vertexFormat, const deUint32 stride)
{
const VkVertexInputBindingDescription bindingDesc =
{
0u, // uint32_t binding;
stride, // uint32_t stride;
VK_VERTEX_INPUT_RATE_VERTEX, // VkVertexInputRate inputRate;
};
const VkVertexInputAttributeDescription attributeDesc =
{
0u, // uint32_t location;
0u, // uint32_t binding;
vertexFormat, // VkFormat format;
0u, // uint32_t offset;
};
m_vertexInputBindings.clear();
m_vertexInputBindings.push_back(bindingDesc);
m_vertexInputAttributes.clear();
m_vertexInputAttributes.push_back(attributeDesc);
return *this;
}
template<typename T>
inline const T* dataPointer (const std::vector<T>& vec)
{
return (vec.size() != 0 ? &vec[0] : DE_NULL);
}
Move<VkPipeline> GraphicsPipelineBuilder::build (const DeviceInterface& vk,
const VkDevice device,
const VkPipelineLayout pipelineLayout,
const VkRenderPass renderPass,
PipelineCacheData& pipelineCacheData)
{
const VkPipelineVertexInputStateCreateInfo vertexInputStateInfo =
{
VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkPipelineVertexInputStateCreateFlags)0, // VkPipelineVertexInputStateCreateFlags flags;
static_cast<deUint32>(m_vertexInputBindings.size()), // uint32_t vertexBindingDescriptionCount;
dataPointer(m_vertexInputBindings), // const VkVertexInputBindingDescription* pVertexBindingDescriptions;
static_cast<deUint32>(m_vertexInputAttributes.size()), // uint32_t vertexAttributeDescriptionCount;
dataPointer(m_vertexInputAttributes), // const VkVertexInputAttributeDescription* pVertexAttributeDescriptions;
};
const VkPrimitiveTopology topology = (m_shaderStageFlags & VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT) ? VK_PRIMITIVE_TOPOLOGY_PATCH_LIST
: m_primitiveTopology;
const VkPipelineInputAssemblyStateCreateInfo pipelineInputAssemblyStateInfo =
{
VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkPipelineInputAssemblyStateCreateFlags)0, // VkPipelineInputAssemblyStateCreateFlags flags;
topology, // VkPrimitiveTopology topology;
VK_FALSE, // VkBool32 primitiveRestartEnable;
};
const VkPipelineTessellationStateCreateInfo pipelineTessellationStateInfo =
{
VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkPipelineTessellationStateCreateFlags)0, // VkPipelineTessellationStateCreateFlags flags;
m_patchControlPoints, // uint32_t patchControlPoints;
};
const VkViewport viewport = makeViewport(m_renderSize);
const VkRect2D scissor = makeRect2D(m_renderSize);
const VkPipelineViewportStateCreateInfo pipelineViewportStateInfo =
{
VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkPipelineViewportStateCreateFlags)0, // VkPipelineViewportStateCreateFlags flags;
1u, // uint32_t viewportCount;
&viewport, // const VkViewport* pViewports;
1u, // uint32_t scissorCount;
&scissor, // const VkRect2D* pScissors;
};
const bool isRasterizationDisabled = ((m_shaderStageFlags & VK_SHADER_STAGE_FRAGMENT_BIT) == 0);
const VkPipelineRasterizationStateCreateInfo pipelineRasterizationStateInfo =
{
VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkPipelineRasterizationStateCreateFlags)0, // VkPipelineRasterizationStateCreateFlags flags;
VK_FALSE, // VkBool32 depthClampEnable;
isRasterizationDisabled, // VkBool32 rasterizerDiscardEnable;
VK_POLYGON_MODE_FILL, // VkPolygonMode polygonMode;
m_cullModeFlags, // VkCullModeFlags cullMode;
m_frontFace, // VkFrontFace frontFace;
VK_FALSE, // VkBool32 depthBiasEnable;
0.0f, // float depthBiasConstantFactor;
0.0f, // float depthBiasClamp;
0.0f, // float depthBiasSlopeFactor;
1.0f, // float lineWidth;
};
const VkPipelineMultisampleStateCreateInfo pipelineMultisampleStateInfo =
{
VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkPipelineMultisampleStateCreateFlags)0, // VkPipelineMultisampleStateCreateFlags flags;
VK_SAMPLE_COUNT_1_BIT, // VkSampleCountFlagBits rasterizationSamples;
VK_FALSE, // VkBool32 sampleShadingEnable;
0.0f, // float minSampleShading;
DE_NULL, // const VkSampleMask* pSampleMask;
VK_FALSE, // VkBool32 alphaToCoverageEnable;
VK_FALSE // VkBool32 alphaToOneEnable;
};
const VkStencilOpState stencilOpState = makeStencilOpState(
VK_STENCIL_OP_KEEP, // stencil fail
VK_STENCIL_OP_KEEP, // depth & stencil pass
VK_STENCIL_OP_KEEP, // depth only fail
VK_COMPARE_OP_NEVER, // compare op
0u, // compare mask
0u, // write mask
0u); // reference
const VkPipelineDepthStencilStateCreateInfo pipelineDepthStencilStateInfo =
{
VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkPipelineDepthStencilStateCreateFlags)0, // VkPipelineDepthStencilStateCreateFlags flags;
VK_FALSE, // VkBool32 depthTestEnable;
VK_FALSE, // VkBool32 depthWriteEnable;
VK_COMPARE_OP_LESS, // VkCompareOp depthCompareOp;
VK_FALSE, // VkBool32 depthBoundsTestEnable;
VK_FALSE, // VkBool32 stencilTestEnable;
stencilOpState, // VkStencilOpState front;
stencilOpState, // VkStencilOpState back;
0.0f, // float minDepthBounds;
1.0f, // float maxDepthBounds;
};
const VkColorComponentFlags colorComponentsAll = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
const VkPipelineColorBlendAttachmentState pipelineColorBlendAttachmentState =
{
m_blendEnable, // VkBool32 blendEnable;
VK_BLEND_FACTOR_SRC_ALPHA, // VkBlendFactor srcColorBlendFactor;
VK_BLEND_FACTOR_ONE, // VkBlendFactor dstColorBlendFactor;
VK_BLEND_OP_ADD, // VkBlendOp colorBlendOp;
VK_BLEND_FACTOR_SRC_ALPHA, // VkBlendFactor srcAlphaBlendFactor;
VK_BLEND_FACTOR_ONE, // VkBlendFactor dstAlphaBlendFactor;
VK_BLEND_OP_ADD, // VkBlendOp alphaBlendOp;
colorComponentsAll, // VkColorComponentFlags colorWriteMask;
};
const VkPipelineColorBlendStateCreateInfo pipelineColorBlendStateInfo =
{
VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkPipelineColorBlendStateCreateFlags)0, // VkPipelineColorBlendStateCreateFlags flags;
VK_FALSE, // VkBool32 logicOpEnable;
VK_LOGIC_OP_COPY, // VkLogicOp logicOp;
1u, // deUint32 attachmentCount;
&pipelineColorBlendAttachmentState, // const VkPipelineColorBlendAttachmentState* pAttachments;
{ 0.0f, 0.0f, 0.0f, 0.0f }, // float blendConstants[4];
};
const VkGraphicsPipelineCreateInfo graphicsPipelineInfo =
{
VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkPipelineCreateFlags)0, // VkPipelineCreateFlags flags;
static_cast<deUint32>(m_shaderStages.size()), // deUint32 stageCount;
&m_shaderStages[0], // const VkPipelineShaderStageCreateInfo* pStages;
&vertexInputStateInfo, // const VkPipelineVertexInputStateCreateInfo* pVertexInputState;
&pipelineInputAssemblyStateInfo, // const VkPipelineInputAssemblyStateCreateInfo* pInputAssemblyState;
(m_shaderStageFlags & VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT ? &pipelineTessellationStateInfo : DE_NULL), // const VkPipelineTessellationStateCreateInfo* pTessellationState;
(isRasterizationDisabled ? DE_NULL : &pipelineViewportStateInfo), // const VkPipelineViewportStateCreateInfo* pViewportState;
&pipelineRasterizationStateInfo, // const VkPipelineRasterizationStateCreateInfo* pRasterizationState;
(isRasterizationDisabled ? DE_NULL : &pipelineMultisampleStateInfo), // const VkPipelineMultisampleStateCreateInfo* pMultisampleState;
(isRasterizationDisabled ? DE_NULL : &pipelineDepthStencilStateInfo), // const VkPipelineDepthStencilStateCreateInfo* pDepthStencilState;
(isRasterizationDisabled ? DE_NULL : &pipelineColorBlendStateInfo), // const VkPipelineColorBlendStateCreateInfo* pColorBlendState;
DE_NULL, // const VkPipelineDynamicStateCreateInfo* pDynamicState;
pipelineLayout, // VkPipelineLayout layout;
renderPass, // VkRenderPass renderPass;
0u, // deUint32 subpass;
DE_NULL, // VkPipeline basePipelineHandle;
0, // deInt32 basePipelineIndex;
};
{
const vk::Unique<vk::VkPipelineCache> pipelineCache (pipelineCacheData.createPipelineCache(vk, device));
vk::Move<vk::VkPipeline> pipeline (createGraphicsPipeline(vk, device, *pipelineCache, &graphicsPipelineInfo));
// Refresh data from cache
pipelineCacheData.setFromPipelineCache(vk, device, *pipelineCache);
return pipeline;
}
}
void requireFeatures (const InstanceInterface& vki, const VkPhysicalDevice physDevice, const FeatureFlags flags)
{
const VkPhysicalDeviceFeatures features = getPhysicalDeviceFeatures(vki, physDevice);
if (((flags & FEATURE_TESSELLATION_SHADER) != 0) && !features.tessellationShader)
throw tcu::NotSupportedError("Tessellation shader not supported");
if (((flags & FEATURE_GEOMETRY_SHADER) != 0) && !features.geometryShader)
throw tcu::NotSupportedError("Geometry shader not supported");
if (((flags & FEATURE_SHADER_FLOAT_64) != 0) && !features.shaderFloat64)
throw tcu::NotSupportedError("Double-precision floats not supported");
if (((flags & FEATURE_VERTEX_PIPELINE_STORES_AND_ATOMICS) != 0) && !features.vertexPipelineStoresAndAtomics)
throw tcu::NotSupportedError("SSBO and image writes not supported in vertex pipeline");
if (((flags & FEATURE_FRAGMENT_STORES_AND_ATOMICS) != 0) && !features.fragmentStoresAndAtomics)
throw tcu::NotSupportedError("SSBO and image writes not supported in fragment shader");
if (((flags & FEATURE_SHADER_TESSELLATION_AND_GEOMETRY_POINT_SIZE) != 0) && !features.shaderTessellationAndGeometryPointSize)
throw tcu::NotSupportedError("Tessellation and geometry shaders don't support PointSize built-in");
}
void requireStorageImageSupport(const InstanceInterface& vki, const VkPhysicalDevice physDevice, const VkFormat fmt)
{
const VkFormatProperties p = getPhysicalDeviceFormatProperties(vki, physDevice, fmt);
if ((p.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) == 0)
throw tcu::NotSupportedError("Storage image format not supported");
}
std::string getResourceName (const ResourceDescription& resource)
{
std::ostringstream str;
if (resource.type == RESOURCE_TYPE_BUFFER)
str << "buffer_" << resource.size.x();
else if (resource.type == RESOURCE_TYPE_IMAGE)
{
str << "image_" << resource.size.x()
<< (resource.size.y() > 0 ? "x" + de::toString(resource.size.y()) : "")
<< (resource.size.z() > 0 ? "x" + de::toString(resource.size.z()) : "")
<< "_" << de::toLower(getFormatName(resource.imageFormat)).substr(10);
}
else if (isIndirectBuffer(resource.type))
str << "indirect_buffer";
else
DE_ASSERT(0);
return str.str();
}
bool isIndirectBuffer (const ResourceType type)
{
switch (type)
{
case RESOURCE_TYPE_INDIRECT_BUFFER_DRAW:
case RESOURCE_TYPE_INDIRECT_BUFFER_DRAW_INDEXED:
case RESOURCE_TYPE_INDIRECT_BUFFER_DISPATCH:
return true;
default:
return false;
}
}
PipelineCacheData::PipelineCacheData (void)
{
}
PipelineCacheData::~PipelineCacheData (void)
{
}
vk::Move<VkPipelineCache> PipelineCacheData::createPipelineCache (const vk::DeviceInterface& vk, const vk::VkDevice device) const
{
const de::ScopedLock dataLock (m_lock);
const struct vk::VkPipelineCacheCreateInfo params =
{
vk::VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO,
DE_NULL,
(vk::VkPipelineCacheCreateFlags)0,
(deUintptr)m_data.size(),
(m_data.empty() ? DE_NULL : &m_data[0])
};
return vk::createPipelineCache(vk, device, ¶ms);
}
void PipelineCacheData::setFromPipelineCache (const vk::DeviceInterface& vk, const vk::VkDevice device, const vk::VkPipelineCache pipelineCache)
{
const de::ScopedLock dataLock (m_lock);
deUintptr dataSize = 0;
VK_CHECK(vk.getPipelineCacheData(device, pipelineCache, &dataSize, DE_NULL));
m_data.resize(dataSize);
if (dataSize > 0)
VK_CHECK(vk.getPipelineCacheData(device, pipelineCache, &dataSize, &m_data[0]));
}
} // synchronization
} // vkt
|
/*
Copyright (c) 2019 Xavier Leclercq
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
#include "XMLTreeDBImpl.h"
#include "XMLTreeDBNodeImpl.h"
#include "XMLTreeDBTransactionImpl.h"
#include <fstream>
namespace DiplodocusDB
{
static const char* rootElementName = "diplodocusdb-xmltreedb";
void XMLTreeDBImpl::create(const boost::filesystem::path& path, Ishiko::Error& error)
{
m_path = path;
pugi::xml_node rootNode = m_document.append_child(rootElementName);
if (rootNode)
{
m_root = TreeDBNode(std::make_shared<XMLTreeDBNodeImpl>(nullptr, rootNode));
std::ofstream file(m_path.string());
m_document.save(file);
}
}
void XMLTreeDBImpl::open(const boost::filesystem::path& path, Ishiko::Error& error)
{
m_path = path;
m_document.load_file(m_path.string().c_str());
m_root = TreeDBNode(std::make_shared<XMLTreeDBNodeImpl>(nullptr, m_document.child(rootElementName)));
}
void XMLTreeDBImpl::close()
{
}
TreeDBNode& XMLTreeDBImpl::root()
{
return m_root;
}
TreeDBValue XMLTreeDBImpl::value(TreeDBNode& node, Ishiko::Error& error)
{
XMLTreeDBNodeImpl& nodeImpl = static_cast<XMLTreeDBNodeImpl&>(*node.impl());
return nodeImpl.value();
}
TreeDBValue XMLTreeDBImpl::value(TreeDBNode& node, const DataType& type, Ishiko::Error& error)
{
TreeDBValue result;
XMLTreeDBNodeImpl& nodeImpl = static_cast<XMLTreeDBNodeImpl&>(*node.impl());
if (nodeImpl.value().type() == type)
{
result = nodeImpl.value();
}
return result;
}
TreeDBValue XMLTreeDBImpl::childValue(TreeDBNode& parent, const std::string& name, Ishiko::Error& error)
{
TreeDBValue result;
TreeDBNode childNode = child(parent, name, error);
if (!error)
{
result = value(childNode, error);
}
return result;
}
TreeDBValue XMLTreeDBImpl::childValue(TreeDBNode& parent, const std::string& name, const DataType& type,
Ishiko::Error& error)
{
TreeDBValue result;
TreeDBNode childNode = child(parent, name, error);
if (!error)
{
result = value(childNode, type, error);
}
return result;
}
TreeDBNode XMLTreeDBImpl::parent(TreeDBNode& node, Ishiko::Error& error)
{
XMLTreeDBNodeImpl& nodeImpl = static_cast<XMLTreeDBNodeImpl&>(*node.impl());
return nodeImpl.parent(error);
}
std::vector<TreeDBNode> XMLTreeDBImpl::childNodes(TreeDBNode& parent, Ishiko::Error& error)
{
XMLTreeDBNodeImpl& parentNodeImpl = static_cast<XMLTreeDBNodeImpl&>(*parent.impl());
return parentNodeImpl.childNodes(error);
}
TreeDBNode XMLTreeDBImpl::child(TreeDBNode& parent, const std::string& name, Ishiko::Error& error)
{
XMLTreeDBNodeImpl& parentNodeImpl = static_cast<XMLTreeDBNodeImpl&>(*parent.impl());
return parentNodeImpl.child(name, error);
}
TreeDBNode XMLTreeDBImpl::previousSibling(TreeDBNode& node, Ishiko::Error& error)
{
XMLTreeDBNodeImpl& nodeImpl = static_cast<XMLTreeDBNodeImpl&>(*node.impl());
return nodeImpl.previousSibling(error);
}
TreeDBNode XMLTreeDBImpl::previousSibling(TreeDBNode& node, const std::string& name, Ishiko::Error& error)
{
XMLTreeDBNodeImpl& nodeImpl = static_cast<XMLTreeDBNodeImpl&>(*node.impl());
return nodeImpl.previousSibling(name, error);
}
TreeDBNode XMLTreeDBImpl::nextSibling(TreeDBNode& node, Ishiko::Error& error)
{
XMLTreeDBNodeImpl& nodeImpl = static_cast<XMLTreeDBNodeImpl&>(*node.impl());
return nodeImpl.nextSibling(error);
}
TreeDBNode XMLTreeDBImpl::nextSibling(TreeDBNode& node, const std::string& name, Ishiko::Error& error)
{
XMLTreeDBNodeImpl& nodeImpl = static_cast<XMLTreeDBNodeImpl&>(*node.impl());
return nodeImpl.nextSibling(name, error);
}
void XMLTreeDBImpl::traverse(TreeDBNode& node, ETreeTraversalOrder order,
void(*callback)(TreeDB& db, TreeDBNode& node), void* callbackData)
{
// TODO
}
TreeDBTransaction XMLTreeDBImpl::createTransaction(Ishiko::Error& error)
{
// TODO
return TreeDBTransaction(std::make_shared<XMLTreeDBTransactionImpl>());
}
void XMLTreeDBImpl::commitTransaction(TreeDBTransaction& transaction, Ishiko::Error& error)
{
// TODO
}
void XMLTreeDBImpl::rollbackTransaction(TreeDBTransaction& transaction)
{
// TODO
}
void XMLTreeDBImpl::setValue(TreeDBNode& node, const TreeDBValue& value, Ishiko::Error& error)
{
XMLTreeDBNodeImpl& nodeImpl = static_cast<XMLTreeDBNodeImpl&>(*node.impl());
nodeImpl.value() = value;
commitNode(nodeImpl, error);
}
TreeDBNode XMLTreeDBImpl::insertChildNode(TreeDBNode& parent, size_t index, const std::string& name,
Ishiko::Error& error)
{
TreeDBValue value;
return insertChildNode(parent, index, name, value, error);
}
TreeDBNode XMLTreeDBImpl::insertChildNode(TreeDBNode& parent, size_t index, const std::string& name,
const TreeDBValue& value, Ishiko::Error& error)
{
XMLTreeDBNodeImpl& parentNodeImpl = static_cast<XMLTreeDBNodeImpl&>(*parent.impl());
TreeDBNode result = parentNodeImpl.insertChildNode(index, name, value, error);
commitNode(parentNodeImpl, error);
return result;
}
TreeDBNode XMLTreeDBImpl::insertChildNodeBefore(TreeDBNode& parent, TreeDBNode& nextChild, const std::string& name,
Ishiko::Error& error)
{
TreeDBValue value;
return insertChildNodeBefore(parent, nextChild, name, value, error);
}
TreeDBNode XMLTreeDBImpl::insertChildNodeBefore(TreeDBNode& parent, TreeDBNode& nextChild, const std::string& name,
const TreeDBValue& value, Ishiko::Error& error)
{
XMLTreeDBNodeImpl& parentNodeImpl = static_cast<XMLTreeDBNodeImpl&>(*parent.impl());
TreeDBNode result = parentNodeImpl.insertChildNodeBefore(nextChild, name, value, error);
commitNode(parentNodeImpl, error);
return result;
}
TreeDBNode XMLTreeDBImpl::insertChildNodeAfter(TreeDBNode& parent, TreeDBNode& previousChild,
const std::string& name, Ishiko::Error& error)
{
TreeDBValue value;
return insertChildNodeAfter(parent, previousChild, name, value, error);
}
TreeDBNode XMLTreeDBImpl::insertChildNodeAfter(TreeDBNode& parent, TreeDBNode& previousChild, const std::string& name,
const TreeDBValue& value, Ishiko::Error& error)
{
XMLTreeDBNodeImpl& parentNodeImpl = static_cast<XMLTreeDBNodeImpl&>(*parent.impl());
TreeDBNode result = parentNodeImpl.insertChildNodeAfter(previousChild, name, value, error);
commitNode(parentNodeImpl, error);
return result;
}
TreeDBNode XMLTreeDBImpl::appendChildNode(TreeDBNode& parent, const std::string& name, Ishiko::Error& error)
{
TreeDBValue value;
return appendChildNode(parent, name, value, error);
}
TreeDBNode XMLTreeDBImpl::appendChildNode(TreeDBTransaction& transaction, TreeDBNode& parent, const std::string& name,
Ishiko::Error& error)
{
TreeDBValue value;
return appendChildNode(transaction, parent, name, value, error);
}
TreeDBNode XMLTreeDBImpl::appendChildNode(TreeDBNode& parent, const std::string& name, const TreeDBValue& value,
Ishiko::Error& error)
{
XMLTreeDBNodeImpl& parentNodeImpl = static_cast<XMLTreeDBNodeImpl&>(*parent.impl());
TreeDBNode result = parentNodeImpl.appendChildNode(name, value, error);
commitNode(parentNodeImpl, error);
return result;
}
TreeDBNode XMLTreeDBImpl::appendChildNode(TreeDBTransaction& transaction, TreeDBNode& parent, const std::string& name,
const TreeDBValue& value, Ishiko::Error& error)
{
// TODO : make this a transaction!!!
XMLTreeDBNodeImpl& parentNodeImpl = static_cast<XMLTreeDBNodeImpl&>(*parent.impl());
TreeDBNode result = parentNodeImpl.appendChildNode(name, value, error);
commitNode(parentNodeImpl, error);
return result;
}
TreeDBNode XMLTreeDBImpl::setChildNode(TreeDBNode& parent, const std::string& name, Ishiko::Error& error)
{
TreeDBValue value;
return setChildNode(parent, name, value, error);
}
TreeDBNode XMLTreeDBImpl::setChildNode(TreeDBNode& parent, const std::string& name, const TreeDBValue& value,
Ishiko::Error& error)
{
XMLTreeDBNodeImpl& parentNodeImpl = static_cast<XMLTreeDBNodeImpl&>(*parent.impl());
TreeDBNode result = parentNodeImpl.setChildNode(name, value, error);
commitNode(parentNodeImpl, error);
return result;
}
size_t XMLTreeDBImpl::removeChildNode(TreeDBNode& parent, const std::string& name, Ishiko::Error& error)
{
XMLTreeDBNodeImpl& parentNodeImpl = static_cast<XMLTreeDBNodeImpl&>(*parent.impl());
size_t result = parentNodeImpl.removeChildNode(name, error);
commitNode(parentNodeImpl, error);
return result;
}
size_t XMLTreeDBImpl::removeAllChildNodes(TreeDBNode& parent, Ishiko::Error& error)
{
XMLTreeDBNodeImpl& parentNodeImpl = static_cast<XMLTreeDBNodeImpl&>(*parent.impl());
size_t result = parentNodeImpl.removeAllChildNodes(error);
commitNode(parentNodeImpl, error);
return result;
}
void XMLTreeDBImpl::commitNode(XMLTreeDBNodeImpl& node, Ishiko::Error& error)
{
node.updateValue();
std::ofstream file(m_path.string());
m_document.save(file, " ");
}
}
|
#include "optionsdialog.h"
#include "ui_optionsdialog.h"
#include "bitcoinamountfield.h"
#include "bitcoinunits.h"
#include "monitoreddatamapper.h"
#include "netbase.h"
#include "optionsmodel.h"
#include "qvalidatedlineedit.h"
#include "qvaluecombobox.h"
#include <QCheckBox>
#include <QDir>
#include <QIntValidator>
#include <QLabel>
#include <QLineEdit>
#include <QLocale>
#include <QMessageBox>
#include <QPushButton>
#include <QRegExp>
#include <QRegExpValidator>
#include <QTabWidget>
#include <QWidget>
OptionsDialog::OptionsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::OptionsDialog),
model(0),
mapper(0),
fRestartWarningDisplayed_Proxy(false),
fRestartWarningDisplayed_Lang(false),
fProxyIpValid(true)
{
ui->setupUi(this);
/* Network elements init */
#ifndef USE_UPNP
ui->mapPortUpnp->setEnabled(false);
#endif
ui->socksVersion->setEnabled(false);
ui->socksVersion->addItem("5", 5);
ui->socksVersion->addItem("4", 4);
ui->socksVersion->setCurrentIndex(0);
ui->proxyIp->setEnabled(false);
ui->proxyPort->setEnabled(false);
ui->proxyPort->setValidator(new QIntValidator(0, 65535, this));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool)));
ui->proxyIp->installEventFilter(this);
/* Window elements init */
#ifdef Q_WS_MAC
ui->tabWindow->setVisible(false);
#endif
/* Display elements init */
QDir translations(":translations");
ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant(""));
foreach(const QString &langStr, translations.entryList())
{
QLocale locale(langStr);
/** check if the locale name consists of 2 parts (language_country) */
if(langStr.contains("_"))
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
else
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language (locale name)", e.g. "German (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
}
ui->unit->setModel(new BitcoinUnits(this));
connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy()));
connect(ui->lang, SIGNAL(activated(int)), this, SLOT(showRestartWarning_Lang()));
/* Widget-to-option mapper */
mapper = new MonitoredDataMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
mapper->setOrientation(Qt::Vertical);
/* enable save buttons when data modified */
connect(mapper, SIGNAL(viewModified()), this, SLOT(enableSaveButtons()));
/* disable save buttons when new data loaded */
connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableSaveButtons()));
/* disable/enable save buttons when proxy IP is invalid/valid */
connect(this, SIGNAL(proxyIpValid(bool)), this, SLOT(setSaveButtonState(bool)));
}
OptionsDialog::~OptionsDialog()
{
delete ui;
}
void OptionsDialog::setModel(OptionsModel *model)
{
this->model = model;
if(model)
{
connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
mapper->setModel(model);
setMapper();
mapper->toFirst();
}
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void OptionsDialog::setMapper()
{
/* Main */
mapper->addMapping(ui->transactionFee, OptionsModel::Fee);
mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup);
mapper->addMapping(ui->detachDatabases, OptionsModel::DetachDatabases);
/* Network */
mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP);
mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse);
mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion);
mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP);
mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort);
/* Window */
#ifndef Q_WS_MAC
mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray);
mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose);
#endif
/* Display */
mapper->addMapping(ui->lang, OptionsModel::Language);
mapper->addMapping(ui->unit, OptionsModel::DisplayUnit);
mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses);
}
void OptionsDialog::enableSaveButtons()
{
// prevent enabling of the save buttons when data modified, if there is an invalid proxy address present
if(fProxyIpValid)
setSaveButtonState(true);
}
void OptionsDialog::disableSaveButtons()
{
setSaveButtonState(false);
}
void OptionsDialog::setSaveButtonState(bool fState)
{
ui->applyButton->setEnabled(fState);
ui->okButton->setEnabled(fState);
}
void OptionsDialog::on_okButton_clicked()
{
mapper->submit();
accept();
}
void OptionsDialog::on_cancelButton_clicked()
{
reject();
}
void OptionsDialog::on_applyButton_clicked()
{
mapper->submit();
ui->applyButton->setEnabled(false);
}
void OptionsDialog::showRestartWarning_Proxy()
{
if(!fRestartWarningDisplayed_Proxy)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Noisecoin."), QMessageBox::Ok);
fRestartWarningDisplayed_Proxy = true;
}
}
void OptionsDialog::showRestartWarning_Lang()
{
if(!fRestartWarningDisplayed_Lang)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Noisecoin."), QMessageBox::Ok);
fRestartWarningDisplayed_Lang = true;
}
}
void OptionsDialog::updateDisplayUnit()
{
if(model)
{
// Update transactionFee with the current unit
ui->transactionFee->setDisplayUnit(model->getDisplayUnit());
}
}
bool OptionsDialog::eventFilter(QObject *object, QEvent *event)
{
if(object == ui->proxyIp && event->type() == QEvent::FocusOut)
{
// Check proxyIP for a valid IPv4/IPv6 address
CService addr;
if(!LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr))
{
ui->proxyIp->setValid(false);
fProxyIpValid = false;
ui->statusLabel->setStyleSheet("QLabel { color: red; }");
ui->statusLabel->setText(tr("The supplied proxy address is invalid."));
emit proxyIpValid(false);
}
else
{
fProxyIpValid = true;
ui->statusLabel->clear();
emit proxyIpValid(true);
}
}
return QDialog::eventFilter(object, event);
}
|
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <unordered_map>
#include <stdint.h>
#include <cmath>
using namespace std;
typedef int64_t Int;
typedef uint64_t UInt;
UInt gcd(UInt a, UInt b) {
if (b == 0) return a;
return gcd(b, a % b);
}
UInt gcd2(UInt a, UInt b) {
while (b != 0) {
UInt oldB = b;
b = a % b;
a = oldB;
}
return a;
}
void testGCDs() {
cout << gcd(12, 16) << endl;
cout << gcd2(12, 16) << endl;
cout << gcd(15, 27) << endl;
cout << gcd2(15, 27) << endl;
}
int main(int argc, char **argv) {
// testGCDs();
UInt x = 0;
UInt y = 0;
UInt a = 0;
UInt b = 0;
cin >> x >> y >> a >> b;
UInt divisor = x * y / gcd2(x, y);
UInt start = a / divisor;
UInt end = b / divisor;
if (a % divisor != 0) {
++start;
}
cout << end - start + 1;
// UInt redBrickFirst = a / x;
// UInt redBrickLast = b / x;
// UInt pinkBrickFirst = a / y;
// UInt pinkBrickLast = b / y;
//
// if (redBrickFirst * x < a) {
// redBrickFirst += 1;
// }
//
// if (pinkBrickFirst * y < a) {
// pinkBrickFirst += 1;
// }
//
// unordered_map<Int, bool> redMap;
//
// while (redBrickFirst <= redBrickLast) {
// redMap.insert(make_pair(redBrickFirst * x, true));
// redBrickFirst += 1;
// }
//
// UInt commonCount = 0;
// while (pinkBrickFirst <= pinkBrickLast) {
// unordered_map<Int, bool>::iterator iter = redMap.find(pinkBrickFirst * y);
//
// if (iter != redMap.end()) {
// ++commonCount;
// }
//
// pinkBrickFirst += 1;
// }
//
// cout << commonCount;
//
return 0;
}
|
/* nlsfuncs.cc: NLS helper functions
Copyright 2010, 2011, 2012, 2013 Red Hat, Inc.
This file is part of Cygwin.
This software is a copyrighted work licensed under the terms of the
Cygwin license. Please consult the file "CYGWIN_LICENSE" for
details. */
#include "winsup.h"
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <wchar.h>
#include "path.h"
#include "fhandler.h"
#include "dtable.h"
#include "cygheap.h"
#include "tls_pbuf.h"
/* Internal headers from newlib */
#include "../locale/timelocal.h"
#include "../locale/lctype.h"
#include "../locale/lnumeric.h"
#include "../locale/lmonetary.h"
#include "../locale/lmessages.h"
#include "lc_msg.h"
#include "lc_era.h"
#define _LC(x) &lc_##x##_ptr,lc_##x##_end-lc_##x##_ptr
#define getlocaleinfo(category,type) \
__getlocaleinfo(lcid,(type),_LC(category))
#define eval_datetimefmt(type,flags) \
__eval_datetimefmt(lcid,(type),(flags),&lc_time_ptr,\
lc_time_end-lc_time_ptr)
#define charfromwchar(category,in) \
__charfromwchar (_##category##_locale->in,_LC(category),\
f_wctomb,charset)
#define has_modifier(x) ((x)[0] && !strcmp (modifier, (x)))
static char last_locale[ENCODING_LEN + 1];
static LCID last_lcid;
/* Fetch LCID from POSIX locale specifier.
Return values:
-1: Invalid locale
0: C or POSIX
>0: LCID
*/
static LCID
__get_lcid_from_locale (const char *name)
{
char locale[ENCODING_LEN + 1];
char *c;
LCID lcid;
/* Speed up reusing the same locale as before, for instance in LC_ALL case. */
if (!strcmp (name, last_locale))
{
debug_printf ("LCID=%04y", last_lcid);
return last_lcid;
}
stpcpy (last_locale, name);
stpcpy (locale, name);
/* Store modifier for later use. */
const char *modifier = strchr (last_locale, '@') ? : "";
/* Drop charset and modifier */
c = strchr (locale, '.');
if (!c)
c = strchr (locale, '@');
if (c)
*c = '\0';
/* "POSIX" already converted to "C" in loadlocale. */
if (!strcmp (locale, "C"))
return last_lcid = 0;
c = strchr (locale, '_');
if (!c)
return last_lcid = (LCID) -1;
if (wincap.has_localenames ())
{
wchar_t wlocale[ENCODING_LEN + 1];
/* Convert to RFC 4646 syntax which is the standard for the locale names
replacing LCIDs starting with Vista. */
*c = '-';
mbstowcs (wlocale, locale, ENCODING_LEN + 1);
lcid = LocaleNameToLCID (wlocale, 0);
if (lcid == 0)
{
/* Unfortunately there are a couple of locales for which no form
without a Script part per RFC 4646 exists.
Linux also supports no_NO which is equivalent to nb_NO. */
struct {
const char *loc;
const wchar_t *wloc;
} sc_only_locale[] = {
{ "az-AZ" , L"az-Latn-AZ" },
{ "bs-BA" , L"bs-Latn-BA" },
{ "chr-US", L"chr-Cher-US"},
{ "ff-SN" , L"ff-Latn-SN" },
{ "ha-NG" , L"ha-Latn-NG" },
{ "iu-CA" , L"iu-Latn-CA" },
{ "ku-IQ" , L"ku-Arab-IQ" },
{ "mn-CN" , L"mn-Mong-CN" },
{ "no-NO" , L"nb-NO" },
{ "pa-PK" , L"pa-Arab-PK" },
{ "sd-PK" , L"sd-Arab-PK" },
{ "sr-BA" , L"sr-Cyrl-BA" },
{ "sr-CS" , L"sr-Cyrl-CS" },
{ "sr-ME" , L"sr-Cyrl-ME" },
{ "sr-RS" , L"sr-Cyrl-RS" },
{ "tg-TJ" , L"tg-Cyrl-TJ" },
{ "tzm-DZ", L"tzm-Latn-DZ" },
{ "tzm-MA", L"tzm-Tfng-MA" },
{ "uz-UZ" , L"uz-Latn-UZ" },
{ NULL , NULL }
};
for (int i = 0; sc_only_locale[i].loc
&& sc_only_locale[i].loc[0] <= locale[0]; ++i)
if (!strcmp (locale, sc_only_locale[i].loc))
{
lcid = LocaleNameToLCID (sc_only_locale[i].wloc, 0);
if (!strncmp (locale, "sr-", 3))
{
/* Vista/2K8 is missing sr-ME and sr-RS. It has only the
deprecated sr-CS. So we map ME and RS to CS here. */
if (lcid == 0)
lcid = LocaleNameToLCID (L"sr-Cyrl-CS", 0);
/* "@latin" modifier for the sr_XY locales changes
collation behaviour so lcid should accommodate that
by being set to the Latin sublang. */
if (lcid != 0 && has_modifier ("@latin"))
lcid = MAKELANGID (lcid & 0x3ff, (lcid >> 10) - 1);
}
else if (!strncmp (locale, "uz-", 3))
{
/* Equivalent for "@cyrillic" modifier in uz_UZ locale */
if (lcid != 0 && has_modifier ("@cyrillic"))
lcid = MAKELANGID (lcid & 0x3ff, (lcid >> 10) + 1);
}
break;
}
}
last_lcid = lcid ?: (LCID) -1;
debug_printf ("LCID=%04y", last_lcid);
return last_lcid;
}
/* Pre-Vista we have to loop through the LCID values and see if they
match language and TERRITORY. */
*c++ = '\0';
/* locale now points to the language, c points to the TERRITORY */
const char *language = locale;
const char *territory = c;
LCID lang, sublang;
char iso[10];
/* In theory the lang part takes 10 bits (0x3ff), but up to Windows 2003 R2
the highest lang value is 0x81. */
for (lang = 1; lang <= 0x81; ++lang)
if (GetLocaleInfo (lang, LOCALE_SISO639LANGNAME, iso, 10)
&& !strcmp (language, iso))
break;
if (lang > 0x81)
lcid = 0;
else if (!territory)
lcid = lang;
else
{
/* In theory the sublang part takes 7 bits (0x3f), but up to
Windows 2003 R2 the highest sublang value is 0x14. */
for (sublang = 1; sublang <= 0x14; ++sublang)
{
lcid = (sublang << 10) | lang;
if (GetLocaleInfo (lcid, LOCALE_SISO3166CTRYNAME, iso, 10)
&& !strcmp (territory, iso))
break;
}
if (sublang > 0x14)
lcid = 0;
}
if (lcid == 0 && territory)
{
/* Unfortunately there are four language LCID number areas representing
multiple languages. Fortunately only two of them already existed
pre-Vista. The concealed languages have to be tested explicitly,
since they are not catched by the above loops.
This also enables the serbian ISO 3166 territory codes which have
been changed post 2003, and maps them to the old wrong (SP was never
a valid ISO 3166 code) territory code sr_SP which fortunately has the
same LCID as the newer sr_CS.
Linux also supports no_NO which is equivalent to nb_NO. */
struct {
const char *loc;
LCID lcid;
} ambiguous_locale[] = {
{ "bs_BA", MAKELANGID (LANG_BOSNIAN, 0x05) },
{ "nn_NO", MAKELANGID (LANG_NORWEGIAN, SUBLANG_NORWEGIAN_NYNORSK) },
{ "no_NO", MAKELANGID (LANG_NORWEGIAN, SUBLANG_NORWEGIAN_BOKMAL) },
{ "sr_BA", MAKELANGID (LANG_BOSNIAN,
SUBLANG_SERBIAN_BOSNIA_HERZEGOVINA_CYRILLIC) },
{ "sr_CS", MAKELANGID (LANG_SERBIAN, SUBLANG_SERBIAN_CYRILLIC) },
{ "sr_ME", MAKELANGID (LANG_SERBIAN, SUBLANG_SERBIAN_CYRILLIC) },
{ "sr_RS", MAKELANGID (LANG_SERBIAN, SUBLANG_SERBIAN_CYRILLIC) },
{ "sr_SP", MAKELANGID (LANG_SERBIAN, SUBLANG_SERBIAN_CYRILLIC) },
{ NULL, 0 },
};
*--c = '_';
for (int i = 0; ambiguous_locale[i].loc
&& ambiguous_locale[i].loc[0] <= locale[0]; ++i)
if (!strcmp (locale, ambiguous_locale[i].loc)
&& GetLocaleInfo (ambiguous_locale[i].lcid, LOCALE_SISO639LANGNAME,
iso, 10))
{
lcid = ambiguous_locale[i].lcid;
/* "@latin" modifier for the sr_XY locales changes collation
behaviour so lcid should accommodate that by being set to
the Latin sublang. */
if (!strncmp (locale, "sr_", 3) && has_modifier ("@latin"))
lcid = MAKELANGID (lcid & 0x3ff, (lcid >> 10) - 1);
break;
}
}
else if (lcid == 0x0443) /* uz_UZ (Uzbek/Uzbekistan) */
{
/* Equivalent for "@cyrillic" modifier in uz_UZ locale */
if (lcid != 0 && has_modifier ("@cyrillic"))
lcid = MAKELANGID (lcid & 0x3ff, (lcid >> 10) + 1);
}
last_lcid = lcid ?: (LCID) -1;
debug_printf ("LCID=%04y", last_lcid);
return last_lcid;
}
/* Never returns -1. Just skips invalid chars instead. Only if return_invalid
is set, s==NULL returns -1 since then it's used to recognize invalid strings
in the used charset. */
static size_t
lc_wcstombs (wctomb_p f_wctomb, const char *charset,
char *s, const wchar_t *pwcs, size_t n,
bool return_invalid = false)
{
char *ptr = s;
size_t max = n;
char buf[8];
size_t i, bytes, num_to_copy;
mbstate_t state;
memset (&state, 0, sizeof state);
if (s == NULL)
{
size_t num_bytes = 0;
while (*pwcs != 0)
{
bytes = f_wctomb (_REENT, buf, *pwcs++, charset, &state);
if (bytes != (size_t) -1)
num_bytes += bytes;
else if (return_invalid)
return (size_t) -1;
}
return num_bytes;
}
while (n > 0)
{
bytes = f_wctomb (_REENT, buf, *pwcs, charset, &state);
if (bytes == (size_t) -1)
{
memset (&state, 0, sizeof state);
++pwcs;
continue;
}
num_to_copy = (n > bytes ? bytes : n);
for (i = 0; i < num_to_copy; ++i)
*ptr++ = buf[i];
if (*pwcs == 0x00)
return ptr - s - (n >= bytes);
++pwcs;
n -= num_to_copy;
}
return max;
}
/* Never returns -1. Invalid sequences are translated to replacement
wide-chars. */
static size_t
lc_mbstowcs (mbtowc_p f_mbtowc, const char *charset,
wchar_t *pwcs, const char *s, size_t n)
{
size_t ret = 0;
char *t = (char *) s;
size_t bytes;
mbstate_t state;
memset (&state, 0, sizeof state);
if (!pwcs)
n = 1;
while (n > 0)
{
bytes = f_mbtowc (_REENT, pwcs, t, 6 /* fake, always enough */,
charset, &state);
if (bytes == (size_t) -1)
{
state.__count = 0;
bytes = 1;
if (pwcs)
*pwcs = L' ';
}
else if (bytes == 0)
break;
t += bytes;
++ret;
if (pwcs)
{
++pwcs;
--n;
}
}
return ret;
}
static int
locale_cmp (const void *a, const void *b)
{
char **la = (char **) a;
char **lb = (char **) b;
return strcmp (*la, *lb);
}
/* Helper function to workaround reallocs which move blocks even if they shrink.
Cygwin's realloc is not doing this, but tcsh's, for instance. All lc_foo
structures consist entirely of pointers so they are practically pointer
arrays. What we do here is just treat the lc_foo pointers as char ** and
rebase all char * pointers within, up to the given size of the structure. */
static void
rebase_locale_buf (const void *ptrv, const void *ptrvend, const char *newbase,
const char *oldbase, const char *oldend)
{
const char **ptrsend = (const char **) ptrvend;
for (const char **ptrs = (const char **) ptrv; ptrs < ptrsend; ++ptrs)
if (*ptrs >= oldbase && *ptrs < oldend)
*ptrs += newbase - oldbase;
}
static wchar_t *
__getlocaleinfo (LCID lcid, LCTYPE type, char **ptr, size_t size)
{
size_t num;
wchar_t *ret;
if ((uintptr_t) *ptr % 1)
++*ptr;
ret = (wchar_t *) *ptr;
num = GetLocaleInfoW (lcid, type, ret, size / sizeof (wchar_t));
*ptr = (char *) (ret + num);
return ret;
}
static char *
__charfromwchar (const wchar_t *in, char **ptr, size_t size,
wctomb_p f_wctomb, const char *charset)
{
size_t num;
char *ret;
num = lc_wcstombs (f_wctomb, charset, ret = *ptr, in, size);
*ptr += num + 1;
return ret;
}
static UINT
getlocaleint (LCID lcid, LCTYPE type)
{
UINT val;
return GetLocaleInfoW (lcid, type | LOCALE_RETURN_NUMBER, (PWCHAR) &val,
sizeof val) ? val : 0;
}
enum dt_flags {
DT_DEFAULT = 0x00,
DT_AMPM = 0x01, /* Enforce 12 hour time format. */
DT_ABBREV = 0x02, /* Enforce abbreviated month and day names. */
};
static wchar_t *
__eval_datetimefmt (LCID lcid, LCTYPE type, dt_flags flags, char **ptr,
size_t size)
{
wchar_t buf[80];
wchar_t fc;
size_t idx;
const wchar_t *day_str = L"edaA";
const wchar_t *mon_str = L"mmbB";
const wchar_t *year_str = L"yyyY";
const wchar_t *hour12_str = L"lI";
const wchar_t *hour24_str = L"kH";
const wchar_t *t_str;
if ((uintptr_t) *ptr % 1)
++*ptr;
wchar_t *ret = (wchar_t *) *ptr;
wchar_t *p = (wchar_t *) *ptr;
GetLocaleInfoW (lcid, type, buf, 80);
for (wchar_t *fmt = buf; *fmt; ++fmt)
switch (fc = *fmt)
{
case L'\'':
if (fmt[1] == L'\'')
*p++ = L'\'';
else
while (fmt[1] && *++fmt != L'\'')
*p++ = *fmt;
break;
case L'd':
case L'M':
case L'y':
t_str = (fc == L'd' ? day_str : fc == L'M' ? mon_str : year_str);
for (idx = 0; fmt[1] == fc; ++idx, ++fmt);
if (idx > 3)
idx = 3;
if ((flags & DT_ABBREV) && fc != L'y' && idx == 3)
idx = 2;
*p++ = L'%';
*p++ = t_str[idx];
break;
case L'g':
/* TODO */
break;
case L'h':
case L'H':
t_str = (fc == L'h' || (flags & DT_AMPM) ? hour12_str : hour24_str);
idx = 0;
if (fmt[1] == fc)
{
++fmt;
idx = 1;
}
*p++ = L'%';
*p++ = t_str[idx];
break;
case L'm':
case L's':
case L't':
if (fmt[1] == fc)
++fmt;
*p++ = L'%';
*p++ = (fc == L'm' ? L'M' : fc == L's' ? L'S' : L'p');
break;
case L'\t':
case L'\n':
case L'%':
*p++ = L'%';
*p++ = fc;
break;
default:
*p++ = *fmt;
break;
}
*p++ = L'\0';
*ptr = (char *) p;
return ret;
}
/* Convert Windows grouping format into POSIX grouping format. */
static char *
conv_grouping (LCID lcid, LCTYPE type, char **lc_ptr)
{
char buf[10]; /* Per MSDN max size of LOCALE_SGROUPING element incl. NUL */
bool repeat = false;
char *ptr = *lc_ptr;
char *ret = ptr;
GetLocaleInfoA (lcid, type, buf, 10);
/* Convert Windows grouping format into POSIX grouping format. */
for (char *c = buf; *c; ++c)
{
if (*c < '0' || *c > '9')
continue;
char val = *c - '0';
if (!val)
{
repeat = true;
break;
}
*ptr++ = val;
}
if (!repeat)
*ptr++ = CHAR_MAX;
*ptr++ = '\0';
*lc_ptr = ptr;
return ret;
}
/* Called from newlib's setlocale() via __time_load_locale() if category
is LC_TIME. Returns LC_TIME values fetched from Windows locale data
in the structure pointed to by _time_locale. This is subsequently
accessed by functions like nl_langinfo, strftime, strptime. */
extern "C" int
__set_lc_time_from_win (const char *name,
const struct lc_time_T *_C_time_locale,
struct lc_time_T *_time_locale,
char **lc_time_buf, wctomb_p f_wctomb,
const char *charset)
{
LCID lcid = __get_lcid_from_locale (name);
if (lcid == (LCID) -1)
return lcid;
if (!lcid && !strcmp (charset, "ASCII"))
return 0;
# define MAX_TIME_BUFFER_SIZE 4096
char *new_lc_time_buf = (char *) malloc (MAX_TIME_BUFFER_SIZE);
const char *lc_time_end = new_lc_time_buf + MAX_TIME_BUFFER_SIZE;
if (!new_lc_time_buf)
return -1;
char *lc_time_ptr = new_lc_time_buf;
/* C.foo is just a copy of "C" with fixed charset. */
if (!lcid)
memcpy (_time_locale, _C_time_locale, sizeof (struct lc_time_T));
/* codeset */
_time_locale->codeset = lc_time_ptr;
lc_time_ptr = stpcpy (lc_time_ptr, charset) + 1;
if (lcid)
{
char locale[ENCODING_LEN + 1];
strcpy (locale, name);
/* Removes the charset from the locale and attach the modifer to the
language_TERRITORY part. */
char *c = strchr (locale, '.');
if (c)
{
*c = '\0';
char *c2 = strchr (c + 1, '@');
/* Ignore @cjknarrow modifier since it's a very personal thing between
Cygwin and newlib... */
if (c2 && strcmp (c2, "@cjknarrow"))
memmove (c, c2, strlen (c2) + 1);
}
/* Now search in the alphabetically order lc_era array for the
locale. */
lc_era_t locale_key = { locale, NULL, NULL, NULL, NULL, NULL ,
NULL, NULL, NULL, NULL, NULL };
lc_era_t *era = (lc_era_t *) bsearch ((void *) &locale_key, (void *) lc_era,
sizeof lc_era / sizeof *lc_era,
sizeof *lc_era, locale_cmp);
/* mon */
/* Windows has a bug in Japanese and Korean locales. In these
locales, strings returned for LOCALE_SABBREVMONTHNAME* are missing
the suffix representing a month. Unfortunately this is not
documented in English. A Japanese article describing the problem
is http://msdn.microsoft.com/ja-jp/library/cc422084.aspx
The workaround is to use LOCALE_SMONTHNAME* in these locales,
even for the abbreviated month name. */
const LCTYPE mon_base =
lcid == MAKELANGID (LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN)
|| lcid == MAKELANGID (LANG_KOREAN, SUBLANG_KOREAN)
? LOCALE_SMONTHNAME1 : LOCALE_SABBREVMONTHNAME1;
for (int i = 0; i < 12; ++i)
{
_time_locale->wmon[i] = getlocaleinfo (time, mon_base + i);
_time_locale->mon[i] = charfromwchar (time, wmon[i]);
}
/* month and alt_month */
for (int i = 0; i < 12; ++i)
{
_time_locale->wmonth[i] = getlocaleinfo (time, LOCALE_SMONTHNAME1 + i);
_time_locale->month[i] = _time_locale->alt_month[i]
= charfromwchar (time, wmonth[i]);
}
/* wday */
_time_locale->wwday[0] = getlocaleinfo (time, LOCALE_SABBREVDAYNAME7);
_time_locale->wday[0] = charfromwchar (time, wwday[0]);
for (int i = 0; i < 6; ++i)
{
_time_locale->wwday[i + 1] = getlocaleinfo (time,
LOCALE_SABBREVDAYNAME1 + i);
_time_locale->wday[i + 1] = charfromwchar (time, wwday[i + 1]);
}
/* weekday */
_time_locale->wweekday[0] = getlocaleinfo (time, LOCALE_SDAYNAME7);
_time_locale->weekday[0] = charfromwchar (time, wweekday[0]);
for (int i = 0; i < 6; ++i)
{
_time_locale->wweekday[i + 1] = getlocaleinfo (time,
LOCALE_SDAYNAME1 + i);
_time_locale->weekday[i + 1] = charfromwchar (time, wweekday[i + 1]);
}
size_t len;
/* X_fmt */
if (era && *era->t_fmt)
{
_time_locale->wX_fmt = (const wchar_t *) lc_time_ptr;
lc_time_ptr = (char *) (wcpcpy ((wchar_t *) _time_locale->wX_fmt,
era->t_fmt) + 1);
}
else
_time_locale->wX_fmt = eval_datetimefmt (LOCALE_STIMEFORMAT, DT_DEFAULT);
_time_locale->X_fmt = charfromwchar (time, wX_fmt);
/* x_fmt */
if (era && *era->d_fmt)
{
_time_locale->wx_fmt = (const wchar_t *) lc_time_ptr;
lc_time_ptr = (char *) (wcpcpy ((wchar_t *) _time_locale->wx_fmt,
era->d_fmt) + 1);
}
else
_time_locale->wx_fmt = eval_datetimefmt (LOCALE_SSHORTDATE, DT_DEFAULT);
_time_locale->x_fmt = charfromwchar (time, wx_fmt);
/* c_fmt */
if (era && *era->d_t_fmt)
{
_time_locale->wc_fmt = (const wchar_t *) lc_time_ptr;
lc_time_ptr = (char *) (wcpcpy ((wchar_t *) _time_locale->wc_fmt,
era->d_t_fmt) + 1);
}
else
{
_time_locale->wc_fmt = eval_datetimefmt (LOCALE_SLONGDATE, DT_ABBREV);
((wchar_t *) lc_time_ptr)[-1] = L' ';
eval_datetimefmt (LOCALE_STIMEFORMAT, DT_DEFAULT);
}
_time_locale->c_fmt = charfromwchar (time, wc_fmt);
/* AM/PM */
_time_locale->wam_pm[0] = getlocaleinfo (time, LOCALE_S1159);
_time_locale->wam_pm[1] = getlocaleinfo (time, LOCALE_S2359);
_time_locale->am_pm[0] = charfromwchar (time, wam_pm[0]);
_time_locale->am_pm[1] = charfromwchar (time, wam_pm[1]);
/* date_fmt */
if (era && *era->date_fmt)
{
_time_locale->wdate_fmt = (const wchar_t *) lc_time_ptr;
lc_time_ptr = (char *) (wcpcpy ((wchar_t *) _time_locale->wdate_fmt,
era->date_fmt) + 1);
}
else
_time_locale->wdate_fmt = _time_locale->wc_fmt;
_time_locale->date_fmt = charfromwchar (time, wdate_fmt);
/* md */
{
wchar_t buf[80];
GetLocaleInfoW (lcid, LOCALE_IDATE, buf, 80);
_time_locale->md_order = (const char *) lc_time_ptr;
lc_time_ptr = stpcpy (lc_time_ptr, *buf == L'1' ? "dm" : "md") + 1;
}
/* ampm_fmt */
if (era)
{
_time_locale->wampm_fmt = (const wchar_t *) lc_time_ptr;
lc_time_ptr = (char *) (wcpcpy ((wchar_t *) _time_locale->wampm_fmt,
era->t_fmt_ampm) + 1);
}
else
_time_locale->wampm_fmt = eval_datetimefmt (LOCALE_STIMEFORMAT, DT_AMPM);
_time_locale->ampm_fmt = charfromwchar (time, wampm_fmt);
if (era)
{
/* Evaluate string length in target charset. Characters invalid in the
target charset are simply ignored, as on Linux. */
len = 0;
len += lc_wcstombs (f_wctomb, charset, NULL, era->era, 0) + 1;
len += lc_wcstombs (f_wctomb, charset, NULL, era->era_d_fmt, 0) + 1;
len += lc_wcstombs (f_wctomb, charset, NULL, era->era_d_t_fmt, 0) + 1;
len += lc_wcstombs (f_wctomb, charset, NULL, era->era_t_fmt, 0) + 1;
len += lc_wcstombs (f_wctomb, charset, NULL, era->alt_digits, 0) + 1;
len += (wcslen (era->era) + 1) * sizeof (wchar_t);
len += (wcslen (era->era_d_fmt) + 1) * sizeof (wchar_t);
len += (wcslen (era->era_d_t_fmt) + 1) * sizeof (wchar_t);
len += (wcslen (era->era_t_fmt) + 1) * sizeof (wchar_t);
len += (wcslen (era->alt_digits) + 1) * sizeof (wchar_t);
/* Make sure data fits into the buffer */
if (lc_time_ptr + len > lc_time_end)
{
len = lc_time_ptr + len - new_lc_time_buf;
char *tmp = (char *) realloc (new_lc_time_buf, len);
if (!tmp)
era = NULL;
else
{
if (tmp != new_lc_time_buf)
rebase_locale_buf (_time_locale, _time_locale + 1, tmp,
new_lc_time_buf, lc_time_ptr);
lc_time_ptr = tmp + (lc_time_ptr - new_lc_time_buf);
new_lc_time_buf = tmp;
lc_time_end = new_lc_time_buf + len;
}
}
/* Copy over */
if (era)
{
/* era */
_time_locale->wera = (const wchar_t *) lc_time_ptr;
lc_time_ptr = (char *) (wcpcpy ((wchar_t *) _time_locale->wera,
era->era) + 1);
_time_locale->era = charfromwchar (time, wera);
/* era_d_fmt */
_time_locale->wera_d_fmt = (const wchar_t *) lc_time_ptr;
lc_time_ptr = (char *) (wcpcpy ((wchar_t *) _time_locale->wera_d_fmt,
era->era_d_fmt) + 1);
_time_locale->era_d_fmt = charfromwchar (time, wera_d_fmt);
/* era_d_t_fmt */
_time_locale->wera_d_t_fmt = (const wchar_t *) lc_time_ptr;
lc_time_ptr = (char *) (wcpcpy ((wchar_t *) _time_locale->wera_d_t_fmt,
era->era_d_t_fmt) + 1);
_time_locale->era_d_t_fmt = charfromwchar (time, wera_d_t_fmt);
/* era_t_fmt */
_time_locale->wera_t_fmt = (const wchar_t *) lc_time_ptr;
lc_time_ptr = (char *) (wcpcpy ((wchar_t *) _time_locale->wera_t_fmt,
era->era_t_fmt) + 1);
_time_locale->era_t_fmt = charfromwchar (time, wera_t_fmt);
/* alt_digits */
_time_locale->walt_digits = (const wchar_t *) lc_time_ptr;
lc_time_ptr = (char *) (wcpcpy ((wchar_t *) _time_locale->walt_digits,
era->alt_digits) + 1);
_time_locale->alt_digits = charfromwchar (time, walt_digits);
}
}
if (!era)
{
_time_locale->wera =
_time_locale->wera_d_fmt =
_time_locale->wera_d_t_fmt =
_time_locale->wera_t_fmt =
_time_locale->walt_digits = (const wchar_t *) lc_time_ptr;
_time_locale->era =
_time_locale->era_d_fmt =
_time_locale->era_d_t_fmt =
_time_locale->era_t_fmt =
_time_locale->alt_digits = (const char *) lc_time_ptr;
/* Twice, to make sure wide char strings are correctly terminated. */
*lc_time_ptr++ = '\0';
*lc_time_ptr++ = '\0';
}
}
char *tmp = (char *) realloc (new_lc_time_buf, lc_time_ptr - new_lc_time_buf);
if (!tmp)
{
free (new_lc_time_buf);
return -1;
}
if (tmp != new_lc_time_buf)
rebase_locale_buf (_time_locale, _time_locale + 1, tmp,
new_lc_time_buf, lc_time_ptr);
if (*lc_time_buf)
free (*lc_time_buf);
*lc_time_buf = tmp;
return 1;
}
/* Called from newlib's setlocale() via __ctype_load_locale() if category
is LC_CTYPE. Returns LC_CTYPE values fetched from Windows locale data
in the structure pointed to by _ctype_locale. This is subsequently
accessed by functions like nl_langinfo, localeconv, printf, etc. */
extern "C" int
__set_lc_ctype_from_win (const char *name,
const struct lc_ctype_T *_C_ctype_locale,
struct lc_ctype_T *_ctype_locale,
char **lc_ctype_buf, wctomb_p f_wctomb,
const char *charset, int mb_cur_max)
{
LCID lcid = __get_lcid_from_locale (name);
if (lcid == (LCID) -1)
return lcid;
if (!lcid && !strcmp (charset, "ASCII"))
return 0;
# define MAX_CTYPE_BUFFER_SIZE 256
char *new_lc_ctype_buf = (char *) malloc (MAX_CTYPE_BUFFER_SIZE);
if (!new_lc_ctype_buf)
return -1;
char *lc_ctype_ptr = new_lc_ctype_buf;
/* C.foo is just a copy of "C" with fixed charset. */
if (!lcid)
memcpy (_ctype_locale, _C_ctype_locale, sizeof (struct lc_ctype_T));
/* codeset */
_ctype_locale->codeset = lc_ctype_ptr;
lc_ctype_ptr = stpcpy (lc_ctype_ptr, charset) + 1;
/* mb_cur_max */
_ctype_locale->mb_cur_max = lc_ctype_ptr;
*lc_ctype_ptr++ = mb_cur_max;
*lc_ctype_ptr++ = '\0';
if (lcid)
{
/* outdigits and woutdigits */
wchar_t digits[11];
GetLocaleInfoW (lcid, LOCALE_SNATIVEDIGITS, digits, 11);
for (int i = 0; i <= 9; ++i)
{
mbstate_t state;
/* Make sure the wchar_t's are always 2 byte aligned. */
if ((uintptr_t) lc_ctype_ptr % 2)
++lc_ctype_ptr;
wchar_t *woutdig = (wchar_t *) lc_ctype_ptr;
_ctype_locale->woutdigits[i] = (const wchar_t *) woutdig;
*woutdig++ = digits[i];
*woutdig++ = L'\0';
lc_ctype_ptr = (char *) woutdig;
_ctype_locale->outdigits[i] = lc_ctype_ptr;
memset (&state, 0, sizeof state);
lc_ctype_ptr += f_wctomb (_REENT, lc_ctype_ptr, digits[i], charset,
&state);
*lc_ctype_ptr++ = '\0';
}
}
char *tmp = (char *) realloc (new_lc_ctype_buf,
lc_ctype_ptr - new_lc_ctype_buf);
if (!tmp)
{
free (new_lc_ctype_buf);
return -1;
}
if (tmp != new_lc_ctype_buf)
rebase_locale_buf (_ctype_locale, _ctype_locale + 1, tmp,
new_lc_ctype_buf, lc_ctype_ptr);
if (*lc_ctype_buf)
free (*lc_ctype_buf);
*lc_ctype_buf = tmp;
return 1;
}
/* Called from newlib's setlocale() via __numeric_load_locale() if category
is LC_NUMERIC. Returns LC_NUMERIC values fetched from Windows locale data
in the structure pointed to by _numeric_locale. This is subsequently
accessed by functions like nl_langinfo, localeconv, printf, etc. */
extern "C" int
__set_lc_numeric_from_win (const char *name,
const struct lc_numeric_T *_C_numeric_locale,
struct lc_numeric_T *_numeric_locale,
char **lc_numeric_buf, wctomb_p f_wctomb,
const char *charset)
{
LCID lcid = __get_lcid_from_locale (name);
if (lcid == (LCID) -1)
return lcid;
if (!lcid && !strcmp (charset, "ASCII"))
return 0;
# define MAX_NUMERIC_BUFFER_SIZE 256
char *new_lc_numeric_buf = (char *) malloc (MAX_NUMERIC_BUFFER_SIZE);
const char *lc_numeric_end = new_lc_numeric_buf + MAX_NUMERIC_BUFFER_SIZE;
if (!new_lc_numeric_buf)
return -1;
char *lc_numeric_ptr = new_lc_numeric_buf;
/* C.foo is just a copy of "C" with fixed charset. */
if (!lcid)
memcpy (_numeric_locale, _C_numeric_locale, sizeof (struct lc_numeric_T));
else
{
/* decimal_point */
_numeric_locale->wdecimal_point = getlocaleinfo (numeric, LOCALE_SDECIMAL);
_numeric_locale->decimal_point = charfromwchar (numeric, wdecimal_point);
/* thousands_sep */
_numeric_locale->wthousands_sep = getlocaleinfo (numeric, LOCALE_STHOUSAND);
_numeric_locale->thousands_sep = charfromwchar (numeric, wthousands_sep);
/* grouping */
_numeric_locale->grouping = conv_grouping (lcid, LOCALE_SGROUPING,
&lc_numeric_ptr);
}
/* codeset */
_numeric_locale->codeset = lc_numeric_ptr;
lc_numeric_ptr = stpcpy (lc_numeric_ptr, charset) + 1;
char *tmp = (char *) realloc (new_lc_numeric_buf,
lc_numeric_ptr - new_lc_numeric_buf);
if (!tmp)
{
free (new_lc_numeric_buf);
return -1;
}
if (tmp != new_lc_numeric_buf)
rebase_locale_buf (_numeric_locale, _numeric_locale + 1, tmp,
new_lc_numeric_buf, lc_numeric_ptr);
if (*lc_numeric_buf)
free (*lc_numeric_buf);
*lc_numeric_buf = tmp;
return 1;
}
/* Called from newlib's setlocale() via __monetary_load_locale() if category
is LC_MONETARY. Returns LC_MONETARY values fetched from Windows locale data
in the structure pointed to by _monetary_locale. This is subsequently
accessed by functions like nl_langinfo, localeconv, printf, etc. */
extern "C" int
__set_lc_monetary_from_win (const char *name,
const struct lc_monetary_T *_C_monetary_locale,
struct lc_monetary_T *_monetary_locale,
char **lc_monetary_buf, wctomb_p f_wctomb,
const char *charset)
{
LCID lcid = __get_lcid_from_locale (name);
if (lcid == (LCID) -1)
return lcid;
if (!lcid && !strcmp (charset, "ASCII"))
return 0;
# define MAX_MONETARY_BUFFER_SIZE 512
char *new_lc_monetary_buf = (char *) malloc (MAX_MONETARY_BUFFER_SIZE);
const char *lc_monetary_end = new_lc_monetary_buf + MAX_MONETARY_BUFFER_SIZE;
if (!new_lc_monetary_buf)
return -1;
char *lc_monetary_ptr = new_lc_monetary_buf;
/* C.foo is just a copy of "C" with fixed charset. */
if (!lcid)
memcpy (_monetary_locale, _C_monetary_locale, sizeof (struct lc_monetary_T));
else
{
/* int_curr_symbol */
_monetary_locale->wint_curr_symbol = getlocaleinfo (monetary,
LOCALE_SINTLSYMBOL);
/* No spacing char means space. */
if (!_monetary_locale->wint_curr_symbol[3])
{
wchar_t *wc = (wchar_t *) _monetary_locale->wint_curr_symbol + 3;
*wc++ = L' ';
*wc++ = L'\0';
lc_monetary_ptr = (char *) wc;
}
_monetary_locale->int_curr_symbol = charfromwchar (monetary,
wint_curr_symbol);
/* currency_symbol */
_monetary_locale->wcurrency_symbol = getlocaleinfo (monetary,
LOCALE_SCURRENCY);
/* As on Linux: If the currency_symbol can't be represented in the
given charset, use int_curr_symbol. */
if (lc_wcstombs (f_wctomb, charset, NULL,
_monetary_locale->wcurrency_symbol,
0, true) == (size_t) -1)
_monetary_locale->currency_symbol = _monetary_locale->int_curr_symbol;
else
_monetary_locale->currency_symbol = charfromwchar (monetary,
wcurrency_symbol);
/* mon_decimal_point */
_monetary_locale->wmon_decimal_point = getlocaleinfo (monetary,
LOCALE_SMONDECIMALSEP);
_monetary_locale->mon_decimal_point = charfromwchar (monetary,
wmon_decimal_point);
/* mon_thousands_sep */
_monetary_locale->wmon_thousands_sep = getlocaleinfo (monetary,
LOCALE_SMONTHOUSANDSEP);
_monetary_locale->mon_thousands_sep = charfromwchar (monetary,
wmon_thousands_sep);
/* mon_grouping */
_monetary_locale->mon_grouping = conv_grouping (lcid, LOCALE_SMONGROUPING,
&lc_monetary_ptr);
/* positive_sign */
_monetary_locale->wpositive_sign = getlocaleinfo (monetary,
LOCALE_SPOSITIVESIGN);
_monetary_locale->positive_sign = charfromwchar (monetary, wpositive_sign);
/* negative_sign */
_monetary_locale->wnegative_sign = getlocaleinfo (monetary,
LOCALE_SNEGATIVESIGN);
_monetary_locale->negative_sign = charfromwchar (monetary, wnegative_sign);
/* int_frac_digits */
*lc_monetary_ptr = (char) getlocaleint (lcid, LOCALE_IINTLCURRDIGITS);
_monetary_locale->int_frac_digits = lc_monetary_ptr++;
/* frac_digits */
*lc_monetary_ptr = (char) getlocaleint (lcid, LOCALE_ICURRDIGITS);
_monetary_locale->frac_digits = lc_monetary_ptr++;
/* p_cs_precedes and int_p_cs_precedes */
*lc_monetary_ptr = (char) getlocaleint (lcid, LOCALE_IPOSSYMPRECEDES);
_monetary_locale->p_cs_precedes
= _monetary_locale->int_p_cs_precedes = lc_monetary_ptr++;
/* p_sep_by_space and int_p_sep_by_space */
*lc_monetary_ptr = (char) getlocaleint (lcid, LOCALE_IPOSSEPBYSPACE);
_monetary_locale->p_sep_by_space
= _monetary_locale->int_p_sep_by_space = lc_monetary_ptr++;
/* n_cs_precedes and int_n_cs_precedes */
*lc_monetary_ptr = (char) getlocaleint (lcid, LOCALE_INEGSYMPRECEDES);
_monetary_locale->n_cs_precedes
= _monetary_locale->int_n_cs_precedes = lc_monetary_ptr++;
/* n_sep_by_space and int_n_sep_by_space */
*lc_monetary_ptr = (char) getlocaleint (lcid, LOCALE_INEGSEPBYSPACE);
_monetary_locale->n_sep_by_space
= _monetary_locale->int_n_sep_by_space = lc_monetary_ptr++;
/* p_sign_posn and int_p_sign_posn */
*lc_monetary_ptr = (char) getlocaleint (lcid, LOCALE_IPOSSIGNPOSN);
_monetary_locale->p_sign_posn
= _monetary_locale->int_p_sign_posn = lc_monetary_ptr++;
/* n_sign_posn and int_n_sign_posn */
*lc_monetary_ptr = (char) getlocaleint (lcid, LOCALE_INEGSIGNPOSN);
_monetary_locale->n_sign_posn
= _monetary_locale->int_n_sign_posn = lc_monetary_ptr++;
}
/* codeset */
_monetary_locale->codeset = lc_monetary_ptr;
lc_monetary_ptr = stpcpy (lc_monetary_ptr, charset) + 1;
char *tmp = (char *) realloc (new_lc_monetary_buf,
lc_monetary_ptr - new_lc_monetary_buf);
if (!tmp)
{
free (new_lc_monetary_buf);
return -1;
}
if (tmp != new_lc_monetary_buf)
rebase_locale_buf (_monetary_locale, _monetary_locale + 1, tmp,
new_lc_monetary_buf, lc_monetary_ptr);
if (*lc_monetary_buf)
free (*lc_monetary_buf);
*lc_monetary_buf = tmp;
return 1;
}
extern "C" int
__set_lc_messages_from_win (const char *name,
const struct lc_messages_T *_C_messages_locale,
struct lc_messages_T *_messages_locale,
char **lc_messages_buf,
wctomb_p f_wctomb, const char *charset)
{
LCID lcid = __get_lcid_from_locale (name);
if (lcid == (LCID) -1)
return lcid;
if (!lcid && !strcmp (charset, "ASCII"))
return 0;
char locale[ENCODING_LEN + 1];
char *c, *c2;
lc_msg_t *msg = NULL;
/* C.foo is just a copy of "C" with fixed charset. */
if (!lcid)
memcpy (_messages_locale, _C_messages_locale, sizeof (struct lc_messages_T));
else
{
strcpy (locale, name);
/* Removes the charset from the locale and attach the modifer to the
language_TERRITORY part. */
c = strchr (locale, '.');
if (c)
{
*c = '\0';
c2 = strchr (c + 1, '@');
/* Ignore @cjknarrow modifier since it's a very personal thing between
Cygwin and newlib... */
if (c2 && strcmp (c2, "@cjknarrow"))
memmove (c, c2, strlen (c2) + 1);
}
/* Now search in the alphabetically order lc_msg array for the
locale. */
lc_msg_t locale_key = { locale, NULL, NULL, NULL, NULL };
msg = (lc_msg_t *) bsearch ((void *) &locale_key, (void *) lc_msg,
sizeof lc_msg / sizeof *lc_msg,
sizeof *lc_msg, locale_cmp);
if (!msg)
return 0;
}
/* Evaluate string length in target charset. Characters invalid in the
target charset are simply ignored, as on Linux. */
size_t len = 0;
len += (strlen (charset) + 1);
if (lcid)
{
len += lc_wcstombs (f_wctomb, charset, NULL, msg->yesexpr, 0) + 1;
len += lc_wcstombs (f_wctomb, charset, NULL, msg->noexpr, 0) + 1;
len += lc_wcstombs (f_wctomb, charset, NULL, msg->yesstr, 0) + 1;
len += lc_wcstombs (f_wctomb, charset, NULL, msg->nostr, 0) + 1;
len += (wcslen (msg->yesexpr) + 1) * sizeof (wchar_t);
len += (wcslen (msg->noexpr) + 1) * sizeof (wchar_t);
len += (wcslen (msg->yesstr) + 1) * sizeof (wchar_t);
len += (wcslen (msg->nostr) + 1) * sizeof (wchar_t);
if (len % 1)
++len;
}
/* Allocate. */
char *new_lc_messages_buf = (char *) malloc (len);
const char *lc_messages_end = new_lc_messages_buf + len;
if (!new_lc_messages_buf)
return -1;
/* Copy over. */
c = new_lc_messages_buf;
/* codeset */
_messages_locale->codeset = c;
c = stpcpy (c, charset) + 1;
if (lcid)
{
_messages_locale->yesexpr = (const char *) c;
len = lc_wcstombs (f_wctomb, charset, c, msg->yesexpr, lc_messages_end - c);
_messages_locale->noexpr = (const char *) (c += len + 1);
len = lc_wcstombs (f_wctomb, charset, c, msg->noexpr, lc_messages_end - c);
_messages_locale->yesstr = (const char *) (c += len + 1);
len = lc_wcstombs (f_wctomb, charset, c, msg->yesstr, lc_messages_end - c);
_messages_locale->nostr = (const char *) (c += len + 1);
len = lc_wcstombs (f_wctomb, charset, c, msg->nostr, lc_messages_end - c);
c += len + 1;
if ((uintptr_t) c % 1)
++c;
wchar_t *wc = (wchar_t *) c;
_messages_locale->wyesexpr = (const wchar_t *) wc;
wc = wcpcpy (wc, msg->yesexpr) + 1;
_messages_locale->wnoexpr = (const wchar_t *) wc;
wc = wcpcpy (wc, msg->noexpr) + 1;
_messages_locale->wyesstr = (const wchar_t *) wc;
wc = wcpcpy (wc, msg->yesstr) + 1;
_messages_locale->wnostr = (const wchar_t *) wc;
wcpcpy (wc, msg->nostr);
}
/* Aftermath. */
if (*lc_messages_buf)
free (*lc_messages_buf);
*lc_messages_buf = new_lc_messages_buf;
return 1;
}
LCID collate_lcid = 0;
static mbtowc_p collate_mbtowc = __ascii_mbtowc;
char collate_charset[ENCODING_LEN + 1] = "ASCII";
/* Called from newlib's setlocale() if category is LC_COLLATE. Stores
LC_COLLATE locale information. This is subsequently accessed by the
below functions strcoll, strxfrm, wcscoll, wcsxfrm. */
extern "C" int
__collate_load_locale (const char *name, mbtowc_p f_mbtowc, const char *charset)
{
LCID lcid = __get_lcid_from_locale (name);
if (lcid == (LCID) -1)
return -1;
collate_lcid = lcid;
collate_mbtowc = f_mbtowc;
stpcpy (collate_charset, charset);
return 0;
}
extern "C" const char *
__get_current_collate_codeset (void)
{
return collate_charset;
}
/* We use the Windows functions for locale-specific string comparison and
transformation. The advantage is that we don't need any files with
collation information. */
extern "C" int
wcscoll (const wchar_t *__restrict ws1, const wchar_t *__restrict ws2)
{
int ret;
if (!collate_lcid)
return wcscmp (ws1, ws2);
ret = CompareStringW (collate_lcid, 0, ws1, -1, ws2, -1);
if (!ret)
set_errno (EINVAL);
return ret - CSTR_EQUAL;
}
extern "C" int
strcoll (const char *__restrict s1, const char *__restrict s2)
{
size_t n1, n2;
wchar_t *ws1, *ws2;
tmp_pathbuf tp;
int ret;
if (!collate_lcid)
return strcmp (s1, s2);
/* The ANSI version of CompareString uses the default charset of the lcid,
so we must use the Unicode version. */
n1 = lc_mbstowcs (collate_mbtowc, collate_charset, NULL, s1, 0) + 1;
ws1 = (n1 > NT_MAX_PATH ? (wchar_t *) malloc (n1 * sizeof (wchar_t))
: tp.w_get ());
lc_mbstowcs (collate_mbtowc, collate_charset, ws1, s1, n1);
n2 = lc_mbstowcs (collate_mbtowc, collate_charset, NULL, s2, 0) + 1;
ws2 = (n2 > NT_MAX_PATH ? (wchar_t *) malloc (n2 * sizeof (wchar_t))
: tp.w_get ());
lc_mbstowcs (collate_mbtowc, collate_charset, ws2, s2, n2);
ret = CompareStringW (collate_lcid, 0, ws1, -1, ws2, -1);
if (n1 > NT_MAX_PATH)
free (ws1);
if (n2 > NT_MAX_PATH)
free (ws2);
if (!ret)
set_errno (EINVAL);
return ret - CSTR_EQUAL;
}
/* BSD. Used from glob.cc, fnmatch.c and regcomp.c. Make sure caller is
using wide chars. Unfortunately the definition of this functions hides
the required input type. */
extern "C" int
__collate_range_cmp (int c1, int c2)
{
wchar_t s1[2] = { (wchar_t) c1, L'\0' };
wchar_t s2[2] = { (wchar_t) c2, L'\0' };
return wcscoll (s1, s2);
}
extern "C" size_t
wcsxfrm (wchar_t *__restrict ws1, const wchar_t *__restrict ws2, size_t wsn)
{
size_t ret;
if (!collate_lcid)
return wcslcpy (ws1, ws2, wsn);
ret = LCMapStringW (collate_lcid, LCMAP_SORTKEY | LCMAP_BYTEREV,
ws2, -1, ws1, wsn * sizeof (wchar_t));
/* LCMapStringW returns byte count including the terminating NUL character,
wcsxfrm is supposed to return length in wchar_t excluding the NUL.
Since the array is only single byte NUL-terminated we must make sure
the result is wchar_t-NUL terminated. */
if (ret)
{
ret = (ret + 1) / sizeof (wchar_t);
if (ret >= wsn)
return wsn;
ws1[ret] = L'\0';
return ret;
}
if (GetLastError () != ERROR_INSUFFICIENT_BUFFER)
set_errno (EINVAL);
return wsn;
}
extern "C" size_t
strxfrm (char *__restrict s1, const char *__restrict s2, size_t sn)
{
size_t ret;
size_t n2;
wchar_t *ws2;
tmp_pathbuf tp;
if (!collate_lcid)
return strlcpy (s1, s2, sn);
/* The ANSI version of LCMapString uses the default charset of the lcid,
so we must use the Unicode version. */
n2 = lc_mbstowcs (collate_mbtowc, collate_charset, NULL, s2, 0) + 1;
ws2 = (n2 > NT_MAX_PATH ? (wchar_t *) malloc (n2 * sizeof (wchar_t))
: tp.w_get ());
lc_mbstowcs (collate_mbtowc, collate_charset, ws2, s2, n2);
/* The sort key is a NUL-terminated byte string. */
ret = LCMapStringW (collate_lcid, LCMAP_SORTKEY, ws2, -1, (PWCHAR) s1, sn);
if (n2 > NT_MAX_PATH)
free (ws2);
if (ret == 0)
{
if (GetLastError () != ERROR_INSUFFICIENT_BUFFER)
set_errno (EINVAL);
return sn;
}
/* LCMapStringW returns byte count including the terminating NUL character.
strxfrm is supposed to return length excluding the NUL. */
return ret - 1;
}
/* Fetch default ANSI codepage from locale info and generate a setlocale
compatible character set code. Called from newlib's setlocale(), if the
charset isn't given explicitely in the POSIX compatible locale specifier. */
extern "C" void
__set_charset_from_locale (const char *locale, char *charset)
{
UINT cp;
LCID lcid = __get_lcid_from_locale (locale);
wchar_t wbuf[9];
/* "C" locale, or invalid locale? */
if (lcid == 0 || lcid == (LCID) -1)
cp = 20127;
else if (!GetLocaleInfoW (lcid,
LOCALE_IDEFAULTANSICODEPAGE | LOCALE_RETURN_NUMBER,
(PWCHAR) &cp, sizeof cp))
cp = 0;
/* Translate codepage and lcid to a charset closely aligned with the default
charsets defined in Glibc. */
const char *cs;
const char *modifier = strchr (locale, '@') ?: "";
switch (cp)
{
case 20127:
cs = "ASCII";
break;
case 874:
cs = "CP874";
break;
case 932:
cs = "EUCJP";
break;
case 936:
cs = "GB2312";
break;
case 949:
cs = "EUCKR";
break;
case 950:
cs = "BIG5";
break;
case 1250:
if (lcid == 0x081a /* sr_CS (Serbian Language/Former
Serbia and Montenegro) */
|| lcid == 0x181a /* sr_BA (Serbian Language/Bosnia
and Herzegovina) */
|| lcid == 0x241a /* sr_RS (Serbian Language/Serbia) */
|| lcid == 0x2c1a /* sr_ME (Serbian Language/Montenegro)*/
|| lcid == 0x0442) /* tk_TM (Turkmen/Turkmenistan) */
cs = "UTF-8";
else if (lcid == 0x041c) /* sq_AL (Albanian/Albania) */
cs = "ISO-8859-1";
else
cs = "ISO-8859-2";
break;
case 1251:
if (lcid == 0x0c1a /* sr_CS (Serbian Language/Former
Serbia and Montenegro) */
|| lcid == 0x1c1a /* sr_BA (Serbian Language/Bosnia
and Herzegovina) */
|| lcid == 0x281a /* sr_RS (Serbian Language/Serbia) */
|| lcid == 0x301a /* sr_ME (Serbian Language/Montenegro)*/
|| lcid == 0x0440 /* ky_KG (Kyrgyz/Kyrgyzstan) */
|| lcid == 0x0843 /* uz_UZ (Uzbek/Uzbekistan) */
/* tt_RU (Tatar/Russia),
IQTElif alphabet */
|| (lcid == 0x0444 && has_modifier ("@iqtelif"))
|| lcid == 0x0450) /* mn_MN (Mongolian/Mongolia) */
cs = "UTF-8";
else if (lcid == 0x0423) /* be_BY (Belarusian/Belarus) */
cs = has_modifier ("@latin") ? "UTF-8" : "CP1251";
else if (lcid == 0x0402) /* bg_BG (Bulgarian/Bulgaria) */
cs = "CP1251";
else if (lcid == 0x0422) /* uk_UA (Ukrainian/Ukraine) */
cs = "KOI8-U";
else
cs = "ISO-8859-5";
break;
case 1252:
if (lcid == 0x0452) /* cy_GB (Welsh/Great Britain) */
cs = "ISO-8859-14";
else if (lcid == 0x4009 /* en_IN (English/India) */
|| lcid == 0x0867 /* ff_SN (Fulah/Senegal) */
|| lcid == 0x0464 /* fil_PH (Filipino/Philippines) */
|| lcid == 0x0462 /* fy_NL (Frisian/Netherlands) */
|| lcid == 0x0468 /* ha_NG (Hausa/Nigeria) */
|| lcid == 0x0475 /* haw_US (Hawaiian/United States) */
|| lcid == 0x0470 /* ig_NG (Igbo/Nigeria) */
|| lcid == 0x085d /* iu_CA (Inuktitut/Canada) */
|| lcid == 0x046c /* nso_ZA (Northern Sotho/South Africa) */
|| lcid == 0x0487 /* rw_RW (Kinyarwanda/Rwanda) */
|| lcid == 0x043b /* se_NO (Northern Saami/Norway) */
|| lcid == 0x0832 /* tn_BW (Tswana/Botswana) */
|| lcid == 0x0432 /* tn_ZA (Tswana/South Africa) */
|| lcid == 0x0488 /* wo_SN (Wolof/Senegal) */
|| lcid == 0x046a) /* yo_NG (Yoruba/Nigeria) */
cs = "UTF-8";
else if (lcid == 0x042e) /* hsb_DE (Upper Sorbian/Germany) */
cs = "ISO-8859-2";
else if (lcid == 0x0491 /* gd_GB (Scots Gaelic/Great Britain) */
|| (has_modifier ("@euro")
&& GetLocaleInfoW (lcid, LOCALE_SINTLSYMBOL, wbuf, 9)
&& !wcsncmp (wbuf, L"EUR", 3)))
cs = "ISO-8859-15";
else
cs = "ISO-8859-1";
break;
case 1253:
cs = "ISO-8859-7";
break;
case 1254:
if (lcid == 0x042c) /* az_AZ (Azeri/Azerbaijan) */
cs = "UTF-8";
else if (lcid == 0x0443) /* uz_UZ (Uzbek/Uzbekistan) */
cs = "ISO-8859-1";
else
cs = "ISO-8859-9";
break;
case 1255:
cs = "ISO-8859-8";
break;
case 1256:
if (lcid == 0x0429 /* fa_IR (Persian/Iran) */
|| lcid == 0x0846 /* pa_PK (Punjabi/Pakistan) */
|| lcid == 0x0859 /* sd_PK (Sindhi/Pakistan) */
|| lcid == 0x0480 /* ug_CN (Uyghur/China) */
|| lcid == 0x0420) /* ur_PK (Urdu/Pakistan) */
cs = "UTF-8";
else
cs = "ISO-8859-6";
break;
case 1257:
if (lcid == 0x0425) /* et_EE (Estonian/Estonia) */
cs = "ISO-8859-15";
else
cs = "ISO-8859-13";
break;
case 1258:
default:
if (lcid == 0x3c09 /* en_HK (English/Hong Kong) */
|| lcid == 0x200c /* fr_RE (French/Réunion) */
|| lcid == 0x240c /* fr_CD (French/Congo) */
|| lcid == 0x280c /* fr_SN (French/Senegal) */
|| lcid == 0x2c0c /* fr_CM (French/Cameroon) */
|| lcid == 0x300c /* fr_CI (French/Ivory Coast) */
|| lcid == 0x340c /* fr_ML (French/Mali) */
|| lcid == 0x380c /* fr_MA (French/Morocco) */
|| lcid == 0x3c0c /* fr_HT (French/Haiti) */
|| lcid == 0x0477 /* so_SO (Somali/Somali) */
|| lcid == 0x0430) /* st_ZA (Sotho/South Africa) */
cs = "ISO-8859-1";
else if (lcid == 0x818) /* ro_MD (Romanian/Moldovia) */
cs = "ISO-8859-2";
else if (lcid == 0x043a) /* mt_MT (Maltese/Malta) */
cs = "ISO-8859-3";
else if (lcid == 0x0481) /* mi_NZ (Maori/New Zealand) */
cs = "ISO-8859-13";
else if (lcid == 0x0437) /* ka_GE (Georgian/Georgia) */
cs = "GEORGIAN-PS";
else if (lcid == 0x043f) /* kk_KZ (Kazakh/Kazakhstan) */
cs = "PT154";
else
cs = "UTF-8";
}
stpcpy (charset, cs);
}
/* This function is called from newlib's loadlocale if the locale identifier
was invalid, one way or the other. It looks for the file
/usr/share/locale/locale.alias
which is part of the gettext package, and if it finds the locale alias
in that file, it replaces the locale with the correct locale string from
that file.
If successful, it returns a pointer to new_locale, NULL otherwise.*/
extern "C" char *
__set_locale_from_locale_alias (const char *locale, char *new_locale)
{
wchar_t wlocale[ENCODING_LEN + 1];
wchar_t walias[ENCODING_LEN + 1];
#define LOCALE_ALIAS_LINE_LEN 255
char alias_buf[LOCALE_ALIAS_LINE_LEN + 1], *c;
wchar_t *wc;
const char *alias, *replace;
char *ret = NULL;
FILE *fp = fopen ("/usr/share/locale/locale.alias", "rt");
if (!fp)
return NULL;
/* The incoming locale is given in the application charset, or in
the Cygwin internal charset. We try both. */
if (mbstowcs (wlocale, locale, ENCODING_LEN + 1) == (size_t) -1)
sys_mbstowcs (wlocale, ENCODING_LEN + 1, locale);
wlocale[ENCODING_LEN] = L'\0';
/* Ignore @cjknarrow modifier since it's a very personal thing between
Cygwin and newlib... */
if ((wc = wcschr (wlocale, L'@')) && !wcscmp (wc + 1, L"cjknarrow"))
*wc = L'\0';
while (fgets (alias_buf, LOCALE_ALIAS_LINE_LEN + 1, fp))
{
alias_buf[LOCALE_ALIAS_LINE_LEN] = '\0';
c = strrchr (alias_buf, '\n');
if (c)
*c = '\0';
c = alias_buf;
c += strspn (c, " \t");
if (!*c || *c == '#')
continue;
alias = c;
c += strcspn (c, " \t");
*c++ = '\0';
c += strspn (c, " \t");
if (*c == '#')
continue;
replace = c;
c += strcspn (c, " \t");
*c++ = '\0';
if (strlen (replace) > ENCODING_LEN)
continue;
/* The file is latin1 encoded */
lc_mbstowcs (__iso_mbtowc, "ISO-8859-1", walias, alias, ENCODING_LEN + 1);
walias[ENCODING_LEN] = L'\0';
if (!wcscmp (wlocale, walias))
{
ret = strcpy (new_locale, replace);
break;
}
}
fclose (fp);
return ret;
}
static char *
check_codepage (char *ret)
{
if (!wincap.has_always_all_codepages ())
{
/* Prior to Windows Vista, many codepages are not installed by
default, or can be deinstalled. The following codepages require
that the respective conversion tables are installed into the OS.
So we check if they are installed and if not, setlocale should
fail. */
CPINFO cpi;
UINT cp = 0;
if (__mbtowc == __sjis_mbtowc)
cp = 932;
else if (__mbtowc == __eucjp_mbtowc)
cp = 20932;
else if (__mbtowc == __gbk_mbtowc)
cp = 936;
else if (__mbtowc == __kr_mbtowc)
cp = 949;
else if (__mbtowc == __big5_mbtowc)
cp = 950;
if (cp && !GetCPInfo (cp, &cpi)
&& GetLastError () == ERROR_INVALID_PARAMETER)
return NULL;
}
return ret;
}
/* Can be called via cygwin_internal (CW_INTERNAL_SETLOCALE) for application
which really (think they) know what they are doing. */
extern "C" void
internal_setlocale ()
{
/* Each setlocale from the environment potentially changes the
multibyte representation of the CWD. Therefore we have to
reevaluate the CWD's posix path and store in the new charset.
Same for the PATH environment variable. */
/* FIXME: Other buffered paths might be affected as well. */
/* FIXME: It could be necessary to convert the entire environment,
not just PATH. */
tmp_pathbuf tp;
char *path;
wchar_t *w_path = NULL, *w_cwd;
/* Don't do anything if the charset hasn't actually changed. */
if (strcmp (cygheap->locale.charset, __locale_charset ()) == 0)
return;
debug_printf ("Cygwin charset changed from %s to %s",
cygheap->locale.charset, __locale_charset ());
/* Fetch PATH and CWD and convert to wchar_t in previous charset. */
path = getenv ("PATH");
if (path && *path) /* $PATH can be potentially unset. */
{
w_path = tp.w_get ();
sys_mbstowcs (w_path, 32768, path);
}
w_cwd = tp.w_get ();
cwdstuff::cwd_lock.acquire ();
sys_mbstowcs (w_cwd, 32768, cygheap->cwd.get_posix ());
/* Set charset for internal conversion functions. */
if (*__locale_charset () == 'A'/*SCII*/)
{
cygheap->locale.mbtowc = __utf8_mbtowc;
cygheap->locale.wctomb = __utf8_wctomb;
}
else
{
cygheap->locale.mbtowc = __mbtowc;
cygheap->locale.wctomb = __wctomb;
}
strcpy (cygheap->locale.charset, __locale_charset ());
/* Restore CWD and PATH in new charset. */
cygheap->cwd.reset_posix (w_cwd);
cwdstuff::cwd_lock.release ();
if (w_path)
{
char *c_path = tp.c_get ();
sys_wcstombs (c_path, 32768, w_path);
setenv ("PATH", c_path, 1);
}
}
/* Called from dll_crt0_1, before fetching the command line from Windows.
Set the internal charset according to the environment locale settings.
Check if a required codepage is available, and only switch internal
charset if so.
Make sure to reset the application locale to "C" per POSIX. */
void
initial_setlocale ()
{
char *ret = _setlocale_r (_REENT, LC_CTYPE, "");
if (ret && check_codepage (ret))
internal_setlocale ();
}
/* Like newlib's setlocale, but additionally check if the charset needs
OS support and the required codepage is actually installed. If codepage
is not available, revert to previous locale and return NULL. For details
about codepage availability, see the comment in check_codepage() above. */
extern "C" char *
setlocale (int category, const char *locale)
{
char old[(LC_MESSAGES + 1) * (ENCODING_LEN + 1/*"/"*/ + 1)];
if (locale && !wincap.has_always_all_codepages ())
stpcpy (old, _setlocale_r (_REENT, category, NULL));
char *ret = _setlocale_r (_REENT, category, locale);
if (ret && locale && !(ret = check_codepage (ret)))
_setlocale_r (_REENT, category, old);
return ret;
}
|
//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#pragma once
#include <memory>
#include "ngraph/op/op.hpp"
namespace ngraph
{
namespace op
{
namespace v0
{
class NGRAPH_API BroadcastDistributed : public Op
{
public:
static constexpr NodeTypeInfo type_info{"BroadcastDistributed", 0};
const NodeTypeInfo& get_type_info() const override { return type_info; }
BroadcastDistributed() = default;
BroadcastDistributed(const Output<Node>& arg, int64_t root_id = 0);
bool visit_attributes(AttributeVisitor& visitor) override;
void validate_and_infer_types() override;
virtual std::shared_ptr<Node>
copy_with_new_args(const NodeVector& new_args) const override;
int64_t get_root_id() const;
void set_root_id(int64_t root_id);
private:
int64_t m_root_id;
};
}
using v0::BroadcastDistributed;
}
}
|
/*
* Copyright 2010 Utkin Dmitry
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* This file is part of the WSF Staff project.
* Please, visit http://code.google.com/p/staff for more information.
*/
#include <staff/common/Exception.h>
#include <axiom_soap_const.h>
#include <axis2_options.h>
#include <axutil_property.h>
#include <axis2_http_transport.h>
#include <axis2_http_header.h>
#include <staff/common/Runtime.h>
#include "Options.h"
#define STAFF_PARAM_UNUSED(param) (void)param
namespace staff
{
Options::Options(axutil_env_t* pEnv):
m_pEnv(pEnv), m_bOwner(true)
{
m_pOptions = axis2_options_create(m_pEnv);
}
Options::Options(axis2_options_t* pOptions, axutil_env_t* pEnv):
m_pOptions(pOptions), m_pEnv(pEnv), m_bOwner(false)
{
}
Options::~Options()
{
if (m_bOwner)
{
axis2_options_free(m_pOptions, m_pEnv);
}
}
bool Options::IsOwner() const
{
return m_bOwner;
}
void Options::SetOwner(bool bOwner /*= true*/)
{
m_bOwner = bOwner;
}
std::string Options::GetAction() const
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
const axis2_char_t* szAction = axis2_options_get_action(m_pOptions, m_pEnv);
STAFF_ASSERT(szAction, "Can't get action");
return reinterpret_cast<const char*>(szAction);
}
void Options::SetAction(const std::string& sAction)
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
axis2_options_set_action(m_pOptions, m_pEnv, sAction.c_str());
}
std::string Options::GetFromAddress() const
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
axis2_endpoint_ref_t* pEndpointRef = axis2_options_get_from(m_pOptions, m_pEnv);
STAFF_ASSERT(pEndpointRef, "Can't get WSA endpoint");
const axis2_char_t* szAddress = axis2_endpoint_ref_get_address(pEndpointRef, m_pEnv);
STAFF_ASSERT(szAddress, "Can't get WSA from address");
return reinterpret_cast<const char*>(szAddress);
}
void Options::SetFromAddress(const std::string& sAddress)
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
axis2_endpoint_ref_t* pEndpointRef = axis2_endpoint_ref_create(m_pEnv, sAddress.c_str());
STAFF_ASSERT(pEndpointRef, "Can't create WSA endpoint");
axis2_options_set_from(m_pOptions, m_pEnv, pEndpointRef);
}
std::string Options::GetToAddress() const
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
axis2_endpoint_ref_t* pEndpointRef = axis2_options_get_to(m_pOptions, m_pEnv);
STAFF_ASSERT(pEndpointRef, "Can't get WSA endpoint");
const axis2_char_t* szAddress = axis2_endpoint_ref_get_address(pEndpointRef, m_pEnv);
STAFF_ASSERT(szAddress, "Can't get WSA to address");
return reinterpret_cast<const char*>(szAddress);
}
void Options::SetToAddress(const std::string& sAddress)
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
axis2_endpoint_ref_t* pEndpointRef = axis2_endpoint_ref_create(m_pEnv, sAddress.c_str());
STAFF_ASSERT(pEndpointRef, "Can't create WSA endpoint");
axis2_options_set_to(m_pOptions, m_pEnv, pEndpointRef);
}
std::string Options::GetReplyToAddress() const
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
axis2_endpoint_ref_t* pEndpointRef = axis2_options_get_reply_to(m_pOptions, m_pEnv);
STAFF_ASSERT(pEndpointRef, "Can't get WSA endpoint");
const axis2_char_t* szAddress = axis2_endpoint_ref_get_address(pEndpointRef, m_pEnv);
STAFF_ASSERT(szAddress, "Can't get WSA reply to address");
return reinterpret_cast<const char*>(szAddress);
}
void Options::SetReplyToAddress(const std::string& sAddress)
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
axis2_endpoint_ref_t* pEndpointRef = axis2_endpoint_ref_create(m_pEnv, sAddress.c_str());
STAFF_ASSERT(pEndpointRef, "Can't create WSA endpoint");
axis2_options_set_reply_to(m_pOptions, m_pEnv, pEndpointRef);
}
std::string Options::GetFaultToAddress() const
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
axis2_endpoint_ref_t* pEndpointRef = axis2_options_get_fault_to(m_pOptions, m_pEnv);
STAFF_ASSERT(pEndpointRef, "Can't get WSA endpoint");
const axis2_char_t* szAddress = axis2_endpoint_ref_get_address(pEndpointRef, m_pEnv);
STAFF_ASSERT(szAddress, "Can't get WSA address");
return reinterpret_cast<const char*>(szAddress);
}
void Options::SetFaultToAddress(const std::string& sAddress)
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
axis2_endpoint_ref_t* pEndpointRef = axis2_endpoint_ref_create(m_pEnv, sAddress.c_str());
STAFF_ASSERT(pEndpointRef, "Can't create WSA endpoint");
axis2_options_set_fault_to(m_pOptions, m_pEnv, pEndpointRef);
}
void Options::UseSeparateListener(bool bUseSeparateListener)
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
axis2_options_set_use_separate_listener(m_pOptions, m_pEnv, bUseSeparateListener ? AXIS2_TRUE : AXIS2_FALSE);
}
bool Options::IsUsingSeparateListener()
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
return axis2_options_get_use_separate_listener(m_pOptions, m_pEnv) == AXIS2_TRUE;
}
void Options::SetHttpAuthInfo(const std::string& sUserName, const std::string& sPassword,
const std::string& sAuthType)
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
axis2_status_t nResult = axis2_options_set_http_auth_info(m_pOptions, m_pEnv,
sUserName.c_str(), sPassword.c_str(), sAuthType.c_str());
STAFF_ASSERT(nResult == AXIS2_SUCCESS, "Failed to setup http auth info");
}
void Options::SetTestHttpAuth(bool bAuth)
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
axis2_options_set_test_http_auth(m_pOptions, m_pEnv, bAuth ? AXIS2_TRUE : AXIS2_FALSE);
}
void Options::SetProxyAuthInfo(const std::string& sUserName, const std::string& sPassword,
const std::string& sAuthType)
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
axis2_status_t nResult = axis2_options_set_proxy_auth_info(m_pOptions, m_pEnv,
sUserName.c_str(), sPassword.c_str(), sAuthType.c_str());
STAFF_ASSERT(nResult == AXIS2_SUCCESS, "Failed to setup proxy auth info");
}
void Options::SetTestProxyAuth(bool bAuth)
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
axis2_options_set_test_proxy_auth(m_pOptions, m_pEnv, bAuth ? AXIS2_TRUE : AXIS2_FALSE);
}
void Options::SetNtlmAuthInfo(const std::string& sUserName, const std::string& sPassword,
const std::string& sDomain, const std::string& sWorkstation,
int nFlags)
{
#ifdef WITH_NTLM
STAFF_ASSERT(m_pOptions, "Options is not initialized");
axis2_options_set_ntlm_http_auth_info(m_pOptions, m_pEnv, sUserName.c_str(),
sPassword.c_str(), nFlags,
sDomain.empty() ? sDomain.c_str() : NULL ,
sWorkstation.empty() ? sWorkstation.c_str() : NULL,
AXIS2_HTTP_AUTH_TYPE_NTLM);
#else
STAFF_PARAM_UNUSED(sUserName);
STAFF_PARAM_UNUSED(sPassword);
STAFF_PARAM_UNUSED(sDomain);
STAFF_PARAM_UNUSED(sWorkstation);
STAFF_PARAM_UNUSED(nFlags);
STAFF_THROW_ASSERT("Staff was built without NTLM support, please recompile with -DWITH_NTLM");
#endif //#ifdef WITH_NTLM
}
void Options::SetTimeout(long lTimeout)
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
axis2_options_set_timeout_in_milli_seconds(m_pOptions, m_pEnv, lTimeout);
}
std::string Options::GetSoapVersionUri() const
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
const axis2_char_t* szUri = axis2_options_get_soap_version_uri(m_pOptions, m_pEnv);
STAFF_ASSERT(szUri, "Can't get SOAP version URI");
return reinterpret_cast<const char*>(szUri);
}
void Options::SetSoapVersionUri(const std::string& sSoapVersionUri)
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
axis2_options_set_soap_version_uri(m_pOptions, m_pEnv, sSoapVersionUri.c_str());
}
Options::SoapVersion Options::GetSoapVersion() const
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
int nVersion = axis2_options_get_soap_version(m_pOptions, m_pEnv);
switch (nVersion)
{
case AXIOM_SOAP11:
return Soap11;
case AXIOM_SOAP12:
return Soap12;
default:
return static_cast<SoapVersion>(nVersion);
}
}
void Options::SetSoapVersion(SoapVersion nSoapVersion)
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
int nAxiomSoapVersion = 0;
switch (nSoapVersion)
{
case Soap11:
nAxiomSoapVersion = AXIOM_SOAP11;
break;
case Soap12:
nAxiomSoapVersion = AXIOM_SOAP12;
break;
default:
nAxiomSoapVersion = static_cast<soap_version>(static_cast<int>(nSoapVersion));
}
axis2_options_set_soap_version(m_pOptions, m_pEnv, nAxiomSoapVersion);
}
std::string Options::GetSoapAction() const
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
const axutil_string_t* psAction = axis2_options_get_soap_action(m_pOptions, m_pEnv);
STAFF_ASSERT(psAction, "Can't get SOAP action");
return reinterpret_cast<const char*>(axutil_string_get_buffer(psAction, m_pEnv));
}
void Options::SetSoapAction(const std::string& sSoapAction)
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
axutil_string_t* psSoapAction = axutil_string_create(m_pEnv, sSoapAction.c_str());
axis2_options_set_soap_action(m_pOptions, m_pEnv, psSoapAction);
axutil_string_free(psSoapAction, m_pEnv);
}
void Options::EnableRest(bool bEnable)
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
axis2_options_set_enable_rest(m_pOptions, m_pEnv, bEnable ? AXIS2_TRUE : AXIS2_FALSE);
}
void Options::SetHttpMethod(const std::string& sHttpMethod)
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
axis2_options_set_http_method(m_pOptions, m_pEnv, sHttpMethod.c_str());
}
void Options::SetHttpHeaders(const StringMap& rmHeaders)
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
axutil_array_list_t* pHeaders = axutil_array_list_create(m_pEnv, rmHeaders.size());
STAFF_ASSERT(pHeaders, "Failed to create http headers");
axis2_http_header_t* pHttpHeader = NULL;
for (StringMap::const_iterator itHeader = rmHeaders.begin();
itHeader != rmHeaders.end(); ++itHeader)
{
pHttpHeader = axis2_http_header_create(m_pEnv, itHeader->first.c_str(),
itHeader->second.c_str());
axutil_array_list_add(pHeaders, m_pEnv, pHttpHeader);
}
axis2_options_set_http_headers(m_pOptions, m_pEnv, pHeaders);
}
bool Options::IsMtomEnabled() const
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
return axis2_options_get_enable_mtom(m_pOptions, m_pEnv) == AXIS2_TRUE;
}
void Options::EnableMtom(bool bEnable)
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
axis2_options_set_enable_mtom(m_pOptions, m_pEnv, bEnable ? AXIS2_TRUE : AXIS2_FALSE);
}
void Options::SetProperty(const std::string& sName, const std::string& sValue)
{
STAFF_ASSERT(m_pOptions, "Options is not initialized");
axutil_property_t* pProp = axutil_property_create(m_pEnv);
axutil_property_set_value(pProp, m_pEnv, axutil_strdup(m_pEnv, sValue.c_str()));
axis2_options_set_property(m_pOptions, m_pEnv, sName.c_str(), pProp);
}
Options& Options::operator=(axis2_options_t* pOptions)
{
if (m_bOwner && m_pOptions)
{
axis2_options_free(m_pOptions, m_pEnv);
}
m_pOptions = pOptions;
m_bOwner = false;
return *this;
}
Options::operator axis2_options_t*()
{
return m_pOptions;
}
const std::string& Options::GetSessionId() const
{
return m_sSessionId;
}
void Options::SetSessionId(const std::string& sSessionId)
{
m_sSessionId = sSessionId;
}
const std::string& Options::GetInstanceId() const
{
return m_sInstanceId;
}
void Options::SetInstanceId(const std::string& sInstanceId)
{
m_sInstanceId = sInstanceId;
}
void Options::SetDefaultNamespace(const std::string& sUri, const std::string& sPrefix /*= ""*/)
{
m_sDefaultNsUri = sUri;
m_sDefaultNsPrefix = sPrefix;
}
const std::string& Options::GetDefaultNamespaceUri() const
{
return m_sDefaultNsUri;
}
const std::string& Options::GetDefaultNamespacePrefix() const
{
return m_sDefaultNsPrefix;
}
}
|
// Copyright Daniel Wallin & Arvid Norberg 2009. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include "boost_python.hpp"
#include <libtorrent/create_torrent.hpp>
#include <libtorrent/file_storage.hpp>
#include "libtorrent/torrent_info.hpp"
#include <libtorrent/version.hpp>
#include "bytes.hpp"
#include "gil.hpp"
using namespace boost::python;
using namespace lt;
#ifdef _MSC_VER
#pragma warning(push)
// warning c4996: x: was declared deprecated
#pragma warning( disable : 4996 )
#endif
namespace
{
void set_hash(create_torrent& c, piece_index_t p, bytes const& b)
{
c.set_hash(p, sha1_hash(b.arr));
}
#if TORRENT_ABI_VERSION < 3
void set_file_hash(create_torrent& c, file_index_t f, bytes const& b)
{
c.set_file_hash(f, sha1_hash(b.arr));
}
#endif
#ifndef BOOST_NO_EXCEPTIONS
void set_piece_hashes_callback(create_torrent& c, std::string const& p
, boost::python::object cb)
{
set_piece_hashes(c, p, std::function<void(piece_index_t)>(
[&](piece_index_t const i) { cb(i); }));
}
#else
void set_piece_hashes_callback(create_torrent& c, std::string const& p
, boost::python::object cb)
{
error_code ec;
set_piece_hashes(c, p, [&](piece_index_t const i) { cb(i); }, ec);
}
void set_piece_hashes0(create_torrent& c, std::string const & s)
{
error_code ec;
set_piece_hashes(c, s, ec);
}
#endif
void add_node(create_torrent& ct, std::string const& addr, int port)
{
ct.add_node(std::make_pair(addr, port));
}
#if TORRENT_ABI_VERSION == 1
void add_file_deprecated(file_storage& ct, file_entry const& fe)
{
python_deprecated("this overload of add_file() is deprecated");
ct.add_file(fe);
}
struct FileIter
{
using value_type = lt::file_entry;
using reference = lt::file_entry;
using pointer = lt::file_entry*;
using difference_type = int;
using iterator_category = std::forward_iterator_tag;
FileIter(file_storage const& fs, file_index_t i) : m_fs(&fs), m_i(i) {}
FileIter(FileIter const&) = default;
FileIter() : m_fs(nullptr), m_i(0) {}
lt::file_entry operator*() const
{ return m_fs->at(m_i); }
FileIter operator++() { m_i++; return *this; }
FileIter operator++(int) { return FileIter(*m_fs, m_i++); }
bool operator==(FileIter const& rhs) const
{ return m_fs == rhs.m_fs && m_i == rhs.m_i; }
int operator-(FileIter const& rhs) const
{
assert(rhs.m_fs == m_fs);
return m_i - rhs.m_i;
}
FileIter& operator=(FileIter const&) = default;
file_storage const* m_fs;
file_index_t m_i;
};
FileIter begin_files(file_storage const& self)
{
python_deprecated("__iter__ is deprecated");
return FileIter(self, file_index_t(0));
}
FileIter end_files(file_storage const& self)
{ return FileIter(self, self.end_file()); }
#endif // TORRENT_ABI_VERSION
void add_files_callback(file_storage& fs, std::string const& file
, boost::python::object cb, create_flags_t const flags)
{
add_files(fs, file, [&](std::string const& i) { return cb(i); }, flags);
}
void add_file(file_storage& fs, std::string const& file, std::int64_t size
, file_flags_t const flags, std::time_t md, std::string link)
{
fs.add_file(file, size, flags, md, link);
}
void add_tracker(create_torrent& ct, std::string url, int tier)
{
ct.add_tracker(url, tier);
}
struct dummy13 {};
struct dummy14 {};
}
void bind_create_torrent()
{
void (file_storage::*set_name0)(std::string const&) = &file_storage::set_name;
void (file_storage::*rename_file0)(file_index_t, std::string const&) = &file_storage::rename_file;
#ifndef BOOST_NO_EXCEPTIONS
void (*set_piece_hashes0)(create_torrent&, std::string const&) = &set_piece_hashes;
#endif
void (*add_files0)(file_storage&, std::string const&, create_flags_t) = add_files;
std::string (file_storage::*file_storage_symlink)(file_index_t) const = &file_storage::symlink;
sha1_hash (file_storage::*file_storage_hash)(file_index_t) const = &file_storage::hash;
std::string (file_storage::*file_storage_file_path)(file_index_t, std::string const&) const = &file_storage::file_path;
string_view (file_storage::*file_storage_file_name)(file_index_t) const = &file_storage::file_name;
std::int64_t (file_storage::*file_storage_file_size)(file_index_t) const = &file_storage::file_size;
std::int64_t (file_storage::*file_storage_file_offset)(file_index_t) const = &file_storage::file_offset;
file_flags_t (file_storage::*file_storage_file_flags)(file_index_t) const = &file_storage::file_flags;
#if TORRENT_ABI_VERSION == 1
file_entry (file_storage::*at)(int) const = &file_storage::at;
#endif
// TODO: 3 move this to its own file
{
scope s = class_<file_storage>("file_storage")
.def("is_valid", &file_storage::is_valid)
.def("add_file", add_file, (arg("path"), arg("size"), arg("flags") = 0, arg("mtime") = 0, arg("linkpath") = ""))
.def("num_files", &file_storage::num_files)
#if TORRENT_ABI_VERSION == 1
.def("at", depr(at))
.def("add_file", add_file_deprecated, arg("entry"))
.def("__iter__", boost::python::range(&begin_files, &end_files))
.def("__len__", depr(&file_storage::num_files))
#endif // TORRENT_ABI_VERSION
.def("hash", file_storage_hash)
.def("symlink", file_storage_symlink)
.def("file_path", file_storage_file_path, (arg("idx"), arg("save_path") = ""))
.def("file_name", file_storage_file_name)
.def("file_size", file_storage_file_size)
.def("root", &file_storage::root)
.def("file_offset", file_storage_file_offset)
.def("file_flags", file_storage_file_flags)
.def("file_index_for_root", &file_storage::file_index_for_root)
.def("piece_index_at_file", &file_storage::piece_index_at_file)
.def("file_index_at_piece", &file_storage::file_index_at_piece)
.def("file_index_at_offset", &file_storage::file_index_at_offset)
.def("file_absolute_path", &file_storage::file_absolute_path)
.def("v2", &file_storage::v2)
.def("total_size", &file_storage::total_size)
.def("set_num_pieces", &file_storage::set_num_pieces)
.def("num_pieces", &file_storage::num_pieces)
.def("set_piece_length", &file_storage::set_piece_length)
.def("piece_length", &file_storage::piece_length)
.def("piece_size", &file_storage::piece_size)
.def("set_name", set_name0)
.def("rename_file", rename_file0)
.def("name", &file_storage::name, return_value_policy<copy_const_reference>())
;
s.attr("flag_pad_file") = file_storage::flag_pad_file;
s.attr("flag_hidden") = file_storage::flag_hidden;
s.attr("flag_executable") = file_storage::flag_executable;
s.attr("flag_symlink") = file_storage::flag_symlink;
}
{
scope s = class_<dummy13>("file_flags_t");
s.attr("flag_pad_file") = file_storage::flag_pad_file;
s.attr("flag_hidden") = file_storage::flag_hidden;
s.attr("flag_executable") = file_storage::flag_executable;
s.attr("flag_symlink") = file_storage::flag_symlink;
}
{
scope s = class_<create_torrent>("create_torrent", no_init)
.def(init<file_storage&>())
.def(init<torrent_info const&>(arg("ti")))
.def(init<file_storage&, int, create_flags_t>((arg("storage"), arg("piece_size") = 0
, arg("flags") = create_flags_t{})))
.def("generate", &create_torrent::generate)
.def("files", &create_torrent::files, return_internal_reference<>())
.def("set_comment", &create_torrent::set_comment)
.def("set_creator", &create_torrent::set_creator)
.def("set_hash", &set_hash)
#if TORRENT_ABI_VERSION < 3
.def("set_file_hash", &set_file_hash)
#endif
.def("add_url_seed", &create_torrent::add_url_seed)
.def("add_http_seed", &create_torrent::add_http_seed)
.def("add_node", &add_node)
.def("add_tracker", add_tracker, (arg("announce_url"), arg("tier") = 0))
.def("set_priv", &create_torrent::set_priv)
.def("num_pieces", &create_torrent::num_pieces)
.def("piece_length", &create_torrent::piece_length)
.def("piece_size", &create_torrent::piece_size)
.def("priv", &create_torrent::priv)
.def("set_root_cert", &create_torrent::set_root_cert, (arg("pem")))
.def("add_collection", &create_torrent::add_collection)
.def("add_similar_torrent", &create_torrent::add_similar_torrent)
;
#if TORRENT_ABI_VERSION <= 2
s.attr("optimize_alignment") = create_torrent::optimize_alignment;
s.attr("merkle") = create_torrent::merkle;
#endif
s.attr("v2_only") = create_torrent::v2_only;
s.attr("v1_only") = create_torrent::v1_only;
s.attr("canonical_files") = create_torrent::canonical_files;
s.attr("modification_time") = create_torrent::modification_time;
s.attr("symlinks") = create_torrent::symlinks;
}
{
scope s = class_<dummy14>("create_torrent_flags_t");
#if TORRENT_ABI_VERSION == 1
s.attr("optimize") = create_torrent::optimize;
#endif
#if TORRENT_ABI_VERSION <= 2
s.attr("optimize_alignment") = create_torrent::optimize_alignment;
s.attr("merkle") = create_torrent::merkle;
#endif
s.attr("v2_only") = create_torrent::v2_only;
s.attr("modification_time") = create_torrent::modification_time;
s.attr("symlinks") = create_torrent::symlinks;
}
def("add_files", add_files0, (arg("fs"), arg("path"), arg("flags") = 0));
def("add_files", add_files_callback, (arg("fs"), arg("path")
, arg("predicate"), arg("flags") = 0));
def("set_piece_hashes", set_piece_hashes0);
def("set_piece_hashes", set_piece_hashes_callback);
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkShadowMapPass.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkShadowMapPass.h"
#include "vtkObjectFactory.h"
#include <cassert>
#include "vtkRenderState.h"
#include "vtkOpenGLRenderer.h"
#include "vtkgl.h"
#include "vtkFrameBufferObject.h"
#include "vtkTextureObject.h"
#include "vtkShaderProgram2.h"
#include "vtkShader2.h"
#include "vtkShader2Collection.h"
#include "vtkUniformVariables.h"
#include "vtkOpenGLRenderWindow.h"
#include "vtkOpenGLError.h"
#include "vtkTextureUnitManager.h"
#include "vtkInformationIntegerKey.h"
#include "vtkMath.h"
// to be able to dump intermediate passes into png files for debugging.
// only for vtkShadowMapPass developers.
//#define VTK_SHADOW_MAP_PASS_DEBUG
//#define DONT_DUPLICATE_LIGHTS
#include "vtkPNGWriter.h"
#include "vtkImageImport.h"
#include "vtkPixelBufferObject.h"
#include "vtkImageExtractComponents.h"
#include "vtkLightCollection.h"
#include "vtkLight.h"
#include "vtkInformation.h"
#include "vtkCamera.h"
#include "vtkAbstractTransform.h" // for helper classes stack and concatenation
#include "vtkPerspectiveTransform.h"
#include "vtkTransform.h"
#include <vtksys/ios/sstream>
#include "vtkStdString.h"
#include "vtkImageShiftScale.h"
#include "vtkImageExport.h"
#include "vtkImageData.h"
#include "vtkImplicitHalo.h"
#include "vtkSampleFunction.h"
#include "vtkImplicitWindowFunction.h"
#include "vtkImplicitSum.h"
// For vtkShadowMapBakerPassTextures, vtkShadowMapBakerPassLightCameras
#include "vtkShadowMapPassInternal.h"
#include "vtkShadowMapBakerPass.h"
#include "vtkMatrixToLinearTransform.h"
// debugging
#include "vtkOpenGLState.h"
#include "vtkTimerLog.h"
//#include "vtkBreakPoint.h"
vtkStandardNewMacro(vtkShadowMapPass);
vtkCxxSetObjectMacro(vtkShadowMapPass,ShadowMapBakerPass,
vtkShadowMapBakerPass);
vtkCxxSetObjectMacro(vtkShadowMapPass,OpaquePass,
vtkRenderPass);
extern const char *vtkShadowMapPassShader_fs;
extern const char *vtkShadowMapPassShader_vs;
extern const char *vtkLighting_s;
// ----------------------------------------------------------------------------
vtkShadowMapPass::vtkShadowMapPass()
{
this->ShadowMapBakerPass=0;
this->OpaquePass=0;
this->Program=0;
this->IntensityMap=0;
this->IntensitySource=0;
this->IntensityExporter=0;
this->Halo=0;
}
// ----------------------------------------------------------------------------
vtkShadowMapPass::~vtkShadowMapPass()
{
if(this->ShadowMapBakerPass!=0)
{
this->ShadowMapBakerPass->Delete();
}
if(this->OpaquePass!=0)
{
this->OpaquePass->Delete();
}
if(this->Program!=0)
{
this->Program->Delete();
}
if(this->IntensityMap!=0)
{
vtkErrorMacro(<<"IntensityMap should have been deleted in ReleaseGraphicsResources().");
}
if(this->IntensitySource!=0)
{
this->IntensitySource->Delete();
}
if(this->IntensityExporter!=0)
{
this->IntensityExporter->Delete();
}
if(this->Halo!=0)
{
this->Halo->Delete();
}
}
// ----------------------------------------------------------------------------
void vtkShadowMapPass::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "ShadowMapBackerPass: ";
if(this->ShadowMapBakerPass!=0)
{
this->ShadowMapBakerPass->PrintSelf(os,indent);
}
else
{
os << "(none)" <<endl;
}
os << indent << "OpaquePass: ";
if(this->OpaquePass!=0)
{
this->OpaquePass->PrintSelf(os,indent);
}
else
{
os << "(none)" <<endl;
}
}
// ----------------------------------------------------------------------------
// Description:
// Perform rendering according to a render state \p s.
// \pre s_exists: s!=0
void vtkShadowMapPass::Render(const vtkRenderState *s)
{
assert("pre: s_exists" && s!=0);
vtkOpenGLClearErrorMacro();
this->NumberOfRenderedProps=0;
vtkOpenGLRenderer *r=static_cast<vtkOpenGLRenderer *>(s->GetRenderer());
vtkOpenGLRenderWindow *context=static_cast<vtkOpenGLRenderWindow *>(
r->GetRenderWindow());
#ifdef VTK_SHADOW_MAP_PASS_DEBUG
vtkOpenGLState *state=new vtkOpenGLState(context);
#endif
if(this->ShadowMapBakerPass!=0 &&
// this->ShadowMapBakerPass->GetOpaquePass()!=0
this->OpaquePass!=0)
{
// Test for Hardware support. If not supported, just render the delegate.
bool supported=vtkFrameBufferObject::IsSupported(r->GetRenderWindow());
if(!supported)
{
vtkErrorMacro("FBOs are not supported by the context. Cannot use shadow mapping.");
}
if(supported)
{
supported=vtkTextureObject::IsSupported(r->GetRenderWindow());
if(!supported)
{
vtkErrorMacro("Texture Objects are not supported by the context. Cannot use shadow mapping.");
}
}
if(supported)
{
supported=
vtkShaderProgram2::IsSupported(static_cast<vtkOpenGLRenderWindow *>(
r->GetRenderWindow()));
if(!supported)
{
vtkErrorMacro("GLSL is not supported by the context. Cannot use shadow mapping.");
}
}
if(!supported)
{
this->OpaquePass->Render(s);
this->NumberOfRenderedProps+=
this->OpaquePass->GetNumberOfRenderedProps();
return;
}
if(!this->ShadowMapBakerPass->GetHasShadows())
{
this->OpaquePass->Render(s);
this->NumberOfRenderedProps+=
this->OpaquePass->GetNumberOfRenderedProps();
return;
}
// Copy the list of lights and the lights. We cannot just modify them in
// place because it will change their modification time.
// Modification time is used directly (or indirectly if there is some
// light actors) to avoid rebuilding the shadow maps.
vtkLightCollection *lights=r->GetLights();
vtkLightCollection *lights2;
#ifdef DONT_DUPLICATE_LIGHTS
if(this->CompositeZPass==0)
{
#endif
// parallel rendering hangs with this technique
lights2=vtkLightCollection::New();
lights->InitTraversal();
vtkLight *l=lights->GetNextItem();
size_t lightIndex=0;
while(l!=0)
{
vtkLight *l2=l->ShallowClone();
lights2->AddItem(l2);
l2->Delete();
l=lights->GetNextItem();
++lightIndex;
}
// save the original light collection.
lights->Register(this);
// make the copy the current light collection on the renderer
r->SetLightCollection(lights2);
#ifdef DONT_DUPLICATE_LIGHTS
}
else
{
// safe and slow for parallel rendering
lights2=lights;
}
#endif
// Render scene with shadowing lights off.
// depth writing and testing on.
// save the lights switches.
bool *lightSwitches=new bool[lights2->GetNumberOfItems()];
lights2->InitTraversal();
l=lights2->GetNextItem();
lightIndex=0;
while(l!=0)
{
lightSwitches[lightIndex]=l->GetSwitch()==1;
l=lights2->GetNextItem();
++lightIndex;
}
bool autoLight=r->GetAutomaticLightCreation()==1;
r->SetAutomaticLightCreation(false);
// switch the shadowing lights off.
lights2->InitTraversal();
l=lights2->GetNextItem();
lightIndex=0;
while(l!=0)
{
if(lightSwitches[lightIndex] &&
this->ShadowMapBakerPass->LightCreatesShadow(l))
{
l->SetSwitch(false);
}
l=lights2->GetNextItem();
++lightIndex;
}
#ifdef VTK_SHADOW_MAP_PASS_DEBUG
cout << "finish before rendering geometry without shadowing lights" << endl;
glFinish();
#endif
// render for real for non shadowing lights.
// note this time we use the list of props after culling.
this->OpaquePass->Render(s);
this->NumberOfRenderedProps+=
this->OpaquePass->GetNumberOfRenderedProps();
#ifdef VTK_SHADOW_MAP_PASS_DEBUG
cout << "finish after rendering geometry without shadowing lights" << endl;
glFinish();
#endif
// now disable depth writing,
// For each shadowing light,
//
glDepthMask(GL_FALSE);
// maybe ivar:
if(this->Program==0)
{
this->Program=vtkShaderProgram2::New();
}
this->Program->SetContext(context);
vtkShader2Collection *shaders=this->Program->GetShaders();
if(this->ShadowMapBakerPass->GetNeedUpdate())
{
this->ShadowMapBakerPass->SetUpToDate();
// we have to perform a concatenation. remove all the shaders first.
this->Program->ReleaseGraphicsResources();
shaders->RemoveAllItems();
size_t nbLights=
this->ShadowMapBakerPass->GetShadowMaps()->Vector.size();
vtksys_ios::ostringstream ostVS;
vtksys_ios::ostringstream numLights;
numLights << endl << "#define VTK_LIGHTING_NUMBER_OF_LIGHTS " << nbLights << endl;
vtkStdString vertShader(vtkShadowMapPassShader_vs);
size_t version_loc = vertShader.find("#version 110");
vertShader.insert(version_loc + 13, numLights.str());
ostVS << vertShader;
vtkStdString *vsCode=new vtkStdString;
(*vsCode)=ostVS.str();
vtksys_ios::ostringstream ostLightingVS;
vtkStdString lightShader(vtkLighting_s);
version_loc = lightShader.find("#version 110");
lightShader.insert(version_loc + 13, numLights.str());
ostLightingVS << lightShader;
vtkStdString *lightingVsCode=new vtkStdString;
(*lightingVsCode)=ostLightingVS.str();
vtksys_ios::ostringstream ostFS;
vtkStdString fragShader(vtkShadowMapPassShader_fs);
version_loc = fragShader.find("#version 110");
fragShader.insert(version_loc + 13, numLights.str());
ostFS << fragShader;
vtkStdString *fsCode=new vtkStdString;
(*fsCode)=ostFS.str();
vtkShader2 *vs=vtkShader2::New();
vs->SetContext(context);
vs->SetType(VTK_SHADER_TYPE_VERTEX);
vs->SetSourceCode(vsCode->c_str());
delete vsCode;
shaders->AddItem(vs);
vs->Delete();
vtkShader2 *lightingVS=vtkShader2::New();
lightingVS->SetContext(context);
lightingVS->SetType(VTK_SHADER_TYPE_VERTEX);
lightingVS->SetSourceCode(lightingVsCode->c_str());
delete lightingVsCode;
shaders->AddItem(lightingVS);
lightingVS->Delete();
vtkShader2 *fs=vtkShader2::New();
fs->SetContext(context);
fs->SetType(VTK_SHADER_TYPE_FRAGMENT);
fs->SetSourceCode(fsCode->c_str());
delete fsCode;
shaders->AddItem(fs);
fs->Delete();
}
#ifdef VTK_SHADOW_MAP_PASS_DEBUG
this->Program->Build();
if(this->Program->GetLastBuildStatus()!=VTK_SHADER_PROGRAM2_LINK_SUCCEEDED)
{
vtkErrorMacro("Couldn't build the shader program. At this point , it can be an error in a shader or a driver bug.");
delete[] lightSwitches;
return;
}
this->Program->PrintActiveUniformVariablesOnCout();
#endif
r->SetShaderProgram(this->Program);
if(this->IntensityMap==0)
{
this->IntensityMap=vtkTextureObject::New();
this->IntensityMap->SetContext(context);
this->IntensityMap->SetWrapS(vtkTextureObject::Clamp);
this->IntensityMap->SetWrapT(vtkTextureObject::Clamp);
this->IntensityMap->SetMinificationFilter(vtkTextureObject::Linear);
this->IntensityMap->SetLinearMagnification(true);
}
if(this->IntensityMap->GetWidth()!=
this->ShadowMapBakerPass->GetResolution())
{
// Load the spotlight intensity map.
vtkPixelBufferObject *pbo=vtkPixelBufferObject::New();
pbo->SetContext(context);
this->BuildSpotLightIntensityMap();
this->IntensityExporter->Update();
#ifdef VTK_SHADOW_MAP_PASS_DEBUG
vtkPNGWriter *writer=vtkPNGWriter::New();
writer->SetFileName("IntensityMap.png");
writer->SetInput(this->IntensityExporter->GetInput());
writer->Write();
writer->Delete();
#endif
unsigned char *rawPointer=
static_cast<unsigned char*>(
this->IntensityExporter->GetPointerToData());
vtkIdType continuousInc[3];
vtkImageData *im=this->IntensityExporter->GetInput();
im->GetContinuousIncrements(im->GetExtent(),continuousInc[0],
continuousInc[1],continuousInc[2]);
unsigned int dims[2];
dims[0]=this->ShadowMapBakerPass->GetResolution();
dims[1]=dims[0];
pbo->Upload2D(VTK_UNSIGNED_CHAR,rawPointer,dims,1,continuousInc);
this->IntensityMap->Create2D(this->ShadowMapBakerPass->GetResolution(),
this->ShadowMapBakerPass->GetResolution(),
1,pbo,false);
pbo->Delete();
}
// set uniforms
// set TO,TU
vtkUniformVariables *u=this->Program->GetUniformVariables();
vtkMatrix4x4 *tmp=vtkMatrix4x4::New();
// WE CANNOT USE THIS WITH Ice-T
// vtkLinearTransform *viewCamera_Inv=r->GetActiveCamera()
// ->GetViewTransformObject()->GetLinearInverse();
// vtkBreakPoint::Break();
// REQUIRED with Ice-T
// We assume that at this point of the execution
// modelview matrix is actually on the view matrix, that is
// model matrix is identity.
GLfloat m[16];
glGetFloatv(GL_MODELVIEW_MATRIX,m);
vtkMatrix4x4 *mat=vtkMatrix4x4::New();
int row=0;
while(row<4)
{
int column=0;
while(column<4)
{
mat->SetElement(row,column,static_cast<double>(m[column*4+row]));
++column;
}
++row;
}
mat->Invert();
vtkMatrixToLinearTransform *viewCamera_Inv
=vtkMatrixToLinearTransform::New();
viewCamera_Inv->SetInput(mat);
mat->Delete();
vtkPerspectiveTransform *transform=vtkPerspectiveTransform::New();
// identity. pre-multiply mode
transform->Translate(0.5,0.5,0.5); // bias
transform->Scale(0.5,0.5,0.5); // scale
// switch the shadowing lights on.
lights2->InitTraversal();
l=lights2->GetNextItem();
lightIndex=0;
int shadowingLightIndex=0;
GLint savedMatrixMode;
glGetIntegerv(GL_MATRIX_MODE,&savedMatrixMode);
while(l!=0)
{
if(lightSwitches[lightIndex] &&
this->ShadowMapBakerPass->LightCreatesShadow(l) )
{
l->SetSwitch(true);
// setup texture matrix.
glMatrixMode(GL_TEXTURE);
vtkgl::ActiveTexture(vtkgl::TEXTURE0+
static_cast<GLenum>(shadowingLightIndex));
glPushMatrix();
// scale_bias*projection_light[i]*view_light[i]*view_camera_inv
vtkCamera *lightCamera=
this->ShadowMapBakerPass->GetLightCameras()->Vector[
static_cast<size_t>(shadowingLightIndex)];
transform->Push();
transform->Concatenate(
lightCamera->GetProjectionTransformObject(1,-1,1));
transform->Concatenate(lightCamera->GetViewTransformObject());
transform->Concatenate(viewCamera_Inv);
transform->GetMatrix(tmp);
transform->Pop();
tmp->Transpose();
glLoadMatrixd(tmp->Element[0]);
// setup shadowMap texture object and texture unit
vtkTextureObject *map=
this->ShadowMapBakerPass->GetShadowMaps()->Vector[
static_cast<size_t>(shadowingLightIndex)];
map->SetDepthTextureCompare(true);
map->SetLinearMagnification(true);
map->SetMinificationFilter(vtkTextureObject::Linear);
map->Bind();
vtksys_ios::ostringstream ostShadowMapTextureUnit;
ostShadowMapTextureUnit << "shadowMaps[" << shadowingLightIndex << "]";
vtkStdString *shadowMapTextureUnitString=new vtkStdString;
(*shadowMapTextureUnitString)=ostShadowMapTextureUnit.str();
u->SetUniformi(shadowMapTextureUnitString->c_str(),1,
&shadowingLightIndex);
delete shadowMapTextureUnitString;
++shadowingLightIndex;
}
else
{
l->SetSwitch(false); // any other light
}
l=lights2->GetNextItem();
++lightIndex;
}
// Ice-T
viewCamera_Inv->Delete();
vtkgl::ActiveTexture(vtkgl::TEXTURE0+
static_cast<GLenum>(shadowingLightIndex));
this->IntensityMap->Bind();
u->SetUniformi("spotLightShape",1,&shadowingLightIndex);
// DO not delete iewCamera_Inv, this is an internal ivar of vtkTransform.
transform->Delete();
tmp->Delete();
#ifdef VTK_SHADOW_MAP_PASS_DEBUG
cout << "finish before rendering geometry with shadowing lights" << endl;
glFinish();
#endif
vtkRenderState s2(r);
s2.SetFrameBuffer(s->GetFrameBuffer());
vtkInformation *requiredKeys=vtkInformation::New();
requiredKeys->Set(vtkShadowMapBakerPass::RECEIVER(),0);
s2.SetRequiredKeys(requiredKeys);
s2.SetPropArrayAndCount(s->GetPropArray(),s->GetPropArrayCount());
// Blend the result with the exising scene
glAlphaFunc(GL_GREATER,0.9f);
glEnable(GL_ALPHA_TEST);
// render scene
bool rendererEraseFlag=r->GetErase()==1;
r->SetErase(0);
glMatrixMode(savedMatrixMode);
this->OpaquePass->Render(&s2);
this->NumberOfRenderedProps+=
this->OpaquePass->GetNumberOfRenderedProps();
requiredKeys->Delete();
r->SetErase(rendererEraseFlag);
glDisable(GL_ALPHA_TEST);
#ifdef VTK_SHADOW_MAP_PASS_DEBUG
cout << "finish after rendering geometry with shadowing lights" << endl;
glFinish();
#endif
// restore texture matrices
int i=0;
glMatrixMode(GL_TEXTURE);
while(i<shadowingLightIndex)
{
vtkgl::ActiveTexture(vtkgl::TEXTURE0+
static_cast<GLenum>(i));
glPopMatrix();
++i;
}
vtkgl::ActiveTexture(vtkgl::TEXTURE0);
r->SetShaderProgram(0);
glMatrixMode(savedMatrixMode);
#ifdef DONT_DUPLICATE_LIGHTS
if(this->CompositeZPass==0)
{
#endif
// restore original light collection
r->SetLightCollection(lights);
lights->Delete();
lights2->Delete();
#ifdef DONT_DUPLICATE_LIGHTS
}
else
{
// restore original light switchs.
lights->InitTraversal();
l=lights->GetNextItem();
lightIndex=0;
while(l!=0)
{
l->SetSwitch(lightSwitches[lightIndex]);
l=lights->GetNextItem();
++lightIndex;
}
}
#endif
delete[] lightSwitches;
r->SetAutomaticLightCreation(autoLight);
glDepthMask(GL_TRUE);
}
else
{
vtkWarningMacro(<<" no ShadowMapBakerPass or no OpaquePass on the ShadowMapBakerPass.");
}
vtkOpenGLCheckErrorMacro("failed after Render");
}
// ----------------------------------------------------------------------------
void vtkShadowMapPass::BuildSpotLightIntensityMap()
{
if(this->IntensitySource==0)
{
this->IntensitySource=vtkSampleFunction::New();
this->IntensityExporter=vtkImageExport::New();
this->Halo=vtkImplicitHalo::New();
vtkImplicitSum *scale=vtkImplicitSum::New();
scale->AddFunction(this->Halo,255.0);
scale->SetNormalizeByWeight(false);
this->IntensitySource->SetImplicitFunction(scale);
scale->Delete();
}
unsigned int resolution=this->ShadowMapBakerPass->GetResolution();
this->Halo->SetRadius(resolution/2.0);
this->Halo->SetCenter(resolution/2.0,
resolution/2.0,0.0);
this->Halo->SetFadeOut(0.1);
this->IntensitySource->SetOutputScalarType(VTK_UNSIGNED_CHAR);
this->IntensitySource->SetSampleDimensions(
static_cast<int>(resolution),
static_cast<int>(resolution),1);
this->IntensitySource->SetModelBounds(0.0,resolution-1.0,
0.0,resolution-1.0,
0.0,0.0);
this->IntensitySource->SetComputeNormals(false);
this->IntensityExporter->SetInputConnection(
this->IntensitySource->GetOutputPort());
}
// ----------------------------------------------------------------------------
// Description:
// Release graphics resources and ask components to release their own
// resources.
// \pre w_exists: w!=0
void vtkShadowMapPass::ReleaseGraphicsResources(vtkWindow *w)
{
assert("pre: w_exists" && w!=0);
if(this->ShadowMapBakerPass!=0)
{
this->ShadowMapBakerPass->ReleaseGraphicsResources(w);
}
if(this->Program!=0)
{
this->Program->ReleaseGraphicsResources();
}
if(this->IntensityMap!=0)
{
this->IntensityMap->Delete();
this->IntensityMap=0;
}
}
|
#include "menu.h"
#include "ui_menu.h"
#include "StartPage.h"
#include "musicmemo.h"
#include <QDialog>
menu::menu(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::menu)
{
ui->setupUi(this);
ui->label->setPixmap(QPixmap(":/picture/menu.jpg"));
ui->label_2->setPixmap(QPixmap(":/picture/red.jpeg"));
ui->label_3->setPixmap(QPixmap(":/picture/blue.jpeg"));
}
menu::~menu()
{
delete ui;
}
void menu::on_pushButton_2_clicked()
{
close();
}
void menu::on_pushButton_clicked()
{
this->hide();
musicmemo music;
music.exec();
}
|
/** \copyright
* Copyright (c) 2021, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file LogonModule.hxx
* Default implementation of a storage and policy module for automatic logon.
*
* @author Balazs Racz
* @date 14 Aug 2021
*/
#ifndef _DCC_LOGONMODULE_HXX_
#define _DCC_LOGONMODULE_HXX_
#include <map>
#include <vector>
#include "dcc/Defs.hxx"
#include "dcc/Logon.hxx"
namespace dcc
{
/// Default implementation of the storage and policy module for trains.
template<class Base>
class ParameterizedLogonModule : public LogonHandlerModule
{
public:
/// We store this structure about each locomotive.
struct LocoInfo : public Base::Storage
{
/// State machine flags about this loco.
uint8_t flags_ {0};
/// The assigned DCC address. The encoding is in the S-9.2.1.1 format.
/// The default value is an invalid address causing an error on the
/// locomotive.
uint16_t assignedAddress_ {Defs::ADR_INVALID};
/// 44-bit decoder unique ID.
uint64_t decoderId_;
};
std::vector<LocoInfo> locos_;
std::map<uint64_t, uint16_t> ids_;
/// @return the number of locomotives known. The locomotive IDs are
/// 0..num_locos() - 1.
unsigned num_locos()
{
return locos_.size();
}
/// @param loco_id a locomotive identifier
/// @return true if this is valid and belongs to a loco we know about.
bool is_valid_loco_id(unsigned loco_id)
{
return loco_id < num_locos();
}
/// Finds the storage cell for a locomotive and returns the flag byte for
/// it.
/// @param loco_id a valid locomotive ID.
/// @return the flag byte for this loco.
uint8_t &loco_flags(unsigned loco_id)
{
return locos_[loco_id].flags_;
}
/// Retrieves the decoder unique ID.
/// @param loco_id the dense locomotive identifier.
/// @return the decoder unique ID (44 bit, LSb-aligned).
uint64_t loco_did(unsigned loco_id)
{
return locos_[loco_id].decoderId_;
}
/// Creates a new locomotive by decoder ID, or looks up an existing
/// locomotive by decoder ID.
/// @param decoder_id 44-bit decoder ID (aligned to LSb).
/// @return locomotive ID for this cell.
unsigned create_or_lookup_loco(uint64_t decoder_id)
{
auto it = ids_.find(decoder_id);
if (it == ids_.end())
{
// create new.
uint16_t lid = locos_.size();
locos_.emplace_back();
locos_[lid].decoderId_ = decoder_id;
ids_[decoder_id] = lid;
return lid;
}
else
{
return it->second;
}
}
/// Runs the locomotive address policy. After the address policy is run,
/// the loco should have the ability to answer the assigned_address
/// question.
/// @param loco_id which locomotive this is
/// @param desired_address the S-9.2.1.1 encoded desired address for this
/// decoder.
void run_address_policy(unsigned loco_id, uint16_t desired_address)
{
/// @todo support accessory decoders.
// Note: we ignore the desired address and start assigning addresses
// from 10000 and up.
locos_[loco_id].assignedAddress_ = nextAddress_++;
}
/// @param loco_id
/// @return the address to be assigned to this locomotive. 14-bit.
uint16_t assigned_address(unsigned loco_id)
{
return locos_[loco_id].assignedAddress_;
}
/// Invoked when the address assignment completes for a decoder.
/// @param loco_id which decoder.
void assign_complete(unsigned loco_id)
{
loco_flags(loco_id) |= LogonHandlerModule::FLAG_COMPLETE;
}
uint16_t nextAddress_ {(Defs::ADR_MOBILE_LONG << 8) + 10000};
}; // class ParameterizedLogonModule
class DefaultBase {
public:
struct Storage {};
};
using DefaultLogonModule = ParameterizedLogonModule<DefaultBase>;
} // namespace dcc
#endif // _DCC_LOGONMODULE_HXX_
|
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxr/usd/usdGeom/motionAPI.h"
#include "pxr/usd/usd/schemaRegistry.h"
#include "pxr/usd/usd/typed.h"
#include "pxr/usd/usd/tokens.h"
#include "pxr/usd/sdf/types.h"
#include "pxr/usd/sdf/assetPath.h"
PXR_NAMESPACE_OPEN_SCOPE
// Register the schema with the TfType system.
TF_REGISTRY_FUNCTION(TfType)
{
TfType::Define<UsdGeomMotionAPI,
TfType::Bases< UsdAPISchemaBase > >();
}
TF_DEFINE_PRIVATE_TOKENS(
_schemaTokens,
(MotionAPI)
);
/* virtual */
UsdGeomMotionAPI::~UsdGeomMotionAPI()
{
}
/* static */
UsdGeomMotionAPI
UsdGeomMotionAPI::Get(const UsdStagePtr &stage, const SdfPath &path)
{
if (!stage) {
TF_CODING_ERROR("Invalid stage");
return UsdGeomMotionAPI();
}
return UsdGeomMotionAPI(stage->GetPrimAtPath(path));
}
/* virtual */
UsdSchemaType UsdGeomMotionAPI::_GetSchemaType() const {
return UsdGeomMotionAPI::schemaType;
}
/* static */
UsdGeomMotionAPI
UsdGeomMotionAPI::Apply(const UsdPrim &prim)
{
return UsdAPISchemaBase::_ApplyAPISchema<UsdGeomMotionAPI>(
prim, _schemaTokens->MotionAPI);
}
/* static */
const TfType &
UsdGeomMotionAPI::_GetStaticTfType()
{
static TfType tfType = TfType::Find<UsdGeomMotionAPI>();
return tfType;
}
/* static */
bool
UsdGeomMotionAPI::_IsTypedSchema()
{
static bool isTyped = _GetStaticTfType().IsA<UsdTyped>();
return isTyped;
}
/* virtual */
const TfType &
UsdGeomMotionAPI::_GetTfType() const
{
return _GetStaticTfType();
}
UsdAttribute
UsdGeomMotionAPI::GetVelocityScaleAttr() const
{
return GetPrim().GetAttribute(UsdGeomTokens->motionVelocityScale);
}
UsdAttribute
UsdGeomMotionAPI::CreateVelocityScaleAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(UsdGeomTokens->motionVelocityScale,
SdfValueTypeNames->Float,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
namespace {
static inline TfTokenVector
_ConcatenateAttributeNames(const TfTokenVector& left,const TfTokenVector& right)
{
TfTokenVector result;
result.reserve(left.size() + right.size());
result.insert(result.end(), left.begin(), left.end());
result.insert(result.end(), right.begin(), right.end());
return result;
}
}
/*static*/
const TfTokenVector&
UsdGeomMotionAPI::GetSchemaAttributeNames(bool includeInherited)
{
static TfTokenVector localNames = {
UsdGeomTokens->motionVelocityScale,
};
static TfTokenVector allNames =
_ConcatenateAttributeNames(
UsdAPISchemaBase::GetSchemaAttributeNames(true),
localNames);
if (includeInherited)
return allNames;
else
return localNames;
}
PXR_NAMESPACE_CLOSE_SCOPE
// ===================================================================== //
// Feel free to add custom code below this line. It will be preserved by
// the code generator.
//
// Just remember to wrap code in the appropriate delimiters:
// 'PXR_NAMESPACE_OPEN_SCOPE', 'PXR_NAMESPACE_CLOSE_SCOPE'.
// ===================================================================== //
// --(BEGIN CUSTOM CODE)--
PXR_NAMESPACE_OPEN_SCOPE
float UsdGeomMotionAPI::ComputeVelocityScale(UsdTimeCode time) const
{
UsdPrim prim = GetPrim();
UsdPrim pseudoRoot = prim.GetStage()->GetPseudoRoot();
float velocityScale = 1.0;
while (prim != pseudoRoot){
UsdAttribute vsAttr =
prim.GetAttribute(UsdGeomTokens->motionVelocityScale);
if (vsAttr.HasAuthoredValue() &&
vsAttr.Get(&velocityScale, time)){
return velocityScale;
}
prim = prim.GetParent();
}
return velocityScale;
}
PXR_NAMESPACE_CLOSE_SCOPE
|
/*
* This software is distributed under BSD 3-clause license (see LICENSE file).
*
* Authors: Evangelos Anagnostopoulos, Bjoern Esser
*/
#include <shogun/base/Parameter.h>
#include <shogun/mathematics/Math.h>
#include <shogun/features/RandomFourierDotFeatures.h>
namespace shogun {
enum KernelName;
CRandomFourierDotFeatures::CRandomFourierDotFeatures()
{
init(NOT_SPECIFIED, SGVector<float64_t>());
}
CRandomFourierDotFeatures::CRandomFourierDotFeatures(CDotFeatures* features,
int32_t D, KernelName kernel_name, SGVector<float64_t> params)
: CRandomKitchenSinksDotFeatures(features, D)
{
init(kernel_name, params);
random_coeff = generate_random_coefficients();
}
CRandomFourierDotFeatures::CRandomFourierDotFeatures(CDotFeatures* features,
int32_t D, KernelName kernel_name, SGVector<float64_t> params,
SGMatrix<float64_t> coeff)
: CRandomKitchenSinksDotFeatures(features, D, coeff)
{
init(kernel_name, params);
}
CRandomFourierDotFeatures::CRandomFourierDotFeatures(CFile* loader)
{
SG_NOTIMPLEMENTED;
}
CRandomFourierDotFeatures::CRandomFourierDotFeatures(const CRandomFourierDotFeatures& orig)
: CRandomKitchenSinksDotFeatures(orig)
{
init(orig.kernel, orig.kernel_params);
}
CRandomFourierDotFeatures::~CRandomFourierDotFeatures()
{
}
void CRandomFourierDotFeatures::init(KernelName kernel_name, SGVector<float64_t> params)
{
kernel = kernel_name;
kernel_params = params;
constant = num_samples > 0 ? std::sqrt(2.0 / num_samples) : 1;
SG_ADD(
&kernel_params, "kernel_params",
"The parameters of the kernel to approximate");
SG_ADD((machine_int_t* ) &kernel, "kernel",
"The kernel to approximate");
SG_ADD(&constant, "constant", "A constant needed");
}
CFeatures* CRandomFourierDotFeatures::duplicate() const
{
return new CRandomFourierDotFeatures(*this);
}
const char* CRandomFourierDotFeatures::get_name() const
{
return "RandomFourierDotFeatures";
}
float64_t CRandomFourierDotFeatures::post_dot(float64_t dot_result, index_t par_idx)
{
dot_result += random_coeff(random_coeff.num_rows-1, par_idx);
return std::cos(dot_result) * constant;
}
SGVector<float64_t> CRandomFourierDotFeatures::generate_random_parameter_vector()
{
SGVector<float64_t> vec(feats->get_dim_feature_space()+1);
switch (kernel)
{
case GAUSSIAN:
for (index_t i=0; i<vec.vlen-1; i++)
{
vec[i] = std::sqrt((float64_t)1 / kernel_params[0]) *
std::sqrt(2.0) * CMath::normal_random(0.0, 1);
}
vec[vec.vlen-1] = CMath::random(0.0, 2 * CMath::PI);
break;
default:
SG_SERROR("Unknown kernel\n");
}
return vec;
}
}
|
/*
Copyright (C) 2021 hidenorly
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.
*/
#ifndef __TESTABILITY_HPP__
#define __TESTABILITY_HPP__
#include "Sink.hpp"
#include "Source.hpp"
#include "Filter.hpp"
#include "AudioFormat.hpp"
#include "PipeAndFilterCommon.hpp"
#include "FifoBufferReadReference.hpp"
#include <memory>
#ifndef __AFW_TEST__
#define __AFW_TEST__ 1
#endif /* __AFW_TEST__ */
class ITestable
{
public:
virtual std::weak_ptr<ITestable> getTestShim(void) = 0;
};
class ICapture : public IUnlockable
{
protected:
std::shared_ptr<FifoBufferReadReference> mpRefBuf;
void enqueToRefBuf(IAudioBuffer& buf);
void setCaptureBufferSize(int nSamples);
public:
ICapture( AudioFormat format = AudioFormat() );
virtual ~ICapture();
virtual void captureRead(IAudioBuffer& buf);
virtual void setCaptureAudioFormat(AudioFormat audioFormat);
virtual void unlock(void);
};
class IInjector : public IUnlockable
{
protected:
std::shared_ptr<FifoBuffer> mpInjectorBuf;
bool mInjectorEnabled;
protected:
void dequeFromInjectBuf(IAudioBuffer& buf);
void setInjectBufferSize(int nSamples);
public:
IInjector( AudioFormat format = AudioFormat() );
virtual ~IInjector();
virtual void setInjectorEnabled(bool bEnabled);
virtual bool getInjectorEnabled(void);
virtual void inject(IAudioBuffer& buf);
virtual void setInjectAudioFormat(AudioFormat audioFormat);
virtual void unlock(void);
};
class SinkTestBase : public ISink
{
protected:
std::shared_ptr<ISink> mpSink;
virtual void setAudioFormatPrimitive(AudioFormat audioFormat);
public:
SinkTestBase(std::shared_ptr<ISink> pSink);
virtual ~SinkTestBase();
virtual std::vector<PRESENTATION> getAvailablePresentations(void);
virtual bool isAvailablePresentation(PRESENTATION presentation);
virtual bool setPresentation(PRESENTATION presentation);
virtual PRESENTATION getPresentation(void);
virtual AudioFormat getAudioFormat(void);
virtual float getVolume(void);
virtual bool setVolume(float volumePercentage);
virtual int getLatencyUSec(void);
virtual int64_t getSinkPts(void);
virtual void dump(void);
virtual int stateResourceConsumption(void);
};
class SinkCapture : public SinkTestBase, public ICapture
{
protected:
virtual void writePrimitive(IAudioBuffer& buf);
virtual void setAudioFormatPrimitive(AudioFormat audioFormat);
public:
SinkCapture(std::shared_ptr<ISink> pSink);
virtual ~SinkCapture();
};
class SinkInjector : public SinkTestBase, public IInjector
{
protected:
virtual void writePrimitive(IAudioBuffer& buf);
virtual void setAudioFormatPrimitive(AudioFormat audioFormat);
public:
SinkInjector(std::shared_ptr<ISink> pSink);
virtual ~SinkInjector();
};
class SourceTestBase : public ISource
{
protected:
std::shared_ptr<ISource> mpSource;
public:
SourceTestBase(std::shared_ptr<ISource> pSource);
virtual ~SourceTestBase();
virtual int getLatencyUSec(void);
virtual int64_t getSourcePts(void);
virtual AudioFormat getAudioFormat(void);
};
class SourceCapture : public SourceTestBase, public ICapture
{
protected:
virtual void readPrimitive(IAudioBuffer& buf);
public:
SourceCapture(std::shared_ptr<ISource> pSource);
virtual ~SourceCapture();
};
class SourceInjector : public SourceTestBase, public IInjector
{
protected:
virtual void readPrimitive(IAudioBuffer& buf);
public:
SourceInjector(std::shared_ptr<ISource> pSource);
virtual ~SourceInjector();
};
class FilterTestBase : public Filter
{
protected:
int mWindowSize;
int mLatency;
int mProcessingResource;
public:
FilterTestBase(int windowSize = DEFAULT_WINDOW_SIZE_USEC, int latencyUsec = DEFAULT_WINDOW_SIZE_USEC, int processingResource = Filter::DEFAULT_REQUIRED_PROCESSING_RESOURCE) : mWindowSize(windowSize), mLatency(latencyUsec), mProcessingResource(processingResource){};
virtual ~FilterTestBase(){};
virtual int getRequiredWindowSizeUsec(void){ return mWindowSize; };
virtual int getLatencyUSec(void){ return mLatency; };
virtual int stateResourceConsumption(void){ return mProcessingResource; };
};
class FilterCapture : public FilterTestBase, public ICapture
{
public:
FilterCapture(int windowSize = DEFAULT_WINDOW_SIZE_USEC, int latencyUsec = DEFAULT_WINDOW_SIZE_USEC, int processingResource = Filter::DEFAULT_REQUIRED_PROCESSING_RESOURCE) : FilterTestBase(windowSize, latencyUsec, processingResource), ICapture(){};
virtual ~FilterCapture(){};
virtual void process(AudioBuffer& inBuf, AudioBuffer& outBuf);
};
class FilterInjector : public FilterTestBase, public IInjector
{
public:
FilterInjector(int windowSize = DEFAULT_WINDOW_SIZE_USEC, int latencyUsec = DEFAULT_WINDOW_SIZE_USEC, int processingResource = Filter::DEFAULT_REQUIRED_PROCESSING_RESOURCE) : FilterTestBase(windowSize, latencyUsec, processingResource), IInjector(){};
virtual ~FilterInjector(){};
virtual void process(AudioBuffer& inBuf, AudioBuffer& outBuf);
};
#endif /* __TESTABILITY_HPP__ */
|
////////////////////////////////////////////////////////////////////////////
// Module : stalker_movement_manager_obstacles_path.cpp
// Created : 18.04.2007
// Modified : 18.04.2007
// Author : Dmitriy Iassenev
// Description : Stalker movement manager: dynamic obstacles avoidance: build path
////////////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include "stalker_movement_manager_obstacles.h"
#include "stalker_movement_manager_space.h"
#include "ai_space.h"
#include "ai/stalker/ai_stalker.h"
#include "restricted_object_obstacle.h"
#include "level_path_manager.h"
#include "xrAICore/Navigation/ai_object_location.h"
#include "moving_objects.h"
#include "detail_path_manager.h"
#include "level_path_builder.h"
#include "ai_obstacle.h"
#ifndef MASTER_GOLD
#include "ai_debug.h"
#endif // MASTER_GOLD
static const float check_time_delta = 1.f;
bool stalker_movement_manager_obstacles::simulate_path_navigation()
{
Fvector current_position = object().Position();
Fvector previous_position = current_position;
u32 current_travel_point = 0;
while (!detail().completed(current_position, !detail().state_patrol_path(), current_travel_point))
{
m_static_obstacles.on_before_query();
m_static_obstacles.query(current_position, previous_position);
if (!m_static_obstacles.process_query(false))
{
m_last_fail_time = Device.dwTimeGlobal;
m_failed_to_build_path = true;
restore_current_state();
return (false);
}
if (m_static_obstacles.need_path_to_rebuild())
return (false);
// float dist_to_target;
// Fvector dir_to_target;
// float distance;
// current_position =
// path_position(1.f,current_position,check_time_delta,current_travel_point,distance,dist_to_target,dir_to_target);
previous_position = current_position;
current_position = predict_position(check_time_delta, current_position, current_travel_point, 1.f);
}
return (true);
}
void stalker_movement_manager_obstacles::save_current_state()
{
m_saved_state = false;
if (level_path().path().empty())
return;
if (level_path().path().back() != level_path_builder().dest_vertex_id())
return;
if (detail().path().empty())
return;
if (detail().dest_vertex_id() != level_path_builder().dest_vertex_id())
return;
m_saved_state = true;
m_level_path.swap(level_path_path());
m_detail_current_index = detail().path().empty() ? u32(-1) : detail().curr_travel_point_index();
m_detail_path.swap(detail().path());
#ifdef DEBUG
m_detail_key_points.swap(detail().key_points());
#endif // DEBUG
m_detail_last_patrol_point = detail().last_patrol_point();
m_saved_current_iteration.copy(m_static_obstacles.current_iteration());
}
void stalker_movement_manager_obstacles::restore_current_state()
{
if (!m_saved_state)
return;
m_level_path.swap(level_path_path());
m_detail_path.swap(detail().path());
detail().m_current_travel_point = m_detail_current_index;
#ifdef DEBUG
m_detail_key_points.swap(detail().key_points());
#endif // DEBUG
detail().last_patrol_point(m_detail_last_patrol_point);
m_saved_current_iteration.swap(m_static_obstacles.current_iteration());
}
IC void stalker_movement_manager_obstacles::remove_query_objects(const Fvector& position, const float& radius)
{
m_static_obstacles.inactive_query().remove_objects(position, radius);
m_static_obstacles.active_query().remove_objects(position, radius);
}
void stalker_movement_manager_obstacles::build_level_path()
{
#ifndef MASTER_GOLD
if (!psAI_Flags.test(aiObstaclesAvoiding))
{
inherited::build_level_path();
return;
}
#endif // MASTER_GOLD
#ifdef DEBUG
CTimer timer;
timer.Start();
#endif // DEBUG
if (m_last_dest_vertex_id != level_path().dest_vertex_id())
remove_query_objects(object().Position(), 5.f);
m_last_fail_time = 0;
m_failed_to_build_path = false;
// Msg ("[%6d] m_failed_to_build_path = %s
//(stalker_movement_manager_obstacles::build_level_path)",Device.dwTimeGlobal,m_failed_to_build_path ? "true" :
//"false");
save_current_state();
m_static_obstacles.inactive_query().copy(m_static_obstacles.active_query());
m_static_obstacles.inactive_query().update_objects(object().Position(), 10000.f);
#ifndef MASTER_GOLD
if (!psAI_Flags.test(aiObstaclesAvoidingStatic))
m_dynamic_obstacles.inactive_query().copy(m_dynamic_obstacles.active_query());
#endif // MASTER_GOLD
bool pure_search_tried = false;
bool pure_search_result = false;
do
{
if (m_failed_to_build_path)
break;
inherited::build_level_path();
if (level_path().failed())
{
if (!pure_search_tried)
{
pure_search_tried = true;
m_static_obstacles.clear();
m_saved_current_iteration.clear();
level_path().invalidate_failed_info();
inherited::build_level_path();
pure_search_result = !level_path().failed();
}
if (!pure_search_result)
{
#ifndef MASTER_GOLD
Msg("! level_path().failed() during navigation");
#endif // #ifndef MASTER_GOLD
break;
}
}
} while (!simulate_path_navigation());
m_last_dest_vertex_id = level_path().dest_vertex_id();
// Msg ("[%6d][%6d][%s][%f]
// build_level_path",Device.dwFrame,Device.dwTimeGlobal,*object().cName(),timer.GetElapsed_sec()*1000.f);
}
|
// Copyright David Abrahams 2001-2004.
// Copyright (c) Jeremy Siek 2001-2003.
// Copyright (c) Thomas Witt 2002.
//
// Copyright (c) 2016 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if !defined(HPX_TESTS_UTIL_ITERATOR_TESTS_HPP)
#define HPX_TESTS_UTIL_ITERATOR_TESTS_HPP
#include <hpx/config.hpp>
#include <hpx/traits/is_iterator.hpp>
#include <hpx/util/always_void.hpp>
#include <hpx/testing.hpp>
#include <cstddef>
#include <iterator>
#include <type_traits>
#include <utility>
namespace tests
{
class dummy_constructor {};
// use this for the value type
struct dummy_type
{
dummy_type()
{
}
dummy_type(dummy_constructor)
{
}
dummy_type(int x)
: x_(x)
{
}
int foo() const
{
return x_;
}
bool operator==(const dummy_type& d) const
{
return x_ == d.x_;
}
int x_;
};
///////////////////////////////////////////////////////////////////////////
// Tests whether type Iterator satisfies the requirements for a
// TrivialIterator.
// Preconditions: i != j, *i == val
template <class Iterator, class T>
void trivial_iterator_test(const Iterator i, const Iterator j, T val)
{
Iterator k;
HPX_TEST(i == i);
HPX_TEST(j == j);
HPX_TEST(i != j);
typename std::iterator_traits<Iterator>::value_type v = *i;
HPX_TEST(v == val);
k = i;
HPX_TEST(k == k);
HPX_TEST(k == i);
HPX_TEST(k != j);
HPX_TEST(*k == val);
}
// Preconditions: *i == v1, *++i == v2
template <typename Iterator, typename T>
void input_iterator_test(Iterator i, T v1, T v2)
{
Iterator i1(i);
HPX_TEST(i == i1);
HPX_TEST(!(i != i1));
// I can see no generic way to create an input iterator
// that is in the domain of== of i and != i.
// The following works for istream_iterator but is not
// guaranteed to work for arbitrary input iterators.
//
// Iterator i2;
//
// HPX_TEST(i != i2);
// HPX_TEST(!(i == i2));
HPX_TEST(*i1 == v1);
HPX_TEST(*i == v1);
// we cannot test for equivalence of (void)++i & (void)i++
// as i is only guaranteed to be single pass.
HPX_TEST(*i++ == v1);
i1 = i;
HPX_TEST(i == i1);
HPX_TEST(!(i != i1));
HPX_TEST(*i1 == v2);
HPX_TEST(*i == v2);
// i is dereferencable, so it must be incrementable.
++i;
// how to test for operator-> ?
}
namespace traits
{
template <typename T, typename Enable = void>
struct is_incrementable
: std::false_type
{};
template <typename T>
struct is_incrementable<T,
typename hpx::util::always_void<
decltype(++std::declval<T&>())
>::type>
: std::true_type
{};
template <typename T, typename Enable = void>
struct is_postfix_incrementable
: std::false_type
{};
template <typename T>
struct is_postfix_incrementable<T,
typename hpx::util::always_void<
decltype(std::declval<T&>()++)
>::type>
: std::true_type
{};
}
// Preconditions: *i == v
// Do separate tests for *i++ so we can treat, e.g., smart pointers,
// as readable and/or writable iterators.
template <typename Iterator, typename T>
void readable_iterator_traversal_test(Iterator i1, T v, std::true_type)
{
T v2(*i1++);
HPX_TEST(v == v2);
}
template <typename Iterator, typename T>
void readable_iterator_traversal_test(const Iterator i1, T v, std::false_type)
{
}
template <typename Iterator, typename T>
void readable_iterator_test(const Iterator i1, T v)
{
typedef typename std::iterator_traits<Iterator>::reference ref_t;
Iterator i2(i1); // Copy Constructible
ref_t r1 = *i1;
ref_t r2 = *i2;
T v1 = r1;
T v2 = r2;
HPX_TEST(v1 == v);
HPX_TEST(v2 == v);
readable_iterator_traversal_test(
i1, v,
typename std::integral_constant<bool,
tests::traits::is_postfix_incrementable<Iterator>::value
>::type());
// I think we don't really need this as it checks the same things as
// the above code.
HPX_TEST(!hpx::traits::is_output_iterator<Iterator>::value);
}
template <typename Iterator, typename T>
void forward_iterator_test(Iterator i, T v1, T v2)
{
input_iterator_test(i, v1, v2);
Iterator i1 = i, i2 = i;
HPX_TEST(i == i1++);
HPX_TEST(i != ++i2);
trivial_iterator_test(i, i1, v1);
trivial_iterator_test(i, i2, v1);
++i;
HPX_TEST(i == i1);
HPX_TEST(i == i2);
++i1;
++i2;
trivial_iterator_test(i, i1, v2);
trivial_iterator_test(i, i2, v2);
// lvalue_test<(std::is_pointer<Iterator>::value)>::check_(i);
}
template <typename Iterator, typename T>
void forward_readable_iterator_test(Iterator i, Iterator j, T val1, T val2)
{
Iterator i2;
Iterator i3(i);
i2 = i;
HPX_TEST(i2 == i3);
HPX_TEST(i != j);
HPX_TEST(i2 != j);
readable_iterator_test(i, val1);
readable_iterator_test(i2, val1);
readable_iterator_test(i3, val1);
HPX_TEST(i == i2++);
HPX_TEST(i != ++i3);
readable_iterator_test(i2, val2);
readable_iterator_test(i3, val2);
readable_iterator_test(i, val1);
}
// Preconditions: *i == v1, *++i == v2
template <typename Iterator, typename T>
void bidirectional_iterator_test(Iterator i, T v1, T v2)
{
forward_iterator_test(i, v1, v2);
++i;
Iterator i1 = i, i2 = i;
HPX_TEST(i == i1--);
HPX_TEST(i != --i2);
trivial_iterator_test(i, i1, v2);
trivial_iterator_test(i, i2, v2);
--i;
HPX_TEST(i == i1);
HPX_TEST(i == i2);
++i1;
++i2;
trivial_iterator_test(i, i1, v1);
trivial_iterator_test(i, i2, v1);
}
// bidirectional
// Preconditions: *i == v1, *++i == v2
template <typename Iterator, typename T>
void bidirectional_readable_iterator_test(Iterator i, T v1, T v2)
{
Iterator j(i);
++j;
forward_readable_iterator_test(i, j, v1, v2);
++i;
Iterator i1 = i, i2 = i;
HPX_TEST(i == i1--);
HPX_TEST(i != --i2);
readable_iterator_test(i, v2);
readable_iterator_test(i1, v1);
readable_iterator_test(i2, v1);
--i;
HPX_TEST(i == i1);
HPX_TEST(i == i2);
++i1;
++i2;
readable_iterator_test(i, v1);
readable_iterator_test(i1, v2);
readable_iterator_test(i2, v2);
}
namespace detail
{
template <typename T>
struct identity
{
typedef T type;
};
// implementation originally suggested by C. Green in
// http://lists.boost.org/MailArchives/boost/msg00886.php
// The use of identity creates a non-deduced form, so that the
// explicit template argument must be supplied
template <typename T>
inline T implicit_cast(typename identity<T>::type x)
{
return x;
}
}
// Preconditions: [i,i+N) is a valid range
template <typename Iterator, typename TrueVals>
void random_access_iterator_test(Iterator i, int N, TrueVals vals)
{
bidirectional_iterator_test(i, vals[0], vals[1]);
const Iterator j = i;
int c;
typedef typename boost::detail::iterator_traits<Iterator>::value_type
value_type;
for (c = 0; c < N - 1; ++c)
{
HPX_TEST(i == j + c);
HPX_TEST(*i == vals[c]);
HPX_TEST(*i == detail::implicit_cast<value_type>(j[c]));
HPX_TEST(*i == *(j + c));
HPX_TEST(*i == *(c + j));
++i;
HPX_TEST(i > j);
HPX_TEST(i >= j);
HPX_TEST(j <= i);
HPX_TEST(j < i);
}
Iterator k = j + N - 1;
for (c = 0; c < N - 1; ++c)
{
HPX_TEST(i == k - c);
HPX_TEST(*i == vals[N - 1 - c]);
HPX_TEST(*i == detail::implicit_cast<value_type>(j[N - 1 - c]));
Iterator q = k - c;
HPX_TEST(*i == *q);
HPX_TEST(i > j);
HPX_TEST(i >= j);
HPX_TEST(j <= i);
HPX_TEST(j < i);
--i;
}
}
// random access
// Preconditions: [i,i+N) is a valid range
template <typename Iterator, typename TrueVals>
void random_access_readable_iterator_test(Iterator i, int N, TrueVals vals)
{
bidirectional_readable_iterator_test(i, vals[0], vals[1]);
const Iterator j = i;
int c;
for (c = 0; c < N - 1; ++c)
{
HPX_TEST(i == j + c);
HPX_TEST(*i == vals[c]);
typename std::iterator_traits<Iterator>::value_type x = j[c];
HPX_TEST(*i == x);
HPX_TEST(*i == *(j + c));
HPX_TEST(*i == *(c + j));
++i;
HPX_TEST(i > j);
HPX_TEST(i >= j);
HPX_TEST(j <= i);
HPX_TEST(j < i);
}
Iterator k = j + N - 1;
for (c = 0; c < N - 1; ++c)
{
HPX_TEST(i == k - c);
HPX_TEST(*i == vals[N - 1 - c]);
typename std::iterator_traits<Iterator>::value_type x = j[N - 1 - c];
HPX_TEST(*i == x);
Iterator q = k - c;
HPX_TEST(*i == *q);
HPX_TEST(i > j);
HPX_TEST(i >= j);
HPX_TEST(j <= i);
HPX_TEST(j < i);
--i;
}
}
template <typename Iterator, typename T>
void constant_lvalue_iterator_test(Iterator i, T v1)
{
Iterator i2(i);
typedef typename std::iterator_traits<Iterator>::value_type value_type;
typedef typename std::iterator_traits<Iterator>::reference reference;
HPX_TEST((std::is_same<const value_type&, reference>::value));
const T& v2 = *i2;
HPX_TEST(v1 == v2);
// HPX_TEST(is_lvalue_iterator<Iterator>::value);
// HPX_TEST(!is_non_const_lvalue_iterator<Iterator>::value);
}
template <typename Iterator, typename T>
void non_const_lvalue_iterator_test(Iterator i, T v1, T v2)
{
Iterator i2(i);
typedef typename std::iterator_traits<Iterator>::value_type value_type;
typedef typename std::iterator_traits<Iterator>::reference reference;
HPX_TEST((std::is_same<value_type&, reference>::value));
T& v3 = *i2;
HPX_TEST(v1 == v3);
// A non-const lvalue iterator is not necessarily writable, but we
// are assuming the value_type is assignable here
*i = v2;
T& v4 = *i2;
HPX_TEST(v2 == v4);
// HPX_TEST(is_lvalue_iterator<Iterator>::value);
// HPX_TEST(is_non_const_lvalue_iterator<Iterator>::value);
}
// Precondition: i != j
template <typename Iterator, typename ConstIterator>
void const_nonconst_iterator_test(Iterator i, ConstIterator j)
{
HPX_TEST(i != j);
HPX_TEST(j != i);
ConstIterator k(i);
HPX_TEST(k == i);
HPX_TEST(i == k);
k = i;
HPX_TEST(k == i);
HPX_TEST(i == k);
}
template <typename Iterator, typename T>
void writable_iterator_traversal_test(Iterator i1, T v, std::true_type)
{
++i1; // we just wrote into that position
*i1++ = v;
Iterator x(i1++);
(void)x;
}
template <class Iterator, class T>
void writable_iterator_traversal_test(const Iterator i1, T v, std::false_type)
{
}
template <class Iterator, class T>
void writable_iterator_test(Iterator i, T v, T v2)
{
Iterator i2(i); // Copy Constructible
*i2 = v;
writable_iterator_traversal_test(
i, v2,
typename std::integral_constant<bool,
tests::traits::is_incrementable<Iterator>::value &&
tests::traits::is_postfix_incrementable<Iterator>::value
>());
}
///////////////////////////////////////////////////////////////////////////
template <class T>
class static_object
{
public:
static T& get()
{
static char d[sizeof(T)];
return *reinterpret_cast<T*>(d);
}
};
template <typename T>
class input_output_iterator_archetype
{
private:
typedef input_output_iterator_archetype self;
struct in_out_tag
: public std::input_iterator_tag, public std::output_iterator_tag
{
};
public:
typedef in_out_tag iterator_category;
typedef T value_type;
struct reference
{
reference& operator=(const T&)
{
return *this;
}
operator value_type()
{
return static_object<T>::get();
}
};
typedef const T* pointer;
typedef std::ptrdiff_t difference_type;
input_output_iterator_archetype()
{
}
self& operator=(const self&)
{
return *this;
}
bool operator==(const self&) const
{
return true;
}
bool operator!=(const self&) const
{
return true;
}
reference operator*() const
{
return reference();
}
self& operator++()
{
return *this;
}
self operator++(int)
{
return *this;
}
};
template <typename T>
class input_iterator_archetype_no_proxy
{
private:
typedef input_iterator_archetype_no_proxy self;
public:
typedef std::input_iterator_tag iterator_category;
typedef T value_type;
typedef const T& reference;
typedef const T* pointer;
typedef std::ptrdiff_t difference_type;
input_iterator_archetype_no_proxy()
{
}
input_iterator_archetype_no_proxy(input_iterator_archetype_no_proxy const&)
{
}
self& operator=(const self&)
{
return *this;
}
bool operator==(const self&) const
{
return true;
}
bool operator!=(const self&) const
{
return true;
}
reference operator*() const
{
return static_object<T>::get();
}
self& operator++()
{
return *this;
}
self operator++(int)
{
return *this;
}
};
template <typename T>
class forward_iterator_archetype
{
public:
typedef forward_iterator_archetype self;
public:
typedef std::forward_iterator_tag iterator_category;
typedef T value_type;
typedef const T& reference;
typedef T const* pointer;
typedef std::ptrdiff_t difference_type;
forward_iterator_archetype()
{
}
forward_iterator_archetype(forward_iterator_archetype const&)
{
}
self& operator=(const self&)
{
return *this;
}
bool operator==(const self&) const
{
return true;
}
bool operator!=(const self&) const
{
return true;
}
reference operator*() const
{
return static_object<T>::get();
}
self& operator++()
{
return *this;
}
self operator++(int)
{
return *this;
}
};
}
#endif
|
#include<bits/stdc++.h>
#define mt make_tuple
#define mp make_pair
#define pu push_back
#define INF 1000000001
#define MOD 1000000007
#define ll long long int
#define ld long double
#define vi vector<int>
#define vll vector<long long int>
#define sc(n) scanf("%d",&n);
#define scll(n) scanf("%lld",&n);
#define scld(n) scanf("%Lf",&n);
#define scr(s) {char temp[1000000];scanf("%s",temp);s = temp;}
using namespace std;
int main()
{
int n;
string s;
scr(s);
n= s.size();
vector<int> v(n,0);
// for(int i=0;i<v.size();i++) cout<<v[i]<<" ";cout<<endl;
int k=n;
for(int i=n-1;i>=0;i--)
{
if(s[i]=='>' && k>(i+1)) {v[i] = k;k--;}
}
int boo = 0;
// for(int i=0;i<v.size();i++) cout<<v[i]<<" ";cout<<endl;
for(int i=n-1;i>=0;i--)
{
if(s[i]=='<'&& k<(i+1)) {v[i] = k;k--;}
else if(s[i]=='<') {boo = 1;break;}
}
// for(int i=0;i<v.size();i++) cout<<v[i]<<" ";cout<<endl;
for(int i=0;i<n;i++) if(v[i]==0) boo = 1;
if(boo) cout<<"Impossible"<<endl;
else
{
cout<<"Possible\n";
for(int i=0;i<v.size();i++) cout<<v[i]<<" ";cout<<endl;
}
return 0;
}
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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.
*
*=========================================================================*/
#include "itkMinimumMaximumImageFilter.h"
#include "itkSimpleFilterWatcher.h"
#include "itkMacro.h"
#include "itkMath.h"
int
itkMinimumMaximumImageFilterTest(int, char *[])
{
using SizeType = itk::Size<3>;
using ImageType = itk::Image<float, 3>;
using MinMaxFilterType = itk::MinimumMaximumImageFilter<ImageType>;
/* Define the image size and physical coordinates */
SizeType size = { { 20, 20, 20 } };
double origin[3] = { 0.0, 0.0, 0.0 };
double spacing[3] = { 1, 1, 1 };
int flag = 0; /* Did this test program work? */
std::cout << "Testing Minimum and Maximum Image Calulator:\n";
// Allocate a simple test image
ImageType::Pointer image = ImageType::New();
ImageType::RegionType region;
region.SetSize(size);
image->SetLargestPossibleRegion(region);
image->SetRequestedRegion(region);
image->SetBufferedRegion(region);
image->Allocate();
// Set origin and spacing of physical coordinates
image->SetOrigin(origin);
image->SetSpacing(spacing);
float minimum = -52;
float maximum = -10;
// Initialize the image contents with the minimum value
itk::Index<3> index;
for (int slice = 0; slice < 20; slice++)
{
index[2] = slice;
for (int row = 0; row < 20; row++)
{
index[1] = row;
for (int col = 0; col < 20; col++)
{
index[0] = col;
image->SetPixel(index, minimum);
}
}
}
// Set voxel (10,10,10) to maximum value
index[0] = 10;
index[1] = 10;
index[2] = 10;
image->SetPixel(index, maximum);
// Create and initialize the filter
MinMaxFilterType::Pointer filter = MinMaxFilterType::New();
itk::SimpleFilterWatcher watcher(filter);
filter->SetInput(image);
filter->Update();
// Return minimum of intensity
float minimumResult = filter->GetMinimum();
std::cout << "The Minimum intensity value is : " << minimumResult << std::endl;
if (itk::Math::NotExactlyEquals(minimumResult, minimum))
{
std::cout << "Minimum Value is wrong : " << minimumResult;
std::cout << " != " << minimum << std::endl;
flag = 1;
}
// Return maximum of intensity
float maximumResult = filter->GetMaximum();
std::cout << "The Maximum intensity value is : " << maximumResult << std::endl;
if (itk::Math::NotExactlyEquals(maximumResult, maximum))
{
std::cout << "Maximum Value is wrong : " << maximumResult;
std::cout << " != " << maximum << std::endl;
flag = 2;
}
// Return results of test
if (flag != 0)
{
std::cout << "*** Some tests failed" << std::endl;
return flag;
}
else
{
std::cout << "All tests successfully passed" << std::endl;
return EXIT_SUCCESS;
}
}
|
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// 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.
//
//------------------------------------------------------------------------------
#include "ledger/chain/transaction_rpc_serializers.hpp"
#include "ledger/storage_unit/transaction_store_sync_protocol.hpp"
#include <algorithm>
#include <cstdint>
#include <vector>
using fetch::byte_array::ConstByteArray;
// TODO(issue 7): Make cache configurable
constexpr uint32_t MAX_CACHE_LIFETIME_MS = 30000;
namespace fetch {
namespace ledger {
/**
* Create a transaction store sync protocol
*
* @param p The protocol id for this service
* @param r The register instance
* @param tp The thread pool instance to be used
* @param store The object store to be used
*/
TransactionStoreSyncProtocol::TransactionStoreSyncProtocol(ObjectStore *store, int lane_id)
: store_(store)
, id_(lane_id)
{
this->Expose(OBJECT_COUNT, this, &Self::ObjectCount);
this->ExposeWithClientContext(PULL_OBJECTS, this, &Self::PullObjects);
this->Expose(PULL_SUBTREE, this, &Self::PullSubtree);
this->Expose(PULL_SPECIFIC_OBJECTS, this, &Self::PullSpecificObjects);
}
void TransactionStoreSyncProtocol::TrimCache()
{
generics::MilliTimer timer("ObjectSync:TrimCache", 500);
FETCH_LOCK(cache_mutex_);
// reserve the space for the next cache
Cache next_cache;
next_cache.reserve(cache_.size()); // worst case
// compute the deadline for the cache entries
auto const cut_off =
CachedObject::Clock::now() - std::chrono::milliseconds(MAX_CACHE_LIFETIME_MS);
// generate the next cache version
std::copy_if(cache_.begin(), cache_.end(), std::back_inserter(next_cache),
[&cut_off](CachedObject const &object) {
// we only copy objects which are young that we want to keep
return object.created > cut_off;
});
auto const next_cache_size = next_cache.size();
auto const curr_cache_size = cache_.size();
if ((curr_cache_size != 0u) && (next_cache_size != curr_cache_size))
{
FETCH_UNUSED(id_); // logging only
FETCH_LOG_DEBUG(LOGGING_NAME, "Lane ", id_, ": New cache size: ", next_cache_size,
" Old cache size: ", curr_cache_size);
}
// replace the old cache
cache_ = std::move(next_cache);
}
/// @}
void TransactionStoreSyncProtocol::OnNewTx(Transaction const &o)
{
FETCH_LOCK(cache_mutex_);
cache_.emplace_back(o);
}
uint64_t TransactionStoreSyncProtocol::ObjectCount()
{
FETCH_LOCK(cache_mutex_);
return store_->Size();
}
/**
* Allow peers to pull large sections of your subtree for synchronisation on entry to the network
*
* @param: client_handle Handle referencing client making the request
*
* @return: the subtree the client is requesting as a vector (size limited)
*/
TransactionStoreSyncProtocol::TxArray TransactionStoreSyncProtocol::PullSubtree(
byte_array::ConstByteArray const &rid, uint64_t bit_count)
{
return store_->PullSubtree(rid, bit_count, PULL_LIMIT_);
}
TransactionStoreSyncProtocol::TxArray TransactionStoreSyncProtocol::PullObjects(
service::CallContext const &call_context)
{
// Creating result
TxArray ret{};
{
generics::MilliTimer timer("ObjectSync:PullObjects", 500);
FETCH_LOCK(cache_mutex_);
if (!cache_.empty())
{
for (auto &c : cache_)
{
if (c.delivered_to.find(call_context.sender_address) == c.delivered_to.end())
{
c.delivered_to.insert(call_context.sender_address);
ret.push_back(c.data);
}
}
}
}
FETCH_LOG_DEBUG(LOGGING_NAME, "Lane ", id_, ": PullObjects: Sending back ", ret.size(), " TXs");
return ret;
}
TransactionStoreSyncProtocol::TxArray TransactionStoreSyncProtocol::PullSpecificObjects(
std::vector<storage::ResourceID> const &rids)
{
TxArray ret;
Transaction tx;
for (auto const &rid : rids)
{
if (store_->Get(rid, tx))
{
ret.push_back(tx);
}
}
return ret;
}
} // namespace ledger
} // namespace fetch
|
// Copyright (c) 2012-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "limitedmap.h"
#include "test/test_Xchange.h"
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(limitedmap_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(limitedmap_test)
{
// create a limitedmap capped at 10 items
limitedmap<int, int> map(10);
// check that the max size is 10
BOOST_CHECK(map.max_size() == 10);
// check that it's empty
BOOST_CHECK(map.size() == 0);
// insert (-1, -1)
map.insert(std::pair<int, int>(-1, -1));
// make sure that the size is updated
BOOST_CHECK(map.size() == 1);
// make sure that the new items is in the map
BOOST_CHECK(map.count(-1) == 1);
// insert 10 new items
for (int i = 0; i < 10; i++) {
map.insert(std::pair<int, int>(i, i + 1));
}
// make sure that the map now contains 10 items...
BOOST_CHECK(map.size() == 10);
// ...and that the first item has been discarded
BOOST_CHECK(map.count(-1) == 0);
// iterate over the map, both with an index and an iterator
limitedmap<int, int>::const_iterator it = map.begin();
for (int i = 0; i < 10; i++) {
// make sure the item is present
BOOST_CHECK(map.count(i) == 1);
// use the iterator to check for the expected key adn value
BOOST_CHECK(it->first == i);
BOOST_CHECK(it->second == i + 1);
// use find to check for the value
BOOST_CHECK(map.find(i)->second == i + 1);
// update and recheck
map.update(it, i + 2);
BOOST_CHECK(map.find(i)->second == i + 2);
it++;
}
// check that we've exhausted the iterator
BOOST_CHECK(it == map.end());
// resize the map to 5 items
map.max_size(5);
// check that the max size and size are now 5
BOOST_CHECK(map.max_size() == 5);
BOOST_CHECK(map.size() == 5);
// check that items less than 5 have been discarded
// and items greater than 5 are retained
for (int i = 0; i < 10; i++) {
if (i < 5) {
BOOST_CHECK(map.count(i) == 0);
} else {
BOOST_CHECK(map.count(i) == 1);
}
}
// erase some items not in the map
for (int i = 100; i < 1000; i += 100) {
map.erase(i);
}
// check that the size is unaffected
BOOST_CHECK(map.size() == 5);
// erase the remaining elements
for (int i = 5; i < 10; i++) {
map.erase(i);
}
// check that the map is now empty
BOOST_CHECK(map.empty());
}
BOOST_AUTO_TEST_SUITE_END()
|
// The code is open source under the MIT license.
// Copyright 2019-2020, Phillip Keldenich, TU Braunschweig, Algorithms Group
// https://ibr.cs.tu-bs.de/alg
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Created by Phillip Keldenich on 22.11.19.
//
#pragma once
namespace ivarp {
namespace impl {
// Handling N-ary operators.
template<typename Context, typename ArgArray, typename Tag, typename... Args_>
struct EvaluateImpl<Context, MathNAry<Tag,Args_...>, ArgArray>
{
using CalledType = MathNAry<Tag,Args_...>;
using CTArgs = typename CalledType::Args;
using NumberType = typename Context::NumberType;
IVARP_HD_OVERLOAD_ON_CUDA_NT(NumberType,
static inline NumberType eval(const CalledType& c, const ArgArray& a)
noexcept(AllowsCUDA<NumberType>::value)
{
return do_eval(c, TupleIndexPack<CTArgs>{}, a);
}
)
private:
IVARP_HD_OVERLOAD_TEMPLATE_ON_CUDA_NT(IVARP_TEMPLATE_PARAMS(std::size_t... Indices), NumberType,
static NumberType
do_eval(const CalledType& c, IndexPack<Indices...>, const ArgArray& a)
noexcept(AllowsCUDA<NumberType>::value)
{
return invoke_tag<Tag, Context>(a, get<Indices>(c.args)...);
}
)
};
}
}
|
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <memory>
// template <ObjectType T> T* addressof(T&& r) = delete;
#include <memory>
#include <cassert>
#include "test_macros.h"
int main(int, char**)
{
#if TEST_STD_VER > 14
const int *p = std::addressof<const int>(0);
#else
#error
#endif
return 0;
}
|
/*
* Copyright (C) 2009 Tommi Maekitalo
*
* 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
* is provided AS IS, WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and
* NON-INFRINGEMENT. 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
*
*/
#include <zim/dirent.h>
#include <iostream>
#include <sstream>
#include <cxxtools/unit/testsuite.h>
#include <cxxtools/unit/registertest.h>
class DirentTest : public cxxtools::unit::TestSuite
{
public:
DirentTest()
: cxxtools::unit::TestSuite("zim::DirentTest")
{
registerMethod("SetGetDataDirent", *this, &DirentTest::SetGetDataDirent);
registerMethod("ReadWriteArticleDirent", *this, &DirentTest::ReadWriteArticleDirent);
registerMethod("ReadWriteArticleDirentUnicode", *this, &DirentTest::ReadWriteArticleDirentUnicode);
registerMethod("ReadWriteArticleDirentParameter", *this, &DirentTest::ReadWriteArticleDirentParameter);
registerMethod("ReadWriteRedirectDirent", *this, &DirentTest::ReadWriteRedirectDirent);
registerMethod("ReadWriteLinktargetDirent", *this, &DirentTest::ReadWriteLinktargetDirent);
registerMethod("ReadWriteDeletedDirent", *this, &DirentTest::ReadWriteDeletedDirent);
registerMethod("DirentSize", *this, &DirentTest::DirentSize);
registerMethod("RedirectDirentSize", *this, &DirentTest::RedirectDirentSize);
}
void SetGetDataDirent()
{
zim::Dirent dirent;
dirent.setUrl('A', "Bar");
dirent.setArticle(17, 45, 1234);
dirent.setVersion(54346);
CXXTOOLS_UNIT_ASSERT(!dirent.isRedirect());
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getNamespace(), 'A');
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getUrl(), "Bar");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getTitle(), "Bar");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getParameter(), "");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getClusterNumber(), 45);
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getBlobNumber(), 1234);
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getVersion(), 54346);
dirent.setTitle("Foo");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getNamespace(), 'A');
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getUrl(), "Bar");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getTitle(), "Foo");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getParameter(), "");
}
void ReadWriteArticleDirent()
{
zim::Dirent dirent;
dirent.setUrl('A', "Bar");
dirent.setTitle("Foo");
dirent.setArticle(17, 45, 1234);
dirent.setVersion(54346);
CXXTOOLS_UNIT_ASSERT(!dirent.isRedirect());
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getNamespace(), 'A');
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getUrl(), "Bar");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getTitle(), "Foo");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getParameter(), "");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getClusterNumber(), 45);
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getBlobNumber(), 1234);
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getVersion(), 54346);
std::stringstream s;
s << dirent;
zim::Dirent dirent2;
s >> dirent2;
CXXTOOLS_UNIT_ASSERT(!s.fail());
CXXTOOLS_UNIT_ASSERT_EQUALS(s.tellg(), s.tellp());
CXXTOOLS_UNIT_ASSERT(!dirent2.isRedirect());
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getNamespace(), 'A');
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getTitle(), "Foo");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getParameter(), "");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getClusterNumber(), 45);
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getBlobNumber(), 1234);
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getVersion(), 54346);
}
void ReadWriteArticleDirentUnicode()
{
zim::Dirent dirent;
dirent.setUrl('A', "L\xc3\xbcliang");
dirent.setArticle(17, 45, 1234);
CXXTOOLS_UNIT_ASSERT(!dirent.isRedirect());
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getNamespace(), 'A');
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getUrl(), "L\xc3\xbcliang");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getTitle(), "L\xc3\xbcliang");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getParameter(), "");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getClusterNumber(), 45);
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getBlobNumber(), 1234);
std::stringstream s;
s << dirent;
zim::Dirent dirent2;
s >> dirent2;
CXXTOOLS_UNIT_ASSERT(!s.fail());
CXXTOOLS_UNIT_ASSERT_EQUALS(s.tellg(), s.tellp());
CXXTOOLS_UNIT_ASSERT(!dirent2.isRedirect());
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getNamespace(), 'A');
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getUrl(), "L\xc3\xbcliang");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getTitle(), "L\xc3\xbcliang");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getParameter(), "");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getClusterNumber(), 45);
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getBlobNumber(), 1234);
}
void ReadWriteArticleDirentParameter()
{
zim::Dirent dirent;
dirent.setUrl('A', "Foo");
dirent.setParameter("bar");
dirent.setArticle(17, 45, 1234);
CXXTOOLS_UNIT_ASSERT(!dirent.isRedirect());
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getNamespace(), 'A');
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getUrl(), "Foo");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getTitle(), "Foo");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getParameter(), "bar");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getClusterNumber(), 45);
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getBlobNumber(), 1234);
std::stringstream s;
s << dirent;
zim::Dirent dirent2;
s >> dirent2;
CXXTOOLS_UNIT_ASSERT(!s.fail());
CXXTOOLS_UNIT_ASSERT_EQUALS(s.tellg(), s.tellp());
CXXTOOLS_UNIT_ASSERT(!dirent2.isRedirect());
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getNamespace(), 'A');
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getTitle(), "Foo");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getParameter(), "bar");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getClusterNumber(), 45);
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getBlobNumber(), 1234);
}
void ReadWriteRedirectDirent()
{
zim::Dirent dirent;
dirent.setUrl('A', "Bar");
dirent.setParameter("baz");
dirent.setRedirect(321);
CXXTOOLS_UNIT_ASSERT(dirent.isRedirect());
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getNamespace(), 'A');
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getUrl(), "Bar");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getParameter(), "baz");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getRedirectIndex(), 321);
std::stringstream s;
s << dirent;
zim::Dirent dirent2;
s >> dirent2;
CXXTOOLS_UNIT_ASSERT_EQUALS(s.tellg(), s.tellp());
CXXTOOLS_UNIT_ASSERT(dirent2.isRedirect());
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getNamespace(), 'A');
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getUrl(), "Bar");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getTitle(), "Bar");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getParameter(), "baz");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getRedirectIndex(), 321);
}
void ReadWriteLinktargetDirent()
{
zim::Dirent dirent;
dirent.setUrl('A', "Bar");
dirent.setLinktarget();
CXXTOOLS_UNIT_ASSERT(!dirent.isRedirect());
CXXTOOLS_UNIT_ASSERT(dirent.isLinktarget());
CXXTOOLS_UNIT_ASSERT(!dirent.isDeleted());
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getNamespace(), 'A');
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getUrl(), "Bar");
std::stringstream s;
s << dirent;
zim::Dirent dirent2;
s >> dirent2;
CXXTOOLS_UNIT_ASSERT_EQUALS(s.tellg(), s.tellp());
CXXTOOLS_UNIT_ASSERT(!dirent2.isRedirect());
CXXTOOLS_UNIT_ASSERT(dirent2.isLinktarget());
CXXTOOLS_UNIT_ASSERT(!dirent2.isDeleted());
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getNamespace(), 'A');
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getUrl(), "Bar");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getTitle(), "Bar");
}
void ReadWriteDeletedDirent()
{
zim::Dirent dirent;
dirent.setUrl('A', "Bar");
dirent.setDeleted();
CXXTOOLS_UNIT_ASSERT(!dirent.isRedirect());
CXXTOOLS_UNIT_ASSERT(!dirent.isLinktarget());
CXXTOOLS_UNIT_ASSERT(dirent.isDeleted());
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getNamespace(), 'A');
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getUrl(), "Bar");
std::stringstream s;
s << dirent;
zim::Dirent dirent2;
s >> dirent2;
CXXTOOLS_UNIT_ASSERT_EQUALS(s.tellg(), s.tellp());
CXXTOOLS_UNIT_ASSERT(!dirent2.isRedirect());
CXXTOOLS_UNIT_ASSERT(!dirent2.isLinktarget());
CXXTOOLS_UNIT_ASSERT(dirent2.isDeleted());
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getNamespace(), 'A');
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getUrl(), "Bar");
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent2.getTitle(), "Bar");
}
std::string direntAsString(const zim::Dirent& dirent)
{
std::ostringstream d;
d << dirent;
return d.str();
}
void DirentSize()
{
zim::Dirent dirent;
std::string s;
dirent.setArticle(17, 45, 1234);
dirent.setUrl('A', "Bar");
// case url set, title empty, extralen empty
s = direntAsString(dirent);
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getDirentSize(), s.size());
// case url set, title set, extralen empty
dirent.setTitle("Foo");
s = direntAsString(dirent);
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getDirentSize(), s.size());
// case url set, title set, extralen set
dirent.setParameter("baz");
s = direntAsString(dirent);
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getDirentSize(), s.size());
// case url set, title empty, extralen set
dirent.setTitle(std::string());
s = direntAsString(dirent);
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getDirentSize(), s.size());
}
void RedirectDirentSize()
{
zim::Dirent dirent;
dirent.setUrl('A', "Bar");
dirent.setParameter("baz");
dirent.setRedirect(321);
std::ostringstream d;
d << dirent;
CXXTOOLS_UNIT_ASSERT_EQUALS(dirent.getDirentSize(), d.str().size());
}
};
cxxtools::unit::RegisterTest<DirentTest> register_DirentTest;
|
#include "WorkingWithEncodings.h"
#include <system/type_info.h>
#include <system/text/encoding.h>
#include <system/string.h>
#include <system/shared_ptr.h>
#include <system/reflection/method_base.h>
#include <system/object.h>
#include <system/io/stream_reader.h>
#include <system/io/stream.h>
#include <system/details/dispose_guard.h>
#include <Project.h>
#include "RunExamples.h"
namespace Aspose {
namespace Tasks {
namespace Examples {
namespace CPP {
namespace WorkingWithProjects {
namespace CreatingReadingAndSaving {
RTTI_INFO_IMPL_HASH(2187330665u, ::Aspose::Tasks::Examples::CPP::WorkingWithProjects::CreatingReadingAndSaving::WorkingWithEncodings, ThisTypeBaseTypesInfo);
// Using statement is translated using System::Details::DisposeGuard class which may store exception and then throw from destructor.
// We block the warnings related as these are false alarms (the exception, if caught, will be re-thrown from the destructor).
#if defined(__MSVC__)
#pragma warning( push )
#pragma warning(disable : 4715)
#pragma warning(disable : 4700)
#pragma warning(disable : 4701)
#elif defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wreturn-type"
#endif
void WorkingWithEncodings::Run()
{
// The path to the documents directory.
System::String dataDir = RunExamples::GetDataDir(System::Reflection::MethodBase::GetCurrentMethod(ASPOSE_CURRENT_FUNCTION)->get_DeclaringType().get_FullName());
// ExStart:WorkingWithEncodings
// Specify Encodings
{
System::SharedPtr<System::IO::StreamReader> streamReader = System::MakeObject<System::IO::StreamReader>(dataDir + u"Project.mpx", System::Text::Encoding::GetEncoding(u"ISO-8859-1"));
// Clearing resources under 'using' statement
System::Details::DisposeGuard<1> __dispose_guard_0({ streamReader});
// ------------------------------------------
try
{
auto project = System::MakeObject<Project>(streamReader->get_BaseStream());
}
catch(...)
{
__dispose_guard_0.SetCurrentException(std::current_exception());
}
}
// ExEnd:WorkingWithEncodings
}
#if defined(__MSVC__)
#pragma warning( pop )
#elif defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
} // namespace CreatingReadingAndSaving
} // namespace WorkingWithProjects
} // namespace CPP
} // namespace Examples
} // namespace Tasks
} // namespace Aspose
|
/*******************************************************************************
* Copyright © 2014, Sergey Radionov <rsatom_gmail.com>
* 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 HOLDER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#include "QmlVlcMarquee.h"
#include "QmlVlcPositions.h"
QString QmlVlcMarquee::get_text()
{
QString text;
char* t = libvlc_video_get_marquee_string( m_player.get_mp(), libvlc_marquee_Text );
if ( t )
text = t;
return text;
}
void QmlVlcMarquee::set_text( const QString& t )
{
libvlc_video_set_marquee_string( m_player.get_mp(), libvlc_marquee_Text, t.toUtf8().constData() );
}
QString QmlVlcMarquee::get_position()
{
int p = get_marquee_int( libvlc_marquee_Position );
return QmlGetPositionById( p );
}
void QmlVlcMarquee::set_position( const QString& position )
{
int p = QmlGetIdByPosition( position );
set_marquee_int( libvlc_marquee_Position, p );
}
int QmlVlcMarquee::get_marquee_int( libvlc_video_marquee_option_t o )
{
return libvlc_video_get_marquee_int( m_player.get_mp(), o );
}
void QmlVlcMarquee::set_marquee_int( libvlc_video_marquee_option_t o, int i )
{
libvlc_video_set_marquee_int( m_player.get_mp(), o, i );
}
|
#ifndef MINERVA_COMPRESSOR_HPP
#define MINERVA_COMPRESSOR_HPP
#include <string>
#include <cstdint>
#include <vector>
namespace minerva
{
enum compressor_algorithm
{
GZIP
};
class compressor
{
public:
compressor();
compressor(compressor_algorithm algorithm, size_t basis_size, uint8_t level=0);
compressor(compressor_algorithm algorithm);
void compress(const std::string& filename);
void compress(std::vector<uint8_t>& data);
void uncompress(std::vector<uint8_t>& data);
private:
void compress_gzip(const std::string& filename);
void compress_gzip(std::vector<uint8_t>& data);
void uncompress_gzip(std::vector<uint8_t>& data);
private:
compressor_algorithm m_algorithm;
size_t m_basis_size;
uint8_t m_level;
};
}
#endif /* MINERVA_COMPRESSOR_HPP */
|
/*
* Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
#include "awt_Toolkit.h"
#include "awt_TextField.h"
#include "awt_TextComponent.h"
#include "awt_Canvas.h"
/* IMPORTANT! Read the README.JNI file for notes on JNI converted AWT code.
*/
/***********************************************************************/
// struct for _SetEchoChar() method
struct SetEchoCharStruct {
jobject textfield;
jchar echoChar;
};
/************************************************************************
* AwtTextField methods
*/
AwtTextField::AwtTextField()
: m_initialRescrollFlag( true )
{
}
/* Create a new AwtTextField object and window. */
AwtTextField* AwtTextField::Create(jobject peer, jobject parent)
{
JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
jobject target = NULL;
AwtTextField* c = NULL;
try {
PDATA pData;
AwtCanvas* awtParent;
JNI_CHECK_PEER_GOTO(parent, done);
awtParent = (AwtCanvas*)pData;
JNI_CHECK_NULL_GOTO(awtParent, "null awtParent", done);
target = env->GetObjectField(peer, AwtObject::targetID);
JNI_CHECK_NULL_GOTO(target, "null target", done);
c = new AwtTextField();
{
DWORD style = WS_CHILD | WS_CLIPSIBLINGS |
ES_LEFT | ES_AUTOHSCROLL;
DWORD exStyle = WS_EX_CLIENTEDGE;
if (GetRTL()) {
exStyle |= WS_EX_RIGHT | WS_EX_LEFTSCROLLBAR;
if (GetRTLReadingOrder())
exStyle |= WS_EX_RTLREADING;
}
jint x = env->GetIntField(target, AwtComponent::xID);
jint y = env->GetIntField(target, AwtComponent::yID);
jint width = env->GetIntField(target, AwtComponent::widthID);
jint height = env->GetIntField(target, AwtComponent::heightID);
c->CreateHWnd(env, L"", style, exStyle,
x, y, width, height,
awtParent->GetHWnd(),
reinterpret_cast<HMENU>(static_cast<INT_PTR>(
awtParent->CreateControlID())),
::GetSysColor(COLOR_WINDOWTEXT),
::GetSysColor(COLOR_WINDOW),
peer);
c->m_backgroundColorSet = TRUE;
/* suppress inheriting parent's color. */
c->UpdateBackground(env, target);
c->SendMessage(EM_SETMARGINS, EC_LEFTMARGIN | EC_RIGHTMARGIN,
MAKELPARAM(1, 1));
/*
* Fix for BugTraq Id 4260109.
* Set the text limit to the maximum.
*/
c->SendMessage(EM_SETLIMITTEXT);
}
} catch (...) {
env->DeleteLocalRef(target);
throw;
}
done:
env->DeleteLocalRef(target);
return c;
}
void AwtTextField::EditSetSel(CHARRANGE &cr) {
SendMessage(EM_SETSEL, cr.cpMin, cr.cpMax);
}
LONG AwtTextField::EditGetCharFromPos(POINT& pt) {
return static_cast<LONG>(SendMessage(EM_CHARFROMPOS, 0, MAKELPARAM(pt.x, pt.y)));
}
LRESULT AwtTextField::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
if (message == WM_UNDO || message == EM_UNDO || message == EM_CANUNDO) {
if (GetWindowLong(GetHWnd(), GWL_STYLE) & ES_READONLY) {
return FALSE;
}
}
return AwtTextComponent::WindowProc(message, wParam, lParam);
}
MsgRouting
AwtTextField::HandleEvent(MSG *msg, BOOL synthetic)
{
MsgRouting returnVal;
/*
* RichEdit 1.0 control starts internal message loop if the
* left mouse button is pressed while the cursor is not over
* the current selection or the current selection is empty.
* Because of this we don't receive WM_MOUSEMOVE messages
* while the left mouse button is pressed. To work around
* this behavior we process the relevant mouse messages
* by ourselves.
* By consuming WM_MOUSEMOVE messages we also don't give
* the RichEdit control a chance to recognize a drag gesture
* and initiate its own drag-n-drop operation.
*
* The workaround also allows us to implement synthetic focus mechanism.
*/
if (IsFocusingMouseMessage(msg)) {
LONG lCurPos = EditGetCharFromPos(msg->pt);
/*
* NOTE: Plain EDIT control always clears selection on mouse
* button press. We are clearing the current selection only if
* the mouse pointer is not over the selected region.
* In this case we sacrifice backward compatibility
* to allow dnd of the current selection.
*/
if (msg->message == WM_LBUTTONDBLCLK) {
SetStartSelectionPos(static_cast<LONG>(SendMessage(
EM_FINDWORDBREAK, WB_MOVEWORDLEFT, lCurPos)));
SetEndSelectionPos(static_cast<LONG>(SendMessage(
EM_FINDWORDBREAK, WB_MOVEWORDRIGHT, lCurPos)));
} else {
SetStartSelectionPos(lCurPos);
SetEndSelectionPos(lCurPos);
}
CHARRANGE cr;
cr.cpMin = GetStartSelectionPos();
cr.cpMax = GetEndSelectionPos();
EditSetSel(cr);
delete msg;
return mrConsume;
} else if (msg->message == WM_LBUTTONUP) {
/*
* If the left mouse button is pressed on the selected region
* we don't clear the current selection. We clear it on button
* release instead. This is to allow dnd of the current selection.
*/
if (GetStartSelectionPos() == -1 && GetEndSelectionPos() == -1) {
CHARRANGE cr;
LONG lCurPos = EditGetCharFromPos(msg->pt);
cr.cpMin = lCurPos;
cr.cpMax = lCurPos;
EditSetSel(cr);
}
/*
* Cleanup the state variables when left mouse button is released.
* These state variables are designed to reflect the selection state
* while the left mouse button is pressed and be set to -1 otherwise.
*/
SetStartSelectionPos(-1);
SetEndSelectionPos(-1);
SetLastSelectionPos(-1);
delete msg;
return mrConsume;
} else if (msg->message == WM_MOUSEMOVE && (msg->wParam & MK_LBUTTON)) {
/*
* We consume WM_MOUSEMOVE while the left mouse button is pressed,
* so we have to simulate autoscrolling when mouse is moved outside
* of the client area.
*/
POINT p;
RECT r;
BOOL bScrollLeft = FALSE;
BOOL bScrollRight = FALSE;
BOOL bScrollUp = FALSE;
BOOL bScrollDown = FALSE;
p.x = msg->pt.x;
p.y = msg->pt.y;
VERIFY(::GetClientRect(GetHWnd(), &r));
if (p.x < 0) {
bScrollLeft = TRUE;
p.x = 0;
} else if (p.x > r.right) {
bScrollRight = TRUE;
p.x = r.right - 1;
}
LONG lCurPos = EditGetCharFromPos(p);
if (GetStartSelectionPos() != -1 &&
GetEndSelectionPos() != -1 &&
lCurPos != GetLastSelectionPos()) {
CHARRANGE cr;
SetLastSelectionPos(lCurPos);
cr.cpMin = GetStartSelectionPos();
cr.cpMax = GetLastSelectionPos();
EditSetSel(cr);
}
if (bScrollLeft == TRUE || bScrollRight == TRUE) {
SCROLLINFO si;
memset(&si, 0, sizeof(si));
si.cbSize = sizeof(si);
si.fMask = SIF_PAGE | SIF_POS | SIF_RANGE;
VERIFY(::GetScrollInfo(GetHWnd(), SB_HORZ, &si));
if (bScrollLeft == TRUE) {
si.nPos = si.nPos - si.nPage / 2;
si.nPos = max(si.nMin, si.nPos);
} else if (bScrollRight == TRUE) {
si.nPos = si.nPos + si.nPage / 2;
si.nPos = min(si.nPos, si.nMax);
}
/*
* Okay to use 16-bit position since RichEdit control adjusts
* its scrollbars so that their range is always 16-bit.
*/
DASSERT(abs(si.nPos) < 0x8000);
SendMessage(WM_HSCROLL,
MAKEWPARAM(SB_THUMBPOSITION, LOWORD(si.nPos)));
}
delete msg;
return mrConsume;
}
/*
* Store the 'synthetic' parameter so that the WM_PASTE security check
* happens only for synthetic events.
*/
m_synthetic = synthetic;
returnVal = AwtComponent::HandleEvent(msg, synthetic);
m_synthetic = FALSE;
return returnVal;
}
void AwtTextField::_SetEchoChar(void *param)
{
JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
SetEchoCharStruct *secs = (SetEchoCharStruct *)param;
jobject self = secs->textfield;
jchar echo = secs->echoChar;
AwtTextField *c = NULL;
PDATA pData;
JNI_CHECK_PEER_GOTO(self, ret);
c = (AwtTextField *)pData;
if (::IsWindow(c->GetHWnd()))
{
c->SendMessage(EM_SETPASSWORDCHAR, echo);
// Fix for 4307281: force redraw so that changes will take effect
VERIFY(::InvalidateRect(c->GetHWnd(), NULL, FALSE));
}
ret:
env->DeleteGlobalRef(self);
delete secs;
}
void AwtTextField::Reshape(int x, int y, int w, int h)
{
AwtTextComponent::Reshape( x, y, w, h );
// Another option would be to call this
// after WM_SIZE notification is handled
initialRescroll();
}
// Windows' Edit control features:
// (i) if text selection is set while control's width or height is 0,
// text is scrolled oddly.
// (ii) if control's size is changed, text seems never be automatically
// rescrolled.
//
// This method is designed for the following scenario: AWT spawns Edit
// control with 0x0 dimensions, then sets text selection, then resizes the
// control (couple of times). This might cause text appear undesirably scrolled.
// So we reset/set selection again to rescroll text. (see also CR 6480547)
void AwtTextField::initialRescroll()
{
if( ! m_initialRescrollFlag ) {
return;
}
::RECT r;
BOOL ok = ::GetClientRect( GetHWnd(), &r );
if( ! ok || r.right==0 || r.bottom==0 ) {
return;
}
m_initialRescrollFlag = false;
DWORD start, end;
SendMessage( EM_GETSEL, (WPARAM)&start, (LPARAM)&end );
SendMessage( EM_SETSEL, (WPARAM)0, (LPARAM)0 );
SendMessage( EM_SETSEL, (WPARAM)start, (LPARAM)end );
}
/************************************************************************
* WTextFieldPeer native methods
*/
extern "C" {
/*
* Class: sun_awt_windows_WTextFieldPeer
* Method: create
* Signature: (Lsun/awt/windows/WComponentPeer;)V
*/
JNIEXPORT void JNICALL
Java_sun_awt_windows_WTextFieldPeer_create(JNIEnv *env, jobject self,
jobject parent)
{
TRY;
PDATA pData;
JNI_CHECK_PEER_RETURN(parent);
AwtToolkit::CreateComponent(self, parent,
(AwtToolkit::ComponentFactory)
AwtTextField::Create);
JNI_CHECK_PEER_CREATION_RETURN(self);
CATCH_BAD_ALLOC;
}
/*
* Class: sun_awt_windows_WTextFieldPeer
* Method: setEchoCharacter
* Signature: (C)V
*/
JNIEXPORT void JNICALL
Java_sun_awt_windows_WTextFieldPeer_setEchoCharacter(JNIEnv *env, jobject self,
jchar ch)
{
TRY;
SetEchoCharStruct *secs = new SetEchoCharStruct;
secs->textfield = env->NewGlobalRef(self);
secs->echoChar = ch;
AwtToolkit::GetInstance().SyncCall(AwtTextField::_SetEchoChar, secs);
// global ref and secs are deleted in _SetEchoChar()
CATCH_BAD_ALLOC;
}
} /* extern "C" */
|
/*
* Copyright 2009-2017 Alibaba Cloud 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.
*/
#include <alibabacloud/openanalytics-open/model/ValidateVirtualClusterNameResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Openanalytics_open;
using namespace AlibabaCloud::Openanalytics_open::Model;
ValidateVirtualClusterNameResult::ValidateVirtualClusterNameResult() :
ServiceResult()
{}
ValidateVirtualClusterNameResult::ValidateVirtualClusterNameResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
ValidateVirtualClusterNameResult::~ValidateVirtualClusterNameResult()
{}
void ValidateVirtualClusterNameResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
if(!dataNode["Legal"].isNull())
data_.legal = dataNode["Legal"].asString();
if(!dataNode["Message"].isNull())
data_.message = dataNode["Message"].asString();
}
ValidateVirtualClusterNameResult::Data ValidateVirtualClusterNameResult::getData()const
{
return data_;
}
|
/**
* The Forgotten Server - a free and open-source MMORPG server emulator
* Copyright (C) 2019 Mark Samman <mark.samman@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "otpch.h"
#include "lua/global/globalevent.h"
#include "utils/tools.h"
#include "game/scheduling/scheduler.h"
#include "utils/pugicast.h"
GlobalEvents::GlobalEvents() :
scriptInterface("GlobalEvent Interface") {
scriptInterface.initState();
}
GlobalEvents::~GlobalEvents() {
clear(false);
}
void GlobalEvents::clearMap(GlobalEventMap& map, bool fromLua) {
for (auto it = map.begin(); it != map.end(); ) {
if (fromLua == it->second.fromLua) {
it = map.erase(it);
} else {
++it;
}
}
}
void GlobalEvents::clear(bool fromLua) {
g_scheduler().stopEvent(thinkEventId);
thinkEventId = 0;
g_scheduler().stopEvent(timerEventId);
timerEventId = 0;
clearMap(thinkMap, fromLua);
clearMap(serverMap, fromLua);
clearMap(timerMap, fromLua);
reInitState(fromLua);
}
Event_ptr GlobalEvents::getEvent(const std::string& nodeName) {
if (strcasecmp(nodeName.c_str(), "globalevent") != 0) {
return nullptr;
}
return Event_ptr(new GlobalEvent(&scriptInterface));
}
bool GlobalEvents::registerEvent(Event_ptr event, const pugi::xml_node&) {
GlobalEvent_ptr globalEvent{static_cast<GlobalEvent*>(event.release())}; //event is guaranteed to be a GlobalEvent
if (globalEvent->getEventType() == GLOBALEVENT_TIMER) {
auto result = timerMap.emplace(globalEvent->getName(), std::move(*globalEvent));
if (result.second) {
if (timerEventId == 0) {
timerEventId = g_scheduler().addEvent(createSchedulerTask(SCHEDULER_MINTICKS, std::bind(&GlobalEvents::timer, this)));
}
return true;
}
} else if (globalEvent->getEventType() != GLOBALEVENT_NONE) {
auto result = serverMap.emplace(globalEvent->getName(), std::move(*globalEvent));
if (result.second) {
return true;
}
} else { // think event
auto result = thinkMap.emplace(globalEvent->getName(), std::move(*globalEvent));
if (result.second) {
if (thinkEventId == 0) {
thinkEventId = g_scheduler().addEvent(createSchedulerTask(SCHEDULER_MINTICKS, std::bind(&GlobalEvents::think, this)));
}
return true;
}
}
SPDLOG_WARN("[GlobalEvents::configureEvent] - "
"Duplicate registered globalevent with name: {}", globalEvent->getName());
return false;
}
bool GlobalEvents::registerLuaEvent(GlobalEvent* event) {
GlobalEvent_ptr globalEvent{ event };
if (globalEvent->getEventType() == GLOBALEVENT_TIMER) {
auto result = timerMap.emplace(globalEvent->getName(), std::move(*globalEvent));
if (result.second) {
if (timerEventId == 0) {
timerEventId = g_scheduler().addEvent(createSchedulerTask(SCHEDULER_MINTICKS, std::bind(&GlobalEvents::timer, this)));
}
return true;
}
} else if (globalEvent->getEventType() != GLOBALEVENT_NONE) {
auto result = serverMap.emplace(globalEvent->getName(), std::move(*globalEvent));
if (result.second) {
return true;
}
} else { // think event
auto result = thinkMap.emplace(globalEvent->getName(), std::move(*globalEvent));
if (result.second) {
if (thinkEventId == 0) {
thinkEventId = g_scheduler().addEvent(createSchedulerTask(SCHEDULER_MINTICKS, std::bind(&GlobalEvents::think, this)));
}
return true;
}
}
SPDLOG_WARN("Duplicate registered globalevent with name: {}", globalEvent->getName());
return false;
}
void GlobalEvents::startup() const {
execute(GLOBALEVENT_STARTUP);
}
void GlobalEvents::timer() {
time_t now = time(nullptr);
int64_t nextScheduledTime = std::numeric_limits<int64_t>::max();
auto it = timerMap.begin();
while (it != timerMap.end()) {
GlobalEvent& globalEvent = it->second;
int64_t nextExecutionTime = globalEvent.getNextExecution() - now;
if (nextExecutionTime > 0) {
if (nextExecutionTime < nextScheduledTime) {
nextScheduledTime = nextExecutionTime;
}
++it;
continue;
}
if (!globalEvent.executeEvent()) {
it = timerMap.erase(it);
continue;
}
nextExecutionTime = 86400;
if (nextExecutionTime < nextScheduledTime) {
nextScheduledTime = nextExecutionTime;
}
globalEvent.setNextExecution(globalEvent.getNextExecution() + nextExecutionTime);
++it;
}
if (nextScheduledTime != std::numeric_limits<int64_t>::max()) {
timerEventId = g_scheduler().addEvent(createSchedulerTask(std::max<int64_t>(1000, nextScheduledTime * 1000),
std::bind(&GlobalEvents::timer, this)));
}
}
void GlobalEvents::think() {
int64_t now = OTSYS_TIME();
int64_t nextScheduledTime = std::numeric_limits<int64_t>::max();
for (auto& it : thinkMap) {
GlobalEvent& globalEvent = it.second;
int64_t nextExecutionTime = globalEvent.getNextExecution() - now;
if (nextExecutionTime > 0) {
if (nextExecutionTime < nextScheduledTime) {
nextScheduledTime = nextExecutionTime;
}
continue;
}
if (!globalEvent.executeEvent()) {
SPDLOG_ERROR("[GlobalEvents::think] - "
"Failed to execute event: {}", globalEvent.getName());
}
nextExecutionTime = globalEvent.getInterval();
if (nextExecutionTime < nextScheduledTime) {
nextScheduledTime = nextExecutionTime;
}
globalEvent.setNextExecution(globalEvent.getNextExecution() + nextExecutionTime);
}
if (nextScheduledTime != std::numeric_limits<int64_t>::max()) {
thinkEventId = g_scheduler().addEvent(createSchedulerTask(nextScheduledTime, std::bind(&GlobalEvents::think, this)));
}
}
void GlobalEvents::execute(GlobalEvent_t type) const {
for (const auto& it : serverMap) {
const GlobalEvent& globalEvent = it.second;
if (globalEvent.getEventType() == type) {
globalEvent.executeEvent();
}
}
}
GlobalEventMap GlobalEvents::getEventMap(GlobalEvent_t type) {
// TODO: This should be better implemented. Maybe have a map for every type.
switch (type) {
case GLOBALEVENT_NONE: return thinkMap;
case GLOBALEVENT_TIMER: return timerMap;
case GLOBALEVENT_PERIODCHANGE:
case GLOBALEVENT_STARTUP:
case GLOBALEVENT_SHUTDOWN:
case GLOBALEVENT_RECORD: {
GlobalEventMap retMap;
for (const auto& it : serverMap) {
if (it.second.getEventType() == type) {
retMap.emplace(it.first, it.second);
}
}
return retMap;
}
default: return GlobalEventMap();
}
}
GlobalEvent::GlobalEvent(LuaScriptInterface* interface) : Event(interface) {}
bool GlobalEvent::configureEvent(const pugi::xml_node& node) {
pugi::xml_attribute nameAttribute = node.attribute("name");
if (!nameAttribute) {
SPDLOG_ERROR("[GlobalEvent::configureEvent] - Missing name for a globalevent");
return false;
}
name = nameAttribute.as_string();
eventType = GLOBALEVENT_NONE;
pugi::xml_attribute attr;
if ((attr = node.attribute("time"))) {
std::vector<int32_t> params = vectorAtoi(explodeString(attr.as_string(), ":"));
int32_t hour = params.front();
if (hour < 0 || hour > 23) {
SPDLOG_ERROR("[GlobalEvent::configureEvent] - "
"Invalid hour {} for globalevent with name: {}", attr.as_string(), name);
return false;
}
interval |= hour << 16;
int32_t min = 0;
int32_t sec = 0;
if (params.size() > 1) {
min = params[1];
if (min < 0 || min > 59) {
SPDLOG_ERROR("[GlobalEvent::configureEvent] - "
"Invalid minute {} for globalevent with name: {}",
attr.as_string(), name);
return false;
}
if (params.size() > 2) {
sec = params[2];
if (sec < 0 || sec > 59) {
SPDLOG_ERROR("[GlobalEvent::configureEvent] - "
"Invalid second {} for globalevent with name: {}",
attr.as_string(), name);
return false;
}
}
}
time_t current_time = time(nullptr);
tm* timeinfo = localtime(¤t_time);
timeinfo->tm_hour = hour;
timeinfo->tm_min = min;
timeinfo->tm_sec = sec;
time_t difference = static_cast<time_t>(difftime(mktime(timeinfo), current_time));
if (difference < 0) {
difference += 86400;
}
nextExecution = current_time + difference;
eventType = GLOBALEVENT_TIMER;
} else if ((attr = node.attribute("type"))) {
const char* value = attr.value();
if (strcasecmp(value, "startup") == 0) {
eventType = GLOBALEVENT_STARTUP;
} else if (strcasecmp(value, "shutdown") == 0) {
eventType = GLOBALEVENT_SHUTDOWN;
} else if (strcasecmp(value, "record") == 0) {
eventType = GLOBALEVENT_RECORD;
} else {
SPDLOG_ERROR("[GlobalEvent::configureEvent] - "
"No valid type {} for globalevent with name: {}",
attr.as_string(), name);
return false;
}
} else if ((attr = node.attribute("interval"))) {
interval = std::max<int32_t>(SCHEDULER_MINTICKS, pugi::cast<int32_t>(attr.value()));
nextExecution = OTSYS_TIME() + interval;
} else {
SPDLOG_ERROR("[GlobalEvent::configureEvent] - "
"No interval for globalevent with name: {}", name);
return false;
}
return true;
}
std::string GlobalEvent::getScriptEventName() const {
switch (eventType) {
case GLOBALEVENT_STARTUP: return "onStartup";
case GLOBALEVENT_SHUTDOWN: return "onShutdown";
case GLOBALEVENT_RECORD: return "onRecord";
case GLOBALEVENT_TIMER: return "onTime";
case GLOBALEVENT_PERIODCHANGE: return "onPeriodChange";
default: return "onThink";
}
}
bool GlobalEvent::executePeriodChange(LightState_t lightState, LightInfo lightInfo) {
//onPeriodChange(lightState, lightTime)
if (!scriptInterface->reserveScriptEnv()) {
SPDLOG_ERROR("[GlobalEvent::executePeriodChange - {}] "
"Call stack overflow. Too many lua script calls being nested.",
getName());
return false;
}
ScriptEnvironment* env = scriptInterface->getScriptEnv();
env->setScriptId(scriptId, scriptInterface);
lua_State* L = scriptInterface->getLuaState();
scriptInterface->pushFunction(scriptId);
lua_pushnumber(L, lightState);
lua_pushnumber(L, lightInfo.level);
return scriptInterface->callFunction(2);
}
bool GlobalEvent::executeRecord(uint32_t current, uint32_t old) {
//onRecord(current, old)
if (!scriptInterface->reserveScriptEnv()) {
SPDLOG_ERROR("[GlobalEvent::executeRecord - {}] "
"Call stack overflow. Too many lua script calls being nested.",
getName());
return false;
}
ScriptEnvironment* env = scriptInterface->getScriptEnv();
env->setScriptId(scriptId, scriptInterface);
lua_State* L = scriptInterface->getLuaState();
scriptInterface->pushFunction(scriptId);
lua_pushnumber(L, current);
lua_pushnumber(L, old);
return scriptInterface->callFunction(2);
}
bool GlobalEvent::executeEvent() const {
if (!scriptInterface->reserveScriptEnv()) {
SPDLOG_ERROR("[GlobalEvent::executeEvent - {}] "
"Call stack overflow. Too many lua script calls being nested.",
getName());
return false;
}
ScriptEnvironment* env = scriptInterface->getScriptEnv();
env->setScriptId(scriptId, scriptInterface);
lua_State* L = scriptInterface->getLuaState();
scriptInterface->pushFunction(scriptId);
int32_t params = 0;
if (eventType == GLOBALEVENT_NONE || eventType == GLOBALEVENT_TIMER) {
lua_pushnumber(L, interval);
params = 1;
}
return scriptInterface->callFunction(params);
}
|
//*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include "gtest/gtest.h"
#include "ngraph/ngraph.hpp"
#include "ngraph/runtime/tensor.hpp"
#include "runtime/backend.hpp"
#include "util/all_close.hpp"
#include "util/all_close_f.hpp"
#include "util/known_element_types.hpp"
#include "util/ndarray.hpp"
#include "util/test_control.hpp"
#include "util/test_tools.hpp"
using namespace std;
using namespace ngraph;
static string s_manifest = "${MANIFEST}";
NGRAPH_TEST(${BACKEND_NAME}, quantized_dot_u8u8)
{
Shape shape_a{1, 2}; // input shape
vector<uint8_t> a_data = {2, 3};
Shape shape_b{2, 3}; // filter shape
vector<uint8_t> b_data = {0, 2, 4, 1, 3, 5};
auto A = make_shared<op::Parameter>(element::u8, shape_a);
auto B = make_shared<op::Parameter>(element::u8, shape_b);
auto input_scale = op::Constant::create(element::f32, Shape{}, {2});
auto input_zero_point = op::Constant::create(element::u8, Shape{}, {0});
auto filter_scale = op::Constant::create(element::f32, Shape{}, {1});
auto filter_zero_point = op::Constant::create(element::u8, Shape{}, {0});
auto output_scale = op::Constant::create(element::f32, Shape{}, {2});
auto output_zero_point = op::Constant::create(element::u8, Shape{}, {0});
AxisSet axes{};
Shape shape_r{1, 3}; // output shape
auto QD = make_shared<op::QuantizedDot>(A,
B,
1,
input_scale,
input_zero_point,
filter_scale,
filter_zero_point,
output_scale,
output_zero_point,
element::u8,
axes,
axes,
axes);
auto f = make_shared<Function>(NodeVector{QD}, ParameterVector{A, B});
auto backend = runtime::Backend::create("${BACKEND_NAME}");
// Create some tensors for input/output
auto a = backend->create_tensor(element::u8, shape_a);
copy_data(a, a_data);
auto b = backend->create_tensor(element::u8, shape_b);
copy_data(b, b_data);
auto result = backend->create_tensor(element::u8, shape_r);
auto handle = backend->compile(f);
handle->call_with_validate({result}, {a, b});
EXPECT_EQ((vector<uint8_t>{3, 13, 23}), read_vector<uint8_t>(result));
}
NGRAPH_TEST(${BACKEND_NAME}, quantized_dot_int32_output)
{
Shape shape_a{1, 2}; // input shape
vector<uint8_t> a_data = {2, 3};
Shape shape_b{2, 3}; // filter shape
vector<int8_t> b_data = {0, 1, 2, 3, 4, 5};
auto A = make_shared<op::Parameter>(element::u8, shape_a);
auto B = make_shared<op::Parameter>(element::i8, shape_b);
auto input_scale = op::Constant::create(element::f32, Shape{}, {1});
auto input_zero_point = op::Constant::create(element::u8, Shape{}, {0});
auto filter_scale = op::Constant::create(element::f32, Shape{}, {1});
auto filter_zero_point = op::Constant::create(element::i8, Shape{}, {0});
auto output_scale = op::Constant::create(element::f32, Shape{}, {1});
auto output_zero_point = op::Constant::create(element::i32, Shape{}, {0});
AxisSet axes{};
Shape shape_r{1, 3}; // output shape
auto QD = make_shared<op::QuantizedDot>(A,
B,
1,
input_scale,
input_zero_point,
filter_scale,
filter_zero_point,
output_scale,
output_zero_point,
element::i32,
axes,
axes,
axes);
auto f = make_shared<Function>(NodeVector{QD}, ParameterVector{A, B});
auto backend = runtime::Backend::create("${BACKEND_NAME}");
// Create some tensors for input/output
auto a = backend->create_tensor(element::u8, shape_a);
copy_data(a, a_data);
auto b = backend->create_tensor(element::i8, shape_b);
copy_data(b, b_data);
auto result = backend->create_tensor(element::i32, shape_r);
auto handle = backend->compile(f);
handle->call_with_validate({result}, {a, b});
EXPECT_EQ((vector<int32_t>{9, 14, 19}), read_vector<int32_t>(result));
}
|
#include "Mesh.h"
#include "numeric_tools.h"
#include <algorithm>
#include <iostream>
using namespace Eigen;
using namespace Numerics;
void Mesh::setMeshKind(GeomKind kind)
{
m_mode = kind;
pm_abGeom = AbstractGeometry::setGeometry(kind);
}
// From cm to m
void Mesh::setBoundaries(VectorXd &boundaries)
{
m_boundaries = boundaries;
m_meshNumber = m_boundaries.size() - 1;
}
// From cm to m
void Mesh::setBoundaries(double cellSide, unsigned meshNumber)
{
m_boundaries = VectorXd::Zero(meshNumber + 1);
for(unsigned i = 0; i <= meshNumber; i++)
{
m_boundaries(i) = i * (cellSide / meshNumber);
}
m_meshNumber = meshNumber;
}
VectorXd Mesh::getVolumes(std::string dim)
{
VectorXd empty = VectorXd::Zero(1);
if(pm_abGeom != nullptr)
{
return pm_abGeom->volumes(m_boundaries, dim);
}
else
{
return empty;
}
}
VectorXd Mesh::getSurfaces(std::string dim)
{
VectorXd empty = VectorXd::Zero(1);
if(pm_abGeom != nullptr)
{
return pm_abGeom->surfaces(m_boundaries, dim);
}
else
{
return empty;
}
}
double Mesh::getExternalSurface(std::string dim)
{
if(pm_abGeom != nullptr)
{
return pm_abGeom->externalSurface(m_boundaries, dim);
}
else
{
return 0.0;
}
}
void Mesh::setTemperatures(std::vector<double> &temperatures)
{
for(size_t i = 0; i < temperatures.size(); i++)
{
m_materials[i]->setTemperature(temperatures[i]);
}
}
void Mesh::setTemperatures(VectorXd &temperatures)
{
for(int i = 0; i < temperatures.size(); i++)
{
m_materials[i]->setTemperature(temperatures[i]);
}
}
VectorXd Mesh::getTemperatures(std::string dim)
{
VectorXd result = VectorXd::Zero(m_meshNumber);
for(size_t i = 0; i < m_meshNumber; i++)
{
result[i] = m_materials[i]->getTemperature();
}
if(dim == "C")
{
return result;
}
else if(dim == "K")
{
return result + 273.15;
}
else
{
return result * -1.0;
}
}
void Mesh::setHeatSources(const VectorXd &sources)
{
for(int i = 0; i < sources.size(); i++)
{
m_materials[i]->setHeatSource(sources(i));
}
}
void Mesh::setHeatSources(std::vector<double> &sources)
{
for(size_t i = 0; i < sources.size(); i++)
{
m_materials[i]->setHeatSource(sources[i]);
}
}
VectorXd Mesh::getHeatSources()
{
VectorXd result = VectorXd::Zero(m_meshNumber);
for(size_t i = 0; i < m_meshNumber; i++)
{
result[i] = m_materials[i]->getHeatSource();
}
return result;
}
VectorXd Mesh::getBoundaries(std::string dim)
{
if(dim == "m")
return m_boundaries;
else if(dim == "cm")
return m_boundaries * 100.0;
else
return m_boundaries * -1.0;
}
VectorXd Mesh::getMeshMiddlePoints()
{
VectorXd result = VectorXd::Zero(m_boundaries.size() - 1);
for(int i = 0; i < result.size(); i++)
result(i) = (m_boundaries(i) + m_boundaries(i + 1)) / 2.0;
return result;
}
void Mesh::createMaterials(std::vector<std::string> materialMap)
{
m_materials.resize(m_meshNumber);
for(unsigned i = 0; i < m_meshNumber; i++)
{
m_materials[i] = std::make_shared<Material>(materialMap[i]);
}
}
void Mesh::setEnergyGroupsNumber(unsigned n)
{
m_energyGroupsNumber = n;
for(unsigned i = 0; i < m_meshNumber; i++)
{
m_materials[i]->setEnergies(n);
}
}
void Mesh::setThermalConductivityLaw(unsigned i, std::vector<std::string> &strVec)
{
m_materials[i]->setThermalConductivityLaw(strVec);
}
Eigen::VectorXd Mesh::getThermalConductivities()
{
VectorXd result = VectorXd::Zero(m_meshNumber);
for(size_t i = 0; i < m_meshNumber; i++)
{
result[i] = m_materials[i]->getThermalConductivity();
}
return result;
}
VectorXd Mesh::getCellSizes(std::string dim)
{
VectorXd result = VectorXd::Zero(m_meshNumber);
for(size_t i = 0; i < m_meshNumber; i++)
{
result[i] = m_boundaries[i + 1] - m_boundaries[i];
}
if(dim == "m")
return result;
else if(dim == "cm")
return result * 100.0;
else
return result * -1.0;
}
MatrixXd Mesh::getNis()
{
MatrixXd nis = MatrixXd::Zero(m_energyGroupsNumber, m_meshNumber);
VectorXd ni = VectorXd::Zero(m_energyGroupsNumber);
for(int m = 0; m < static_cast<int>(m_meshNumber); m++)
{
ni = m_materials[m]->getNi();
for(int i = 0; i < static_cast<int>(m_energyGroupsNumber); i++)
{
nis(i, m) = ni(i);
}
}
return nis;
}
MatrixXd Mesh::getChis()
{
MatrixXd chis = MatrixXd::Zero(m_energyGroupsNumber, m_meshNumber);
VectorXd chi = VectorXd::Zero(m_energyGroupsNumber);
for(int m = 0; m < static_cast<int>(m_meshNumber); m++)
{
chi = m_materials[m]->getChi();
for(int i = 0; i < static_cast<int>(m_energyGroupsNumber); i++)
{
chis(i, m) = chi(i);
}
}
return chis;
}
MatrixXd Mesh::getTotalXSs()
{
MatrixXd tots = MatrixXd::Zero(m_energyGroupsNumber, m_meshNumber);
VectorXd tot = VectorXd::Zero(m_energyGroupsNumber);
for(int m = 0; m < static_cast<int>(m_meshNumber); m++)
{
tot = m_materials[m]->getTotalXS();
for(int i = 0; i < static_cast<int>(m_energyGroupsNumber); i++)
{
tots(i, m) = tot(i);
}
}
return tots;
}
MatrixXd Mesh::getDiffusionConstants()
{
MatrixXd diffs = MatrixXd::Zero(m_energyGroupsNumber, m_meshNumber);
VectorXd diff = VectorXd::Zero(m_energyGroupsNumber);
for(int m = 0; m < static_cast<int>(m_meshNumber); m++)
{
diff = m_materials[m]->getDiffusionConstants();
for(int i = 0; i < static_cast<int>(m_energyGroupsNumber); i++)
{
diffs(i, m) = diff(i);
}
}
return diffs;
}
MatrixXd Mesh::getFissionXSs()
{
MatrixXd fiss = MatrixXd::Zero(m_energyGroupsNumber, m_meshNumber);
VectorXd fis = VectorXd::Zero(m_energyGroupsNumber);
for(int m = 0; m < static_cast<int>(m_meshNumber); m++)
{
fis = m_materials[m]->getFissionXS();
for(int i = 0; i < static_cast<int>(m_energyGroupsNumber); i++)
{
fiss(i, m) = fis(i);
}
}
return fiss;
}
MatrixXd Mesh::getRemovalXSs()
{
MatrixXd rem = MatrixXd::Zero(m_energyGroupsNumber, m_meshNumber);
MatrixXd tot = getTotalXSs();
Tensor3d scatt = getScattMatrices();
for(int m = 0; m < static_cast<int>(m_meshNumber); m++)
{
for(int i = 0; i < static_cast<int>(m_energyGroupsNumber); i++)
{
rem(i, m) = tot(i, m) - scatt(i, i, m);
}
}
return rem;
}
Tensor3d Mesh::getScattMatrices()
{
Tensor3d scatts(m_energyGroupsNumber, m_energyGroupsNumber, m_meshNumber);
MatrixXd scatt = MatrixXd::Zero(m_energyGroupsNumber, m_energyGroupsNumber);
for(int m = 0; m < static_cast<int>(m_meshNumber); m++)
{
scatt = m_materials[m]->getScattMatrix();
for(int i = 0; i < static_cast<int>(m_energyGroupsNumber); i++)
{
for(int j = 0; j < static_cast<int>(m_energyGroupsNumber); j++)
{
scatts(i, j, m) = scatt(i, j);
}
}
}
return scatts;
}
void Mesh::setNeutronFluxes(Eigen::MatrixXd &neutronFluxes)
{
for(int m = 0; m < static_cast<int>(m_meshNumber); m++)
{
m_materials[m]->setNeutronFlux(neutronFluxes.col(m));
}
}
MatrixXd Mesh::getNeutronFluxes()
{
MatrixXd neutronFluxes = MatrixXd::Zero(m_energyGroupsNumber, m_meshNumber);
VectorXd neutronFlux = VectorXd::Zero(m_energyGroupsNumber);
for(int m = 0; m < static_cast<int>(m_meshNumber); m++)
{
neutronFlux = m_materials[m]->getNeutronFlux();
for(int i = 0; i < static_cast<int>(m_energyGroupsNumber); i++)
{
neutronFluxes(i, m) = neutronFlux(i);
}
}
return neutronFluxes;
}
|
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtNetwork module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qlocalsocket.h"
#include "qlocalsocket_p.h"
#ifndef QT_NO_LOCALSOCKET
QT_BEGIN_NAMESPACE
/*!
\class QLocalSocket
\since 4.4
\inmodule QtNetwork
\brief The QLocalSocket class provides a local socket.
On Windows this is a named pipe and on Unix this is a local domain socket.
If an error occurs, socketError() returns the type of error, and
errorString() can be called to get a human readable description
of what happened.
Although QLocalSocket is designed for use with an event loop, it's possible
to use it without one. In that case, you must use waitForConnected(),
waitForReadyRead(), waitForBytesWritten(), and waitForDisconnected()
which blocks until the operation is complete or the timeout expires.
\note This feature is not supported on versions of Windows earlier than
Windows XP.
\sa QLocalServer
*/
/*!
\fn void QLocalSocket::connectToServer(OpenMode openMode)
\since 5.1
Attempts to make a connection to serverName().
setServerName() must be called before you open the connection.
Alternatively you can use connectToServer(const QString &name, OpenMode openMode);
The socket is opened in the given \a openMode and first enters ConnectingState.
If a connection is established, QLocalSocket enters ConnectedState and emits connected().
After calling this function, the socket can emit error() to signal that an error occurred.
\sa state(), serverName(), waitForConnected()
*/
/*!
\fn void QLocalSocket::open(OpenMode openMode)
Equivalent to connectToServer(OpenMode mode).
The socket is opened in the given \a openMode to the server defined by setServerName().
Note that unlike in most other QIODevice subclasses, open() may not open the device directly.
The function return false if the socket was already connected or if the server to connect
to was not defined and true in any other case. The connected() or error() signals will be
emitted once the device is actualy open (or the connection failed).
See connectToServer() for more details.
*/
/*!
\fn void QLocalSocket::connected()
This signal is emitted after connectToServer() has been called and
a connection has been successfully established.
\sa connectToServer(), disconnected()
*/
/*!
\fn bool QLocalSocket::setSocketDescriptor(qintptr socketDescriptor,
LocalSocketState socketState, OpenMode openMode)
Initializes QLocalSocket with the native socket descriptor
\a socketDescriptor. Returns \c true if socketDescriptor is accepted
as a valid socket descriptor; otherwise returns \c false. The socket is
opened in the mode specified by \a openMode, and enters the socket state
specified by \a socketState.
\note It is not possible to initialize two local sockets with the same
native socket descriptor.
\sa socketDescriptor(), state(), openMode()
*/
/*!
\fn qintptr QLocalSocket::socketDescriptor() const
Returns the native socket descriptor of the QLocalSocket object if
this is available; otherwise returns -1.
The socket descriptor is not available when QLocalSocket
is in UnconnectedState.
\sa setSocketDescriptor()
*/
/*!
\fn qint64 QLocalSocket::readData(char *data, qint64 c)
\reimp
*/
/*!
\fn qint64 QLocalSocket::writeData(const char *data, qint64 c)
\reimp
*/
/*!
\fn void QLocalSocket::abort()
Aborts the current connection and resets the socket.
Unlike disconnectFromServer(), this function immediately closes the socket,
clearing any pending data in the write buffer.
\sa disconnectFromServer(), close()
*/
/*!
\fn qint64 QLocalSocket::bytesAvailable() const
\reimp
*/
/*!
\fn qint64 QLocalSocket::bytesToWrite() const
\reimp
*/
/*!
\fn bool QLocalSocket::canReadLine() const
\reimp
*/
/*!
\fn void QLocalSocket::close()
\reimp
*/
/*!
\fn bool QLocalSocket::waitForBytesWritten(int msecs)
\reimp
*/
/*!
\fn bool QLocalSocket::flush()
This function writes as much as possible from the internal write buffer
to the socket, without blocking. If any data was written, this function
returns \c true; otherwise false is returned.
Call this function if you need QLocalSocket to start sending buffered data
immediately. The number of bytes successfully written depends on the
operating system. In most cases, you do not need to call this function,
because QLocalSocket will start sending data automatically once control
goes back to the event loop. In the absence of an event loop, call
waitForBytesWritten() instead.
\sa write(), waitForBytesWritten()
*/
/*!
\fn void QLocalSocket::disconnectFromServer()
Attempts to close the socket. If there is pending data waiting to be
written, QLocalSocket will enter ClosingState and wait until all data
has been written. Eventually, it will enter UnconnectedState and emit
the disconnectedFromServer() signal.
\sa connectToServer()
*/
/*!
\fn QLocalSocket::LocalSocketError QLocalSocket::error() const
Returns the type of error that last occurred.
\sa state(), errorString()
*/
/*!
\fn bool QLocalSocket::isValid() const
Returns \c true if the socket is valid and ready for use; otherwise
returns \c false.
\note The socket's state must be ConnectedState before reading
and writing can occur.
\sa state(), connectToServer()
*/
/*!
\fn qint64 QLocalSocket::readBufferSize() const
Returns the size of the internal read buffer. This limits the amount of
data that the client can receive before you call read() or readAll().
A read buffer size of 0 (the default) means that the buffer has no size
limit, ensuring that no data is lost.
\sa setReadBufferSize(), read()
*/
/*!
\fn void QLocalSocket::setReadBufferSize(qint64 size)
Sets the size of QLocalSocket's internal read buffer to be \a size bytes.
If the buffer size is limited to a certain size, QLocalSocket won't
buffer more than this size of data. Exceptionally, a buffer size of 0
means that the read buffer is unlimited and all incoming data is buffered.
This is the default.
This option is useful if you only read the data at certain points in
time (e.g., in a real-time streaming application) or if you want to
protect your socket against receiving too much data, which may eventually
cause your application to run out of memory.
\sa readBufferSize(), read()
*/
/*!
\fn bool QLocalSocket::waitForConnected(int msecs)
Waits until the socket is connected, up to \a msecs milliseconds. If the
connection has been established, this function returns \c true; otherwise
it returns \c false. In the case where it returns \c false, you can call
error() to determine the cause of the error.
The following example waits up to one second for a connection
to be established:
\snippet code/src_network_socket_qlocalsocket_unix.cpp 0
If \a msecs is -1, this function will not time out.
\sa connectToServer(), connected()
*/
/*!
\fn bool QLocalSocket::waitForDisconnected(int msecs)
Waits until the socket has disconnected, up to \a msecs
milliseconds. If the connection has been disconnected, this
function returns \c true; otherwise it returns \c false. In the case
where it returns \c false, you can call error() to determine
the cause of the error.
The following example waits up to one second for a connection
to be closed:
\snippet code/src_network_socket_qlocalsocket_unix.cpp 1
If \a msecs is -1, this function will not time out.
\sa disconnectFromServer(), close()
*/
/*!
\fn bool QLocalSocket::waitForReadyRead(int msecs)
This function blocks until data is available for reading and the
\l{QIODevice::}{readyRead()} signal has been emitted. The function
will timeout after \a msecs milliseconds; the default timeout is
30000 milliseconds.
The function returns \c true if data is available for reading;
otherwise it returns \c false (if an error occurred or the
operation timed out).
\sa waitForBytesWritten()
*/
/*!
\fn void QLocalSocket::disconnected()
This signal is emitted when the socket has been disconnected.
\sa connectToServer(), disconnectFromServer(), abort(), connected()
*/
/*!
\fn void QLocalSocket::error(QLocalSocket::LocalSocketError socketError)
This signal is emitted after an error occurred. The \a socketError
parameter describes the type of error that occurred.
QLocalSocket::LocalSocketError is not a registered metatype, so for queued
connections, you will have to register it with Q_DECLARE_METATYPE() and
qRegisterMetaType().
\sa error(), errorString(), {Creating Custom Qt Types}
*/
/*!
\fn void QLocalSocket::stateChanged(QLocalSocket::LocalSocketState socketState)
This signal is emitted whenever QLocalSocket's state changes.
The \a socketState parameter is the new state.
QLocalSocket::SocketState is not a registered metatype, so for queued
connections, you will have to register it with Q_DECLARE_METATYPE() and
qRegisterMetaType().
\sa state(), {Creating Custom Qt Types}
*/
/*!
Creates a new local socket. The \a parent argument is passed to
QObject's constructor.
*/
QLocalSocket::QLocalSocket(QObject * parent)
: QIODevice(*new QLocalSocketPrivate, parent)
{
Q_D(QLocalSocket);
d->init();
}
/*!
Destroys the socket, closing the connection if necessary.
*/
QLocalSocket::~QLocalSocket()
{
close();
#if !defined(Q_OS_WIN) && !defined(QT_LOCALSOCKET_TCP)
Q_D(QLocalSocket);
d->unixSocket.setParent(0);
#endif
}
bool QLocalSocket::open(OpenMode openMode)
{
connectToServer(openMode);
return isOpen();
}
/*! \overload
Set the server \a name and attempts to make a connection to it.
The socket is opened in the given \a openMode and first enters ConnectingState.
If a connection is established, QLocalSocket enters ConnectedState and emits connected().
After calling this function, the socket can emit error() to signal that an error occurred.
\sa state(), serverName(), waitForConnected()
*/
void QLocalSocket::connectToServer(const QString &name, OpenMode openMode)
{
setServerName(name);
connectToServer(openMode);
}
/*!
\since 5.1
Set the \a name of the peer to connect to.
On Windows name is the name of a named pipe; on Unix name is the name of a local domain socket.
This function must be called when the socket is not connected.
*/
void QLocalSocket::setServerName(const QString & name)
{
Q_D(QLocalSocket);
if (d->state != UnconnectedState) {
qWarning("QLocalSocket::setServerName() called while not in unconnected state");
return;
}
d->serverName = name;
}
/*!
Returns the name of the peer as specified by setServerName(), or an
empty QString if setServerName() has not been called or connectToServer() failed.
\sa connectToServer(), fullServerName()
*/
QString QLocalSocket::serverName() const
{
Q_D(const QLocalSocket);
return d->serverName;
}
/*!
Returns the server path that the socket is connected to.
\note The return value of this function is platform specific.
\sa connectToServer(), serverName()
*/
QString QLocalSocket::fullServerName() const
{
Q_D(const QLocalSocket);
return d->fullServerName;
}
/*!
Returns the state of the socket.
\sa error()
*/
QLocalSocket::LocalSocketState QLocalSocket::state() const
{
Q_D(const QLocalSocket);
return d->state;
}
/*! \reimp
*/
bool QLocalSocket::isSequential() const
{
return true;
}
/*!
\enum QLocalSocket::LocalSocketError
The LocalServerError enumeration represents the errors that can occur.
The most recent error can be retrieved through a call to
\l QLocalSocket::error().
\value ConnectionRefusedError The connection was refused by
the peer (or timed out).
\value PeerClosedError The remote socket closed the connection.
Note that the client socket (i.e., this socket) will be closed
after the remote close notification has been sent.
\value ServerNotFoundError The local socket name was not found.
\value SocketAccessError The socket operation failed because the
application lacked the required privileges.
\value SocketResourceError The local system ran out of resources
(e.g., too many sockets).
\value SocketTimeoutError The socket operation timed out.
\value DatagramTooLargeError The datagram was larger than the operating
system's limit (which can be as low as 8192 bytes).
\value ConnectionError An error occurred with the connection.
\value UnsupportedSocketOperationError The requested socket operation
is not supported by the local operating system.
\value OperationError An operation was attempted while the socket was in a state that
did not permit it.
\value UnknownSocketError An unidentified error occurred.
*/
/*!
\enum QLocalSocket::LocalSocketState
This enum describes the different states in which a socket can be.
\sa QLocalSocket::state()
\value UnconnectedState The socket is not connected.
\value ConnectingState The socket has started establishing a connection.
\value ConnectedState A connection is established.
\value ClosingState The socket is about to close
(data may still be waiting to be written).
*/
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug debug, QLocalSocket::LocalSocketError error)
{
switch (error) {
case QLocalSocket::ConnectionRefusedError:
debug << "QLocalSocket::ConnectionRefusedError";
break;
case QLocalSocket::PeerClosedError:
debug << "QLocalSocket::PeerClosedError";
break;
case QLocalSocket::ServerNotFoundError:
debug << "QLocalSocket::ServerNotFoundError";
break;
case QLocalSocket::SocketAccessError:
debug << "QLocalSocket::SocketAccessError";
break;
case QLocalSocket::SocketResourceError:
debug << "QLocalSocket::SocketResourceError";
break;
case QLocalSocket::SocketTimeoutError:
debug << "QLocalSocket::SocketTimeoutError";
break;
case QLocalSocket::DatagramTooLargeError:
debug << "QLocalSocket::DatagramTooLargeError";
break;
case QLocalSocket::ConnectionError:
debug << "QLocalSocket::ConnectionError";
break;
case QLocalSocket::UnsupportedSocketOperationError:
debug << "QLocalSocket::UnsupportedSocketOperationError";
break;
case QLocalSocket::UnknownSocketError:
debug << "QLocalSocket::UnknownSocketError";
break;
default:
debug << "QLocalSocket::SocketError(" << int(error) << ')';
break;
}
return debug;
}
QDebug operator<<(QDebug debug, QLocalSocket::LocalSocketState state)
{
switch (state) {
case QLocalSocket::UnconnectedState:
debug << "QLocalSocket::UnconnectedState";
break;
case QLocalSocket::ConnectingState:
debug << "QLocalSocket::ConnectingState";
break;
case QLocalSocket::ConnectedState:
debug << "QLocalSocket::ConnectedState";
break;
case QLocalSocket::ClosingState:
debug << "QLocalSocket::ClosingState";
break;
default:
debug << "QLocalSocket::SocketState(" << int(state) << ')';
break;
}
return debug;
}
#endif
QT_END_NAMESPACE
#endif
#include "moc_qlocalsocket.cpp"
|
// -*- Mode: C++; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-
#include "logic_inb.h"
#include "app_class.h"
#include "tokenizer.h"
#include "servant_utils.h"
namespace LogicService {
Yb::ElementTree::ElementPtr ping(
Yb::Session &session, Yb::ILogger &logger,
const Yb::StringDict ¶ms)
{
session.engine()->exec_select("select 1 from dual", Yb::Values());
Yb::ElementTree::ElementPtr resp = mk_resp("success");
return resp;
}
Yb::ElementTree::ElementPtr check_kek(
Yb::Session &session, Yb::ILogger &logger,
const Yb::StringDict ¶ms)
{
Yb::ElementTree::ElementPtr resp = mk_resp("success");
#ifdef TOKENIZER_CONFIG_SINGLETON
TokenizerConfig &tcfg(theTokenizerConfig::instance().refresh());
#else
TokenizerConfig tcfg;
#endif
std::string ver = params.get("kek_version", "");
int kek_version = -1;
if (ver.empty())
kek_version = tcfg.get_active_master_key_version();
else
kek_version = boost::lexical_cast<int>(ver);
resp->sub_element("check_kek",
tcfg.is_kek_valid(kek_version)? "true": "false");
return resp;
}
} // LogicService
// vim:ts=4:sts=4:sw=4:et:
|
/* ================================================================
*
* AtlasWerks Project
*
* Copyright (c) Sarang C. Joshi, Bradley C. Davis, J. Samuel Preston,
* Linh K. Ha. All rights reserved. See Copyright.txt or for details.
*
* This software is distributed WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the above copyright notice for more information.
*
* ================================================================ */
#include <cmath>
#include "AtlasWerksTypes.h"
#include "Array3D.h"
#include "Array3DUtils.h"
#include "ImageUtils.h"
#include "ApplicationUtils.h"
#include "HField3DUtils.h"
#include "ImageUtils.h"
#include <tclap/CmdLine.h>
int main(int argc, char *argv[]){
try
{
TCLAP::CmdLine cmd("ExtractROI");
TCLAP::ValueArg<std::string>
originArg("o","origin",
"origin (in world coordinates) of the start of the ROI, specify as -o ox,oy,oz",
true,"","float x 3", cmd);
TCLAP::ValueArg<std::string>
sizeArg("s","size",
"size, in pixels, of the ROI, specify as -s sx,sy,sz",
true,"","int x 3", cmd);
TCLAP::ValueArg<std::string>
spacingArg("p","spacing",
"spacing of output image, defaults to spacing of input. specify as -p sx,sy,sz",
false,"","float x 3", cmd);
TCLAP::ValueArg<float>
backgroundArg("b","background",
"background value to use, zero by default",
false,0,"float", cmd);
TCLAP::UnlabeledValueArg<std::string>
inputImageArg("inputImage",
"image to crop",
true,"","file",cmd);
TCLAP::UnlabeledValueArg<std::string>
outputImageArg("outputImage",
"cropped image",
true,"","file",cmd);
cmd.parse(argc, argv);
SizeType size;
OriginType origin;
SpacingType spacing;
RealImage inputImage;
// Load the input image
ApplicationUtils::LoadImageITK(inputImageArg.getValue().c_str(),
inputImage);
// spacing defaults to input spacing
spacing = inputImage.getSpacing();
// parse vectors
int parsed;
parsed = sscanf(sizeArg.getValue().c_str(), "%u,%u,%u", &(size.x), &(size.y), &(size.z));
if(parsed != 3){
throw AtlasWerksException(__FILE__,__LINE__,"Error, problem reading size vector");
}
std::cout << "Size is " << size << std::endl;
parsed = sscanf(originArg.getValue().c_str(), "%lf,%lf,%lf", &(origin.x), &(origin.y), &(origin.z));
if(parsed != 3){
throw AtlasWerksException(__FILE__,__LINE__,"Error, problem reading origin vector");
}
std::cout << "Origin is " << origin << std::endl;
std::cout << "Spacing arg is " << spacingArg.getValue() << std::endl;
if(spacingArg.isSet()){
parsed = sscanf(spacingArg.getValue().c_str(), "%lf,%lf,%lf", &(spacing.x), &(spacing.y), &(spacing.z));
}
std::cout << "Spacing is " << spacing << std::endl;
RealImage outputImage(size, origin, spacing);
ImageUtils::resampleNew<Real, Array3DUtils::BACKGROUND_STRATEGY_VAL, DEFAULT_SCALAR_INTERP>
(inputImage, outputImage, backgroundArg.getValue());
ApplicationUtils::SaveImageITK(outputImageArg.getValue().c_str(), outputImage);
}
catch (TCLAP::ArgException &e)
{
std::cerr << "error: " << e.error() << " for arg " << e.argId()
<< std::endl;
exit(1);
}
}
|
// Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Nazara Engine - Renderer module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_VULKANRENDERER_VULKANRENDERIMAGE_HPP
#define NAZARA_VULKANRENDERER_VULKANRENDERIMAGE_HPP
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Renderer/RenderImage.hpp>
#include <Nazara/VulkanRenderer/VulkanUploadPool.hpp>
#include <Nazara/VulkanRenderer/Wrapper/CommandBuffer.hpp>
#include <Nazara/VulkanRenderer/Wrapper/CommandPool.hpp>
#include <Nazara/VulkanRenderer/Wrapper/Fence.hpp>
#include <Nazara/VulkanRenderer/Wrapper/Semaphore.hpp>
#include <vector>
namespace Nz
{
class VkRenderWindow;
class NAZARA_VULKANRENDERER_API VulkanRenderImage : public RenderImage
{
public:
VulkanRenderImage(VkRenderWindow& owner);
VulkanRenderImage(const VulkanRenderImage&) = delete;
VulkanRenderImage(VulkanRenderImage&&) noexcept = default;
~VulkanRenderImage();
void Execute(const std::function<void(CommandBufferBuilder& builder)>& callback, QueueTypeFlags queueTypeFlags) override;
inline Vk::Fence& GetInFlightFence();
inline Vk::Semaphore& GetImageAvailableSemaphore();
inline UInt32 GetImageIndex();
inline Vk::Semaphore& GetRenderFinishedSemaphore();
VulkanUploadPool& GetUploadPool() override;
void SubmitCommandBuffer(CommandBuffer* commandBuffer, QueueTypeFlags queueTypeFlags) override;
void SubmitCommandBuffer(VkCommandBuffer commandBuffer, QueueTypeFlags queueTypeFlags);
void Present() override;
inline void Reset(UInt32 imageIndex);
VulkanRenderImage& operator=(const VulkanRenderImage&) = delete;
VulkanRenderImage& operator=(VulkanRenderImage&&) = delete;
private:
std::size_t m_currentCommandBuffer;
std::vector<Vk::AutoCommandBuffer> m_inFlightCommandBuffers;
std::vector<VkCommandBuffer> m_graphicalCommandsBuffers;
VkRenderWindow& m_owner;
Vk::CommandPool m_commandPool;
Vk::Fence m_inFlightFence;
Vk::Semaphore m_imageAvailableSemaphore;
Vk::Semaphore m_renderFinishedSemaphore;
VulkanUploadPool m_uploadPool;
UInt32 m_imageIndex;
};
}
#include <Nazara/VulkanRenderer/VulkanRenderImage.inl>
#endif // NAZARA_VULKANRENDERER_VULKANRENDERIMAGE_HPP
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <rpc/blockchain.h>
#include <amount.h>
#include <blockfilter.h>
#include <chain.h>
#include <chainparams.h>
#include <coins.h>
#include <consensus/validation.h>
#include <core_io.h>
#include <hash.h>
#include <index/blockfilterindex.h>
#include <node/coinstats.h>
#include <node/context.h>
#include <node/utxo_snapshot.h>
#include <policy/feerate.h>
#include <policy/policy.h>
#include <policy/rbf.h>
#include <primitives/transaction.h>
#include <rpc/server.h>
#include <rpc/util.h>
#include <script/descriptor.h>
#include <streams.h>
#include <sync.h>
#include <txdb.h>
#include <txmempool.h>
#include <undo.h>
#include <util/strencodings.h>
#include <util/system.h>
#include <util/validation.h>
#include <validation.h>
#include <validationinterface.h>
#include <warnings.h>
#include <stdint.h>
#include <univalue.h>
#include <condition_variable>
#include <memory>
#include <mutex>
struct CUpdatedBlock
{
uint256 hash;
int height;
};
static Mutex cs_blockchange;
static std::condition_variable cond_blockchange;
static CUpdatedBlock latestblock;
CTxMemPool& EnsureMemPool()
{
CHECK_NONFATAL(g_rpc_node);
if (!g_rpc_node->mempool) {
throw JSONRPCError(RPC_CLIENT_MEMPOOL_DISABLED, "Mempool disabled or instance not found");
}
return *g_rpc_node->mempool;
}
/* Calculate the difficulty for a given block index.
*/
double GetDifficulty(const CBlockIndex* blockindex)
{
CHECK_NONFATAL(blockindex);
int nShift = (blockindex->nBits >> 24) & 0xff;
double dDiff =
(double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
while (nShift < 29)
{
dDiff *= 256.0;
nShift++;
}
while (nShift > 29)
{
dDiff /= 256.0;
nShift--;
}
return dDiff;
}
static int ComputeNextBlockAndDepth(const CBlockIndex* tip, const CBlockIndex* blockindex, const CBlockIndex*& next)
{
next = tip->GetAncestor(blockindex->nHeight + 1);
if (next && next->pprev == blockindex) {
return tip->nHeight - blockindex->nHeight + 1;
}
next = nullptr;
return blockindex == tip ? 1 : -1;
}
UniValue blockheaderToJSON(const CBlockIndex* tip, const CBlockIndex* blockindex)
{
// Serialize passed information without accessing chain state of the active chain!
AssertLockNotHeld(cs_main); // For performance reasons
UniValue result(UniValue::VOBJ);
result.pushKV("hash", blockindex->GetBlockHash().GetHex());
const CBlockIndex* pnext;
int confirmations = ComputeNextBlockAndDepth(tip, blockindex, pnext);
result.pushKV("confirmations", confirmations);
result.pushKV("height", blockindex->nHeight);
result.pushKV("version", blockindex->nVersion);
result.pushKV("versionHex", strprintf("%08x", blockindex->nVersion));
result.pushKV("merkleroot", blockindex->hashMerkleRoot.GetHex());
result.pushKV("time", (int64_t)blockindex->nTime);
result.pushKV("mediantime", (int64_t)blockindex->GetMedianTimePast());
result.pushKV("nonce", (uint64_t)blockindex->nNonce);
result.pushKV("bits", strprintf("%08x", blockindex->nBits));
result.pushKV("difficulty", GetDifficulty(blockindex));
result.pushKV("chainwork", blockindex->nChainWork.GetHex());
result.pushKV("nTx", (uint64_t)blockindex->nTx);
if (blockindex->pprev)
result.pushKV("previousblockhash", blockindex->pprev->GetBlockHash().GetHex());
if (pnext)
result.pushKV("nextblockhash", pnext->GetBlockHash().GetHex());
return result;
}
UniValue blockToJSON(const CBlock& block, const CBlockIndex* tip, const CBlockIndex* blockindex, bool txDetails)
{
// Serialize passed information without accessing chain state of the active chain!
AssertLockNotHeld(cs_main); // For performance reasons
UniValue result(UniValue::VOBJ);
result.pushKV("hash", blockindex->GetBlockHash().GetHex());
const CBlockIndex* pnext;
int confirmations = ComputeNextBlockAndDepth(tip, blockindex, pnext);
result.pushKV("confirmations", confirmations);
result.pushKV("strippedsize", (int)::GetSerializeSize(block, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS));
result.pushKV("size", (int)::GetSerializeSize(block, PROTOCOL_VERSION));
result.pushKV("weight", (int)::GetBlockWeight(block));
result.pushKV("height", blockindex->nHeight);
result.pushKV("version", block.nVersion);
result.pushKV("versionHex", strprintf("%08x", block.nVersion));
result.pushKV("merkleroot", block.hashMerkleRoot.GetHex());
UniValue txs(UniValue::VARR);
for(const auto& tx : block.vtx)
{
if(txDetails)
{
UniValue objTx(UniValue::VOBJ);
TxToUniv(*tx, uint256(), objTx, true, RPCSerializationFlags());
txs.push_back(objTx);
}
else
txs.push_back(tx->GetHash().GetHex());
}
result.pushKV("tx", txs);
result.pushKV("time", block.GetBlockTime());
result.pushKV("mediantime", (int64_t)blockindex->GetMedianTimePast());
result.pushKV("nonce", (uint64_t)block.nNonce);
result.pushKV("bits", strprintf("%08x", block.nBits));
result.pushKV("difficulty", GetDifficulty(blockindex));
result.pushKV("chainwork", blockindex->nChainWork.GetHex());
result.pushKV("nTx", (uint64_t)blockindex->nTx);
if (blockindex->pprev)
result.pushKV("previousblockhash", blockindex->pprev->GetBlockHash().GetHex());
if (pnext)
result.pushKV("nextblockhash", pnext->GetBlockHash().GetHex());
return result;
}
static UniValue getblockcount(const JSONRPCRequest& request)
{
RPCHelpMan{"getblockcount",
"\nReturns the height of the most-work fully-validated chain.\n"
"The genesis block has height 0.\n",
{},
RPCResult{
"n (numeric) The current block count\n"
},
RPCExamples{
HelpExampleCli("getblockcount", "")
+ HelpExampleRpc("getblockcount", "")
},
}.Check(request);
LOCK(cs_main);
return ::ChainActive().Height();
}
static UniValue getbestblockhash(const JSONRPCRequest& request)
{
RPCHelpMan{"getbestblockhash",
"\nReturns the hash of the best (tip) block in the most-work fully-validated chain.\n",
{},
RPCResult{
"\"hex\" (string) the block hash, hex-encoded\n"
},
RPCExamples{
HelpExampleCli("getbestblockhash", "")
+ HelpExampleRpc("getbestblockhash", "")
},
}.Check(request);
LOCK(cs_main);
return ::ChainActive().Tip()->GetBlockHash().GetHex();
}
void RPCNotifyBlockChange(bool ibd, const CBlockIndex * pindex)
{
if(pindex) {
std::lock_guard<std::mutex> lock(cs_blockchange);
latestblock.hash = pindex->GetBlockHash();
latestblock.height = pindex->nHeight;
}
cond_blockchange.notify_all();
}
static UniValue waitfornewblock(const JSONRPCRequest& request)
{
RPCHelpMan{"waitfornewblock",
"\nWaits for a specific new block and returns useful info about it.\n"
"\nReturns the current block on timeout or exit.\n",
{
{"timeout", RPCArg::Type::NUM, /* default */ "0", "Time in milliseconds to wait for a response. 0 indicates no timeout."},
},
RPCResult{
"{ (json object)\n"
" \"hash\" : { (string) The blockhash\n"
" \"height\" : { (int) Block height\n"
"}\n"
},
RPCExamples{
HelpExampleCli("waitfornewblock", "1000")
+ HelpExampleRpc("waitfornewblock", "1000")
},
}.Check(request);
int timeout = 0;
if (!request.params[0].isNull())
timeout = request.params[0].get_int();
CUpdatedBlock block;
{
WAIT_LOCK(cs_blockchange, lock);
block = latestblock;
if(timeout)
cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); });
else
cond_blockchange.wait(lock, [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); });
block = latestblock;
}
UniValue ret(UniValue::VOBJ);
ret.pushKV("hash", block.hash.GetHex());
ret.pushKV("height", block.height);
return ret;
}
static UniValue waitforblock(const JSONRPCRequest& request)
{
RPCHelpMan{"waitforblock",
"\nWaits for a specific new block and returns useful info about it.\n"
"\nReturns the current block on timeout or exit.\n",
{
{"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "Block hash to wait for."},
{"timeout", RPCArg::Type::NUM, /* default */ "0", "Time in milliseconds to wait for a response. 0 indicates no timeout."},
},
RPCResult{
"{ (json object)\n"
" \"hash\" : { (string) The blockhash\n"
" \"height\" : { (int) Block height\n"
"}\n"
},
RPCExamples{
HelpExampleCli("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
+ HelpExampleRpc("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
},
}.Check(request);
int timeout = 0;
uint256 hash(ParseHashV(request.params[0], "blockhash"));
if (!request.params[1].isNull())
timeout = request.params[1].get_int();
CUpdatedBlock block;
{
WAIT_LOCK(cs_blockchange, lock);
if(timeout)
cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&hash]{return latestblock.hash == hash || !IsRPCRunning();});
else
cond_blockchange.wait(lock, [&hash]{return latestblock.hash == hash || !IsRPCRunning(); });
block = latestblock;
}
UniValue ret(UniValue::VOBJ);
ret.pushKV("hash", block.hash.GetHex());
ret.pushKV("height", block.height);
return ret;
}
static UniValue waitforblockheight(const JSONRPCRequest& request)
{
RPCHelpMan{"waitforblockheight",
"\nWaits for (at least) block height and returns the height and hash\n"
"of the current tip.\n"
"\nReturns the current block on timeout or exit.\n",
{
{"height", RPCArg::Type::NUM, RPCArg::Optional::NO, "Block height to wait for."},
{"timeout", RPCArg::Type::NUM, /* default */ "0", "Time in milliseconds to wait for a response. 0 indicates no timeout."},
},
RPCResult{
"{ (json object)\n"
" \"hash\" : { (string) The blockhash\n"
" \"height\" : { (int) Block height\n"
"}\n"
},
RPCExamples{
HelpExampleCli("waitforblockheight", "\"100\", 1000")
+ HelpExampleRpc("waitforblockheight", "\"100\", 1000")
},
}.Check(request);
int timeout = 0;
int height = request.params[0].get_int();
if (!request.params[1].isNull())
timeout = request.params[1].get_int();
CUpdatedBlock block;
{
WAIT_LOCK(cs_blockchange, lock);
if(timeout)
cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&height]{return latestblock.height >= height || !IsRPCRunning();});
else
cond_blockchange.wait(lock, [&height]{return latestblock.height >= height || !IsRPCRunning(); });
block = latestblock;
}
UniValue ret(UniValue::VOBJ);
ret.pushKV("hash", block.hash.GetHex());
ret.pushKV("height", block.height);
return ret;
}
static UniValue syncwithvalidationinterfacequeue(const JSONRPCRequest& request)
{
RPCHelpMan{"syncwithvalidationinterfacequeue",
"\nWaits for the validation interface queue to catch up on everything that was there when we entered this function.\n",
{},
RPCResults{},
RPCExamples{
HelpExampleCli("syncwithvalidationinterfacequeue","")
+ HelpExampleRpc("syncwithvalidationinterfacequeue","")
},
}.Check(request);
SyncWithValidationInterfaceQueue();
return NullUniValue;
}
static UniValue getdifficulty(const JSONRPCRequest& request)
{
RPCHelpMan{"getdifficulty",
"\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n",
{},
RPCResult{
"n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
},
RPCExamples{
HelpExampleCli("getdifficulty", "")
+ HelpExampleRpc("getdifficulty", "")
},
}.Check(request);
LOCK(cs_main);
return GetDifficulty(::ChainActive().Tip());
}
static std::string EntryDescriptionString()
{
return " \"vsize\" : n, (numeric) virtual transaction size as defined in BIP 141. This is different from actual serialized size for witness transactions as witness data is discounted.\n"
" \"size\" : n, (numeric) (DEPRECATED) same as vsize. Only returned if BGLd is started with -deprecatedrpc=size\n"
" size will be completely removed in v0.20.\n"
" \"weight\" : n, (numeric) transaction weight as defined in BIP 141.\n"
" \"fee\" : n, (numeric) transaction fee in " + CURRENCY_UNIT + " (DEPRECATED)\n"
" \"modifiedfee\" : n, (numeric) transaction fee with fee deltas used for mining priority (DEPRECATED)\n"
" \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n"
" \"height\" : n, (numeric) block height when transaction entered pool\n"
" \"descendantcount\" : n, (numeric) number of in-mempool descendant transactions (including this one)\n"
" \"descendantsize\" : n, (numeric) virtual transaction size of in-mempool descendants (including this one)\n"
" \"descendantfees\" : n, (numeric) modified fees (see above) of in-mempool descendants (including this one) (DEPRECATED)\n"
" \"ancestorcount\" : n, (numeric) number of in-mempool ancestor transactions (including this one)\n"
" \"ancestorsize\" : n, (numeric) virtual transaction size of in-mempool ancestors (including this one)\n"
" \"ancestorfees\" : n, (numeric) modified fees (see above) of in-mempool ancestors (including this one) (DEPRECATED)\n"
" \"wtxid\" : hash, (string) hash of serialized transaction, including witness data\n"
" \"fees\" : {\n"
" \"base\" : n, (numeric) transaction fee in " + CURRENCY_UNIT + "\n"
" \"modified\" : n, (numeric) transaction fee with fee deltas used for mining priority in " + CURRENCY_UNIT + "\n"
" \"ancestor\" : n, (numeric) modified fees (see above) of in-mempool ancestors (including this one) in " + CURRENCY_UNIT + "\n"
" \"descendant\" : n, (numeric) modified fees (see above) of in-mempool descendants (including this one) in " + CURRENCY_UNIT + "\n"
" }\n"
" \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n"
" \"transactionid\", (string) parent transaction id\n"
" ... ]\n"
" \"spentby\" : [ (array) unconfirmed transactions spending outputs from this transaction\n"
" \"transactionid\", (string) child transaction id\n"
" ... ]\n"
" \"bip125-replaceable\" : true|false, (boolean) Whether this transaction could be replaced due to BIP125 (replace-by-fee)\n";
}
static void entryToJSON(const CTxMemPool& pool, UniValue& info, const CTxMemPoolEntry& e) EXCLUSIVE_LOCKS_REQUIRED(pool.cs)
{
AssertLockHeld(pool.cs);
UniValue fees(UniValue::VOBJ);
fees.pushKV("base", ValueFromAmount(e.GetFee()));
fees.pushKV("modified", ValueFromAmount(e.GetModifiedFee()));
fees.pushKV("ancestor", ValueFromAmount(e.GetModFeesWithAncestors()));
fees.pushKV("descendant", ValueFromAmount(e.GetModFeesWithDescendants()));
info.pushKV("fees", fees);
info.pushKV("vsize", (int)e.GetTxSize());
if (IsDeprecatedRPCEnabled("size")) info.pushKV("size", (int)e.GetTxSize());
info.pushKV("weight", (int)e.GetTxWeight());
info.pushKV("fee", ValueFromAmount(e.GetFee()));
info.pushKV("modifiedfee", ValueFromAmount(e.GetModifiedFee()));
info.pushKV("time", count_seconds(e.GetTime()));
info.pushKV("height", (int)e.GetHeight());
info.pushKV("descendantcount", e.GetCountWithDescendants());
info.pushKV("descendantsize", e.GetSizeWithDescendants());
info.pushKV("descendantfees", e.GetModFeesWithDescendants());
info.pushKV("ancestorcount", e.GetCountWithAncestors());
info.pushKV("ancestorsize", e.GetSizeWithAncestors());
info.pushKV("ancestorfees", e.GetModFeesWithAncestors());
info.pushKV("wtxid", pool.vTxHashes[e.vTxHashesIdx].first.ToString());
const CTransaction& tx = e.GetTx();
std::set<std::string> setDepends;
for (const CTxIn& txin : tx.vin)
{
if (pool.exists(txin.prevout.hash))
setDepends.insert(txin.prevout.hash.ToString());
}
UniValue depends(UniValue::VARR);
for (const std::string& dep : setDepends)
{
depends.push_back(dep);
}
info.pushKV("depends", depends);
UniValue spent(UniValue::VARR);
const CTxMemPool::txiter& it = pool.mapTx.find(tx.GetHash());
const CTxMemPool::setEntries& setChildren = pool.GetMemPoolChildren(it);
for (CTxMemPool::txiter childiter : setChildren) {
spent.push_back(childiter->GetTx().GetHash().ToString());
}
info.pushKV("spentby", spent);
// Add opt-in RBF status
bool rbfStatus = false;
RBFTransactionState rbfState = IsRBFOptIn(tx, pool);
if (rbfState == RBFTransactionState::UNKNOWN) {
throw JSONRPCError(RPC_MISC_ERROR, "Transaction is not in mempool");
} else if (rbfState == RBFTransactionState::REPLACEABLE_BIP125) {
rbfStatus = true;
}
info.pushKV("bip125-replaceable", rbfStatus);
}
UniValue MempoolToJSON(const CTxMemPool& pool, bool verbose)
{
if (verbose) {
LOCK(pool.cs);
UniValue o(UniValue::VOBJ);
for (const CTxMemPoolEntry& e : pool.mapTx) {
const uint256& hash = e.GetTx().GetHash();
UniValue info(UniValue::VOBJ);
entryToJSON(pool, info, e);
// Mempool has unique entries so there is no advantage in using
// UniValue::pushKV, which checks if the key already exists in O(N).
// UniValue::__pushKV is used instead which currently is O(1).
o.__pushKV(hash.ToString(), info);
}
return o;
} else {
std::vector<uint256> vtxid;
pool.queryHashes(vtxid);
UniValue a(UniValue::VARR);
for (const uint256& hash : vtxid)
a.push_back(hash.ToString());
return a;
}
}
static UniValue getrawmempool(const JSONRPCRequest& request)
{
RPCHelpMan{"getrawmempool",
"\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n"
"\nHint: use getmempoolentry to fetch a specific transaction from the mempool.\n",
{
{"verbose", RPCArg::Type::BOOL, /* default */ "false", "True for a json object, false for array of transaction ids"},
},
RPCResult{"for verbose = false",
"[ (json array of string)\n"
" \"transactionid\" (string) The transaction id\n"
" ,...\n"
"]\n"
"\nResult: (for verbose = true):\n"
"{ (json object)\n"
" \"transactionid\" : { (json object)\n"
+ EntryDescriptionString()
+ " }, ...\n"
"}\n"
},
RPCExamples{
HelpExampleCli("getrawmempool", "true")
+ HelpExampleRpc("getrawmempool", "true")
},
}.Check(request);
bool fVerbose = false;
if (!request.params[0].isNull())
fVerbose = request.params[0].get_bool();
return MempoolToJSON(EnsureMemPool(), fVerbose);
}
static UniValue getmempoolancestors(const JSONRPCRequest& request)
{
RPCHelpMan{"getmempoolancestors",
"\nIf txid is in the mempool, returns all in-mempool ancestors.\n",
{
{"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id (must be in mempool)"},
{"verbose", RPCArg::Type::BOOL, /* default */ "false", "True for a json object, false for array of transaction ids"},
},
{
RPCResult{"for verbose = false",
"[ (json array of strings)\n"
" \"transactionid\" (string) The transaction id of an in-mempool ancestor transaction\n"
" ,...\n"
"]\n"
},
RPCResult{"for verbose = true",
"{ (json object)\n"
" \"transactionid\" : { (json object)\n"
+ EntryDescriptionString()
+ " }, ...\n"
"}\n"
},
},
RPCExamples{
HelpExampleCli("getmempoolancestors", "\"mytxid\"")
+ HelpExampleRpc("getmempoolancestors", "\"mytxid\"")
},
}.Check(request);
bool fVerbose = false;
if (!request.params[1].isNull())
fVerbose = request.params[1].get_bool();
uint256 hash = ParseHashV(request.params[0], "parameter 1");
const CTxMemPool& mempool = EnsureMemPool();
LOCK(mempool.cs);
CTxMemPool::txiter it = mempool.mapTx.find(hash);
if (it == mempool.mapTx.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
}
CTxMemPool::setEntries setAncestors;
uint64_t noLimit = std::numeric_limits<uint64_t>::max();
std::string dummy;
mempool.CalculateMemPoolAncestors(*it, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false);
if (!fVerbose) {
UniValue o(UniValue::VARR);
for (CTxMemPool::txiter ancestorIt : setAncestors) {
o.push_back(ancestorIt->GetTx().GetHash().ToString());
}
return o;
} else {
UniValue o(UniValue::VOBJ);
for (CTxMemPool::txiter ancestorIt : setAncestors) {
const CTxMemPoolEntry &e = *ancestorIt;
const uint256& _hash = e.GetTx().GetHash();
UniValue info(UniValue::VOBJ);
entryToJSON(mempool, info, e);
o.pushKV(_hash.ToString(), info);
}
return o;
}
}
static UniValue getmempooldescendants(const JSONRPCRequest& request)
{
RPCHelpMan{"getmempooldescendants",
"\nIf txid is in the mempool, returns all in-mempool descendants.\n",
{
{"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id (must be in mempool)"},
{"verbose", RPCArg::Type::BOOL, /* default */ "false", "True for a json object, false for array of transaction ids"},
},
{
RPCResult{"for verbose = false",
"[ (json array of strings)\n"
" \"transactionid\" (string) The transaction id of an in-mempool descendant transaction\n"
" ,...\n"
"]\n"
},
RPCResult{"for verbose = true",
"{ (json object)\n"
" \"transactionid\" : { (json object)\n"
+ EntryDescriptionString()
+ " }, ...\n"
"}\n"
},
},
RPCExamples{
HelpExampleCli("getmempooldescendants", "\"mytxid\"")
+ HelpExampleRpc("getmempooldescendants", "\"mytxid\"")
},
}.Check(request);
bool fVerbose = false;
if (!request.params[1].isNull())
fVerbose = request.params[1].get_bool();
uint256 hash = ParseHashV(request.params[0], "parameter 1");
const CTxMemPool& mempool = EnsureMemPool();
LOCK(mempool.cs);
CTxMemPool::txiter it = mempool.mapTx.find(hash);
if (it == mempool.mapTx.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
}
CTxMemPool::setEntries setDescendants;
mempool.CalculateDescendants(it, setDescendants);
// CTxMemPool::CalculateDescendants will include the given tx
setDescendants.erase(it);
if (!fVerbose) {
UniValue o(UniValue::VARR);
for (CTxMemPool::txiter descendantIt : setDescendants) {
o.push_back(descendantIt->GetTx().GetHash().ToString());
}
return o;
} else {
UniValue o(UniValue::VOBJ);
for (CTxMemPool::txiter descendantIt : setDescendants) {
const CTxMemPoolEntry &e = *descendantIt;
const uint256& _hash = e.GetTx().GetHash();
UniValue info(UniValue::VOBJ);
entryToJSON(mempool, info, e);
o.pushKV(_hash.ToString(), info);
}
return o;
}
}
static UniValue getmempoolentry(const JSONRPCRequest& request)
{
RPCHelpMan{"getmempoolentry",
"\nReturns mempool data for given transaction\n",
{
{"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id (must be in mempool)"},
},
RPCResult{
"{ (json object)\n"
+ EntryDescriptionString()
+ "}\n"
},
RPCExamples{
HelpExampleCli("getmempoolentry", "\"mytxid\"")
+ HelpExampleRpc("getmempoolentry", "\"mytxid\"")
},
}.Check(request);
uint256 hash = ParseHashV(request.params[0], "parameter 1");
const CTxMemPool& mempool = EnsureMemPool();
LOCK(mempool.cs);
CTxMemPool::txiter it = mempool.mapTx.find(hash);
if (it == mempool.mapTx.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
}
const CTxMemPoolEntry &e = *it;
UniValue info(UniValue::VOBJ);
entryToJSON(mempool, info, e);
return info;
}
static UniValue getblockhash(const JSONRPCRequest& request)
{
RPCHelpMan{"getblockhash",
"\nReturns hash of block in best-block-chain at height provided.\n",
{
{"height", RPCArg::Type::NUM, RPCArg::Optional::NO, "The height index"},
},
RPCResult{
"\"hash\" (string) The block hash\n"
},
RPCExamples{
HelpExampleCli("getblockhash", "1000")
+ HelpExampleRpc("getblockhash", "1000")
},
}.Check(request);
LOCK(cs_main);
int nHeight = request.params[0].get_int();
if (nHeight < 0 || nHeight > ::ChainActive().Height())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
CBlockIndex* pblockindex = ::ChainActive()[nHeight];
return pblockindex->GetBlockHash().GetHex();
}
static UniValue getblockheader(const JSONRPCRequest& request)
{
RPCHelpMan{"getblockheader",
"\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n"
"If verbose is true, returns an Object with information about blockheader <hash>.\n",
{
{"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The block hash"},
{"verbose", RPCArg::Type::BOOL, /* default */ "true", "true for a json object, false for the hex-encoded data"},
},
{
RPCResult{"for verbose = true",
"{\n"
" \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
" \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
" \"height\" : n, (numeric) The block height or index\n"
" \"version\" : n, (numeric) The block version\n"
" \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
" \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
" \"time\" : ttt, (numeric) The block time expressed in " + UNIX_EPOCH_TIME + "\n"
" \"mediantime\" : ttt, (numeric) The median block time expressed in " + UNIX_EPOCH_TIME + "\n"
" \"nonce\" : n, (numeric) The nonce\n"
" \"bits\" : \"1d00ffff\", (string) The bits\n"
" \"difficulty\" : x.xxx, (numeric) The difficulty\n"
" \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n"
" \"nTx\" : n, (numeric) The number of transactions in the block.\n"
" \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
" \"nextblockhash\" : \"hash\", (string) The hash of the next block\n"
"}\n"
},
RPCResult{"for verbose=false",
"\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
},
},
RPCExamples{
HelpExampleCli("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
+ HelpExampleRpc("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
},
}.Check(request);
uint256 hash(ParseHashV(request.params[0], "hash"));
bool fVerbose = true;
if (!request.params[1].isNull())
fVerbose = request.params[1].get_bool();
const CBlockIndex* pblockindex;
const CBlockIndex* tip;
{
LOCK(cs_main);
pblockindex = LookupBlockIndex(hash);
tip = ::ChainActive().Tip();
}
if (!pblockindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
}
if (!fVerbose)
{
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << pblockindex->GetBlockHeader();
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
return strHex;
}
return blockheaderToJSON(tip, pblockindex);
}
static CBlock GetBlockChecked(const CBlockIndex* pblockindex)
{
CBlock block;
if (IsBlockPruned(pblockindex)) {
throw JSONRPCError(RPC_MISC_ERROR, "Block not available (pruned data)");
}
if (!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus())) {
// Block not found on disk. This could be because we have the block
// header in our index but don't have the block (for example if a
// non-whitelisted node sends us an unrequested long chain of valid
// blocks, we add the headers to our index, but don't accept the
// block).
throw JSONRPCError(RPC_MISC_ERROR, "Block not found on disk");
}
return block;
}
static CBlockUndo GetUndoChecked(const CBlockIndex* pblockindex)
{
CBlockUndo blockUndo;
if (IsBlockPruned(pblockindex)) {
throw JSONRPCError(RPC_MISC_ERROR, "Undo data not available (pruned data)");
}
if (!UndoReadFromDisk(blockUndo, pblockindex)) {
throw JSONRPCError(RPC_MISC_ERROR, "Can't read undo data from disk");
}
return blockUndo;
}
static UniValue getblock(const JSONRPCRequest& request)
{
RPCHelpMan{"getblock",
"\nIf verbosity is 0, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
"If verbosity is 1, returns an Object with information about block <hash>.\n"
"If verbosity is 2, returns an Object with information about block <hash> and information about each transaction. \n",
{
{"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The block hash"},
{"verbosity", RPCArg::Type::NUM, /* default */ "1", "0 for hex-encoded data, 1 for a json object, and 2 for json object with transaction data"},
},
{
RPCResult{"for verbosity = 0",
"\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
},
RPCResult{"for verbosity = 1",
"{\n"
" \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
" \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
" \"size\" : n, (numeric) The block size\n"
" \"strippedsize\" : n, (numeric) The block size excluding witness data\n"
" \"weight\" : n (numeric) The block weight as defined in BIP 141\n"
" \"height\" : n, (numeric) The block height or index\n"
" \"version\" : n, (numeric) The block version\n"
" \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
" \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
" \"tx\" : [ (array of string) The transaction ids\n"
" \"transactionid\" (string) The transaction id\n"
" ,...\n"
" ],\n"
" \"time\" : ttt, (numeric) The block time expressed in " + UNIX_EPOCH_TIME + "\n"
" \"mediantime\" : ttt, (numeric) The median block time expressed in " + UNIX_EPOCH_TIME + "\n"
" \"nonce\" : n, (numeric) The nonce\n"
" \"bits\" : \"1d00ffff\", (string) The bits\n"
" \"difficulty\" : x.xxx, (numeric) The difficulty\n"
" \"chainwork\" : \"xxxx\", (string) Expected number of hashes required to produce the chain up to this block (in hex)\n"
" \"nTx\" : n, (numeric) The number of transactions in the block.\n"
" \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
" \"nextblockhash\" : \"hash\" (string) The hash of the next block\n"
"}\n"
},
RPCResult{"for verbosity = 2",
"{\n"
" ..., Same output as verbosity = 1.\n"
" \"tx\" : [ (array of Objects) The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 \"tx\" result.\n"
" ,...\n"
" ],\n"
" ,... Same output as verbosity = 1.\n"
"}\n"
},
},
RPCExamples{
HelpExampleCli("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
+ HelpExampleRpc("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
},
}.Check(request);
uint256 hash(ParseHashV(request.params[0], "blockhash"));
int verbosity = 1;
if (!request.params[1].isNull()) {
if(request.params[1].isNum())
verbosity = request.params[1].get_int();
else
verbosity = request.params[1].get_bool() ? 1 : 0;
}
CBlock block;
const CBlockIndex* pblockindex;
const CBlockIndex* tip;
{
LOCK(cs_main);
pblockindex = LookupBlockIndex(hash);
tip = ::ChainActive().Tip();
if (!pblockindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
}
block = GetBlockChecked(pblockindex);
}
if (verbosity <= 0)
{
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
ssBlock << block;
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
return strHex;
}
return blockToJSON(block, tip, pblockindex, verbosity >= 2);
}
static UniValue pruneblockchain(const JSONRPCRequest& request)
{
RPCHelpMan{"pruneblockchain", "",
{
{"height", RPCArg::Type::NUM, RPCArg::Optional::NO, "The block height to prune up to. May be set to a discrete height, or to a " + UNIX_EPOCH_TIME + "\n"
" to prune blocks whose block time is at least 2 hours older than the provided timestamp."},
},
RPCResult{
"n (numeric) Height of the last block pruned.\n"
},
RPCExamples{
HelpExampleCli("pruneblockchain", "1000")
+ HelpExampleRpc("pruneblockchain", "1000")
},
}.Check(request);
if (!fPruneMode)
throw JSONRPCError(RPC_MISC_ERROR, "Cannot prune blocks because node is not in prune mode.");
LOCK(cs_main);
int heightParam = request.params[0].get_int();
if (heightParam < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative block height.");
// Height value more than a billion is too high to be a block height, and
// too low to be a block time (corresponds to timestamp from Sep 2001).
if (heightParam > 1000000000) {
// Add a 2 hour buffer to include blocks which might have had old timestamps
CBlockIndex* pindex = ::ChainActive().FindEarliestAtLeast(heightParam - TIMESTAMP_WINDOW, 0);
if (!pindex) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Could not find block with at least the specified timestamp.");
}
heightParam = pindex->nHeight;
}
unsigned int height = (unsigned int) heightParam;
unsigned int chainHeight = (unsigned int) ::ChainActive().Height();
if (chainHeight < Params().PruneAfterHeight())
throw JSONRPCError(RPC_MISC_ERROR, "Blockchain is too short for pruning.");
else if (height > chainHeight)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Blockchain is shorter than the attempted prune height.");
else if (height > chainHeight - MIN_BLOCKS_TO_KEEP) {
LogPrint(BCLog::RPC, "Attempt to prune blocks close to the tip. Retaining the minimum number of blocks.\n");
height = chainHeight - MIN_BLOCKS_TO_KEEP;
}
PruneBlockFilesManual(height);
const CBlockIndex* block = ::ChainActive().Tip();
CHECK_NONFATAL(block);
while (block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA)) {
block = block->pprev;
}
return uint64_t(block->nHeight);
}
static UniValue gettxoutsetinfo(const JSONRPCRequest& request)
{
RPCHelpMan{"gettxoutsetinfo",
"\nReturns statistics about the unspent transaction output set.\n"
"Note this call may take some time.\n",
{},
RPCResult{
"{\n"
" \"height\":n, (numeric) The current block height (index)\n"
" \"bestblock\": \"hex\", (string) The hash of the block at the tip of the chain\n"
" \"transactions\": n, (numeric) The number of transactions with unspent outputs\n"
" \"txouts\": n, (numeric) The number of unspent transaction outputs\n"
" \"bogosize\": n, (numeric) A meaningless metric for UTXO set size\n"
" \"hash_serialized_2\": \"hash\", (string) The serialized hash\n"
" \"disk_size\": n, (numeric) The estimated size of the chainstate on disk\n"
" \"total_amount\": x.xxx (numeric) The total amount\n"
"}\n"
},
RPCExamples{
HelpExampleCli("gettxoutsetinfo", "")
+ HelpExampleRpc("gettxoutsetinfo", "")
},
}.Check(request);
UniValue ret(UniValue::VOBJ);
CCoinsStats stats;
::ChainstateActive().ForceFlushStateToDisk();
CCoinsView* coins_view = WITH_LOCK(cs_main, return &ChainstateActive().CoinsDB());
if (GetUTXOStats(coins_view, stats)) {
ret.pushKV("height", (int64_t)stats.nHeight);
ret.pushKV("bestblock", stats.hashBlock.GetHex());
ret.pushKV("transactions", (int64_t)stats.nTransactions);
ret.pushKV("txouts", (int64_t)stats.nTransactionOutputs);
ret.pushKV("bogosize", (int64_t)stats.nBogoSize);
ret.pushKV("hash_serialized_2", stats.hashSerialized.GetHex());
ret.pushKV("disk_size", stats.nDiskSize);
ret.pushKV("total_amount", ValueFromAmount(stats.nTotalAmount));
} else {
throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set");
}
return ret;
}
UniValue gettxout(const JSONRPCRequest& request)
{
RPCHelpMan{"gettxout",
"\nReturns details about an unspent transaction output.\n",
{
{"txid", RPCArg::Type::STR, RPCArg::Optional::NO, "The transaction id"},
{"n", RPCArg::Type::NUM, RPCArg::Optional::NO, "vout number"},
{"include_mempool", RPCArg::Type::BOOL, /* default */ "true", "Whether to include the mempool. Note that an unspent output that is spent in the mempool won't appear."},
},
RPCResult{
"{\n"
" \"bestblock\": \"hash\", (string) The hash of the block at the tip of the chain\n"
" \"confirmations\" : n, (numeric) The number of confirmations\n"
" \"value\" : x.xxx, (numeric) The transaction value in " + CURRENCY_UNIT + "\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"code\", (string) \n"
" \"hex\" : \"hex\", (string) \n"
" \"reqSigs\" : n, (numeric) Number of required signatures\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n"
" \"addresses\" : [ (array of string) array of BGL addresses\n"
" \"address\" (string) BGL address\n"
" ,...\n"
" ]\n"
" },\n"
" \"coinbase\" : true|false (boolean) Coinbase or not\n"
"}\n"
},
RPCExamples{
"\nGet unspent transactions\n"
+ HelpExampleCli("listunspent", "") +
"\nView the details\n"
+ HelpExampleCli("gettxout", "\"txid\" 1") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("gettxout", "\"txid\", 1")
},
}.Check(request);
LOCK(cs_main);
UniValue ret(UniValue::VOBJ);
uint256 hash(ParseHashV(request.params[0], "txid"));
int n = request.params[1].get_int();
COutPoint out(hash, n);
bool fMempool = true;
if (!request.params[2].isNull())
fMempool = request.params[2].get_bool();
Coin coin;
CCoinsViewCache* coins_view = &::ChainstateActive().CoinsTip();
if (fMempool) {
const CTxMemPool& mempool = EnsureMemPool();
LOCK(mempool.cs);
CCoinsViewMemPool view(coins_view, mempool);
if (!view.GetCoin(out, coin) || mempool.isSpent(out)) {
return NullUniValue;
}
} else {
if (!coins_view->GetCoin(out, coin)) {
return NullUniValue;
}
}
const CBlockIndex* pindex = LookupBlockIndex(coins_view->GetBestBlock());
ret.pushKV("bestblock", pindex->GetBlockHash().GetHex());
if (coin.nHeight == MEMPOOL_HEIGHT) {
ret.pushKV("confirmations", 0);
} else {
ret.pushKV("confirmations", (int64_t)(pindex->nHeight - coin.nHeight + 1));
}
ret.pushKV("value", ValueFromAmount(coin.out.nValue));
UniValue o(UniValue::VOBJ);
ScriptPubKeyToUniv(coin.out.scriptPubKey, o, true);
ret.pushKV("scriptPubKey", o);
ret.pushKV("coinbase", (bool)coin.fCoinBase);
return ret;
}
static UniValue verifychain(const JSONRPCRequest& request)
{
int nCheckLevel = gArgs.GetArg("-checklevel", DEFAULT_CHECKLEVEL);
int nCheckDepth = gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS);
RPCHelpMan{"verifychain",
"\nVerifies blockchain database.\n",
{
{"checklevel", RPCArg::Type::NUM, /* default */ strprintf("%d, range=0-4", nCheckLevel), "How thorough the block verification is."},
{"nblocks", RPCArg::Type::NUM, /* default */ strprintf("%d, 0=all", nCheckDepth), "The number of blocks to check."},
},
RPCResult{
"true|false (boolean) Verified or not\n"
},
RPCExamples{
HelpExampleCli("verifychain", "")
+ HelpExampleRpc("verifychain", "")
},
}.Check(request);
LOCK(cs_main);
if (!request.params[0].isNull())
nCheckLevel = request.params[0].get_int();
if (!request.params[1].isNull())
nCheckDepth = request.params[1].get_int();
return CVerifyDB().VerifyDB(
Params(), &::ChainstateActive().CoinsTip(), nCheckLevel, nCheckDepth);
}
static void BuriedForkDescPushBack(UniValue& softforks, const std::string &name, int height) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
{
// For buried deployments.
// A buried deployment is one where the height of the activation has been hardcoded into
// the client implementation long after the consensus change has activated. See BIP 90.
// Buried deployments with activation height value of
// std::numeric_limits<int>::max() are disabled and thus hidden.
if (height == std::numeric_limits<int>::max()) return;
UniValue rv(UniValue::VOBJ);
rv.pushKV("type", "buried");
// getblockchaininfo reports the softfork as active from when the chain height is
// one below the activation height
rv.pushKV("active", ::ChainActive().Tip()->nHeight + 1 >= height);
rv.pushKV("height", height);
softforks.pushKV(name, rv);
}
static void BIP9SoftForkDescPushBack(UniValue& softforks, const std::string &name, const Consensus::Params& consensusParams, Consensus::DeploymentPos id) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
{
// For BIP9 deployments.
// Deployments (e.g. testdummy) with timeout value before Jan 1, 2009 are hidden.
// A timeout value of 0 guarantees a softfork will never be activated.
// This is used when merging logic to implement a proposed softfork without a specified deployment schedule.
if (consensusParams.vDeployments[id].nTimeout <= 1230768000) return;
UniValue bip9(UniValue::VOBJ);
const ThresholdState thresholdState = VersionBitsTipState(consensusParams, id);
switch (thresholdState) {
case ThresholdState::DEFINED: bip9.pushKV("status", "defined"); break;
case ThresholdState::STARTED: bip9.pushKV("status", "started"); break;
case ThresholdState::LOCKED_IN: bip9.pushKV("status", "locked_in"); break;
case ThresholdState::ACTIVE: bip9.pushKV("status", "active"); break;
case ThresholdState::FAILED: bip9.pushKV("status", "failed"); break;
}
if (ThresholdState::STARTED == thresholdState)
{
bip9.pushKV("bit", consensusParams.vDeployments[id].bit);
}
bip9.pushKV("start_time", consensusParams.vDeployments[id].nStartTime);
bip9.pushKV("timeout", consensusParams.vDeployments[id].nTimeout);
int64_t since_height = VersionBitsTipStateSinceHeight(consensusParams, id);
bip9.pushKV("since", since_height);
if (ThresholdState::STARTED == thresholdState)
{
UniValue statsUV(UniValue::VOBJ);
BIP9Stats statsStruct = VersionBitsTipStatistics(consensusParams, id);
statsUV.pushKV("period", statsStruct.period);
statsUV.pushKV("threshold", statsStruct.threshold);
statsUV.pushKV("elapsed", statsStruct.elapsed);
statsUV.pushKV("count", statsStruct.count);
statsUV.pushKV("possible", statsStruct.possible);
bip9.pushKV("statistics", statsUV);
}
UniValue rv(UniValue::VOBJ);
rv.pushKV("type", "bip9");
rv.pushKV("bip9", bip9);
if (ThresholdState::ACTIVE == thresholdState) {
rv.pushKV("height", since_height);
}
rv.pushKV("active", ThresholdState::ACTIVE == thresholdState);
softforks.pushKV(name, rv);
}
UniValue getblockchaininfo(const JSONRPCRequest& request)
{
RPCHelpMan{"getblockchaininfo",
"Returns an object containing various state info regarding blockchain processing.\n",
{},
RPCResult{
"{\n"
" \"chain\": \"xxxx\", (string) current network name (main, test, regtest)\n"
" \"blocks\": xxxxxx, (numeric) the height of the most-work fully-validated chain. The genesis block has height 0\n"
" \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n"
" \"bestblockhash\": \"...\", (string) the hash of the currently best block\n"
" \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
" \"mediantime\": xxxxxx, (numeric) median time for the current best block\n"
" \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n"
" \"initialblockdownload\": xxxx, (bool) (debug information) estimate of whether this node is in Initial Block Download mode.\n"
" \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n"
" \"size_on_disk\": xxxxxx, (numeric) the estimated size of the block and undo files on disk\n"
" \"pruned\": xx, (boolean) if the blocks are subject to pruning\n"
" \"pruneheight\": xxxxxx, (numeric) lowest-height complete block stored (only present if pruning is enabled)\n"
" \"automatic_pruning\": xx, (boolean) whether automatic pruning is enabled (only present if pruning is enabled)\n"
" \"prune_target_size\": xxxxxx, (numeric) the target size used by pruning (only present if automatic pruning is enabled)\n"
" \"softforks\": { (object) status of softforks\n"
" \"xxxx\" : { (string) name of the softfork\n"
" \"type\": \"xxxx\", (string) one of \"buried\", \"bip9\"\n"
" \"bip9\": { (object) status of bip9 softforks (only for \"bip9\" type)\n"
" \"status\": \"xxxx\", (string) one of \"defined\", \"started\", \"locked_in\", \"active\", \"failed\"\n"
" \"bit\": xx, (numeric) the bit (0-28) in the block version field used to signal this softfork (only for \"started\" status)\n"
" \"start_time\": xx, (numeric) the minimum median time past of a block at which the bit gains its meaning\n"
" \"timeout\": xx, (numeric) the median time past of a block at which the deployment is considered failed if not yet locked in\n"
" \"since\": xx, (numeric) height of the first block to which the status applies\n"
" \"statistics\": { (object) numeric statistics about BIP9 signalling for a softfork\n"
" \"period\": xx, (numeric) the length in blocks of the BIP9 signalling period \n"
" \"threshold\": xx, (numeric) the number of blocks with the version bit set required to activate the feature \n"
" \"elapsed\": xx, (numeric) the number of blocks elapsed since the beginning of the current period \n"
" \"count\": xx, (numeric) the number of blocks with the version bit set in the current period \n"
" \"possible\": xx (boolean) returns false if there are not enough blocks left in this period to pass activation threshold \n"
" }\n"
" },\n"
" \"height\": \"xxxxxx\", (numeric) height of the first block which the rules are or will be enforced (only for \"buried\" type, or \"bip9\" type with \"active\" status)\n"
" \"active\": xx, (boolean) true if the rules are enforced for the mempool and the next block\n"
" }\n"
" }\n"
" \"warnings\" : \"...\", (string) any network and blockchain warnings.\n"
"}\n"
},
RPCExamples{
HelpExampleCli("getblockchaininfo", "")
+ HelpExampleRpc("getblockchaininfo", "")
},
}.Check(request);
LOCK(cs_main);
const CBlockIndex* tip = ::ChainActive().Tip();
UniValue obj(UniValue::VOBJ);
obj.pushKV("chain", Params().NetworkIDString());
obj.pushKV("blocks", (int)::ChainActive().Height());
obj.pushKV("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1);
obj.pushKV("bestblockhash", tip->GetBlockHash().GetHex());
obj.pushKV("difficulty", (double)GetDifficulty(tip));
obj.pushKV("mediantime", (int64_t)tip->GetMedianTimePast());
obj.pushKV("verificationprogress", GuessVerificationProgress(Params().TxData(), tip));
obj.pushKV("initialblockdownload", ::ChainstateActive().IsInitialBlockDownload());
obj.pushKV("chainwork", tip->nChainWork.GetHex());
obj.pushKV("size_on_disk", CalculateCurrentUsage());
obj.pushKV("pruned", fPruneMode);
if (fPruneMode) {
const CBlockIndex* block = tip;
CHECK_NONFATAL(block);
while (block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA)) {
block = block->pprev;
}
obj.pushKV("pruneheight", block->nHeight);
// if 0, execution bypasses the whole if block.
bool automatic_pruning = (gArgs.GetArg("-prune", 0) != 1);
obj.pushKV("automatic_pruning", automatic_pruning);
if (automatic_pruning) {
obj.pushKV("prune_target_size", nPruneTarget);
}
}
const Consensus::Params& consensusParams = Params().GetConsensus();
UniValue softforks(UniValue::VOBJ);
BuriedForkDescPushBack(softforks, "bip34", consensusParams.BIP34Height);
BuriedForkDescPushBack(softforks, "bip66", consensusParams.BIP66Height);
BuriedForkDescPushBack(softforks, "bip65", consensusParams.BIP65Height);
BuriedForkDescPushBack(softforks, "csv", consensusParams.CSVHeight);
BuriedForkDescPushBack(softforks, "segwit", consensusParams.SegwitHeight);
BIP9SoftForkDescPushBack(softforks, "testdummy", consensusParams, Consensus::DEPLOYMENT_TESTDUMMY);
obj.pushKV("softforks", softforks);
obj.pushKV("warnings", GetWarnings(false));
return obj;
}
/** Comparison function for sorting the getchaintips heads. */
struct CompareBlocksByHeight
{
bool operator()(const CBlockIndex* a, const CBlockIndex* b) const
{
/* Make sure that unequal blocks with the same height do not compare
equal. Use the pointers themselves to make a distinction. */
if (a->nHeight != b->nHeight)
return (a->nHeight > b->nHeight);
return a < b;
}
};
static UniValue getchaintips(const JSONRPCRequest& request)
{
RPCHelpMan{"getchaintips",
"Return information about all known tips in the block tree,"
" including the main chain as well as orphaned branches.\n",
{},
RPCResult{
"[\n"
" {\n"
" \"height\": xxxx, (numeric) height of the chain tip\n"
" \"hash\": \"xxxx\", (string) block hash of the tip\n"
" \"branchlen\": 0 (numeric) zero for main chain\n"
" \"status\": \"active\" (string) \"active\" for the main chain\n"
" },\n"
" {\n"
" \"height\": xxxx,\n"
" \"hash\": \"xxxx\",\n"
" \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n"
" \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n"
" }\n"
"]\n"
"Possible values for status:\n"
"1. \"invalid\" This branch contains at least one invalid block\n"
"2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n"
"3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n"
"4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n"
"5. \"active\" This is the tip of the active main chain, which is certainly valid\n"
},
RPCExamples{
HelpExampleCli("getchaintips", "")
+ HelpExampleRpc("getchaintips", "")
},
}.Check(request);
LOCK(cs_main);
/*
* Idea: the set of chain tips is ::ChainActive().tip, plus orphan blocks which do not have another orphan building off of them.
* Algorithm:
* - Make one pass through g_blockman.m_block_index, picking out the orphan blocks, and also storing a set of the orphan block's pprev pointers.
* - Iterate through the orphan blocks. If the block isn't pointed to by another orphan, it is a chain tip.
* - add ::ChainActive().Tip()
*/
std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
std::set<const CBlockIndex*> setOrphans;
std::set<const CBlockIndex*> setPrevs;
for (const std::pair<const uint256, CBlockIndex*>& item : ::BlockIndex())
{
if (!::ChainActive().Contains(item.second)) {
setOrphans.insert(item.second);
setPrevs.insert(item.second->pprev);
}
}
for (std::set<const CBlockIndex*>::iterator it = setOrphans.begin(); it != setOrphans.end(); ++it)
{
if (setPrevs.erase(*it) == 0) {
setTips.insert(*it);
}
}
// Always report the currently active tip.
setTips.insert(::ChainActive().Tip());
/* Construct the output array. */
UniValue res(UniValue::VARR);
for (const CBlockIndex* block : setTips)
{
UniValue obj(UniValue::VOBJ);
obj.pushKV("height", block->nHeight);
obj.pushKV("hash", block->phashBlock->GetHex());
const int branchLen = block->nHeight - ::ChainActive().FindFork(block)->nHeight;
obj.pushKV("branchlen", branchLen);
std::string status;
if (::ChainActive().Contains(block)) {
// This block is part of the currently active chain.
status = "active";
} else if (block->nStatus & BLOCK_FAILED_MASK) {
// This block or one of its ancestors is invalid.
status = "invalid";
} else if (!block->HaveTxsDownloaded()) {
// This block cannot be connected because full block data for it or one of its parents is missing.
status = "headers-only";
} else if (block->IsValid(BLOCK_VALID_SCRIPTS)) {
// This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized.
status = "valid-fork";
} else if (block->IsValid(BLOCK_VALID_TREE)) {
// The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain.
status = "valid-headers";
} else {
// No clue.
status = "unknown";
}
obj.pushKV("status", status);
res.push_back(obj);
}
return res;
}
UniValue MempoolInfoToJSON(const CTxMemPool& pool)
{
// Make sure this call is atomic in the pool.
LOCK(pool.cs);
UniValue ret(UniValue::VOBJ);
ret.pushKV("loaded", pool.IsLoaded());
ret.pushKV("size", (int64_t)pool.size());
ret.pushKV("bytes", (int64_t)pool.GetTotalTxSize());
ret.pushKV("usage", (int64_t)pool.DynamicMemoryUsage());
size_t maxmempool = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
ret.pushKV("maxmempool", (int64_t) maxmempool);
ret.pushKV("mempoolminfee", ValueFromAmount(std::max(pool.GetMinFee(maxmempool), ::minRelayTxFee).GetFeePerK()));
ret.pushKV("minrelaytxfee", ValueFromAmount(::minRelayTxFee.GetFeePerK()));
return ret;
}
static UniValue getmempoolinfo(const JSONRPCRequest& request)
{
RPCHelpMan{"getmempoolinfo",
"\nReturns details on the active state of the TX memory pool.\n",
{},
RPCResult{
"{\n"
" \"loaded\": true|false (boolean) True if the mempool is fully loaded\n"
" \"size\": xxxxx, (numeric) Current tx count\n"
" \"bytes\": xxxxx, (numeric) Sum of all virtual transaction sizes as defined in BIP 141. Differs from actual serialized size because witness data is discounted\n"
" \"usage\": xxxxx, (numeric) Total memory usage for the mempool\n"
" \"maxmempool\": xxxxx, (numeric) Maximum memory usage for the mempool\n"
" \"mempoolminfee\": xxxxx (numeric) Minimum fee rate in " + CURRENCY_UNIT + "/kB for tx to be accepted. Is the maximum of minrelaytxfee and minimum mempool fee\n"
" \"minrelaytxfee\": xxxxx (numeric) Current minimum relay fee for transactions\n"
"}\n"
},
RPCExamples{
HelpExampleCli("getmempoolinfo", "")
+ HelpExampleRpc("getmempoolinfo", "")
},
}.Check(request);
return MempoolInfoToJSON(EnsureMemPool());
}
static UniValue preciousblock(const JSONRPCRequest& request)
{
RPCHelpMan{"preciousblock",
"\nTreats a block as if it were received before others with the same work.\n"
"\nA later preciousblock call can override the effect of an earlier one.\n"
"\nThe effects of preciousblock are not retained across restarts.\n",
{
{"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hash of the block to mark as precious"},
},
RPCResults{},
RPCExamples{
HelpExampleCli("preciousblock", "\"blockhash\"")
+ HelpExampleRpc("preciousblock", "\"blockhash\"")
},
}.Check(request);
uint256 hash(ParseHashV(request.params[0], "blockhash"));
CBlockIndex* pblockindex;
{
LOCK(cs_main);
pblockindex = LookupBlockIndex(hash);
if (!pblockindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
}
}
BlockValidationState state;
PreciousBlock(state, Params(), pblockindex);
if (!state.IsValid()) {
throw JSONRPCError(RPC_DATABASE_ERROR, FormatStateMessage(state));
}
return NullUniValue;
}
static UniValue invalidateblock(const JSONRPCRequest& request)
{
RPCHelpMan{"invalidateblock",
"\nPermanently marks a block as invalid, as if it violated a consensus rule.\n",
{
{"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hash of the block to mark as invalid"},
},
RPCResults{},
RPCExamples{
HelpExampleCli("invalidateblock", "\"blockhash\"")
+ HelpExampleRpc("invalidateblock", "\"blockhash\"")
},
}.Check(request);
uint256 hash(ParseHashV(request.params[0], "blockhash"));
BlockValidationState state;
CBlockIndex* pblockindex;
{
LOCK(cs_main);
pblockindex = LookupBlockIndex(hash);
if (!pblockindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
}
}
InvalidateBlock(state, Params(), pblockindex);
if (state.IsValid()) {
ActivateBestChain(state, Params());
}
if (!state.IsValid()) {
throw JSONRPCError(RPC_DATABASE_ERROR, FormatStateMessage(state));
}
return NullUniValue;
}
static UniValue reconsiderblock(const JSONRPCRequest& request)
{
RPCHelpMan{"reconsiderblock",
"\nRemoves invalidity status of a block, its ancestors and its descendants, reconsider them for activation.\n"
"This can be used to undo the effects of invalidateblock.\n",
{
{"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hash of the block to reconsider"},
},
RPCResults{},
RPCExamples{
HelpExampleCli("reconsiderblock", "\"blockhash\"")
+ HelpExampleRpc("reconsiderblock", "\"blockhash\"")
},
}.Check(request);
uint256 hash(ParseHashV(request.params[0], "blockhash"));
{
LOCK(cs_main);
CBlockIndex* pblockindex = LookupBlockIndex(hash);
if (!pblockindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
}
ResetBlockFailureFlags(pblockindex);
}
BlockValidationState state;
ActivateBestChain(state, Params());
if (!state.IsValid()) {
throw JSONRPCError(RPC_DATABASE_ERROR, FormatStateMessage(state));
}
return NullUniValue;
}
static UniValue getchaintxstats(const JSONRPCRequest& request)
{
RPCHelpMan{"getchaintxstats",
"\nCompute statistics about the total number and rate of transactions in the chain.\n",
{
{"nblocks", RPCArg::Type::NUM, /* default */ "one month", "Size of the window in number of blocks"},
{"blockhash", RPCArg::Type::STR_HEX, /* default */ "chain tip", "The hash of the block that ends the window."},
},
RPCResult{
"{\n"
" \"time\": xxxxx, (numeric) The timestamp for the final block in the window, expressed in " + UNIX_EPOCH_TIME + ".\n"
" \"txcount\": xxxxx, (numeric) The total number of transactions in the chain up to that point.\n"
" \"window_final_block_hash\": \"...\", (string) The hash of the final block in the window.\n"
" \"window_final_block_height\": xxxxx, (numeric) The height of the final block in the window.\n"
" \"window_block_count\": xxxxx, (numeric) Size of the window in number of blocks.\n"
" \"window_tx_count\": xxxxx, (numeric) The number of transactions in the window. Only returned if \"window_block_count\" is > 0.\n"
" \"window_interval\": xxxxx, (numeric) The elapsed time in the window in seconds. Only returned if \"window_block_count\" is > 0.\n"
" \"txrate\": x.xx, (numeric) The average rate of transactions per second in the window. Only returned if \"window_interval\" is > 0.\n"
"}\n"
},
RPCExamples{
HelpExampleCli("getchaintxstats", "")
+ HelpExampleRpc("getchaintxstats", "2016")
},
}.Check(request);
const CBlockIndex* pindex;
int blockcount = 30 * 24 * 60 * 60 / Params().GetConsensus().nPowTargetSpacing; // By default: 1 month
if (request.params[1].isNull()) {
LOCK(cs_main);
pindex = ::ChainActive().Tip();
} else {
uint256 hash(ParseHashV(request.params[1], "blockhash"));
LOCK(cs_main);
pindex = LookupBlockIndex(hash);
if (!pindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
}
if (!::ChainActive().Contains(pindex)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Block is not in main chain");
}
}
CHECK_NONFATAL(pindex != nullptr);
if (request.params[0].isNull()) {
blockcount = std::max(0, std::min(blockcount, pindex->nHeight - 1));
} else {
blockcount = request.params[0].get_int();
if (blockcount < 0 || (blockcount > 0 && blockcount >= pindex->nHeight)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid block count: should be between 0 and the block's height - 1");
}
}
const CBlockIndex* pindexPast = pindex->GetAncestor(pindex->nHeight - blockcount);
int nTimeDiff = pindex->GetMedianTimePast() - pindexPast->GetMedianTimePast();
int nTxDiff = pindex->nChainTx - pindexPast->nChainTx;
UniValue ret(UniValue::VOBJ);
ret.pushKV("time", (int64_t)pindex->nTime);
ret.pushKV("txcount", (int64_t)pindex->nChainTx);
ret.pushKV("window_final_block_hash", pindex->GetBlockHash().GetHex());
ret.pushKV("window_final_block_height", pindex->nHeight);
ret.pushKV("window_block_count", blockcount);
if (blockcount > 0) {
ret.pushKV("window_tx_count", nTxDiff);
ret.pushKV("window_interval", nTimeDiff);
if (nTimeDiff > 0) {
ret.pushKV("txrate", ((double)nTxDiff) / nTimeDiff);
}
}
return ret;
}
template<typename T>
static T CalculateTruncatedMedian(std::vector<T>& scores)
{
size_t size = scores.size();
if (size == 0) {
return 0;
}
std::sort(scores.begin(), scores.end());
if (size % 2 == 0) {
return (scores[size / 2 - 1] + scores[size / 2]) / 2;
} else {
return scores[size / 2];
}
}
void CalculatePercentilesByWeight(CAmount result[NUM_GETBLOCKSTATS_PERCENTILES], std::vector<std::pair<CAmount, int64_t>>& scores, int64_t total_weight)
{
if (scores.empty()) {
return;
}
std::sort(scores.begin(), scores.end());
// 10th, 25th, 50th, 75th, and 90th percentile weight units.
const double weights[NUM_GETBLOCKSTATS_PERCENTILES] = {
total_weight / 10.0, total_weight / 4.0, total_weight / 2.0, (total_weight * 3.0) / 4.0, (total_weight * 9.0) / 10.0
};
int64_t next_percentile_index = 0;
int64_t cumulative_weight = 0;
for (const auto& element : scores) {
cumulative_weight += element.second;
while (next_percentile_index < NUM_GETBLOCKSTATS_PERCENTILES && cumulative_weight >= weights[next_percentile_index]) {
result[next_percentile_index] = element.first;
++next_percentile_index;
}
}
// Fill any remaining percentiles with the last value.
for (int64_t i = next_percentile_index; i < NUM_GETBLOCKSTATS_PERCENTILES; i++) {
result[i] = scores.back().first;
}
}
template<typename T>
static inline bool SetHasKeys(const std::set<T>& set) {return false;}
template<typename T, typename Tk, typename... Args>
static inline bool SetHasKeys(const std::set<T>& set, const Tk& key, const Args&... args)
{
return (set.count(key) != 0) || SetHasKeys(set, args...);
}
// outpoint (needed for the utxo index) + nHeight + fCoinBase
static constexpr size_t PER_UTXO_OVERHEAD = sizeof(COutPoint) + sizeof(uint32_t) + sizeof(bool);
static UniValue getblockstats(const JSONRPCRequest& request)
{
RPCHelpMan{"getblockstats",
"\nCompute per block statistics for a given window. All amounts are in satoshis.\n"
"It won't work for some heights with pruning.\n",
{
{"hash_or_height", RPCArg::Type::NUM, RPCArg::Optional::NO, "The block hash or height of the target block", "", {"", "string or numeric"}},
{"stats", RPCArg::Type::ARR, /* default */ "all values", "Values to plot (see result below)",
{
{"height", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Selected statistic"},
{"time", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Selected statistic"},
},
"stats"},
},
RPCResult{
"{ (json object)\n"
" \"avgfee\": xxxxx, (numeric) Average fee in the block\n"
" \"avgfeerate\": xxxxx, (numeric) Average feerate (in satoshis per virtual byte)\n"
" \"avgtxsize\": xxxxx, (numeric) Average transaction size\n"
" \"blockhash\": xxxxx, (string) The block hash (to check for potential reorgs)\n"
" \"feerate_percentiles\": [ (array of numeric) Feerates at the 10th, 25th, 50th, 75th, and 90th percentile weight unit (in satoshis per virtual byte)\n"
" \"10th_percentile_feerate\", (numeric) The 10th percentile feerate\n"
" \"25th_percentile_feerate\", (numeric) The 25th percentile feerate\n"
" \"50th_percentile_feerate\", (numeric) The 50th percentile feerate\n"
" \"75th_percentile_feerate\", (numeric) The 75th percentile feerate\n"
" \"90th_percentile_feerate\", (numeric) The 90th percentile feerate\n"
" ],\n"
" \"height\": xxxxx, (numeric) The height of the block\n"
" \"ins\": xxxxx, (numeric) The number of inputs (excluding coinbase)\n"
" \"maxfee\": xxxxx, (numeric) Maximum fee in the block\n"
" \"maxfeerate\": xxxxx, (numeric) Maximum feerate (in satoshis per virtual byte)\n"
" \"maxtxsize\": xxxxx, (numeric) Maximum transaction size\n"
" \"medianfee\": xxxxx, (numeric) Truncated median fee in the block\n"
" \"mediantime\": xxxxx, (numeric) The block median time past\n"
" \"mediantxsize\": xxxxx, (numeric) Truncated median transaction size\n"
" \"minfee\": xxxxx, (numeric) Minimum fee in the block\n"
" \"minfeerate\": xxxxx, (numeric) Minimum feerate (in satoshis per virtual byte)\n"
" \"mintxsize\": xxxxx, (numeric) Minimum transaction size\n"
" \"outs\": xxxxx, (numeric) The number of outputs\n"
" \"subsidy\": xxxxx, (numeric) The block subsidy\n"
" \"swtotal_size\": xxxxx, (numeric) Total size of all segwit transactions\n"
" \"swtotal_weight\": xxxxx, (numeric) Total weight of all segwit transactions divided by segwit scale factor (4)\n"
" \"swtxs\": xxxxx, (numeric) The number of segwit transactions\n"
" \"time\": xxxxx, (numeric) The block time\n"
" \"total_out\": xxxxx, (numeric) Total amount in all outputs (excluding coinbase and thus reward [ie subsidy + totalfee])\n"
" \"total_size\": xxxxx, (numeric) Total size of all non-coinbase transactions\n"
" \"total_weight\": xxxxx, (numeric) Total weight of all non-coinbase transactions divided by segwit scale factor (4)\n"
" \"totalfee\": xxxxx, (numeric) The fee total\n"
" \"txs\": xxxxx, (numeric) The number of transactions (excluding coinbase)\n"
" \"utxo_increase\": xxxxx, (numeric) The increase/decrease in the number of unspent outputs\n"
" \"utxo_size_inc\": xxxxx, (numeric) The increase/decrease in size for the utxo index (not discounting op_return and similar)\n"
"}\n"
},
RPCExamples{
HelpExampleCli("getblockstats", "1000 '[\"minfeerate\",\"avgfeerate\"]'")
+ HelpExampleRpc("getblockstats", "1000 '[\"minfeerate\",\"avgfeerate\"]'")
},
}.Check(request);
LOCK(cs_main);
CBlockIndex* pindex;
if (request.params[0].isNum()) {
const int height = request.params[0].get_int();
const int current_tip = ::ChainActive().Height();
if (height < 0) {
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Target block height %d is negative", height));
}
if (height > current_tip) {
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Target block height %d after current tip %d", height, current_tip));
}
pindex = ::ChainActive()[height];
} else {
const uint256 hash(ParseHashV(request.params[0], "hash_or_height"));
pindex = LookupBlockIndex(hash);
if (!pindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
}
if (!::ChainActive().Contains(pindex)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Block is not in chain %s", Params().NetworkIDString()));
}
}
CHECK_NONFATAL(pindex != nullptr);
std::set<std::string> stats;
if (!request.params[1].isNull()) {
const UniValue stats_univalue = request.params[1].get_array();
for (unsigned int i = 0; i < stats_univalue.size(); i++) {
const std::string stat = stats_univalue[i].get_str();
stats.insert(stat);
}
}
const CBlock block = GetBlockChecked(pindex);
const CBlockUndo blockUndo = GetUndoChecked(pindex);
const bool do_all = stats.size() == 0; // Calculate everything if nothing selected (default)
const bool do_mediantxsize = do_all || stats.count("mediantxsize") != 0;
const bool do_medianfee = do_all || stats.count("medianfee") != 0;
const bool do_feerate_percentiles = do_all || stats.count("feerate_percentiles") != 0;
const bool loop_inputs = do_all || do_medianfee || do_feerate_percentiles ||
SetHasKeys(stats, "utxo_size_inc", "totalfee", "avgfee", "avgfeerate", "minfee", "maxfee", "minfeerate", "maxfeerate");
const bool loop_outputs = do_all || loop_inputs || stats.count("total_out");
const bool do_calculate_size = do_mediantxsize ||
SetHasKeys(stats, "total_size", "avgtxsize", "mintxsize", "maxtxsize", "swtotal_size");
const bool do_calculate_weight = do_all || SetHasKeys(stats, "total_weight", "avgfeerate", "swtotal_weight", "avgfeerate", "feerate_percentiles", "minfeerate", "maxfeerate");
const bool do_calculate_sw = do_all || SetHasKeys(stats, "swtxs", "swtotal_size", "swtotal_weight");
CAmount maxfee = 0;
CAmount maxfeerate = 0;
CAmount minfee = MAX_MONEY;
CAmount minfeerate = MAX_MONEY;
CAmount total_out = 0;
CAmount totalfee = 0;
int64_t inputs = 0;
int64_t maxtxsize = 0;
int64_t mintxsize = MAX_BLOCK_SERIALIZED_SIZE;
int64_t outputs = 0;
int64_t swtotal_size = 0;
int64_t swtotal_weight = 0;
int64_t swtxs = 0;
int64_t total_size = 0;
int64_t total_weight = 0;
int64_t utxo_size_inc = 0;
std::vector<CAmount> fee_array;
std::vector<std::pair<CAmount, int64_t>> feerate_array;
std::vector<int64_t> txsize_array;
for (size_t i = 0; i < block.vtx.size(); ++i) {
const auto& tx = block.vtx.at(i);
outputs += tx->vout.size();
CAmount tx_total_out = 0;
if (loop_outputs) {
for (const CTxOut& out : tx->vout) {
tx_total_out += out.nValue;
utxo_size_inc += GetSerializeSize(out, PROTOCOL_VERSION) + PER_UTXO_OVERHEAD;
}
}
if (tx->IsCoinBase()) {
continue;
}
inputs += tx->vin.size(); // Don't count coinbase's fake input
total_out += tx_total_out; // Don't count coinbase reward
int64_t tx_size = 0;
if (do_calculate_size) {
tx_size = tx->GetTotalSize();
if (do_mediantxsize) {
txsize_array.push_back(tx_size);
}
maxtxsize = std::max(maxtxsize, tx_size);
mintxsize = std::min(mintxsize, tx_size);
total_size += tx_size;
}
int64_t weight = 0;
if (do_calculate_weight) {
weight = GetTransactionWeight(*tx);
total_weight += weight;
}
if (do_calculate_sw && tx->HasWitness()) {
++swtxs;
swtotal_size += tx_size;
swtotal_weight += weight;
}
if (loop_inputs) {
CAmount tx_total_in = 0;
const auto& txundo = blockUndo.vtxundo.at(i - 1);
for (const Coin& coin: txundo.vprevout) {
const CTxOut& prevoutput = coin.out;
tx_total_in += prevoutput.nValue;
utxo_size_inc -= GetSerializeSize(prevoutput, PROTOCOL_VERSION) + PER_UTXO_OVERHEAD;
}
CAmount txfee = tx_total_in - tx_total_out;
CHECK_NONFATAL(MoneyRange(txfee));
if (do_medianfee) {
fee_array.push_back(txfee);
}
maxfee = std::max(maxfee, txfee);
minfee = std::min(minfee, txfee);
totalfee += txfee;
// New feerate uses satoshis per virtual byte instead of per serialized byte
CAmount feerate = weight ? (txfee * WITNESS_SCALE_FACTOR) / weight : 0;
if (do_feerate_percentiles) {
feerate_array.emplace_back(std::make_pair(feerate, weight));
}
maxfeerate = std::max(maxfeerate, feerate);
minfeerate = std::min(minfeerate, feerate);
}
}
CAmount feerate_percentiles[NUM_GETBLOCKSTATS_PERCENTILES] = { 0 };
CalculatePercentilesByWeight(feerate_percentiles, feerate_array, total_weight);
UniValue feerates_res(UniValue::VARR);
for (int64_t i = 0; i < NUM_GETBLOCKSTATS_PERCENTILES; i++) {
feerates_res.push_back(feerate_percentiles[i]);
}
UniValue ret_all(UniValue::VOBJ);
ret_all.pushKV("avgfee", (block.vtx.size() > 1) ? totalfee / (block.vtx.size() - 1) : 0);
ret_all.pushKV("avgfeerate", total_weight ? (totalfee * WITNESS_SCALE_FACTOR) / total_weight : 0); // Unit: sat/vbyte
ret_all.pushKV("avgtxsize", (block.vtx.size() > 1) ? total_size / (block.vtx.size() - 1) : 0);
ret_all.pushKV("blockhash", pindex->GetBlockHash().GetHex());
ret_all.pushKV("feerate_percentiles", feerates_res);
ret_all.pushKV("height", (int64_t)pindex->nHeight);
ret_all.pushKV("ins", inputs);
ret_all.pushKV("maxfee", maxfee);
ret_all.pushKV("maxfeerate", maxfeerate);
ret_all.pushKV("maxtxsize", maxtxsize);
ret_all.pushKV("medianfee", CalculateTruncatedMedian(fee_array));
ret_all.pushKV("mediantime", pindex->GetMedianTimePast());
ret_all.pushKV("mediantxsize", CalculateTruncatedMedian(txsize_array));
ret_all.pushKV("minfee", (minfee == MAX_MONEY) ? 0 : minfee);
ret_all.pushKV("minfeerate", (minfeerate == MAX_MONEY) ? 0 : minfeerate);
ret_all.pushKV("mintxsize", mintxsize == MAX_BLOCK_SERIALIZED_SIZE ? 0 : mintxsize);
ret_all.pushKV("outs", outputs);
ret_all.pushKV("subsidy", GetBlockSubsidy(pindex->nHeight, Params().GetConsensus()));
ret_all.pushKV("swtotal_size", swtotal_size);
ret_all.pushKV("swtotal_weight", swtotal_weight);
ret_all.pushKV("swtxs", swtxs);
ret_all.pushKV("time", pindex->GetBlockTime());
ret_all.pushKV("total_out", total_out);
ret_all.pushKV("total_size", total_size);
ret_all.pushKV("total_weight", total_weight);
ret_all.pushKV("totalfee", totalfee);
ret_all.pushKV("txs", (int64_t)block.vtx.size());
ret_all.pushKV("utxo_increase", outputs - inputs);
ret_all.pushKV("utxo_size_inc", utxo_size_inc);
if (do_all) {
return ret_all;
}
UniValue ret(UniValue::VOBJ);
for (const std::string& stat : stats) {
const UniValue& value = ret_all[stat];
if (value.isNull()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid selected statistic %s", stat));
}
ret.pushKV(stat, value);
}
return ret;
}
static UniValue savemempool(const JSONRPCRequest& request)
{
RPCHelpMan{"savemempool",
"\nDumps the mempool to disk. It will fail until the previous dump is fully loaded.\n",
{},
RPCResults{},
RPCExamples{
HelpExampleCli("savemempool", "")
+ HelpExampleRpc("savemempool", "")
},
}.Check(request);
const CTxMemPool& mempool = EnsureMemPool();
if (!mempool.IsLoaded()) {
throw JSONRPCError(RPC_MISC_ERROR, "The mempool was not loaded yet");
}
if (!DumpMempool(mempool)) {
throw JSONRPCError(RPC_MISC_ERROR, "Unable to dump mempool to disk");
}
return NullUniValue;
}
//! Search for a given set of pubkey scripts
bool FindScriptPubKey(std::atomic<int>& scan_progress, const std::atomic<bool>& should_abort, int64_t& count, CCoinsViewCursor* cursor, const std::set<CScript>& needles, std::map<COutPoint, Coin>& out_results) {
scan_progress = 0;
count = 0;
while (cursor->Valid()) {
COutPoint key;
Coin coin;
if (!cursor->GetKey(key) || !cursor->GetValue(coin)) return false;
if (++count % 8192 == 0) {
if (should_abort) {
// allow to abort the scan via the abort reference
return false;
}
}
if (count % 256 == 0) {
// update progress reference every 256 item
uint32_t high = 0x100 * *key.hash.begin() + *(key.hash.begin() + 1);
scan_progress = (int)(high * 100.0 / 65536.0 + 0.5);
}
if (needles.count(coin.out.scriptPubKey)) {
out_results.emplace(key, coin);
}
cursor->Next();
}
scan_progress = 100;
return true;
}
/** RAII object to prevent concurrency issue when scanning the txout set */
static std::mutex g_utxosetscan;
static std::atomic<int> g_scan_progress;
static std::atomic<bool> g_scan_in_progress;
static std::atomic<bool> g_should_abort_scan;
class CoinsViewScanReserver
{
private:
bool m_could_reserve;
public:
explicit CoinsViewScanReserver() : m_could_reserve(false) {}
bool reserve() {
CHECK_NONFATAL(!m_could_reserve);
std::lock_guard<std::mutex> lock(g_utxosetscan);
if (g_scan_in_progress) {
return false;
}
g_scan_in_progress = true;
m_could_reserve = true;
return true;
}
~CoinsViewScanReserver() {
if (m_could_reserve) {
std::lock_guard<std::mutex> lock(g_utxosetscan);
g_scan_in_progress = false;
}
}
};
UniValue scantxoutset(const JSONRPCRequest& request)
{
RPCHelpMan{"scantxoutset",
"\nEXPERIMENTAL warning: this call may be removed or changed in future releases.\n"
"\nScans the unspent transaction output set for entries that match certain output descriptors.\n"
"Examples of output descriptors are:\n"
" addr(<address>) Outputs whose scriptPubKey corresponds to the specified address (does not include P2PK)\n"
" raw(<hex script>) Outputs whose scriptPubKey equals the specified hex scripts\n"
" combo(<pubkey>) P2PK, P2PKH, P2WPKH, and P2SH-P2WPKH outputs for the given pubkey\n"
" pkh(<pubkey>) P2PKH outputs for the given pubkey\n"
" sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\n"
"\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
"or more path elements separated by \"/\", and optionally ending in \"/*\" (unhardened), or \"/*'\" or \"/*h\" (hardened) to specify all\n"
"unhardened or hardened child keys.\n"
"In the latter case, a range needs to be specified by below if different from 1000.\n"
"For more information on output descriptors, see the documentation in the doc/descriptors.md file.\n",
{
{"action", RPCArg::Type::STR, RPCArg::Optional::NO, "The action to execute\n"
" \"start\" for starting a scan\n"
" \"abort\" for aborting the current scan (returns true when abort was successful)\n"
" \"status\" for progress report (in %) of the current scan"},
{"scanobjects", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "Array of scan objects. Required for \"start\" action\n"
" Every scan object is either a string descriptor or an object:",
{
{"descriptor", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "An output descriptor"},
{"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "An object with output descriptor and metadata",
{
{"desc", RPCArg::Type::STR, RPCArg::Optional::NO, "An output descriptor"},
{"range", RPCArg::Type::RANGE, /* default */ "1000", "The range of HD chain indexes to explore (either end or [begin,end])"},
},
},
},
"[scanobjects,...]"},
},
RPCResult{
"{\n"
" \"success\": true|false, (boolean) Whether the scan was completed\n"
" \"txouts\": n, (numeric) The number of unspent transaction outputs scanned\n"
" \"height\": n, (numeric) The current block height (index)\n"
" \"bestblock\": \"hex\", (string) The hash of the block at the tip of the chain\n"
" \"unspents\": [\n"
" {\n"
" \"txid\": \"hash\", (string) The transaction id\n"
" \"vout\": n, (numeric) The vout value\n"
" \"scriptPubKey\": \"script\", (string) The script key\n"
" \"desc\": \"descriptor\", (string) A specialized descriptor for the matched scriptPubKey\n"
" \"amount\": x.xxx, (numeric) The total amount in " + CURRENCY_UNIT + " of the unspent output\n"
" \"height\": n, (numeric) Height of the unspent transaction output\n"
" }\n"
" ,...],\n"
" \"total_amount\": x.xxx, (numeric) The total amount of all found unspent outputs in " + CURRENCY_UNIT + "\n"
"]\n"
},
RPCExamples{""},
}.Check(request);
RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR});
UniValue result(UniValue::VOBJ);
if (request.params[0].get_str() == "status") {
CoinsViewScanReserver reserver;
if (reserver.reserve()) {
// no scan in progress
return NullUniValue;
}
result.pushKV("progress", g_scan_progress);
return result;
} else if (request.params[0].get_str() == "abort") {
CoinsViewScanReserver reserver;
if (reserver.reserve()) {
// reserve was possible which means no scan was running
return false;
}
// set the abort flag
g_should_abort_scan = true;
return true;
} else if (request.params[0].get_str() == "start") {
CoinsViewScanReserver reserver;
if (!reserver.reserve()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Scan already in progress, use action \"abort\" or \"status\"");
}
if (request.params.size() < 2) {
throw JSONRPCError(RPC_MISC_ERROR, "scanobjects argument is required for the start action");
}
std::set<CScript> needles;
std::map<CScript, std::string> descriptors;
CAmount total_in = 0;
// loop through the scan objects
for (const UniValue& scanobject : request.params[1].get_array().getValues()) {
FlatSigningProvider provider;
auto scripts = EvalDescriptorStringOrObject(scanobject, provider);
for (const auto& script : scripts) {
std::string inferred = InferDescriptor(script, provider)->ToString();
needles.emplace(script);
descriptors.emplace(std::move(script), std::move(inferred));
}
}
// Scan the unspent transaction output set for inputs
UniValue unspents(UniValue::VARR);
std::vector<CTxOut> input_txos;
std::map<COutPoint, Coin> coins;
g_should_abort_scan = false;
g_scan_progress = 0;
int64_t count = 0;
std::unique_ptr<CCoinsViewCursor> pcursor;
CBlockIndex* tip;
{
LOCK(cs_main);
::ChainstateActive().ForceFlushStateToDisk();
pcursor = std::unique_ptr<CCoinsViewCursor>(::ChainstateActive().CoinsDB().Cursor());
CHECK_NONFATAL(pcursor);
tip = ::ChainActive().Tip();
CHECK_NONFATAL(tip);
}
bool res = FindScriptPubKey(g_scan_progress, g_should_abort_scan, count, pcursor.get(), needles, coins);
result.pushKV("success", res);
result.pushKV("txouts", count);
result.pushKV("height", tip->nHeight);
result.pushKV("bestblock", tip->GetBlockHash().GetHex());
for (const auto& it : coins) {
const COutPoint& outpoint = it.first;
const Coin& coin = it.second;
const CTxOut& txo = coin.out;
input_txos.push_back(txo);
total_in += txo.nValue;
UniValue unspent(UniValue::VOBJ);
unspent.pushKV("txid", outpoint.hash.GetHex());
unspent.pushKV("vout", (int32_t)outpoint.n);
unspent.pushKV("scriptPubKey", HexStr(txo.scriptPubKey.begin(), txo.scriptPubKey.end()));
unspent.pushKV("desc", descriptors[txo.scriptPubKey]);
unspent.pushKV("amount", ValueFromAmount(txo.nValue));
unspent.pushKV("height", (int32_t)coin.nHeight);
unspents.push_back(unspent);
}
result.pushKV("unspents", unspents);
result.pushKV("total_amount", ValueFromAmount(total_in));
} else {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid command");
}
return result;
}
static UniValue getblockfilter(const JSONRPCRequest& request)
{
RPCHelpMan{"getblockfilter",
"\nRetrieve a BIP 157 content filter for a particular block.\n",
{
{"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hash of the block"},
{"filtertype", RPCArg::Type::STR, /*default*/ "basic", "The type name of the filter"},
},
RPCResult{
"{\n"
" \"filter\" : (string) the hex-encoded filter data\n"
" \"header\" : (string) the hex-encoded filter header\n"
"}\n"
},
RPCExamples{
HelpExampleCli("getblockfilter", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" \"basic\"")
}
}.Check(request);
uint256 block_hash = ParseHashV(request.params[0], "blockhash");
std::string filtertype_name = "basic";
if (!request.params[1].isNull()) {
filtertype_name = request.params[1].get_str();
}
BlockFilterType filtertype;
if (!BlockFilterTypeByName(filtertype_name, filtertype)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unknown filtertype");
}
BlockFilterIndex* index = GetBlockFilterIndex(filtertype);
if (!index) {
throw JSONRPCError(RPC_MISC_ERROR, "Index is not enabled for filtertype " + filtertype_name);
}
const CBlockIndex* block_index;
bool block_was_connected;
{
LOCK(cs_main);
block_index = LookupBlockIndex(block_hash);
if (!block_index) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
}
block_was_connected = block_index->IsValid(BLOCK_VALID_SCRIPTS);
}
bool index_ready = index->BlockUntilSyncedToCurrentChain();
BlockFilter filter;
uint256 filter_header;
if (!index->LookupFilter(block_index, filter) ||
!index->LookupFilterHeader(block_index, filter_header)) {
int err_code;
std::string errmsg = "Filter not found.";
if (!block_was_connected) {
err_code = RPC_INVALID_ADDRESS_OR_KEY;
errmsg += " Block was not connected to active chain.";
} else if (!index_ready) {
err_code = RPC_MISC_ERROR;
errmsg += " Block filters are still in the process of being indexed.";
} else {
err_code = RPC_INTERNAL_ERROR;
errmsg += " This error is unexpected and indicates index corruption.";
}
throw JSONRPCError(err_code, errmsg);
}
UniValue ret(UniValue::VOBJ);
ret.pushKV("filter", HexStr(filter.GetEncodedFilter()));
ret.pushKV("header", filter_header.GetHex());
return ret;
}
/**
* Serialize the UTXO set to a file for loading elsewhere.
*
* @see SnapshotMetadata
*/
UniValue dumptxoutset(const JSONRPCRequest& request)
{
RPCHelpMan{
"dumptxoutset",
"\nWrite the serialized UTXO set to disk.\n"
"Incidentally flushes the latest coinsdb (leveldb) to disk.\n",
{
{"path",
RPCArg::Type::STR,
RPCArg::Optional::NO,
/* default_val */ "",
"path to the output file. If relative, will be prefixed by datadir."},
},
RPCResult{
"{\n"
" \"coins_written\": n, (numeric) the number of coins written in the snapshot\n"
" \"base_hash\": \"...\", (string) the hash of the base of the snapshot\n"
" \"base_height\": n, (string) the height of the base of the snapshot\n"
" \"path\": \"...\" (string) the absolute path that the snapshot was written to\n"
"]\n"
},
RPCExamples{
HelpExampleCli("dumptxoutset", "utxo.dat")
}
}.Check(request);
fs::path path = fs::absolute(request.params[0].get_str(), GetDataDir());
// Write to a temporary path and then move into `path` on completion
// to avoid confusion due to an interruption.
fs::path temppath = fs::absolute(request.params[0].get_str() + ".incomplete", GetDataDir());
if (fs::exists(path)) {
throw JSONRPCError(
RPC_INVALID_PARAMETER,
path.string() + " already exists. If you are sure this is what you want, "
"move it out of the way first");
}
FILE* file{fsbridge::fopen(temppath, "wb")};
CAutoFile afile{file, SER_DISK, CLIENT_VERSION};
std::unique_ptr<CCoinsViewCursor> pcursor;
CCoinsStats stats;
CBlockIndex* tip;
{
// We need to lock cs_main to ensure that the coinsdb isn't written to
// between (i) flushing coins cache to disk (coinsdb), (ii) getting stats
// based upon the coinsdb, and (iii) constructing a cursor to the
// coinsdb for use below this block.
//
// Cursors returned by leveldb iterate over snapshots, so the contents
// of the pcursor will not be affected by simultaneous writes during
// use below this block.
//
// See discussion here:
// https://github.com/BGL/BGL/pull/15606#discussion_r274479369
//
LOCK(::cs_main);
::ChainstateActive().ForceFlushStateToDisk();
if (!GetUTXOStats(&::ChainstateActive().CoinsDB(), stats)) {
throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set");
}
pcursor = std::unique_ptr<CCoinsViewCursor>(::ChainstateActive().CoinsDB().Cursor());
tip = LookupBlockIndex(stats.hashBlock);
CHECK_NONFATAL(tip);
}
SnapshotMetadata metadata{tip->GetBlockHash(), stats.coins_count, tip->nChainTx};
afile << metadata;
COutPoint key;
Coin coin;
unsigned int iter{0};
while (pcursor->Valid()) {
if (iter % 5000 == 0 && !IsRPCRunning()) {
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
}
++iter;
if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
afile << key;
afile << coin;
}
pcursor->Next();
}
afile.fclose();
fs::rename(temppath, path);
UniValue result(UniValue::VOBJ);
result.pushKV("coins_written", stats.coins_count);
result.pushKV("base_hash", tip->GetBlockHash().ToString());
result.pushKV("base_height", tip->nHeight);
result.pushKV("path", path.string());
return result;
}
// clang-format off
static const CRPCCommand commands[] =
{ // category name actor (function) argNames
// --------------------- ------------------------ ----------------------- ----------
{ "blockchain", "getblockchaininfo", &getblockchaininfo, {} },
{ "blockchain", "getchaintxstats", &getchaintxstats, {"nblocks", "blockhash"} },
{ "blockchain", "getblockstats", &getblockstats, {"hash_or_height", "stats"} },
{ "blockchain", "getbestblockhash", &getbestblockhash, {} },
{ "blockchain", "getblockcount", &getblockcount, {} },
{ "blockchain", "getblock", &getblock, {"blockhash","verbosity|verbose"} },
{ "blockchain", "getblockhash", &getblockhash, {"height"} },
{ "blockchain", "getblockheader", &getblockheader, {"blockhash","verbose"} },
{ "blockchain", "getchaintips", &getchaintips, {} },
{ "blockchain", "getdifficulty", &getdifficulty, {} },
{ "blockchain", "getmempoolancestors", &getmempoolancestors, {"txid","verbose"} },
{ "blockchain", "getmempooldescendants", &getmempooldescendants, {"txid","verbose"} },
{ "blockchain", "getmempoolentry", &getmempoolentry, {"txid"} },
{ "blockchain", "getmempoolinfo", &getmempoolinfo, {} },
{ "blockchain", "getrawmempool", &getrawmempool, {"verbose"} },
{ "blockchain", "gettxout", &gettxout, {"txid","n","include_mempool"} },
{ "blockchain", "gettxoutsetinfo", &gettxoutsetinfo, {} },
{ "blockchain", "pruneblockchain", &pruneblockchain, {"height"} },
{ "blockchain", "savemempool", &savemempool, {} },
{ "blockchain", "verifychain", &verifychain, {"checklevel","nblocks"} },
{ "blockchain", "preciousblock", &preciousblock, {"blockhash"} },
{ "blockchain", "scantxoutset", &scantxoutset, {"action", "scanobjects"} },
{ "blockchain", "getblockfilter", &getblockfilter, {"blockhash", "filtertype"} },
/* Not shown in help */
{ "hidden", "invalidateblock", &invalidateblock, {"blockhash"} },
{ "hidden", "reconsiderblock", &reconsiderblock, {"blockhash"} },
{ "hidden", "waitfornewblock", &waitfornewblock, {"timeout"} },
{ "hidden", "waitforblock", &waitforblock, {"blockhash","timeout"} },
{ "hidden", "waitforblockheight", &waitforblockheight, {"height","timeout"} },
{ "hidden", "syncwithvalidationinterfacequeue", &syncwithvalidationinterfacequeue, {} },
{ "hidden", "dumptxoutset", &dumptxoutset, {"path"} },
};
// clang-format on
void RegisterBlockchainRPCCommands(CRPCTable &t)
{
for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
t.appendCommand(commands[vcidx].name, &commands[vcidx]);
}
NodeContext* g_rpc_node = nullptr;
|
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2017 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "dcp_add_failover_log.h"
#include <daemon/mcbp.h>
#include <mcbp/protocol/datatype.h>
/** Callback from the engine adding the response */
ENGINE_ERROR_CODE add_failover_log(vbucket_failover_t* entries,
size_t nentries,
gsl::not_null<const void*> cookie) {
ENGINE_ERROR_CODE ret;
size_t ii;
for (ii = 0; ii < nentries; ++ii) {
entries[ii].uuid = htonll(entries[ii].uuid);
entries[ii].seqno = htonll(entries[ii].seqno);
}
if (mcbpResponseHandlerFn(
{},
{},
{reinterpret_cast<const char*>(entries),
(uint32_t)(nentries * sizeof(vbucket_failover_t))},
PROTOCOL_BINARY_RAW_BYTES,
cb::mcbp::Status::Success,
0,
(void*)cookie.get())) {
ret = ENGINE_SUCCESS;
} else {
ret = ENGINE_ENOMEM;
}
for (ii = 0; ii < nentries; ++ii) {
entries[ii].uuid = htonll(entries[ii].uuid);
entries[ii].seqno = htonll(entries[ii].seqno);
}
return ret;
}
|
#include<iostream>
#include<string.h>
using namespace std;
int main(){
char a[]="syamalarao";
char b[11];
int i=0;
int j=strlen(a)-1;
for(i=0;i<strlen(a);i++,j--){
cout<<&a[i]<<endl;
b[j]=a[i];
}
cout<<b<<endl;
cout<<strlen(a-1)<<endl;
}
|
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/framework/common_shape_fns.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/shape_inference.h"
namespace tensorflow {
using shape_inference::InferenceContext;
using shape_inference::ShapeHandle;
// --------------------------------------------------------------------------
namespace {
Status SwitchShape(InferenceContext* c) {
ShapeHandle unused;
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 0, &unused));
ShapeHandle out = c->input(0);
c->set_output(0, out);
c->set_output(1, out);
// Handle resource shape / dtype.
auto* handle_data = c->input_handle_shapes_and_types(0);
if (handle_data != nullptr) {
c->set_output_handle_shapes_and_types(0, *handle_data);
c->set_output_handle_shapes_and_types(1, *handle_data);
}
return Status::OK();
}
Status SwitchNShape(InferenceContext* c) {
ShapeHandle unused;
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 0, &unused));
ShapeHandle out = c->input(0);
int num_outs;
TF_RETURN_IF_ERROR(c->GetAttr("num_outs", &num_outs));
for (int i = 0; i < num_outs; i++) {
c->set_output(i, out);
}
// Handle resource shape / dtype.
auto* handle_data = c->input_handle_shapes_and_types(0);
if (handle_data != nullptr) {
for (int i = 0; i < num_outs; i++) {
c->set_output_handle_shapes_and_types(i, *handle_data);
}
}
return Status::OK();
}
} // namespace
REGISTER_OP("Switch")
.Input("data: T")
.Input("pred: bool")
.Output("output_false: T")
.Output("output_true: T")
.Attr("T: type")
.SetShapeFn(SwitchShape);
REGISTER_OP("RefSwitch")
.Input("data: Ref(T)")
.Input("pred: bool")
.Output("output_false: Ref(T)")
.Output("output_true: Ref(T)")
.Attr("T: type")
.SetAllowsUninitializedInput()
.SetShapeFn(SwitchShape);
REGISTER_OP("_SwitchN")
.Input("data: T")
.Input("output_index: int32")
.Output("outputs: num_outs * T")
.Attr("num_outs: int >= 1")
.Attr("T: type")
.SetShapeFn(SwitchNShape);
// --------------------------------------------------------------------------
REGISTER_OP("RefSelect")
.Input("index: int32")
.Input("inputs: Ref(N * T)")
.Output("output: Ref(T)")
.Attr("T: type")
.Attr("N: int >= 1")
.SetShapeFn([](InferenceContext* c) {
ShapeHandle unused;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 0, &unused));
ShapeHandle first_input = c->input(1);
if (!c->FullyDefined(first_input)) {
c->set_output(0, c->UnknownShape());
return Status::OK();
}
// If any inputs aren't fully defined or don't match, we return unknown.
for (int i = 2; i < c->num_inputs(); ++i) {
ShapeHandle input = c->input(i);
if (!c->FullyDefined(input) ||
!c->Merge(first_input, input, &unused).ok()) {
c->set_output(0, c->UnknownShape());
return Status::OK();
}
}
c->set_output(0, first_input);
return Status::OK();
});
// --------------------------------------------------------------------------
namespace {
Status MergeShape(InferenceContext* c) {
ShapeHandle out = c->input(0);
if (!c->RankKnown(out)) {
out = c->UnknownShape();
} else {
int32_t rank = c->Rank(out);
for (int i = 1; i < c->num_inputs(); ++i) {
ShapeHandle input = c->input(i);
if (!c->RankKnown(input) || c->Rank(input) != rank) {
out = c->UnknownShape();
break;
}
for (int d = 0; d < rank; ++d) {
if (c->Value(c->Dim(input, d)) != c->Value(c->Dim(out, d))) {
TF_RETURN_IF_ERROR(c->ReplaceDim(out, d, c->UnknownDim(), &out));
}
}
}
}
c->set_output(0, out);
c->set_output(1, c->Scalar());
return Status::OK();
}
} // namespace
REGISTER_OP("Merge")
.Input("inputs: N * T")
.Output("output: T")
.Output("value_index: int32")
.Attr("T: type")
.Attr("N: int >= 1")
.SetShapeFn(MergeShape);
REGISTER_OP("RefMerge")
.Input("inputs: Ref(N * T)")
.Output("output: Ref(T)")
.Output("value_index: int32")
.Attr("T: type")
.Attr("N: int >= 1")
.SetShapeFn(MergeShape);
// --------------------------------------------------------------------------
REGISTER_OP("Enter")
.Input("data: T")
.Output("output: T")
.Attr("T: type")
.Attr("frame_name: string")
.Attr("is_constant: bool = false")
.Attr("parallel_iterations: int = 10")
.SetShapeFn([](InferenceContext* c) {
c->set_output(0, c->UnknownShape());
// Handle resource shape / dtype, if present.
auto* handle_data = c->input_handle_shapes_and_types(0);
if (handle_data != nullptr) {
c->set_output_handle_shapes_and_types(0, *handle_data);
}
// Propagate shape if output is a constant.
bool is_constant;
TF_RETURN_IF_ERROR(c->GetAttr("is_constant", &is_constant));
if (is_constant) {
c->set_output(0, c->input(0));
}
return Status::OK();
});
// --------------------------------------------------------------------------
REGISTER_OP("RefEnter")
.Input("data: Ref(T)")
.Output("output: Ref(T)")
.Attr("T: type")
.Attr("frame_name: string")
.Attr("is_constant: bool = false")
.Attr("parallel_iterations: int = 10")
.SetShapeFn(shape_inference::UnchangedShape);
// --------------------------------------------------------------------------
REGISTER_OP("Exit")
.Input("data: T")
.Output("output: T")
.Attr("T: type")
.SetShapeFn(shape_inference::UnchangedShape);
REGISTER_OP("RefExit")
.Input("data: Ref(T)")
.Output("output: Ref(T)")
.Attr("T: type")
.SetShapeFn(shape_inference::UnchangedShape);
// --------------------------------------------------------------------------
REGISTER_OP("NextIteration")
.Input("data: T")
.Output("output: T")
.Attr("T: type")
.SetShapeFn(shape_inference::UnchangedShape);
REGISTER_OP("RefNextIteration")
.Input("data: Ref(T)")
.Output("output: Ref(T)")
.Attr("T: type")
.SetShapeFn(shape_inference::UnchangedShape);
// --------------------------------------------------------------------------
REGISTER_OP("LoopCond")
.Input("input: bool")
.Output("output: bool")
.SetShapeFn([](InferenceContext* c) {
return shape_inference::UnchangedShapeWithRank(c, 0);
});
// --------------------------------------------------------------------------
REGISTER_OP("ControlTrigger").SetShapeFn(shape_inference::NoOutputs);
// --------------------------------------------------------------------------
REGISTER_OP("Abort")
.Attr("error_msg: string = ''")
.Attr("exit_without_error: bool = false")
.SetShapeFn(shape_inference::NoOutputs);
} // namespace tensorflow
|
//
// Created by cc on 2020/6/15.
//
#include "HttpHelper.h"
#include <QFile>
#include <QApplication>
#include <QEventLoop>
#include "../http/QtHttpRequest.h"
using namespace std;
HttpHelper::HttpHelper() = default;
string HttpHelper::get(const std::string& url) {
string res;
auto http = pool.enqueue([&res, url](){
QtHttpRequest request(url);
request.addRequestHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36");
request.startSynchronous();
res = request.getResponseData();
});
http.get();
return res;
}
void HttpHelper::downloadFile(const std::string& url, const std::string& savePath, const std::function<void(bool)>& callBack) {
auto http = pool.enqueue([url, savePath, callBack](){
QtHttpRequest request(url);
request.addRequestHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36");
request.startSynchronous();
auto res = request.getResponseData();
QFile file(savePath.data());
if(!res.empty() && file.open(QIODevice::WriteOnly))
{
file.write(res.data(), res.size());
file.close();
callBack(true);
} else
callBack(false);
});
}
|
#include <catch2/catch.hpp>
#include "mocks/entity.hpp"
#include "mocks/server.hpp"
#include <map/offset.hpp>
#include <stdlib.h>
#include <unordered_map>
SCENARIO("Offset can be created and manipulated", "[offset]") {
GIVEN("All possible hex coordinates") {
WHEN("offsets are built") {
THEN("all hashes are unique") {
std::unordered_map<uint64_t, uint8_t> hashes;
// Not whole range
for (int16_t y = -326; y < 327; ++y)
{
for (int16_t x = -326; x < 327; ++x)
{
const Offset offset(x, y);
if (hashes.find(offset.hash()) != hashes.end())
{
INFO("Failed for " << offset.hash());
REQUIRE(false);
}
hashes[offset.hash()] = 0;
}
}
hashes.clear();
REQUIRE(true);
}
}
}
GIVEN("Some random 2D coordinates") {
int32_t x = (int32_t)(rand() - RAND_MAX / 2.0);
int32_t y = (int32_t)(rand() - RAND_MAX / 2.0);
WHEN("the offset is created") {
const Offset offset = offsetOf(x, y);
THEN("hex coordinates are coherent") {
REQUIRE(offset.q() + offset.r() + offset.s() == 0);
}
THEN("hash is build from q and r") {
REQUIRE((int32_t)(offset.hash() >> 32) == offset.q());
REQUIRE((int32_t)(offset.hash() & 0xFFFFFFFF) == offset.r());
}
}
}
GIVEN("Two offsets at distance 1") {
const Offset offset1(0, 0);
const Offset offset2(0, 1);
WHEN("the radius is computed") {
THEN("the result is 1") {
REQUIRE(offset1.distance(offset2) == 1);
}
}
}
}
|
// Copyright 2010-2021, Google 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:
//
// * 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.
#include "storage/louds/louds_trie_builder.h"
#include <algorithm>
#include <string>
#include <vector>
#include "base/logging.h"
#include "base/port.h"
#include "storage/louds/bit_stream.h"
namespace mozc {
namespace storage {
namespace louds {
LoudsTrieBuilder::LoudsTrieBuilder() : built_(false) {}
void LoudsTrieBuilder::Add(const std::string &word) {
CHECK(!built_);
CHECK(!word.empty());
word_list_.push_back(word);
}
namespace {
// A pair of word and its original index in the (sorted) word_list_.
class Entry {
public:
Entry(const std::string &word, size_t original_index)
: word_(&word), original_index_(original_index) {}
const std::string &word() const { return *word_; }
size_t original_index() const { return original_index_; }
private:
const std::string *word_;
size_t original_index_;
};
class EntryLengthLessThan {
public:
explicit EntryLengthLessThan(size_t length) : length_(length) {}
bool operator()(const Entry &entry) {
return entry.word().length() < length_;
}
private:
size_t length_;
};
void PushInt(size_t value, std::string *image) {
// Make sure the value is fit in the 32-bit value.
CHECK_EQ(value & ~0xFFFFFFFF, 0);
// Output LSB to MSB.
image->push_back(static_cast<char>(value & 0xFF));
image->push_back(static_cast<char>((value >> 8) & 0xFF));
image->push_back(static_cast<char>((value >> 16) & 0xFF));
image->push_back(static_cast<char>((value >> 24) & 0xFF));
}
} // namespace
void LoudsTrieBuilder::Build() {
CHECK(!built_);
// Initialize for the build. Sort and de-dup the words.
std::sort(word_list_.begin(), word_list_.end());
word_list_.erase(std::unique(word_list_.begin(), word_list_.end()),
word_list_.end());
std::vector<Entry> entry_list;
entry_list.reserve(word_list_.size());
for (size_t i = 0; i < word_list_.size(); ++i) {
entry_list.push_back(Entry(word_list_[i], i));
}
id_list_.resize(word_list_.size(), -1);
// Output the tree to streams.
BitStream trie_stream;
BitStream terminal_stream;
std::string edge_character;
// Push root.
trie_stream.PushBit(1);
trie_stream.PushBit(0);
edge_character.push_back('\0');
terminal_stream.PushBit(0);
// Then, traverse the sorted word list.
// The basic concept to output the trie is simple:
// - Iterate the depth beginning with 0.
// - If the entry is the first one in the word list, the corresponding
// node should be newly created.
// - If the prefix[0:depth] (inclusive) is different from the previous entry
// (if exists), the corresponding node should be newly created.
// - Otherwise, the node should be shared with the previous entry.
// So, if it turned out that we need to create a new node, just output '1'
// for LOUDS to represent an "edge," output the corresponding character,
// and output a bit representing whether the node is terminal or not.
// In addition, output the 'id' of the word.
//
// Then we check if we need to output '0' for LOUDS as the stop bit of
// a node. It should be done when the entry is the last child of its parent.
// - If the entry is the last one in the word list, it should be the last
// child of its parent.
// - If the prefix[0:depth) (exclusive, i.e. [0:depth - 1] inclusive) is
// different from the next entry (if exists), it should be the last child
// of its parent.
// - Otherwise, the node is not the last child of its parent, because it
// is shared with the next entry.
//
// Finally, to keep the pre-condition of above algorithms, we remove
// entries which we already output.
//
// Here, there is an issue. Considering a very simple case; only 'a' is in
// the word list.
// At first, output '1' to LOUDS stream, and 'a' to the edge character.
// Also as it is the terminal, output '1' to the terminal stream and
// store the id '0'.
// Then, as 'a' is the last entry, output '0' to the LOUDS stream.
// Then 'a' is removed since it has already been output as a terminal node.
// Now, look at the LOUDS stream, it's '10'. However, '100' is expected,
// because the child node also needs stop bit '0' as a leaf.
// To achieve this, we keep entries which are output as terminals one more
// depth, and skip "edge check" for the entries.
// This doesn't break the edge check condition, and stop bit check condition,
// but adds a chance to output stop bits for leaves.
int id = 0;
for (size_t depth = 0; !entry_list.empty(); ++depth) {
for (size_t i = 0; i < entry_list.size(); ++i) {
const std::string &word = entry_list[i].word();
if (word.length() > depth &&
(i == 0 ||
// To ensure the entry_list[i - 1].word().length >= depth + 1,
// we call c_str() (which adds '\0' if necessary) as a hack.
word.compare(0, depth + 1, entry_list[i - 1].word().c_str(), 0,
depth + 1) != 0)) {
// This is the first string of this node. Output an edge.
trie_stream.PushBit(1);
edge_character.push_back(entry_list[i].word()[depth]);
if (entry_list[i].word().length() == depth + 1) {
// This is a terminal node.
// Note that the terminal string should be at the first of
// strings sharing the node. So the check above should work well.
terminal_stream.PushBit(1);
id_list_[entry_list[i].original_index()] = id;
++id;
} else {
// This is not a terminal node.
terminal_stream.PushBit(0);
}
}
if (i == entry_list.size() - 1 ||
word.compare(0, depth, entry_list[i + 1].word(), 0, depth) != 0) {
// This is the last child (string) for the parent.
trie_stream.PushBit(0);
}
}
// Remove all terminal strings.
entry_list.erase(std::remove_if(entry_list.begin(), entry_list.end(),
EntryLengthLessThan(depth + 1)),
entry_list.end());
}
// Set 32-bits alignment.
trie_stream.FillPadding32();
terminal_stream.FillPadding32();
// Output
PushInt(trie_stream.ByteSize(), &image_);
PushInt(terminal_stream.ByteSize(), &image_);
// The num bits of each character annoated to each edge.
PushInt(8, &image_);
PushInt(edge_character.size(), &image_);
image_.append(trie_stream.image());
image_.append(terminal_stream.image());
image_.append(edge_character);
built_ = true;
}
const std::string &LoudsTrieBuilder::image() const {
CHECK(built_);
return image_;
}
int LoudsTrieBuilder::GetId(const std::string &word) const {
CHECK(built_);
// Binary search the word.
std::vector<std::string>::const_iterator iter =
std::lower_bound(word_list_.begin(), word_list_.end(), word);
if (iter == word_list_.end() || *iter != word) {
// Not found.
return -1;
}
return id_list_[std::distance(word_list_.begin(), iter)];
}
} // namespace louds
} // namespace storage
} // namespace mozc
|
// ArduinoJson - arduinojson.org
// Copyright Benoit Blanchon 2014-2019
// MIT License
#pragma once
#include "../Polyfills/type_traits.hpp"
#include "convertNumber.hpp"
#include "parseNumber.hpp"
namespace ARDUINOJSON_NAMESPACE {
template <typename T>
T parseInteger(const char *s) {
// try to reuse the same parameters as JsonDeserializer
typedef typename choose_largest<UInt, typename make_unsigned<T>::type>::type
TUInt;
return parseNumber<Float, TUInt>(s).template as<T>();
}
} // namespace ARDUINOJSON_NAMESPACE
|
//
// 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 NVIDIA CORPORATION 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 ``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.
//
// Copyright (c) 2008-2018 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "PsAllocator.h"
#include <new>
#include <stdio.h>
#include "CmPhysXCommon.h"
#include "DySolverBody.h"
#include "DySolverConstraint1D.h"
#include "DySolverContact.h"
#include "DyThresholdTable.h"
#include "DySolverControl.h"
#include "DyArticulationHelper.h"
#include "PsAtomic.h"
#include "PsIntrinsics.h"
#include "DyArticulationPImpl.h"
#include "PsThread.h"
#include "DySolverConstraintDesc.h"
#include "DySolverContext.h"
#include "DySolverControlPF.h"
namespace physx
{
namespace Dy
{
//-----------------------------------
void solve1DBlock (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveExt1DBlock (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solve1D4_Block (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solve1DConcludeBlock (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveExt1DConcludeBlock (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solve1D4Block_Conclude (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solve1DBlockWriteBack (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveExt1DBlockWriteBack (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solve1D4Block_WriteBack (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void writeBack1DBlock (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void ext1DBlockWriteBack (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void writeBack1D4Block (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveFrictionBlock (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveFriction_BStaticBlock (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveExtFrictionBlock (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveContactCoulombBlock (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveExtContactCoulombBlock (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveContactCoulomb_BStaticBlock (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveContactCoulombConcludeBlock (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveExtContactCoulombConcludeBlock (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveContactCoulomb_BStaticConcludeBlock (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveContactCoulombBlockWriteBack (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveExtContactCoulombBlockWriteBack (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveContactCoulomb_BStaticBlockWriteBack (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveFrictionBlockWriteBack (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveFriction_BStaticBlockWriteBack (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveExtFrictionBlockWriteBack (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
//Pre-block 1d/2d friction stuff...
void solveContactCoulombPreBlock (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveContactCoulombPreBlock_Static (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveContactCoulombPreBlock_Conclude (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveContactCoulombPreBlock_ConcludeStatic (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveContactCoulombPreBlock_WriteBack (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveContactCoulombPreBlock_WriteBackStatic(const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveFrictionCoulombPreBlock (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveFrictionCoulombPreBlock_Static (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveFrictionCoulombPreBlock_Conclude (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveFrictionCoulombPreBlock_ConcludeStatic(const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveFrictionCoulombPreBlock_WriteBack (const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
void solveFrictionCoulombPreBlock_WriteBackStatic(const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache);
// could move this to PxPreprocessor.h but
// no implementation available for MSVC
#if PX_GCC_FAMILY
#define PX_UNUSED_ATTRIBUTE __attribute__((unused))
#else
#define PX_UNUSED_ATTRIBUTE
#endif
#define DYNAMIC_ARTICULATION_REGISTRATION(x) 0
static SolveBlockMethod gVTableSolveBlockCoulomb[] PX_UNUSED_ATTRIBUTE =
{
0,
solveContactCoulombBlock, // DY_SC_TYPE_RB_CONTACT
solve1DBlock, // DY_SC_TYPE_RB_1D
DYNAMIC_ARTICULATION_REGISTRATION(solveExtContactCoulombBlock), // DY_SC_TYPE_EXT_CONTACT
DYNAMIC_ARTICULATION_REGISTRATION(solveExt1DBlock), // DY_SC_TYPE_EXT_1D
solveContactCoulomb_BStaticBlock, // DY_SC_TYPE_STATIC_CONTACT
solveContactCoulombBlock, // DY_SC_TYPE_NOFRICTION_RB_CONTACT
solveContactCoulombPreBlock, // DY_SC_TYPE_BLOCK_RB_CONTACT
solveContactCoulombPreBlock_Static, // DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT
solve1D4_Block, // DY_SC_TYPE_BLOCK_1D,
solveFrictionBlock, // DY_SC_TYPE_FRICTION_CONSTRAINT
solveFriction_BStaticBlock, // DY_SC_TYPE_STATIC_FRICTION_CONSTRAINT
DYNAMIC_ARTICULATION_REGISTRATION(solveExtFrictionBlock), // DY_SC_TYPE_EXT_FRICTION_CONSTRAINT
solveFrictionCoulombPreBlock, // DY_SC_TYPE_BLOCK_FRICTION
solveFrictionCoulombPreBlock_Static // DY_SC_TYPE_BLOCK_STATIC_FRICTION
};
static SolveWriteBackBlockMethod gVTableSolveWriteBackBlockCoulomb[] PX_UNUSED_ATTRIBUTE =
{
0,
solveContactCoulombBlockWriteBack, // DY_SC_TYPE_RB_CONTACT
solve1DBlockWriteBack, // DY_SC_TYPE_RB_1D
DYNAMIC_ARTICULATION_REGISTRATION(solveExtContactCoulombBlockWriteBack), // DY_SC_TYPE_EXT_CONTACT
DYNAMIC_ARTICULATION_REGISTRATION(solveExt1DBlockWriteBack), // DY_SC_TYPE_EXT_1D
solveContactCoulomb_BStaticBlockWriteBack, // DY_SC_TYPE_STATIC_CONTACT
solveContactCoulombBlockWriteBack, // DY_SC_TYPE_NOFRICTION_RB_CONTACT
solveContactCoulombPreBlock_WriteBack, // DY_SC_TYPE_BLOCK_RB_CONTACT
solveContactCoulombPreBlock_WriteBackStatic, // DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT
solve1D4Block_WriteBack, // DY_SC_TYPE_BLOCK_1D,
solveFrictionBlockWriteBack, // DY_SC_TYPE_FRICTION_CONSTRAINT
solveFriction_BStaticBlockWriteBack, // DY_SC_TYPE_STATIC_FRICTION_CONSTRAINT
DYNAMIC_ARTICULATION_REGISTRATION(solveExtFrictionBlockWriteBack), // DY_SC_TYPE_EXT_FRICTION_CONSTRAINT
solveFrictionCoulombPreBlock_WriteBack, // DY_SC_TYPE_BLOCK_FRICTION
solveFrictionCoulombPreBlock_WriteBackStatic // DY_SC_TYPE_BLOCK_STATIC_FRICTION
};
static SolveBlockMethod gVTableSolveConcludeBlockCoulomb[] PX_UNUSED_ATTRIBUTE =
{
0,
solveContactCoulombConcludeBlock, // DY_SC_TYPE_RB_CONTACT
solve1DConcludeBlock, // DY_SC_TYPE_RB_1D
DYNAMIC_ARTICULATION_REGISTRATION(solveExtContactCoulombConcludeBlock), // DY_SC_TYPE_EXT_CONTACT
DYNAMIC_ARTICULATION_REGISTRATION(solveExt1DConcludeBlock), // DY_SC_TYPE_EXT_1D
solveContactCoulomb_BStaticConcludeBlock, // DY_SC_TYPE_STATIC_CONTACT
solveContactCoulombConcludeBlock, // DY_SC_TYPE_NOFRICTION_RB_CONTACT
solveContactCoulombPreBlock_Conclude, // DY_SC_TYPE_BLOCK_RB_CONTACT
solveContactCoulombPreBlock_ConcludeStatic, // DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT
solve1D4Block_Conclude, // DY_SC_TYPE_BLOCK_1D,
solveFrictionBlock, // DY_SC_TYPE_FRICTION_CONSTRAINT
solveFriction_BStaticBlock, // DY_SC_TYPE_STATIC_FRICTION_CONSTRAINT
DYNAMIC_ARTICULATION_REGISTRATION(solveExtFrictionBlock), // DY_SC_TYPE_EXT_FRICTION_CONSTRAINT
solveFrictionCoulombPreBlock_Conclude, // DY_SC_TYPE_BLOCK_FRICTION
solveFrictionCoulombPreBlock_ConcludeStatic // DY_SC_TYPE_BLOCK_STATIC_FRICTION
};
void SolverCoreRegisterArticulationFnsCoulomb()
{
gVTableSolveBlockCoulomb[DY_SC_TYPE_EXT_CONTACT] = solveExtContactCoulombBlock;
gVTableSolveBlockCoulomb[DY_SC_TYPE_EXT_1D] = solveExt1DBlock;
gVTableSolveWriteBackBlockCoulomb[DY_SC_TYPE_EXT_CONTACT] = solveExtContactCoulombBlockWriteBack;
gVTableSolveWriteBackBlockCoulomb[DY_SC_TYPE_EXT_1D] = solveExt1DBlockWriteBack;
gVTableSolveConcludeBlockCoulomb[DY_SC_TYPE_EXT_CONTACT] = solveExtContactCoulombConcludeBlock;
gVTableSolveConcludeBlockCoulomb[DY_SC_TYPE_EXT_1D] = solveExt1DConcludeBlock;
gVTableSolveBlockCoulomb[DY_SC_TYPE_EXT_FRICTION] = solveExtFrictionBlock;
gVTableSolveWriteBackBlockCoulomb[DY_SC_TYPE_EXT_FRICTION] = solveExtFrictionBlockWriteBack;
gVTableSolveConcludeBlockCoulomb[DY_SC_TYPE_EXT_FRICTION] = solveExtFrictionBlock;
}
SolverCoreGeneralPF* SolverCoreGeneralPF::create()
{
SolverCoreGeneralPF* scg = reinterpret_cast<SolverCoreGeneralPF*>(
PX_ALLOC(sizeof(SolverCoreGeneralPF), "SolverCoreGeneral"));
if(scg)
new (scg) SolverCoreGeneralPF;
return scg;
}
void SolverCoreGeneralPF::destroyV()
{
this->~SolverCoreGeneralPF();
PX_FREE(this);
}
void SolverCoreGeneralPF::solveV_Blocks(SolverIslandParams& params) const
{
const PxI32 TempThresholdStreamSize = 32;
ThresholdStreamElement tempThresholdStream[TempThresholdStreamSize];
SolverContext cache;
cache.solverBodyArray = params.bodyDataList;
cache.mThresholdStream = tempThresholdStream;
cache.mThresholdStreamLength = TempThresholdStreamSize;
cache.mThresholdStreamIndex = 0;
cache.writeBackIteration = false;
cache.deltaV = params.deltaV;
cache.Z = params.Z;
PxI32 batchCount = PxI32(params.numConstraintHeaders);
PxSolverBody* PX_RESTRICT bodyListStart = params.bodyListStart;
const PxU32 bodyListSize = params.bodyListSize;
Cm::SpatialVector* PX_RESTRICT motionVelocityArray = params.motionVelocityArray;
const PxU32 velocityIterations = params.velocityIterations;
const PxU32 positionIterations = params.positionIterations;
const PxU32 numConstraintHeaders = params.numConstraintHeaders;
const PxU32 articulationListSize = params.articulationListSize;
ArticulationSolverDesc* PX_RESTRICT articulationListStart = params.articulationListStart;
PX_ASSERT(velocityIterations >= 1);
PX_ASSERT(positionIterations >= 1);
if(numConstraintHeaders == 0)
{
for (PxU32 baIdx = 0; baIdx < bodyListSize; baIdx++)
{
Cm::SpatialVector& motionVel = motionVelocityArray[baIdx];
PxSolverBody& atom = bodyListStart[baIdx];
motionVel.linear = atom.linearVelocity;
motionVel.angular = atom.angularState;
}
for (PxU32 i = 0; i < articulationListSize; i++)
ArticulationPImpl::saveVelocity(articulationListStart[i], cache.deltaV);
return;
}
BatchIterator contactIterator(params.constraintBatchHeaders, params.numConstraintHeaders);
BatchIterator frictionIterator(params.frictionConstraintBatches, params.numFrictionConstraintHeaders);
PxI32 frictionBatchCount = PxI32(params.numFrictionConstraintHeaders);
PxSolverConstraintDesc* PX_RESTRICT constraintList = params.constraintList;
PxSolverConstraintDesc* PX_RESTRICT frictionConstraintList = params.frictionConstraintList;
//0-(n-1) iterations
PxI32 normalIter = 0;
PxI32 frictionIter = 0;
for (PxU32 iteration = positionIterations; iteration > 0; iteration--) //decreasing positive numbers == position iters
{
SolveBlockParallel(constraintList, batchCount, normalIter * batchCount, batchCount,
cache, contactIterator, iteration == 1 ? gVTableSolveConcludeBlockCoulomb : gVTableSolveBlockCoulomb, normalIter);
++normalIter;
}
if(frictionBatchCount>0)
{
const PxU32 numIterations = positionIterations * 2;
for (PxU32 iteration = numIterations; iteration > 0; iteration--) //decreasing positive numbers == position iters
{
SolveBlockParallel(frictionConstraintList, frictionBatchCount, frictionIter * frictionBatchCount, frictionBatchCount,
cache, frictionIterator, iteration == 1 ? gVTableSolveConcludeBlockCoulomb : gVTableSolveBlockCoulomb, frictionIter);
++frictionIter;
}
}
for (PxU32 baIdx = 0; baIdx < bodyListSize; baIdx++)
{
const PxSolverBody& atom = bodyListStart[baIdx];
Cm::SpatialVector& motionVel = motionVelocityArray[baIdx];
motionVel.linear = atom.linearVelocity;
motionVel.angular = atom.angularState;
}
for (PxU32 i = 0; i < articulationListSize; i++)
ArticulationPImpl::saveVelocity(articulationListStart[i], cache.deltaV);
const PxU32 velItersMinOne = velocityIterations - 1;
PxU32 iteration = 0;
for(; iteration < velItersMinOne; ++iteration)
{
SolveBlockParallel(constraintList, batchCount, normalIter * batchCount, batchCount,
cache, contactIterator, gVTableSolveBlockCoulomb, normalIter);
++normalIter;
if(frictionBatchCount > 0)
{
SolveBlockParallel(frictionConstraintList, frictionBatchCount, frictionIter * frictionBatchCount, frictionBatchCount,
cache, frictionIterator, gVTableSolveBlockCoulomb, frictionIter);
++frictionIter;
}
}
PxI32* outThresholdPairs = params.outThresholdPairs;
ThresholdStreamElement* PX_RESTRICT thresholdStream = params.thresholdStream;
PxU32 thresholdStreamLength = params.thresholdStreamLength;
cache.writeBackIteration = true;
cache.mSharedOutThresholdPairs = outThresholdPairs;
cache.mSharedThresholdStreamLength = thresholdStreamLength;
cache.mSharedThresholdStream = thresholdStream;
for(; iteration < velocityIterations; ++iteration)
{
SolveBlockParallel(constraintList, batchCount, normalIter * batchCount, batchCount,
cache, contactIterator, gVTableSolveWriteBackBlockCoulomb, normalIter);
++normalIter;
if(frictionBatchCount > 0)
{
SolveBlockParallel(frictionConstraintList, frictionBatchCount, frictionIter * frictionBatchCount, frictionBatchCount,
cache, frictionIterator, gVTableSolveWriteBackBlockCoulomb, frictionIter);
++frictionIter;
}
}
//Write back remaining threshold streams
if(cache.mThresholdStreamIndex > 0)
{
//Write back to global buffer
PxI32 threshIndex = physx::shdfnd::atomicAdd(reinterpret_cast<PxI32*>(&outThresholdPairs), PxI32(cache.mThresholdStreamIndex)) - PxI32(cache.mThresholdStreamIndex);
for(PxU32 b = 0; b < cache.mThresholdStreamIndex; ++b)
{
thresholdStream[b + threshIndex] = cache.mThresholdStream[b];
}
cache.mThresholdStreamIndex = 0;
}
}
PxI32 SolverCoreGeneralPF::solveVParallelAndWriteBack(SolverIslandParams& params,
Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV) const
{
SolverContext cache;
cache.solverBodyArray = params.bodyDataList;
const PxI32 UnrollCount = PxI32(params.batchSize);
const PxI32 SaveUnrollCount = 64;
const PxI32 TempThresholdStreamSize = 32;
ThresholdStreamElement tempThresholdStream[TempThresholdStreamSize];
const PxI32 batchCount = PxI32(params.numConstraintHeaders);
const PxI32 frictionBatchCount = PxI32(params.numFrictionConstraintHeaders);//frictionConstraintBatches.size();
cache.mThresholdStream = tempThresholdStream;
cache.mThresholdStreamLength = TempThresholdStreamSize;
cache.mThresholdStreamIndex = 0;
cache.Z = Z;
cache.deltaV = deltaV;
const PxI32 positionIterations = PxI32(params.positionIterations);
const PxU32 velocityIterations = params.velocityIterations;
const PxI32 bodyListSize = PxI32(params.bodyListSize);
const PxI32 articulationListSize = PxI32(params.articulationListSize);
PX_ASSERT(velocityIterations >= 1);
PX_ASSERT(positionIterations >= 1);
PxI32* constraintIndex = ¶ms.constraintIndex;
PxI32* constraintIndex2 = ¶ms.constraintIndex2;
PxI32* frictionConstraintIndex = ¶ms.frictionConstraintIndex;
PxI32 endIndexCount = UnrollCount;
PxI32 index = physx::shdfnd::atomicAdd(constraintIndex, UnrollCount) - UnrollCount;
PxI32 frictionIndex = physx::shdfnd::atomicAdd(frictionConstraintIndex, UnrollCount) - UnrollCount;
BatchIterator contactIter(params.constraintBatchHeaders, params.numConstraintHeaders);
BatchIterator frictionIter(params.frictionConstraintBatches, params.numFrictionConstraintHeaders);
PxU32* headersPerPartition = params.headersPerPartition;
PxU32 nbPartitions = params.nbPartitions;
PxU32* frictionHeadersPerPartition = params.frictionHeadersPerPartition;
PxU32 nbFrictionPartitions = params.nbFrictionPartitions;
PxSolverConstraintDesc* PX_RESTRICT constraintList = params.constraintList;
PxSolverConstraintDesc* PX_RESTRICT frictionConstraintList = params.frictionConstraintList;
PxI32 maxNormalIndex = 0;
PxI32 maxProgress = 0;
PxI32 frictionEndIndexCount = UnrollCount;
PxI32 maxFrictionIndex = 0;
PxI32 normalIteration = 0;
PxI32 frictionIteration = 0;
PxU32 a = 0;
for(PxU32 i = 0; i < 2; ++i)
{
SolveBlockMethod* solveTable = i == 0 ? gVTableSolveBlockCoulomb : gVTableSolveConcludeBlockCoulomb;
for(; a < positionIterations - 1 + i; ++a)
{
for(PxU32 b = 0; b < nbPartitions; ++b)
{
WAIT_FOR_PROGRESS(constraintIndex2, maxProgress);
maxNormalIndex += headersPerPartition[b];
maxProgress += headersPerPartition[b];
PxI32 nbSolved = 0;
while(index < maxNormalIndex)
{
const PxI32 remainder = PxMin(maxNormalIndex - index, endIndexCount);
SolveBlockParallel(constraintList, remainder, index, batchCount, cache, contactIter, solveTable,
normalIteration);
index += remainder;
endIndexCount -= remainder;
nbSolved += remainder;
if(endIndexCount == 0)
{
endIndexCount = UnrollCount;
index = physx::shdfnd::atomicAdd(constraintIndex, UnrollCount) - UnrollCount;
}
}
if(nbSolved)
{
Ps::memoryBarrier();
Ps::atomicAdd(constraintIndex2, nbSolved);
}
}
++normalIteration;
}
}
for(PxU32 i = 0; i < 2; ++i)
{
SolveBlockMethod* solveTable = i == 0 ? gVTableSolveBlockCoulomb : gVTableSolveConcludeBlockCoulomb;
const PxI32 numIterations = positionIterations *2;
for(; a < numIterations - 1 + i; ++a)
{
for(PxU32 b = 0; b < nbFrictionPartitions; ++b)
{
WAIT_FOR_PROGRESS(constraintIndex2, maxProgress);
maxProgress += frictionHeadersPerPartition[b];
maxFrictionIndex += frictionHeadersPerPartition[b];
PxI32 nbSolved = 0;
while(frictionIndex < maxFrictionIndex)
{
const PxI32 remainder = PxMin(maxFrictionIndex - frictionIndex, frictionEndIndexCount);
SolveBlockParallel(frictionConstraintList, remainder, frictionIndex, frictionBatchCount, cache, frictionIter,
solveTable, frictionIteration);
frictionIndex += remainder;
frictionEndIndexCount -= remainder;
nbSolved += remainder;
if(frictionEndIndexCount == 0)
{
frictionEndIndexCount = UnrollCount;
frictionIndex = physx::shdfnd::atomicAdd(frictionConstraintIndex, UnrollCount) - UnrollCount;
}
}
if(nbSolved)
{
Ps::memoryBarrier();
Ps::atomicAdd(constraintIndex2, nbSolved);
}
}
++frictionIteration;
}
}
WAIT_FOR_PROGRESS(constraintIndex2, maxProgress);
PxI32* bodyListIndex = ¶ms.bodyListIndex;
ArticulationSolverDesc* PX_RESTRICT articulationListStart = params.articulationListStart;
PxSolverBody* PX_RESTRICT bodyListStart = params.bodyListStart;
Cm::SpatialVector* PX_RESTRICT motionVelocityArray = params.motionVelocityArray;
PxI32* bodyListIndex2 = ¶ms.bodyListIndex2;
PxI32 endIndexCount2 = SaveUnrollCount;
PxI32 index2 = physx::shdfnd::atomicAdd(bodyListIndex, SaveUnrollCount) - SaveUnrollCount;
{
PxI32 nbConcluded = 0;
while(index2 < articulationListSize)
{
const PxI32 remainder = PxMin(SaveUnrollCount, (articulationListSize - index2));
endIndexCount2 -= remainder;
for(PxI32 b = 0; b < remainder; ++b, ++index2)
{
ArticulationPImpl::saveVelocity(articulationListStart[index2], cache.deltaV);
}
nbConcluded += remainder;
if(endIndexCount2 == 0)
{
index2 = physx::shdfnd::atomicAdd(bodyListIndex, SaveUnrollCount) - SaveUnrollCount;
endIndexCount2 = SaveUnrollCount;
}
nbConcluded += remainder;
}
index2 -= articulationListSize;
//save velocity
while(index2 < bodyListSize)
{
const PxI32 remainder = PxMin(endIndexCount2, (bodyListSize - index2));
endIndexCount2 -= remainder;
for(PxI32 b = 0; b < remainder; ++b, ++index2)
{
Ps::prefetchLine(&bodyListStart[index2 + 8]);
Ps::prefetchLine(&motionVelocityArray[index2 + 8]);
PxSolverBody& body = bodyListStart[index2];
Cm::SpatialVector& motionVel = motionVelocityArray[index2];
motionVel.linear = body.linearVelocity;
motionVel.angular = body.angularState;
PX_ASSERT(motionVel.linear.isFinite());
PX_ASSERT(motionVel.angular.isFinite());
}
nbConcluded += remainder;
//Branch not required because this is the last time we use this atomic variable
//if(index2 < articulationListSizePlusbodyListSize)
{
index2 = physx::shdfnd::atomicAdd(bodyListIndex, SaveUnrollCount) - SaveUnrollCount - articulationListSize;
endIndexCount2 = SaveUnrollCount;
}
}
if(nbConcluded)
{
Ps::memoryBarrier();
physx::shdfnd::atomicAdd(bodyListIndex2, nbConcluded);
}
}
WAIT_FOR_PROGRESS(bodyListIndex2, (bodyListSize + articulationListSize));
a = 0;
for(; a < velocityIterations-1; ++a)
{
for(PxU32 b = 0; b < nbPartitions; ++b)
{
WAIT_FOR_PROGRESS(constraintIndex2, maxProgress);
maxNormalIndex += headersPerPartition[b];
maxProgress += headersPerPartition[b];
PxI32 nbSolved = 0;
while(index < maxNormalIndex)
{
const PxI32 remainder = PxMin(maxNormalIndex - index, endIndexCount);
SolveBlockParallel(constraintList, remainder, index, batchCount, cache, contactIter, gVTableSolveBlockCoulomb, normalIteration);
index += remainder;
endIndexCount -= remainder;
nbSolved += remainder;
if(endIndexCount == 0)
{
endIndexCount = UnrollCount;
index = physx::shdfnd::atomicAdd(constraintIndex, UnrollCount) - UnrollCount;
}
}
if(nbSolved)
{
Ps::memoryBarrier();
Ps::atomicAdd(constraintIndex2, nbSolved);
}
}
++normalIteration;
for(PxU32 b = 0; b < nbFrictionPartitions; ++b)
{
WAIT_FOR_PROGRESS(constraintIndex2, maxProgress);
maxFrictionIndex += frictionHeadersPerPartition[b];
maxProgress += frictionHeadersPerPartition[b];
PxI32 nbSolved = 0;
while(frictionIndex < maxFrictionIndex)
{
const PxI32 remainder = PxMin(maxFrictionIndex - frictionIndex, frictionEndIndexCount);
SolveBlockParallel(constraintList, remainder, index, batchCount, cache, contactIter, gVTableSolveBlockCoulomb,
normalIteration);
frictionIndex += remainder;
frictionEndIndexCount -= remainder;
nbSolved += remainder;
if(frictionEndIndexCount == 0)
{
frictionEndIndexCount = UnrollCount;
frictionIndex = physx::shdfnd::atomicAdd(frictionConstraintIndex, UnrollCount) - UnrollCount;
}
}
if(nbSolved)
{
Ps::memoryBarrier();
Ps::atomicAdd(constraintIndex2, nbSolved);
}
}
++frictionIteration;
}
ThresholdStreamElement* PX_RESTRICT thresholdStream = params.thresholdStream;
const PxU32 thresholdStreamLength = params.thresholdStreamLength;
PxI32* outThresholdPairs = params.outThresholdPairs;
cache.mSharedThresholdStream = thresholdStream;
cache.mSharedOutThresholdPairs = outThresholdPairs;
cache.mSharedThresholdStreamLength = thresholdStreamLength;
{
for(PxU32 b = 0; b < nbPartitions; ++b)
{
WAIT_FOR_PROGRESS(constraintIndex2, maxProgress);
maxNormalIndex += headersPerPartition[b];
maxProgress += headersPerPartition[b];
PxI32 nbSolved = 0;
while(index < maxNormalIndex)
{
const PxI32 remainder = PxMin(maxNormalIndex - index, endIndexCount);
SolveBlockParallel(constraintList, remainder, normalIteration * batchCount, batchCount,
cache, contactIter, gVTableSolveWriteBackBlockCoulomb, normalIteration);
index += remainder;
endIndexCount -= remainder;
nbSolved += remainder;
if(endIndexCount == 0)
{
endIndexCount = UnrollCount;
index = physx::shdfnd::atomicAdd(constraintIndex, UnrollCount) - UnrollCount;
}
}
if(nbSolved)
{
Ps::memoryBarrier();
Ps::atomicAdd(constraintIndex2, nbSolved);
}
}
++normalIteration;
cache.mSharedOutThresholdPairs = outThresholdPairs;
cache.mSharedThresholdStream = thresholdStream;
cache.mSharedThresholdStreamLength = thresholdStreamLength;
for(PxU32 b = 0; b < nbFrictionPartitions; ++b)
{
WAIT_FOR_PROGRESS(constraintIndex2, maxProgress);
maxFrictionIndex += frictionHeadersPerPartition[b];
maxProgress += frictionHeadersPerPartition[b];
PxI32 nbSolved = 0;
while(frictionIndex < maxFrictionIndex)
{
const PxI32 remainder = PxMin(maxFrictionIndex - frictionIndex, frictionEndIndexCount);
SolveBlockParallel(frictionConstraintList, remainder, frictionIndex, frictionBatchCount, cache, frictionIter,
gVTableSolveWriteBackBlockCoulomb, frictionIteration);
frictionIndex += remainder;
frictionEndIndexCount -= remainder;
nbSolved += remainder;
if(frictionEndIndexCount == 0)
{
frictionEndIndexCount = UnrollCount;
frictionIndex = physx::shdfnd::atomicAdd(frictionConstraintIndex, UnrollCount) - UnrollCount;
}
}
if(nbSolved)
{
Ps::memoryBarrier();
Ps::atomicAdd(constraintIndex2, nbSolved);
}
}
if(cache.mThresholdStreamIndex > 0)
{
//Write back to global buffer
PxI32 threshIndex = physx::shdfnd::atomicAdd(outThresholdPairs, PxI32(cache.mThresholdStreamIndex)) - PxI32(cache.mThresholdStreamIndex);
for(PxU32 b = 0; b < cache.mThresholdStreamIndex; ++b)
{
thresholdStream[b + threshIndex] = cache.mThresholdStream[b];
}
cache.mThresholdStreamIndex = 0;
}
++frictionIteration;
}
return normalIteration * batchCount + frictionIteration * frictionBatchCount;
}
void SolverCoreGeneralPF::writeBackV
(const PxSolverConstraintDesc* PX_RESTRICT constraintList, const PxU32 /*constraintListSize*/, PxConstraintBatchHeader* batchHeaders, const PxU32 numBatches,
ThresholdStreamElement* PX_RESTRICT thresholdStream, const PxU32 thresholdStreamLength, PxU32& outThresholdPairs,
PxSolverBodyData* atomListData, WriteBackBlockMethod writeBackTable[]) const
{
SolverContext cache;
cache.solverBodyArray = atomListData;
cache.mThresholdStream = thresholdStream;
cache.mThresholdStreamLength = thresholdStreamLength;
cache.mThresholdStreamIndex = 0;
PxI32 outThreshIndex = 0;
for(PxU32 j = 0; j < numBatches; ++j)
{
PxU8 type = *constraintList[batchHeaders[j].mStartIndex].constraint;
writeBackTable[type](constraintList + batchHeaders[j].mStartIndex,
batchHeaders[j].mStride, cache);
}
outThresholdPairs = PxU32(outThreshIndex);
}
}
}
//#endif
|
/*
* Copyright (c) 2011-2013,2017-2018 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* 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 the copyright holders 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.
*
* Authors: Gabe Black
*/
#ifndef __ARCH_ARM_INSTS_MISC64_HH__
#define __ARCH_ARM_INSTS_MISC64_HH__
#include "arch/arm/insts/static_inst.hh"
class ImmOp64 : public ArmStaticInst
{
protected:
uint64_t imm;
ImmOp64(const char *mnem, ExtMachInst _machInst,
OpClass __opClass, uint64_t _imm) :
ArmStaticInst(mnem, _machInst, __opClass), imm(_imm)
{}
std::string generateDisassembly(
Addr pc, const SymbolTable *symtab) const override;
};
class RegRegImmImmOp64 : public ArmStaticInst
{
protected:
IntRegIndex dest;
IntRegIndex op1;
uint64_t imm1;
uint64_t imm2;
RegRegImmImmOp64(const char *mnem, ExtMachInst _machInst,
OpClass __opClass, IntRegIndex _dest, IntRegIndex _op1,
uint64_t _imm1, uint64_t _imm2) :
ArmStaticInst(mnem, _machInst, __opClass),
dest(_dest), op1(_op1), imm1(_imm1), imm2(_imm2)
{}
std::string generateDisassembly(
Addr pc, const SymbolTable *symtab) const override;
};
class RegRegRegImmOp64 : public ArmStaticInst
{
protected:
IntRegIndex dest;
IntRegIndex op1;
IntRegIndex op2;
uint64_t imm;
RegRegRegImmOp64(const char *mnem, ExtMachInst _machInst,
OpClass __opClass, IntRegIndex _dest, IntRegIndex _op1,
IntRegIndex _op2, uint64_t _imm) :
ArmStaticInst(mnem, _machInst, __opClass),
dest(_dest), op1(_op1), op2(_op2), imm(_imm)
{}
std::string generateDisassembly(
Addr pc, const SymbolTable *symtab) const override;
};
class UnknownOp64 : public ArmStaticInst
{
protected:
UnknownOp64(const char *mnem, ExtMachInst _machInst, OpClass __opClass) :
ArmStaticInst(mnem, _machInst, __opClass)
{}
std::string generateDisassembly(
Addr pc, const SymbolTable *symtab) const override;
};
/**
* This class is implementing the Base class for a generic AArch64
* instruction which is making use of system registers (MiscReg), like
* MSR,MRS,SYS. The common denominator or those instruction is the
* chance that the system register access is trapped to an upper
* Exception level. MiscRegOp64 is providing that feature. Other
* "pseudo" instructions, like access to implementation defined
* registers can inherit from this class to make use of the trapping
* functionalities even if there is no data movement between GPRs and
* system register.
*/
class MiscRegOp64 : public ArmStaticInst
{
protected:
bool miscRead;
MiscRegOp64(const char *mnem, ExtMachInst _machInst,
OpClass __opClass, bool misc_read) :
ArmStaticInst(mnem, _machInst, __opClass),
miscRead(misc_read)
{}
Fault trap(ThreadContext *tc, MiscRegIndex misc_reg,
ExceptionLevel el, uint32_t immediate) const;
private:
bool checkEL1Trap(ThreadContext *tc, const MiscRegIndex misc_reg,
ExceptionLevel el) const;
bool checkEL2Trap(ThreadContext *tc, const MiscRegIndex misc_reg,
ExceptionLevel el, bool *is_vfp_neon) const;
bool checkEL3Trap(ThreadContext *tc, const MiscRegIndex misc_reg,
ExceptionLevel el, bool *is_vfp_neon) const;
};
class MiscRegRegImmOp64 : public MiscRegOp64
{
protected:
MiscRegIndex dest;
IntRegIndex op1;
uint32_t imm;
MiscRegRegImmOp64(const char *mnem, ExtMachInst _machInst,
OpClass __opClass, MiscRegIndex _dest,
IntRegIndex _op1, uint32_t _imm) :
MiscRegOp64(mnem, _machInst, __opClass, false),
dest(_dest), op1(_op1), imm(_imm)
{}
std::string generateDisassembly(
Addr pc, const SymbolTable *symtab) const override;
};
class RegMiscRegImmOp64 : public MiscRegOp64
{
protected:
IntRegIndex dest;
MiscRegIndex op1;
uint32_t imm;
RegMiscRegImmOp64(const char *mnem, ExtMachInst _machInst,
OpClass __opClass, IntRegIndex _dest,
MiscRegIndex _op1, uint32_t _imm) :
MiscRegOp64(mnem, _machInst, __opClass, true),
dest(_dest), op1(_op1), imm(_imm)
{}
std::string generateDisassembly(
Addr pc, const SymbolTable *symtab) const override;
};
class MiscRegImplDefined64 : public MiscRegOp64
{
protected:
const std::string fullMnemonic;
const MiscRegIndex miscReg;
const uint32_t imm;
const bool warning;
public:
MiscRegImplDefined64(const char *mnem, ExtMachInst _machInst,
MiscRegIndex misc_reg, bool misc_read,
uint32_t _imm, const std::string full_mnem,
bool _warning) :
MiscRegOp64(mnem, _machInst, No_OpClass, misc_read),
fullMnemonic(full_mnem), miscReg(misc_reg), imm(_imm),
warning(_warning)
{
assert(miscReg == MISCREG_IMPDEF_UNIMPL);
}
protected:
Fault execute(ExecContext *xc,
Trace::InstRecord *traceData) const override;
std::string generateDisassembly(
Addr pc, const SymbolTable *symtab) const override;
};
#endif
|
/*
* Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
* Copyright (C) 2008 INdT - Instituto Nokia de Tecnologia
* Copyright (C) 2009-2010 ProFUSION embedded systems
* Copyright (C) 2009-2010 Samsung Electronics
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "config.h"
#include "PopupMenuEfl.h"
#include "Chrome.h"
#include "ChromeClientEfl.h"
#include "Frame.h"
#include "FrameView.h"
#include "Page.h"
#include "PopupMenuClient.h"
namespace WebCore {
PopupMenuEfl::PopupMenuEfl(PopupMenuClient* client)
: m_popupClient(client)
, m_view(0)
{
}
PopupMenuEfl::~PopupMenuEfl()
{
// Tell client to destroy data related to this popup since this object is
// going away.
if (m_view)
hide();
}
void PopupMenuEfl::show(const IntRect& rect, FrameView* view, int index)
{
ASSERT(m_popupClient);
ChromeClientEfl* chromeClient = static_cast<ChromeClientEfl*>(view->frame()->page()->chrome().client());
ASSERT(chromeClient);
m_view = view;
chromeClient->createSelectPopup(m_popupClient, index, rect);
}
void PopupMenuEfl::hide()
{
ASSERT(m_view);
ChromeClientEfl* chromeClient = static_cast<ChromeClientEfl*>(m_view->frame()->page()->chrome().client());
ASSERT(chromeClient);
chromeClient->destroySelectPopup();
}
void PopupMenuEfl::updateFromElement()
{
client()->setTextFromItem(client()->selectedIndex());
}
void PopupMenuEfl::disconnectClient()
{
m_popupClient = 0;
}
}
|
// Implementation of ARIA Cryptosystem with 128 bit key
// Written by Siddharth Ramachandran
// November 1, 2015
#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
#include <string>
#include <algorithm>
#include <stdlib.h>
using namespace boost::multiprecision;
// Intialise S-Box values
static const uint8_t sb1[256] =
{
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,
0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,
0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,
0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16
};
static const uint8_t sb2[256] =
{
0xE2, 0x4E, 0x54, 0xFC, 0x94, 0xC2, 0x4A, 0xCC, 0x62, 0x0D, 0x6A, 0x46, 0x3C, 0x4D, 0x8B, 0xD1,
0x5E, 0xFA, 0x64, 0xCB, 0xB4, 0x97, 0xBE, 0x2B, 0xBC, 0x77, 0x2E, 0x03, 0xD3, 0x19, 0x59, 0xC1,
0x1D, 0x06, 0x41, 0x6B, 0x55, 0xF0, 0x99, 0x69, 0xEA, 0x9C, 0x18, 0xAE, 0x63, 0xDF, 0xE7, 0xBB,
0x00, 0x73, 0x66, 0xFB, 0x96, 0x4C, 0x85, 0xE4, 0x3A, 0x09, 0x45, 0xAA, 0x0F, 0xEE, 0x10, 0xEB,
0x2D, 0x7F, 0xF4, 0x29, 0xAC, 0xCF, 0xAD, 0x91, 0x8D, 0x78, 0xC8, 0x95, 0xF9, 0x2F, 0xCE, 0xCD,
0x08, 0x7A, 0x88, 0x38, 0x5C, 0x83, 0x2A, 0x28, 0x47, 0xDB, 0xB8, 0xC7, 0x93, 0xA4, 0x12, 0x53,
0xFF, 0x87, 0x0E, 0x31, 0x36, 0x21, 0x58, 0x48, 0x01, 0x8E, 0x37, 0x74, 0x32, 0xCA, 0xE9, 0xB1,
0xB7, 0xAB, 0x0C, 0xD7, 0xC4, 0x56, 0x42, 0x26, 0x07, 0x98, 0x60, 0xD9, 0xB6, 0xB9, 0x11, 0x40,
0xEC, 0x20, 0x8C, 0xBD, 0xA0, 0xC9, 0x84, 0x04, 0x49, 0x23, 0xF1, 0x4F, 0x50, 0x1F, 0x13, 0xDC,
0xD8, 0xC0, 0x9E, 0x57, 0xE3, 0xC3, 0x7B, 0x65, 0x3B, 0x02, 0x8F, 0x3E, 0xE8, 0x25, 0x92, 0xE5,
0x15, 0xDD, 0xFD, 0x17, 0xA9, 0xBF, 0xD4, 0x9A, 0x7E, 0xC5, 0x39, 0x67, 0xFE, 0x76, 0x9D, 0x43,
0xA7, 0xE1, 0xD0, 0xF5, 0x68, 0xF2, 0x1B, 0x34, 0x70, 0x05, 0xA3, 0x8A, 0xD5, 0x79, 0x86, 0xA8,
0x30, 0xC6, 0x51, 0x4B, 0x1E, 0xA6, 0x27, 0xF6, 0x35, 0xD2, 0x6E, 0x24, 0x16, 0x82, 0x5F, 0xDA,
0xE6, 0x75, 0xA2, 0xEF, 0x2C, 0xB2, 0x1C, 0x9F, 0x5D, 0x6F, 0x80, 0x0A, 0x72, 0x44, 0x9B, 0x6C,
0x90, 0x0B, 0x5B, 0x33, 0x7D, 0x5A, 0x52, 0xF3, 0x61, 0xA1, 0xF7, 0xB0, 0xD6, 0x3F, 0x7C, 0x6D,
0xED, 0x14, 0xE0, 0xA5, 0x3D, 0x22, 0xB3, 0xF8, 0x89, 0xDE, 0x71, 0x1A, 0xAF, 0xBA, 0xB5, 0x81
};
static const uint8_t sb3[256] =
{
0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB,
0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB,
0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E,
0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25,
0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92,
0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84,
0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06,
0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B,
0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73,
0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E,
0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B,
0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4,
0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F,
0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF,
0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D
};
static const uint8_t sb4[256] =
{
0x30, 0x68, 0x99, 0x1B, 0x87, 0xB9, 0x21, 0x78, 0x50, 0x39, 0xDB, 0xE1, 0x72, 0x09, 0x62, 0x3C,
0x3E, 0x7E, 0x5E, 0x8E, 0xF1, 0xA0, 0xCC, 0xA3, 0x2A, 0x1D, 0xFB, 0xB6, 0xD6, 0x20, 0xC4, 0x8D,
0x81, 0x65, 0xF5, 0x89, 0xCB, 0x9D, 0x77, 0xC6, 0x57, 0x43, 0x56, 0x17, 0xD4, 0x40, 0x1A, 0x4D,
0xC0, 0x63, 0x6C, 0xE3, 0xB7, 0xC8, 0x64, 0x6A, 0x53, 0xAA, 0x38, 0x98, 0x0C, 0xF4, 0x9B, 0xED,
0x7F, 0x22, 0x76, 0xAF, 0xDD, 0x3A, 0x0B, 0x58, 0x67, 0x88, 0x06, 0xC3, 0x35, 0x0D, 0x01, 0x8B,
0x8C, 0xC2, 0xE6, 0x5F, 0x02, 0x24, 0x75, 0x93, 0x66, 0x1E, 0xE5, 0xE2, 0x54, 0xD8, 0x10, 0xCE,
0x7A, 0xE8, 0x08, 0x2C, 0x12, 0x97, 0x32, 0xAB, 0xB4, 0x27, 0x0A, 0x23, 0xDF, 0xEF, 0xCA, 0xD9,
0xB8, 0xFA, 0xDC, 0x31, 0x6B, 0xD1, 0xAD, 0x19, 0x49, 0xBD, 0x51, 0x96, 0xEE, 0xE4, 0xA8, 0x41,
0xDA, 0xFF, 0xCD, 0x55, 0x86, 0x36, 0xBE, 0x61, 0x52, 0xF8, 0xBB, 0x0E, 0x82, 0x48, 0x69, 0x9A,
0xE0, 0x47, 0x9E, 0x5C, 0x04, 0x4B, 0x34, 0x15, 0x79, 0x26, 0xA7, 0xDE, 0x29, 0xAE, 0x92, 0xD7,
0x84, 0xE9, 0xD2, 0xBA, 0x5D, 0xF3, 0xC5, 0xB0, 0xBF, 0xA4, 0x3B, 0x71, 0x44, 0x46, 0x2B, 0xFC,
0xEB, 0x6F, 0xD5, 0xF6, 0x14, 0xFE, 0x7C, 0x70, 0x5A, 0x7D, 0xFD, 0x2F, 0x18, 0x83, 0x16, 0xA5,
0x91, 0x1F, 0x05, 0x95, 0x74, 0xA9, 0xC1, 0x5B, 0x4A, 0x85, 0x6D, 0x13, 0x07, 0x4F, 0x4E, 0x45,
0xB2, 0x0F, 0xC9, 0x1C, 0xA6, 0xBC, 0xEC, 0x73, 0x90, 0x7B, 0xCF, 0x59, 0x8F, 0xA1, 0xF9, 0x2D,
0xF2, 0xB1, 0x00, 0x94, 0x37, 0x9F, 0xD0, 0x2E, 0x9C, 0x6E, 0x28, 0x3F, 0x80, 0xF0, 0x3D, 0xD3,
0x25, 0x8A, 0xB5, 0xE7, 0x42, 0xB3, 0xC7, 0xEA, 0xF7, 0x4C, 0x11, 0x33, 0x03, 0xA2, 0xAC, 0x60
};
uint128_t CK1, CK2, CK3, KL, KR, W0, W1, W2, W3;
uint128_t ek[18], dk[18];
// 8 bit XOR
int xor_8(int x, int y)
{
return (~(x & y) & ~(~x & ~y));
}
uint128_t a(uint128_t v1)
{
int x[16],y[16],i=0;
uint128_t out=0x0;
for (i=0;i<16;i++)
{
uint128_t val= v1 & 0xff;
v1=v1>>8;
x[15-i]= val.template convert_to<int>();
}
y[0] = xor_8(xor_8(xor_8(xor_8(xor_8(xor_8(x[3],x[4]),x[6]),x[8]),x[9]),x[13]),x[14]);
y[1] = xor_8(xor_8(xor_8(xor_8(xor_8(xor_8(x[2],x[5]),x[7]),x[8]),x[9]),x[12]),x[15]);
y[2] = xor_8(xor_8(xor_8(xor_8(xor_8(xor_8(x[1],x[4]),x[6]),x[10]),x[11]),x[12]),x[15]);
y[3] = xor_8(xor_8(xor_8(xor_8(xor_8(xor_8(x[0],x[5]),x[7]),x[10]),x[11]),x[13]),x[14]);
y[4] = xor_8(xor_8(xor_8(xor_8(xor_8(xor_8(x[0],x[2]),x[5]),x[8]),x[11]),x[14]),x[15]);
y[5] = xor_8(xor_8(xor_8(xor_8(xor_8(xor_8(x[1],x[3]),x[4]),x[9]),x[10]),x[14]),x[15]);
y[6] = xor_8(xor_8(xor_8(xor_8(xor_8(xor_8(x[0],x[2]),x[7]),x[9]),x[10]),x[12]),x[13]);
y[7] = xor_8(xor_8(xor_8(xor_8(xor_8(xor_8(x[1],x[3]),x[6]),x[8]),x[11]),x[12]),x[13]);
y[8] = xor_8(xor_8(xor_8(xor_8(xor_8(xor_8(x[0],x[1]),x[4]),x[7]),x[10]),x[13]),x[15]);
y[9] = xor_8(xor_8(xor_8(xor_8(xor_8(xor_8(x[0],x[1]),x[5]),x[6]),x[11]),x[12]),x[14]);
y[10] = xor_8(xor_8(xor_8(xor_8(xor_8(xor_8(x[2],x[3]),x[5]),x[6]),x[8]),x[13]),x[15]);
y[11] = xor_8(xor_8(xor_8(xor_8(xor_8(xor_8(x[2],x[3]),x[4]),x[7]),x[9]),x[12]),x[14]);
y[12] = xor_8(xor_8(xor_8(xor_8(xor_8(xor_8(x[1],x[2]),x[6]),x[7]),x[9]),x[11]),x[12]);
y[13] = xor_8(xor_8(xor_8(xor_8(xor_8(xor_8(x[0],x[3]),x[6]),x[7]),x[8]),x[10]),x[13]);
y[14] = xor_8(xor_8(xor_8(xor_8(xor_8(xor_8(x[0],x[3]),x[4]),x[5]),x[9]),x[11]),x[14]);
y[15] = xor_8(xor_8(xor_8(xor_8(xor_8(xor_8(x[1],x[2]),x[4]),x[5]),x[8]),x[10]),x[15]);
for(i=0;i<16;i++)
{
out=out<<8;
out = out | y[i];
}
return out;
}
//Substitution Layer 1
uint128_t sl1(uint128_t v1)
{
int x[16],y[16],i=0;
uint128_t out=0x0;
for (i=0;i<16;i++)
{
uint128_t val= v1 & 0xff;
v1=v1>>8;
x[15-i]= val.template convert_to<int>();
}
for (i=0; i<16;i+=4)
{
y[i] = sb1[x[i]];
y[i+1] = sb2[x[i+1]];
y[i+2] = sb3[x[i+2]];
y[i+3] = sb4[x[i+3]];
}
for(i=0;i<16;i++)
{
out=out<<8;
out = out | y[i];
}
return out;
}
//Substitution Layer 2
uint128_t sl2(uint128_t v1)
{
int x[16],y[16],i=0;
uint128_t out=0x0;
for (i=0;i<16;i++)
{
uint128_t val= v1 & 0xff;
v1=v1>>8;
x[15-i]= val.template convert_to<int>();
}
for (i=0; i<16;i+=4)
{
y[i] = sb3[x[i]];
y[i+1] = sb4[x[i+1]];
y[i+2] = sb1[x[i+2]];
y[i+3] = sb2[x[i+3]];
}
for(i=0;i<16;i++)
{
out=out<<8;
out = out | y[i];
}
return out;
}
// 128 bit XOR
uint128_t xor_128(uint128_t x, uint128_t y )
{
return (~(x & y) & ~(~x & ~y));
}
// Round function for odd rounds
uint128_t fo(uint128_t d, uint128_t rk)
{
return a(sl1(xor_128(d,rk)));
}
// Round function for even rounds
uint128_t fe(uint128_t d, uint128_t rk)
{
return a(sl2(xor_128(d,rk)));
}
// 128 bit circular right shift
uint128_t ror_128(uint128_t x, int num)
{
return (x >> num) | (x << (128-num));
}
// 128 bit circular left shift
uint128_t rol_128(uint128_t x, int num)
{
return (x << num) | (x >> (128-num));
}
// Initialise the constants
void init_const()
{
uint32_t x1=0x517CC1B7;
uint32_t x2=0x27220A94;
uint32_t x3=0xFE13ABE8;
uint32_t x4=0xFA9A6EE0;
CK1=x1;
CK1=CK1<<32;
CK1=CK1+x2;
CK1=CK1<<32;
CK1=CK1+x3;
CK1=CK1<<32;
CK1=CK1+x4;
x1=0x6DB14ACC;
x2=0x9E21C820;
x3=0xFF28B1D5;
x4=0xEF5DE2B0;
CK2=x1;
CK2=CK2<<32;
CK2=CK2+x2;
CK2=CK2<<32;
CK2=CK2+x3;
CK2=CK2<<32;
CK2=CK2+x4;
x1=0xDB92371D;
x2=0x2126E970;
x3=0x03249775;
x4=0x04E8C90E;
CK3=x1;
CK3=CK3<<32;
CK3=CK3+x2;
CK3=CK3<<32;
CK3=CK3+x3;
CK3=CK3<<32;
CK3=CK3+x4;
//Fiestel Round value init
W0 = KL;
W1 = xor_128(fo(W0,CK1),KR);
W2 = xor_128(fe(W1,CK2),W0);
W3 = xor_128(fo(W2,CK3),W1);
}
// Rounds key generation
void round_key_gen()
{
int i=1, num=19;
for (i=1; i <= 8; i+=4)
{
ek[i] = xor_128(W0,ror_128(W1,num));
ek[i+1] = xor_128(W1,ror_128(W2,num));
ek[i+2] = xor_128(W2,ror_128(W3,num));
ek[i+3] = xor_128(ror_128(W0,num),W3);
num+=12;
}
num=61;
for(i=9; i<= 16; i+=4)
{
ek[i] = xor_128(W0,rol_128(W1,num));
ek[i+1] = xor_128(W1, rol_128(W2,num));
ek[i+2] = xor_128(W2, rol_128(W3,num));
ek[i+3] = xor_128(rol_128(W0,num),W3);
num-=30;
}
ek[17] = xor_128(W0, rol_128(W1,19));
}
// Perform 12 round encryption using appropriate round function
uint128_t encrypt(uint128_t P)
{
int i=1;
for (i=1;i<=11;i++)
{
if(i % 2 == 1)
{
P = fo(P,ek[i]);
}
else if (i % 2 == 0)
{
P = fe(P,ek[i]);
}
}
return (xor_128(sl2(xor_128(P,ek[12])),ek[13]));
}
// Decryption round key generation
void decrypt_round_key_gen()
{
int i=0, count=2;
dk[1] = ek[13];
for (i=12; i >= 2; --i)
{
dk[count] = a(ek[i]);
++count;
}
dk[count] = ek[1];
}
// Performs the decryption
uint128_t decrypt(uint128_t P)
{
int i=1;
for (i=1;i<=11;i++)
{
if(i % 2 == 1)
{
P = fo(P,dk[i]);
}
else if (i % 2 == 0)
{
P = fe(P,dk[i]);
}
}
return (xor_128(sl2(xor_128(P,dk[12])),dk[13]));
}
int main() {
int i=0;
char choice;
std::string key;
std::cout<<"Enter 128 bit key: \n";
std::getline(std::cin,key);
for(i=0;i<32;i+=2)
{
int x = strtoul(key.substr(i,2).c_str(), NULL, 16);
KL = KL << 8;
KL = KL | x;
}
init_const();
round_key_gen();
while (1)
{
uint128_t P, cipher_text, plain_text, temp;
int count =0, g=0;
uint8_t x=0;
std::string input, output, tp;
std::cout<<"1. Encrypt \n";
std::cout<<"2. Decrypt \n";
std::cout<<"3. Exit \n";
std::cout<<"\n\nEnter choice: ";
std::cin>>choice;
switch (choice)
{
case '1': // Encrypt
input.clear();
std::cin.ignore();
std::cout<<"Enter a string: \n";
std::getline(std::cin, input);
std::cout<<"Cipher Text: ";
count =0;
for (i=0;i<input.length();++i)
{
++count;
P = P << 8;
uint8_t t= input[i];
P = P | t;
if (count == 16)
{
cipher_text=encrypt(P);
std::cout<<std::hex<<cipher_text;
count=0;
P = P << 128;
}
}
if (count < 16 && count > 0)
{
P = P << ((16 - count)*8);
cipher_text=encrypt(P);
std::cout<<std::hex<<cipher_text;
}
std::cout<<"\n\n\n";
break;
case '2': // Decrypt
decrypt_round_key_gen();
input.clear();
std::cin.ignore();
std::cout<<"Enter cipher text: \n";
std::getline(std::cin, input);
for (i=0;i<input.length();i+=2)
{
count+=2;
x = strtoul(input.substr(i,2).c_str(), NULL, 16);
cipher_text = cipher_text<<8;
cipher_text = cipher_text | x;
if (count == 32)
{
plain_text = decrypt(cipher_text);
for(g=0;g<16;g++)
{
temp = plain_text & 0xff;
plain_text = plain_text >> 8;
tp.push_back(temp.template convert_to<int>());
}
count=0;
cipher_text = cipher_text << 128;
std::reverse(tp.begin(), tp.end());
output.append(tp);
tp.clear();
}
}
std::cout<<"\nThe plain text: "<<output<<"\n\n\n";
break;
case '3':
return 0;
break;
}
}
return 0;
}
|
/**
* Copyright 2019 Huawei Technologies Co., Ltd
* 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.
*/
#include "minddata/dataset/engine/datasetops/source/celeba_op.h"
#include <fstream>
#include <iomanip>
#include "minddata/dataset/core/config_manager.h"
#include "minddata/dataset/util/path.h"
#include "minddata/dataset/engine/datasetops/source/sampler/sequential_sampler.h"
#include "minddata/dataset/engine/data_schema.h"
#include "minddata/dataset/engine/execution_tree.h"
#include "minddata/dataset/engine/opt/pass.h"
#include "minddata/dataset/kernels/image/image_utils.h"
namespace mindspore {
namespace dataset {
CelebAOp::Builder::Builder() : builder_decode_(false), builder_sampler_(nullptr) {
std::shared_ptr<ConfigManager> cfg = GlobalContext::config_manager();
builder_num_workers_ = cfg->num_parallel_workers();
builder_rows_per_buffer_ = cfg->rows_per_buffer();
builder_op_connector_size_ = cfg->op_connector_size();
}
Status CelebAOp::Builder::Build(std::shared_ptr<CelebAOp> *op) {
MS_LOG(DEBUG) << "Celeba dataset directory is " << builder_dir_.c_str() << ".";
MS_LOG(DEBUG) << "Celeba dataset type is " << builder_usage_.c_str() << ".";
RETURN_IF_NOT_OK(SanityCheck());
if (builder_sampler_ == nullptr) {
const int64_t num_samples = 0;
const int64_t start_index = 0;
builder_sampler_ = std::make_shared<SequentialSampler>(start_index, num_samples);
}
builder_schema_ = std::make_unique<DataSchema>();
RETURN_IF_NOT_OK(
builder_schema_->AddColumn(ColDescriptor("image", DataType(DataType::DE_UINT8), TensorImpl::kFlexible, 1)));
// label is like this:0 1 0 0 1......
RETURN_IF_NOT_OK(
builder_schema_->AddColumn(ColDescriptor("attr", DataType(DataType::DE_UINT32), TensorImpl::kFlexible, 1)));
*op = std::make_shared<CelebAOp>(builder_num_workers_, builder_rows_per_buffer_, builder_dir_,
builder_op_connector_size_, builder_decode_, builder_usage_, builder_extensions_,
std::move(builder_schema_), std::move(builder_sampler_));
if (*op == nullptr) {
return Status(StatusCode::kUnexpectedError, __LINE__, __FILE__, "CelebAOp init failed.");
}
return Status::OK();
}
Status CelebAOp::Builder::SanityCheck() {
Path dir(builder_dir_);
std::string err_msg;
err_msg += dir.IsDirectory() == false
? "Invalid parameter, CelebA path is invalid or not set, path: " + builder_dir_ + ".\n"
: "";
err_msg += builder_num_workers_ <= 0 ? "Invalid parameter, num_parallel_workers must be greater than 0, but got " +
std::to_string(builder_num_workers_) + ".\n"
: "";
return err_msg.empty() ? Status::OK() : Status(StatusCode::kUnexpectedError, __LINE__, __FILE__, err_msg);
}
CelebAOp::CelebAOp(int32_t num_workers, int32_t rows_per_buffer, const std::string &dir, int32_t queue_size,
bool decode, const std::string &usage, const std::set<std::string> &exts,
std::unique_ptr<DataSchema> schema, std::shared_ptr<Sampler> sampler)
: ParallelOp(num_workers, queue_size, std::move(sampler)),
rows_per_buffer_(rows_per_buffer),
folder_path_(dir),
decode_(decode),
extensions_(exts),
data_schema_(std::move(schema)),
num_rows_in_attr_file_(0),
usage_(usage) {
attr_info_queue_ = std::make_unique<Queue<std::vector<std::string>>>(queue_size);
io_block_queues_.Init(num_workers_, queue_size);
}
Status CelebAOp::LaunchThreadsAndInitOp() {
if (tree_ == nullptr) {
return Status(StatusCode::kUnexpectedError, __LINE__, __FILE__, "Pipeline init failed, Execution tree not set.");
}
RETURN_IF_NOT_OK(io_block_queues_.Register(tree_->AllTasks()));
RETURN_IF_NOT_OK(attr_info_queue_->Register(tree_->AllTasks()));
RETURN_IF_NOT_OK(wait_for_workers_post_.Register(tree_->AllTasks()));
RETURN_IF_NOT_OK(tree_->AllTasks()->CreateAsyncTask("Walking attr file", std::bind(&CelebAOp::ParseAttrFile, this)));
RETURN_IF_NOT_OK(tree_->LaunchWorkers(num_workers_, std::bind(&CelebAOp::WorkerEntry, this, std::placeholders::_1)));
TaskManager::FindMe()->Post();
RETURN_IF_NOT_OK(ParseImageAttrInfo());
RETURN_IF_NOT_OK(sampler_->HandshakeRandomAccessOp(this));
return Status::OK();
}
Status CelebAOp::ParseAttrFile() {
TaskManager::FindMe()->Post();
Path folder_path(folder_path_);
std::ifstream attr_file((folder_path / "list_attr_celeba.txt").toString());
if (!attr_file.is_open()) {
std::string attr_file_name = (folder_path / "list_attr_celeba.txt").toString();
return Status(StatusCode::kFileNotExist, __LINE__, __FILE__,
"Invalid file, failed to open Celeba attr file: " + attr_file_name);
}
const auto PushBackToQueue = [this](std::vector<std::string> &vec, std::ifstream &attr_file,
std::ifstream &partition_file) {
Status s = attr_info_queue_->EmplaceBack(vec);
if (s.IsError()) {
CLOSE_FILE(attr_file, partition_file);
return s;
}
return Status::OK();
};
std::string rows_num;
std::string attr_name;
(void)getline(attr_file, rows_num);
try {
num_rows_in_attr_file_ = static_cast<int64_t>(std::stoul(rows_num)); // First line is rows number in attr file
} catch (std::invalid_argument &e) {
RETURN_STATUS_UNEXPECTED(
"Invalid data, failed to convert rows_num from attr_file to unsigned long, invalid argument: " + rows_num);
} catch (std::out_of_range &e) {
RETURN_STATUS_UNEXPECTED(
"Invalid data, failed to convert rows_num from attr_file to unsigned long, out of range: " + rows_num);
}
(void)getline(attr_file, attr_name); // Second line is attribute name,ignore it
std::string image_info;
std::vector<std::string> image_infos;
image_infos.reserve(oc_queue_size_);
while (getline(attr_file, image_info)) {
if ((image_info.empty()) || (usage_ != "all" && !CheckDatasetTypeValid())) {
continue;
}
image_infos.push_back(image_info);
if (image_info.size() % oc_queue_size_ == 0) {
RETURN_IF_NOT_OK(PushBackToQueue(image_infos, attr_file, partition_file_));
image_infos.clear();
}
}
if (!image_infos.empty()) {
RETURN_IF_NOT_OK(PushBackToQueue(image_infos, attr_file, partition_file_));
}
std::vector<std::string> end_indicator = std::vector<std::string>(0);
RETURN_IF_NOT_OK(PushBackToQueue(end_indicator, attr_file, partition_file_)); // end indicator
CLOSE_FILE(attr_file, partition_file_);
return Status::OK();
}
bool CelebAOp::CheckDatasetTypeValid() {
if (!partition_file_.is_open()) {
Path folder_path(folder_path_);
partition_file_.open((folder_path / "list_eval_partition.txt").toString());
if (!partition_file_.is_open()) {
MS_LOG(ERROR) << "Celeba partition file does not exist!";
return false;
}
}
std::string line;
(void)getline(partition_file_, line);
std::vector<std::string> vec = Split(line);
if (vec.size() != 2) {
return false;
}
int32_t type;
try {
type = std::stoi(vec[1]);
} catch (std::invalid_argument &e) {
MS_LOG(WARNING) << "Invalid data, failed to convert to unsigned long, invalid argument: " << vec[1] << ".";
return false;
} catch (std::out_of_range &e) {
MS_LOG(WARNING) << "Invalid data, failed to convert to unsigned long, out of range: " << vec[1] << ".";
return false;
}
// train:0, valid=1, test=2
if (usage_ == "train" && (type == 0)) {
return true;
} else if (usage_ == "valid" && (type == 1)) {
return true;
} else if (usage_ == "test" && (type == 2)) {
return true;
}
return false;
}
Status CelebAOp::ParseImageAttrInfo() {
std::vector<std::string> image_infos;
bool needMoreData = true;
RETURN_IF_NOT_OK(attr_info_queue_->PopFront(&image_infos));
while (!image_infos.empty() && needMoreData) {
for (uint32_t index = 0; index < image_infos.size(); index++) {
std::string image_info = image_infos[index];
std::vector<std::string> split = Split(image_info);
std::pair<std::string, std::vector<int32_t>> image_labels;
Path path(folder_path_);
Path file_path = path / split[0];
if (!extensions_.empty() && extensions_.find(file_path.Extension()) == extensions_.end()) {
MS_LOG(WARNING) << "Unsupported file found at " << file_path.toString().c_str() << ", its extension is "
<< file_path.Extension().c_str() << ".";
continue;
}
image_labels.first = split[0];
for (uint32_t label_index = 1; label_index < split.size(); label_index++) {
int32_t value;
try {
value = std::stoi(split[label_index]);
} catch (std::invalid_argument &e) {
RETURN_STATUS_UNEXPECTED("Invalid data, failed to convert to ulong, invalid argument: " + split[label_index]);
} catch (std::out_of_range &e) {
RETURN_STATUS_UNEXPECTED("Conversion to int failed, out of range: " + split[label_index]);
}
image_labels.second.push_back(value);
}
image_labels_vec_.push_back(image_labels);
}
RETURN_IF_NOT_OK(attr_info_queue_->PopFront(&image_infos));
}
num_rows_ = image_labels_vec_.size();
if (num_rows_ == 0) {
RETURN_STATUS_UNEXPECTED(
"Invalid data, no valid data matching the dataset API CelebADataset. Please check file path or dataset API.");
}
MS_LOG(DEBUG) << "Celeba dataset rows number is " << num_rows_ << ".";
return Status::OK();
}
std::vector<std::string> CelebAOp::Split(const std::string &line) {
std::string str = line;
std::string::size_type pos;
std::vector<std::string> split;
str += " ";
int size = str.size();
for (uint32_t index = 0; index < size;) {
pos = str.find(" ", index);
if (pos != index) { // skip space
std::string s = str.substr(index, pos - index);
split.push_back(s);
}
index = pos + 1;
}
return split;
}
// Main logic, Register Queue with TaskGroup, launch all threads and do the functor's work
Status CelebAOp::operator()() {
RETURN_IF_NOT_OK(LaunchThreadsAndInitOp());
std::unique_ptr<DataBuffer> data_buffer;
RETURN_IF_NOT_OK(sampler_->GetNextSample(&data_buffer));
RETURN_IF_NOT_OK(AddIOBlock(&data_buffer));
return Status::OK();
}
Status CelebAOp::AddIOBlock(std::unique_ptr<DataBuffer> *data_buffer) {
int64_t buff_count = 0;
while (true) {
std::vector<int64_t> keys;
keys.reserve(rows_per_buffer_);
int64_t row_count = 0;
while (!(*data_buffer)->eoe()) {
TensorRow sample_row;
RETURN_IF_NOT_OK((*data_buffer)->PopRow(&sample_row));
std::shared_ptr<Tensor> sample_ids = sample_row[0];
for (auto itr = sample_ids->begin<int64_t>(); itr != sample_ids->end<int64_t>(); ++itr) {
if ((*itr) >= num_rows_) {
MS_LOG(WARNING) << "Sample Id (" << *itr << ") is out of bounds, skipping. Max id is " << num_rows_ << ".";
continue;
}
keys.push_back(*itr);
row_count++;
if (row_count % rows_per_buffer_ == 0) {
RETURN_IF_NOT_OK(io_block_queues_[buff_count++ % num_workers_]->Add(
std::make_unique<IOBlock>(IOBlock(keys, IOBlock::kDeIoBlockNone))));
keys.clear();
}
}
RETURN_IF_NOT_OK(sampler_->GetNextSample(data_buffer));
}
if (!keys.empty()) {
RETURN_IF_NOT_OK(io_block_queues_[(buff_count++) % num_workers_]->Add(
std::make_unique<IOBlock>(IOBlock(keys, IOBlock::kDeIoBlockNone))));
}
if (IsLastIteration()) {
RETURN_IF_NOT_OK(
io_block_queues_[(buff_count++) % num_workers_]->Add(std::make_unique<IOBlock>(IOBlock::kDeIoBlockFlagEoe)));
RETURN_IF_NOT_OK(
io_block_queues_[(buff_count++) % num_workers_]->Add(std::make_unique<IOBlock>(IOBlock::kDeIoBlockFlagEof)));
for (int32_t i = 0; i < num_workers_; i++) {
RETURN_IF_NOT_OK(
io_block_queues_[i]->Add(std::make_unique<IOBlock>(std::vector<int64_t>(), IOBlock::kDeIoBlockNone)));
}
return Status::OK();
} else { // not the last repeat.
RETURN_IF_NOT_OK(
io_block_queues_[(buff_count++) % num_workers_]->Add(std::make_unique<IOBlock>(IOBlock::kDeIoBlockFlagEoe)));
}
if (epoch_sync_flag_) {
// If epoch_sync_flag_ is set, then master thread sleeps until all the worker threads have finished their job for
// the current epoch.
RETURN_IF_NOT_OK(WaitForWorkers());
}
// If not the last repeat, self-reset and go to loop again.
if (!IsLastIteration()) {
RETURN_IF_NOT_OK(Reset());
RETURN_IF_NOT_OK(sampler_->GetNextSample(data_buffer));
}
UpdateRepeatAndEpochCounter();
}
}
Status CelebAOp::WorkerEntry(int32_t worker_id) {
TaskManager::FindMe()->Post();
int64_t buffer_id = worker_id;
std::unique_ptr<IOBlock> io_block;
RETURN_IF_NOT_OK(io_block_queues_[worker_id]->PopFront(&io_block));
while (io_block != nullptr) {
if (io_block->wait() == true) {
// Sync io_block is a signal that master thread wants us to pause and sync with other workers.
// The last guy who comes to this sync point should reset the counter and wake up the master thread.
if (++num_workers_paused_ == num_workers_) {
wait_for_workers_post_.Set();
}
} else if (io_block->eoe() == true) {
RETURN_IF_NOT_OK(out_connector_->Add(worker_id, std::make_unique<DataBuffer>(0, DataBuffer::kDeBFlagEOE)));
buffer_id = worker_id;
} else if (io_block->eof() == true) {
RETURN_IF_NOT_OK(out_connector_->Add(worker_id, std::make_unique<DataBuffer>(0, DataBuffer::kDeBFlagEOF)));
} else {
std::vector<int64_t> keys;
RETURN_IF_NOT_OK(io_block->GetKeys(&keys));
if (keys.empty()) {
return Status::OK(); // empty key is a quit signal for workers
}
std::unique_ptr<DataBuffer> db = std::make_unique<DataBuffer>(buffer_id, DataBuffer::kDeBFlagNone);
RETURN_IF_NOT_OK(LoadBuffer(keys, &db));
RETURN_IF_NOT_OK(out_connector_->Add(worker_id, std::move(db)));
buffer_id += num_workers_;
}
RETURN_IF_NOT_OK(io_block_queues_[worker_id]->PopFront(&io_block));
}
return Status(StatusCode::kUnexpectedError, __LINE__, __FILE__, "Unexpected nullptr received in worker.");
}
Status CelebAOp::LoadBuffer(const std::vector<int64_t> &keys, std::unique_ptr<DataBuffer> *db) {
std::unique_ptr<TensorQTable> deq = std::make_unique<TensorQTable>();
for (const auto &key : keys) {
TensorRow row;
RETURN_IF_NOT_OK(LoadTensorRow(key, image_labels_vec_[key], &row));
deq->push_back(std::move(row));
}
(*db)->set_tensor_table(std::move(deq));
return Status::OK();
}
Status CelebAOp::LoadTensorRow(row_id_type row_id, const std::pair<std::string, std::vector<int32_t>> &image_label,
TensorRow *row) {
std::shared_ptr<Tensor> image;
std::shared_ptr<Tensor> label;
Path path(folder_path_);
Path image_path = path / image_label.first;
RETURN_IF_NOT_OK(Tensor::CreateFromFile(image_path.toString(), &image));
if (decode_ == true) {
Status rc = Decode(image, &image);
if (rc.IsError()) {
image = nullptr;
std::string err_msg = "Invalid data, failed to decode image: " + image_path.toString();
return Status(StatusCode::kUnexpectedError, __LINE__, __FILE__, err_msg);
}
}
RETURN_IF_NOT_OK(
Tensor::CreateEmpty(TensorShape({1, (uint32_t)image_label.second.size()}), data_schema_->column(1).type(), &label));
RETURN_IF_NOT_OK(label->Zero());
for (uint32_t index = 0; index < image_label.second.size(); index++) {
if (image_label.second[index] == 1) {
label->SetItemAt<uint32_t>({0, static_cast<dsize_t>(index)}, 1);
} else {
label->SetItemAt<uint32_t>({0, static_cast<dsize_t>(index)}, 0);
}
}
label->Squeeze();
(*row) = TensorRow(row_id, {std::move(image), std::move(label)});
return Status::OK();
}
void CelebAOp::Print(std::ostream &out, bool show_all) const {
if (!show_all) {
// Call the super class for displaying any common 1-liner info
ParallelOp::Print(out, show_all);
// Then show any custom derived-internal 1-liner info for this op
out << "\n";
} else {
// Call the super class for displaying any common detailed info
ParallelOp::Print(out, show_all);
// Then show any custom derived-internal stuff
out << "\nNumber of rows:" << num_rows_ << "\nceleba dir: " << folder_path_ << "\n\n";
}
}
// Reset Sampler and wakeup Master thread (functor)
Status CelebAOp::Reset() {
MS_LOG(DEBUG) << Name() << " performing a self-reset.";
RETURN_IF_NOT_OK(sampler_->ResetSampler());
return Status::OK();
}
// Visitor accept method for NodePass
Status CelebAOp::Accept(NodePass *p, bool *modified) {
// Downcast shared pointer then call visitor
return p->RunOnNode(shared_from_base<CelebAOp>(), modified);
}
Status CelebAOp::ComputeColMap() {
// Set the column name map (base class field)
if (column_name_id_map_.empty()) {
for (int32_t index = 0; index < data_schema_->NumColumns(); index++) {
column_name_id_map_[data_schema_->column(index).name()] = index;
}
} else {
MS_LOG(WARNING) << "Column name map is already set!";
}
return Status::OK();
}
} // namespace dataset
} // namespace mindspore
|
#ifndef TVEventChangeHandler_hxx_seen
#define TVEventChangeHandler_hxx_seen
#include <TObject.h>
namespace EDep {
class TVEventChangeHandler;
}
/// A base class for handlers called by TEventChangeManager. The
/// TEventChangeManager keeps a vector of possible handlers that are used
/// everytime the event has changed (or needs to be reset). The handlers need
/// to implement the XXX class, and should check to see if they are enabled
/// using the GUI class.
class EDep::TVEventChangeHandler: public TObject {
public:
TVEventChangeHandler() {}
virtual ~TVEventChangeHandler() {}
/// Apply the change handler to the current event. This does all of the
/// work.
virtual void Apply() = 0;
};
#endif
|
/**
* @file RandomOrderVertexSet.hpp
* @brief The RandomOrderVertexSet class.
* @author Dominique LaSalle <dominique@solidlake.com>
* Copyright 2018
* @version 1
* @date 2018-05-19
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#ifndef POROS_SRC_RANDOMORDERVERTEXSET_HPP
#define POROS_SRC_RANDOMORDERVERTEXSET_HPP
#include "graph/PermutedVertexSet.hpp"
#include "graph/VertexSet.hpp"
namespace poros
{
class RandomEngine;
class RandomOrderVertexSet
{
public:
/**
* @brief Create a random order of a given vertex set.
*
* @param set The vertex set to traverse in a random order.
* @param entropyEngine The source of random decisions.
*/
static PermutedVertexSet generate(
VertexSet set,
RandomEngine * randomEngine);
};
}
#endif
|
// --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2017.
//
// This software is released under a three-clause BSD license:
// * 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 any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: George Rosenberger $
// $Authors: George Rosenberger $
// --------------------------------------------------------------------------
#include <OpenMS/ANALYSIS/OPENSWATH/MRMAssay.h>
#include <OpenMS/ANALYSIS/OPENSWATH/TransitionTSVFile.h>
#include <OpenMS/ANALYSIS/OPENSWATH/TransitionPQPFile.h>
#include <OpenMS/APPLICATIONS/TOPPBase.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/FORMAT/TraMLFile.h>
#include <OpenMS/CHEMISTRY/AASequence.h>
#include <OpenMS/ANALYSIS/OPENSWATH/SwathWindowLoader.h>
#include <OpenMS/MATH/MISC/MathFunctions.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/FORMAT/FileTypes.h>
#include <OpenMS/CHEMISTRY/ModificationsDB.h>
#include <iostream>
using namespace OpenMS;
//-------------------------------------------------------------
//Doxygen docu
//-------------------------------------------------------------
/**
@page TOPP_OpenSwathAssayGenerator OpenSwathAssayGenerator
@brief Generates filtered and optimized assays using TraML files.
<CENTER>
<table>
<tr>
<td ALIGN = "center" BGCOLOR="#EBEBEB"> potential predecessor tools </td>
<td VALIGN="middle" ROWSPAN=2> \f$ \longrightarrow \f$ OpenSwathAssayGenerator \f$ \longrightarrow \f$</td>
<td ALIGN = "center" BGCOLOR="#EBEBEB"> potential successor tools </td>
</tr>
<tr>
<td VALIGN="middle" ALIGN = "center" ROWSPAN=1> @ref TOPP_OpenSwathDecoyGenerator </td>
</tr>
</table>
</CENTER>
This module generates assays for targeted proteomics using a set of rules
that was found to improve the sensitivity and selectivity for detection
of typical peptides (Schubert et al., 2015). The tool operates on TraML
files, which can come from TargetedFileConverter or any other tool. In a
first step, the tool will annotate all transitions according to the
predefined criteria. In a second step, the transitions will be filtered
to improve sensitivity for detection of peptides.
Optionally, theoretical identification transitions can be generated when
the TraML will be used for IPF scoring in OpenSWATH.
<B>The command line parameters of this tool are:</B>
@verbinclude TOPP_OpenSwathAssayGenerator.cli
<B>The algorithm parameters for the Analyzer filter are:</B>
@htmlinclude TOPP_OpenSwathAssayGenerator.html
*/
// We do not want this class to show up in the docu:
/// @cond TOPPCLASSES
class TOPPOpenSwathAssayGenerator :
public TOPPBase
{
public:
TOPPOpenSwathAssayGenerator() :
TOPPBase("OpenSwathAssayGenerator", "Generates assays according to different models for a specific TraML", true)
{
}
protected:
void registerOptionsAndFlags_() override
{
registerInputFile_("in", "<file>", "", "Input file");
registerStringOption_("in_type", "<type>", "", "Input file type -- default: determined from file extension or content\n", false);
String formats("tsv,mrm,pqp,TraML");
setValidFormats_("in", ListUtils::create<String>(formats));
setValidStrings_("in_type", ListUtils::create<String>(formats));
formats = "tsv,pqp,TraML";
registerOutputFile_("out", "<file>", "", "Output file");
setValidFormats_("out", ListUtils::create<String>(formats));
registerStringOption_("out_type", "<type>", "", "Output file type -- default: determined from file extension or content\n", false);
setValidStrings_("out_type", ListUtils::create<String>(formats));
registerIntOption_("min_transitions", "<int>", 6, "minimal number of transitions", false);
registerIntOption_("max_transitions", "<int>", 6, "maximal number of transitions", false);
registerStringOption_("allowed_fragment_types", "<type>", "b,y", "allowed fragment types", false);
registerStringOption_("allowed_fragment_charges", "<type>", "1,2,3,4", "allowed fragment charge states", false);
registerFlag_("enable_detection_specific_losses", "set this flag if specific neutral losses for detection fragment ions should be allowed");
registerFlag_("enable_detection_unspecific_losses", "set this flag if unspecific neutral losses (H2O1, H3N1, C1H2N2, C1H2N1O1) for detection fragment ions should be allowed");
registerDoubleOption_("precursor_mz_threshold", "<double>", 0.025, "MZ threshold in Thomson for precursor ion selection", false);
registerDoubleOption_("precursor_lower_mz_limit", "<double>", 400, "lower MZ limit for precursor ions", false);
registerDoubleOption_("precursor_upper_mz_limit", "<double>", 1200, "upper MZ limit for precursor ions", false);
registerDoubleOption_("product_mz_threshold", "<double>", 0.025, "MZ threshold in Thomson for fragment ion annotation", false);
registerDoubleOption_("product_lower_mz_limit", "<double>", 350, "lower MZ limit for fragment ions", false);
registerDoubleOption_("product_upper_mz_limit", "<double>", 2000, "upper MZ limit for fragment ions", false);
registerInputFile_("swath_windows_file", "<file>", "", "Tab separated file containing the SWATH windows for exclusion of fragment ions falling into the precursor isolation window: lower_offset upper_offset \\newline 400 425 \\newline ... Note that the first line is a header and will be skipped.", false, false);
setValidFormats_("swath_windows_file", ListUtils::create<String>("txt"));
registerInputFile_("unimod_file", "<file>", "", "(Modified) Unimod XML file (http://www.unimod.org/xml/unimod.xml) describing residue modifiability", false, false);
setValidFormats_("unimod_file", ListUtils::create<String>("xml"));
registerFlag_("enable_ipf", "IPF: set this flag if identification transitions should be generated for IPF. Note: Requires setting 'unimod_file'.");
registerIntOption_("max_num_alternative_localizations", "<int>", 10000, "IPF: maximum number of site-localization permutations", false, true);
registerFlag_("disable_identification_ms2_precursors", "IPF: set this flag if MS2-level precursor ions for identification should not be allowed for extraction of the precursor signal from the fragment ion data (MS2-level).", true);
registerFlag_("disable_identification_specific_losses", "IPF: set this flag if specific neutral losses for identification fragment ions should not be allowed", true);
registerFlag_("enable_identification_unspecific_losses", "IPF: set this flag if unspecific neutral losses (H2O1, H3N1, C1H2N2, C1H2N1O1) for identification fragment ions should be allowed", true);
registerFlag_("enable_swath_specifity", "IPF: set this flag if identification transitions without precursor specificity (i.e. across whole precursor isolation window instead of precursor MZ) should be generated.", true);
}
ExitCodes main_(int, const char**) override
{
FileHandler fh;
//input file type
String in = getStringOption_("in");
FileTypes::Type in_type = FileTypes::nameToType(getStringOption_("in_type"));
if (in_type == FileTypes::UNKNOWN)
{
in_type = fh.getType(in);
writeDebug_(String("Input file type: ") + FileTypes::typeToName(in_type), 2);
}
if (in_type == FileTypes::UNKNOWN)
{
writeLog_("Error: Could not determine input file type!");
return PARSE_ERROR;
}
//output file names and types
String out = getStringOption_("out");
FileTypes::Type out_type = FileTypes::nameToType(getStringOption_("out_type"));
if (out_type == FileTypes::UNKNOWN)
{
out_type = fh.getTypeByFileName(out);
}
if (out_type == FileTypes::UNKNOWN)
{
writeLog_("Error: Could not determine output file type!");
return PARSE_ERROR;
}
Int min_transitions = getIntOption_("min_transitions");
Int max_transitions = getIntOption_("max_transitions");
String allowed_fragment_types_string = getStringOption_("allowed_fragment_types");
String allowed_fragment_charges_string = getStringOption_("allowed_fragment_charges");
bool enable_detection_specific_losses = getFlag_("enable_detection_specific_losses");
bool enable_detection_unspecific_losses = getFlag_("enable_detection_unspecific_losses");
bool enable_identification_specific_losses = !getFlag_("disable_identification_specific_losses");
bool enable_identification_unspecific_losses = getFlag_("enable_identification_unspecific_losses");
bool enable_identification_ms2_precursors = !getFlag_("disable_identification_ms2_precursors");
bool enable_ipf = getFlag_("enable_ipf");
bool enable_swath_specifity = getFlag_("enable_swath_specifity");
size_t max_num_alternative_localizations = getIntOption_("max_num_alternative_localizations");
double precursor_mz_threshold = getDoubleOption_("precursor_mz_threshold");
double precursor_lower_mz_limit = getDoubleOption_("precursor_lower_mz_limit");
double precursor_upper_mz_limit = getDoubleOption_("precursor_upper_mz_limit");
double product_mz_threshold = getDoubleOption_("product_mz_threshold");
double product_lower_mz_limit = getDoubleOption_("product_lower_mz_limit");
double product_upper_mz_limit = getDoubleOption_("product_upper_mz_limit");
String swath_windows_file = getStringOption_("swath_windows_file");
String unimod_file = getStringOption_("unimod_file");
bool is_test = getFlag_("test");
// Set specific seed for test mode
int uis_seed = -1;
bool disable_decoy_transitions = false;
if (is_test)
{
uis_seed = 42;
disable_decoy_transitions = true;
}
std::vector<String> allowed_fragment_types;
allowed_fragment_types_string.split(",", allowed_fragment_types);
std::vector<String> allowed_fragment_charges_string_vector;
std::vector<size_t> allowed_fragment_charges;
allowed_fragment_charges_string.split(",", allowed_fragment_charges_string_vector);
for (size_t i = 0; i < allowed_fragment_charges_string_vector.size(); i++)
{
size_t charge = std::atoi(allowed_fragment_charges_string_vector.at(i).c_str());
allowed_fragment_charges.push_back(charge);
}
// Require Unimod XML file when running IPF to prevent accidential mistakes
if (enable_ipf && unimod_file.empty())
{
throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Please provide a valid Unimod XML file for IPF.");
}
// Load Unimod file
if (!unimod_file.empty())
{
if (!ModificationsDB::isInstantiated()) // We need to ensure that ModificationsDB was not instantiated before!
{
ModificationsDB* ptr = ModificationsDB::getInstance(unimod_file, String(""), String(""));
LOG_INFO << "Unimod XML: " << ptr->getNumberOfModifications() << " modification types and residue specificities imported from file: " << unimod_file << std::endl;
}
else
{
throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "ModificationsDB has been instantiated before and can not be generated from the provided Unimod XML file.");
}
}
std::vector<std::pair<double, double> > swathes;
// Check swath window input
if (!swath_windows_file.empty())
{
LOG_INFO << "Validate provided Swath windows file:" << std::endl;
std::vector<double> swath_prec_lower;
std::vector<double> swath_prec_upper;
SwathWindowLoader::readSwathWindows(swath_windows_file, swath_prec_lower, swath_prec_upper);
LOG_INFO << "Read Swath maps file with " << swath_prec_lower.size() << " windows." << std::endl;
for (Size i = 0; i < swath_prec_lower.size(); i++)
{
swathes.push_back(std::make_pair(swath_prec_lower[i], swath_prec_upper[i]));
LOG_DEBUG << "Read lower swath window " << swath_prec_lower[i] << " and upper window " << swath_prec_upper[i] << std::endl;
}
}
TargetedExperiment targeted_exp;
// Load data
LOG_INFO << "Loading " << in << std::endl;
if (in_type == FileTypes::TSV || in_type == FileTypes::MRM)
{
const char* tr_file = in.c_str();
Param reader_parameters = getParam_().copy("algorithm:", true);
TransitionTSVFile tsv_reader = TransitionTSVFile();
tsv_reader.setLogType(log_type_);
tsv_reader.setParameters(reader_parameters);
tsv_reader.convertTSVToTargetedExperiment(tr_file, in_type, targeted_exp);
tsv_reader.validateTargetedExperiment(targeted_exp);
}
else if (in_type == FileTypes::PQP)
{
const char* tr_file = in.c_str();
TransitionPQPFile pqp_reader = TransitionPQPFile();
Param reader_parameters = getParam_().copy("algorithm:", true);
pqp_reader.setLogType(log_type_);
pqp_reader.setParameters(reader_parameters);
pqp_reader.convertPQPToTargetedExperiment(tr_file, targeted_exp);
pqp_reader.validateTargetedExperiment(targeted_exp);
}
else if (in_type == FileTypes::TRAML)
{
TraMLFile traml;
traml.load(in, targeted_exp);
}
MRMAssay assays = MRMAssay();
assays.setLogType(ProgressLogger::CMD);
LOG_INFO << "Annotating transitions" << std::endl;
assays.reannotateTransitions(targeted_exp, precursor_mz_threshold, product_mz_threshold, allowed_fragment_types, allowed_fragment_charges, enable_detection_specific_losses, enable_detection_unspecific_losses);
LOG_INFO << "Annotating detecting transitions" << std::endl;
assays.restrictTransitions(targeted_exp, product_lower_mz_limit, product_upper_mz_limit, swathes);
assays.detectingTransitions(targeted_exp, min_transitions, max_transitions);
if (enable_ipf)
{
std::vector<std::pair<double, double> > uis_swathes;
if (!enable_swath_specifity)
{
int num_precursor_windows = static_cast<int>(Math::round((precursor_upper_mz_limit - precursor_lower_mz_limit) / precursor_mz_threshold));
for (int i = 0; i < num_precursor_windows; i++)
{
uis_swathes.push_back(std::make_pair((precursor_lower_mz_limit+(i*precursor_mz_threshold)),(precursor_lower_mz_limit+((i+1)*precursor_mz_threshold))));
}
}
else {uis_swathes = swathes;}
LOG_INFO << "Generating identifying transitions for IPF" << std::endl;
assays.uisTransitions(targeted_exp, allowed_fragment_types, allowed_fragment_charges, enable_identification_specific_losses, enable_identification_unspecific_losses, enable_identification_ms2_precursors, product_mz_threshold, uis_swathes, -4, max_num_alternative_localizations, uis_seed, disable_decoy_transitions);
std::vector<std::pair<double, double> > empty_swathes;
assays.restrictTransitions(targeted_exp, product_lower_mz_limit, product_upper_mz_limit, empty_swathes);
}
LOG_INFO << "Writing assays " << out << std::endl;
if (out_type == FileTypes::TSV)
{
const char* tr_file = out.c_str();
TransitionTSVFile tsv_reader = TransitionTSVFile();
tsv_reader.setLogType(log_type_);
tsv_reader.convertTargetedExperimentToTSV(tr_file, targeted_exp);
}
if (out_type == FileTypes::PQP)
{
const char * tr_file = out.c_str();
TransitionPQPFile pqp_reader = TransitionPQPFile();
pqp_reader.setLogType(log_type_);
pqp_reader.convertTargetedExperimentToPQP(tr_file, targeted_exp);
}
else if (out_type == FileTypes::TRAML)
{
TraMLFile traml;
traml.store(out, targeted_exp);
}
return EXECUTION_OK;
}
};
int main(int argc, const char** argv)
{
TOPPOpenSwathAssayGenerator gen;
return gen.main(argc, argv);
}
/// @endcond
|
#include <iostream>
using namespace std;
// disable padding
#pragma pack(push, 1)
struct Person {
char name[50];
int age;
double weight;
};
#pragma pack(pop)
int main(){
cout << sizeof(Person) << endl;
return 0;
}
|
/*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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.
*/
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "itkBinaryImageToLabelMapFilter.h"
#include "otbAttributesMapLabelObjectWithClassLabel.h"
#include "otbShapeAttributesLabelMapFilter.h"
#include "itkVariableLengthVector.h"
#include "itkListSample.h"
#include "otbLabelMapWithClassLabelToLabeledSampleListFilter.h"
int otbLabelMapWithClassLabelToLabeledSampleListFilter(int argc, char* argv[])
{
const char* infname = argv[1];
// Labeled image type
const unsigned int Dimension = 2;
typedef unsigned short LabelType;
typedef otb::Image<LabelType, Dimension> LabeledImageType;
typedef otb::ImageFileReader<LabeledImageType> LabeledReaderType;
typedef otb::AttributesMapLabelObjectWithClassLabel<LabelType, Dimension, double, LabelType> LabelObjectType;
typedef itk::LabelMap<LabelObjectType> LabelMapType;
typedef itk::BinaryImageToLabelMapFilter<LabeledImageType, LabelMapType> LabelMapFilterType;
typedef otb::ShapeAttributesLabelMapFilter<LabelMapType> ShapeLabelMapFilterType;
typedef itk::VariableLengthVector<double> VectorType;
typedef itk::FixedArray<LabelType, 1> TrainingVectorType;
typedef itk::Statistics::ListSample<VectorType> ListSampleType;
typedef itk::Statistics::ListSample<TrainingVectorType> TrainingListSampleType;
typedef otb::LabelMapWithClassLabelToLabeledSampleListFilter<LabelMapType, ListSampleType, TrainingListSampleType> LabelMap2ListSampleFilterType;
// instantiation
LabeledReaderType::Pointer lreader = LabeledReaderType::New();
lreader->SetFileName(infname);
LabelMapFilterType::Pointer labelMapFilter = LabelMapFilterType::New();
labelMapFilter->SetInput(lreader->GetOutput());
labelMapFilter->SetInputForegroundValue(1);
ShapeLabelMapFilterType::Pointer shapeLabelMapFilter = ShapeLabelMapFilterType::New();
shapeLabelMapFilter->SetInput(labelMapFilter->GetOutput());
shapeLabelMapFilter->Update();
LabelMap2ListSampleFilterType::Pointer filter = LabelMap2ListSampleFilterType::New();
filter->SetInputLabelMap(shapeLabelMapFilter->GetOutput());
filter->GetMeasurementFunctor().AddAttribute("test");
filter->GetMeasurementFunctor().RemoveAttribute("test");
filter->GetMeasurementFunctor().AddAttribute("test");
filter->GetMeasurementFunctor().ClearAttributes();
for (int i = 2; i < argc; ++i)
{
filter->GetMeasurementFunctor().AddAttribute(argv[i]);
}
std::cout << "Number of attributes: " << filter->GetMeasurementFunctor().GetNumberOfAttributes() << std::endl;
shapeLabelMapFilter->GetOutput()->GetLabelObject(1)->SetClassLabel(1);
filter->Update();
return EXIT_SUCCESS;
}
|
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "glow/Graph/Context.h"
#include "glow/Graph/Graph.h"
#include "glow/Graph/Node.h"
#include "glow/Graph/Nodes.h"
#include "glow/IR/IR.h"
#include "glow/Optimizer/Optimizer.h"
#include "gtest/gtest.h"
using namespace glow;
class GraphOptz : public ::testing::Test {
public:
GraphOptz() { F_ = mod_.createFunction("main"); }
protected:
Module mod_;
Function *F_;
Context ctx_;
};
/// \returns the number of nodes in \p F of kind \p kind.
static unsigned countNodeKind(Function *F, Kinded::Kind kind) {
unsigned count = 0;
for (auto &n : F->getNodes()) {
if (n.getKind() == kind) {
count++;
}
}
return count;
}
TEST_F(GraphOptz, DCE) {
Node *K = mod_.createPlaceholder(ElemKind::FloatTy, {4, 320, 200, 3}, "input",
false);
for (int i = 0; i < 40; i++) {
K = F_->createRELU("relu", K);
// Add a graph structure that diverges and converges, to catch algorithms
// that perform a dump recursive scan.
K = F_->createAdd("arith", K, K);
}
// Check that we know how many nodes we've created.
EXPECT_EQ(F_->getNodes().size(), 80);
// Optimize all of the dead code.
::glow::optimize(F_, CompilationMode::Infer);
// All of the nodes are gone.
EXPECT_EQ(F_->getNodes().size(), 0);
EXPECT_EQ(mod_.getConstants().size(), 0);
}
/// Check that predicated instructions are DCE'ed like
/// regular instructions.
TEST_F(GraphOptz, DCEwithPredicate) {
Node *K = mod_.createPlaceholder(ElemKind::FloatTy, {4, 320, 200, 3}, "input",
false);
Node *predicatedBatch =
mod_.createPlaceholder(ElemKind::FloatTy, {4}, "predicate", true);
for (int i = 0; i < 40; i++) {
K = F_->createRELU("relu", K);
K->setPredicate(predicatedBatch);
// Add a graph structure that diverges and converges, to catch algorithms
// that perform a dump recursive scan.
K = F_->createAdd("arith", K, K);
K->setPredicate(predicatedBatch);
}
// Check that we know how many nodes we've created.
EXPECT_EQ(F_->getNodes().size(), 80);
// Optimize all of the dead code.
::glow::optimize(F_, CompilationMode::Infer);
// All of the nodes are gone.
EXPECT_EQ(F_->getNodes().size(), 0);
EXPECT_EQ(mod_.getConstants().size(), 0);
}
TEST_F(GraphOptz, liveCodeNotEliminated) {
Node *K = mod_.createPlaceholder(ElemKind::FloatTy, {4, 320, 200, 3}, "input",
false);
auto *Ex = mod_.createPlaceholder(ElemKind::Int64ITy, {4, 1}, "Ex", false);
for (int i = 0; i < 40; i++) {
K = F_->createRELU("relu", K);
K = F_->createAdd("arith", K, K);
}
K = F_->createSoftMax("Regression", K, Ex);
F_->createSave("ret", K);
// Check that we know how many nodes we've created.
EXPECT_EQ(F_->getNodes().size(), 82);
// This should not optimize code because none is dead.
::glow::optimize(F_, CompilationMode::Infer);
// Nothing got optimized.
EXPECT_EQ(F_->getNodes().size(), 82);
EXPECT_EQ(mod_.getPlaceholders().size(), 3);
}
TEST_F(GraphOptz, optimizeBatchNormAfterConv) {
Node *A =
mod_.createPlaceholder(ElemKind::FloatTy, {1, 10, 20, 3}, "A", false);
Node *CV = F_->createConv(ctx_, "conv", A, 16, 5, 1, 2, 1);
Node *BN = F_->createBatchNormalization(ctx_, "batch", CV, 3, 0.0001, 0.9);
F_->createSave("ret", BN);
EXPECT_EQ(F_->getNodes().size(), 3);
::glow::convertPlaceholdersToConstants(F_, ctx_, {});
::glow::optimize(F_, CompilationMode::Infer);
EXPECT_EQ(F_->getNodes().size(), 2);
ASSERT_EQ(A->getNumUsers(), 1);
Node *newCV = A->getUsers().begin()->getUser();
EXPECT_TRUE(llvm::isa<ConvolutionNode>(newCV));
ASSERT_EQ(newCV->getNumUsers(), 1);
Node *save = newCV->getUsers().begin()->getUser();
EXPECT_TRUE(llvm::isa<SaveNode>(save));
}
/// Verify that the Conv-BatchNorm merging optimization is not impacted by
/// multiple users on the filter/bias.
TEST_F(GraphOptz, optimizeBatchNormAfterConvMultiple) {
Placeholder *A =
mod_.createPlaceholder(ElemKind::FloatTy, {1, 10, 20, 3}, "A", false);
ConvolutionNode *CV = F_->createConv(ctx_, "conv", A, 16, 5, 1, 2, 1);
BatchNormalizationNode *BN =
F_->createBatchNormalization(ctx_, "batch", CV, 3, 0.0001, 0.9);
F_->createSave("ret", BN);
// Adding these saves means the filter and bias have multiple uses. This
// should not impact the Conv-BatchNorm merging optimization.
F_->createSave("saveFilter", CV->getFilter());
F_->createSave("saveBias", CV->getBias());
// Three Saves, one Conv, and one BatchNorm.
EXPECT_EQ(F_->getNodes().size(), 5);
::glow::convertPlaceholdersToConstants(F_, ctx_, {});
// Conv's Filter and Bias, plus BN's Scale, Bias, Mean, and Var.
EXPECT_EQ(mod_.getConstants().size(), 6);
::glow::optimize(F_, CompilationMode::Infer);
// BatchNorm should have been merged into the Conv.
EXPECT_EQ(F_->getNodes().size(), 4);
// Filter and Bias should have been duplicated so that the Conv-BN
// optimization does not modify the filter/bias being saved, equaling 4
// Constants. Additionally, the BN's Scale, Bias, Mean, and Var should be
// eliminated due to the opti.
EXPECT_EQ(mod_.getConstants().size(), 4);
ASSERT_EQ(A->getNumUsers(), 1);
Node *newCV = A->getUsers().begin()->getUser();
EXPECT_TRUE(llvm::isa<ConvolutionNode>(newCV));
ASSERT_EQ(newCV->getNumUsers(), 1);
Node *save = newCV->getUsers().begin()->getUser();
EXPECT_TRUE(llvm::isa<SaveNode>(save));
EXPECT_EQ(countNodeKind(F_, Kinded::Kind::BatchNormalizationNodeKind), 0);
}
TEST_F(GraphOptz, optimizeBatchNormAfterConvFP16) {
Node *A =
mod_.createPlaceholder(ElemKind::Float16Ty, {1, 10, 20, 3}, "A", false);
Node *CV = F_->createConv(ctx_, "conv", A, 16, 5, 1, 2, 1);
Node *BN = F_->createBatchNormalization(ctx_, "batch", CV, 3, 0.0001, 0.9);
F_->createSave("ret", BN);
EXPECT_EQ(F_->getNodes().size(), 3);
::glow::convertPlaceholdersToConstants(F_, ctx_, {});
::glow::optimize(F_, CompilationMode::Infer);
EXPECT_EQ(F_->getNodes().size(), 2);
ASSERT_EQ(A->getNumUsers(), 1);
Node *newCV = A->getUsers().begin()->getUser();
EXPECT_TRUE(llvm::isa<ConvolutionNode>(newCV));
ASSERT_EQ(newCV->getNumUsers(), 1);
Node *save = newCV->getUsers().begin()->getUser();
EXPECT_TRUE(llvm::isa<SaveNode>(save));
}
/// Check that transpose constant folding is done before BatchNorm optimization,
/// which allows to merge BatchNorm into Convolution with transposed weights.
TEST_F(GraphOptz, optimizeBatchNormAfterConvWithTransposedWeights) {
auto *input =
mod_.createPlaceholder(ElemKind::FloatTy, {1, 10, 20, 3}, "input", false);
auto *filter =
mod_.createPlaceholder(ElemKind::FloatTy, {16, 3, 5, 5}, "filter", false);
auto *bias = mod_.createPlaceholder(ElemKind::FloatTy, {16}, "bias", false);
auto *TN = F_->createTranspose("transpose", filter, NCHW2NHWC);
auto *CV = F_->createConv("conv", input, TN, bias,
mod_.uniqueType(ElemKind::FloatTy, {1, 10, 20, 16}),
5, 1, 2, 1);
auto *BN = F_->createBatchNormalization(ctx_, "batch", CV, 3, 0.0001, 0.9);
F_->createSave("ret", BN);
// Initialize to ensure that constant tensors are not optimized out.
ctx_.allocate(filter)->getHandle().randomize(-1.0, 1.0, mod_.getPRNG());
ctx_.allocate(bias)->getHandle().randomize(-1.0, 1.0, mod_.getPRNG());
::glow::convertPlaceholdersToConstants(F_, ctx_, {input});
EXPECT_EQ(F_->getNodes().size(), 4);
::glow::optimize(F_, CompilationMode::Infer);
EXPECT_EQ(F_->getNodes().size(), 2);
EXPECT_EQ(countNodeKind(F_, Kinded::Kind::BatchNormalizationNodeKind), 0);
}
/// Check that the batch normalization optimization is
/// not blocked by predicates and that it preserves them.
TEST_F(GraphOptz, optimizeBatchNormAfterConvWithPred) {
Node *A =
mod_.createPlaceholder(ElemKind::FloatTy, {1, 10, 20, 3}, "A", false);
Node *pred1 =
mod_.createPlaceholder(ElemKind::FloatTy, {1}, "predicate", false);
Node *pred2 =
mod_.createPlaceholder(ElemKind::FloatTy, {1}, "predicate", false);
Node *CV = F_->createConv(ctx_, "conv", A, 16, 5, 1, 2, 1);
CV->setPredicate(pred1);
Node *BN = F_->createBatchNormalization(ctx_, "batch", CV, 3, 0.0001, 0.9);
BN->setPredicate(pred2);
F_->createSave("ret", BN);
EXPECT_EQ(F_->getNodes().size(), 3);
::glow::convertPlaceholdersToConstants(F_, ctx_, {});
::glow::optimize(F_, CompilationMode::Infer);
EXPECT_EQ(F_->getNodes().size(), 2);
ASSERT_EQ(A->getNumUsers(), 1);
Node *newCV = A->getUsers().begin()->getUser();
EXPECT_TRUE(llvm::isa<ConvolutionNode>(newCV));
ASSERT_TRUE(newCV->hasPredicate());
EXPECT_EQ(newCV->getPredicate().getNode(), pred2);
ASSERT_EQ(newCV->getNumUsers(), 1);
Node *save = newCV->getUsers().begin()->getUser();
EXPECT_TRUE(llvm::isa<SaveNode>(save));
}
/// Check CSE will not merge two nodes that have all the same inputs but
/// different predicates.
TEST_F(GraphOptz, cseRespectsPredicates) {
Node *in = mod_.createPlaceholder(ElemKind::FloatTy, {5}, "in", false);
Node *pred1 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *pred2 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *RN1 = F_->createRELU("relu1", in);
RN1->setPredicate(pred1);
SaveNode *save1 = F_->createSave("save1", RN1);
save1->setPredicate(pred1);
Node *RN2 = F_->createRELU("relu2", in);
RN2->setPredicate(pred2);
SaveNode *save2 = F_->createSave("save2", RN2);
save2->setPredicate(pred2);
// Two RELUS and two Saves.
EXPECT_EQ(F_->getNodes().size(), 4);
EXPECT_EQ(countNodeKind(F_, Kinded::Kind::ReluNodeKind), 2);
EXPECT_EQ(countNodeKind(F_, Kinded::Kind::SaveNodeKind), 2);
::glow::convertPlaceholdersToConstants(F_, ctx_, {});
::glow::optimize(F_, CompilationMode::Infer);
// Two RELUS and two Saves should still be there.
EXPECT_EQ(F_->getNodes().size(), 4);
EXPECT_EQ(countNodeKind(F_, Kinded::Kind::ReluNodeKind), 2);
EXPECT_EQ(countNodeKind(F_, Kinded::Kind::SaveNodeKind), 2);
}
TEST_F(GraphOptz, optimizeBatchNormAfterConvButConvReused) {
Node *A =
mod_.createPlaceholder(ElemKind::FloatTy, {1, 10, 20, 3}, "A", false);
Node *CV = F_->createConv(ctx_, "conv", A, 16, 5, 1, 2, 1);
Node *BN = F_->createBatchNormalization(ctx_, "batch", CV, 3, 0.0001, 0.9);
SaveNode *ret = F_->createSave("ret", BN);
SaveNode *convSave = F_->createSave("convSave", CV);
EXPECT_EQ(F_->getNodes().size(), 4);
::glow::optimize(F_, CompilationMode::Infer);
// Make sure the structure of the graph did not change, since the convolution
// node is used more than once.
EXPECT_EQ(F_->getNodes().size(), 4);
EXPECT_TRUE(llvm::isa<ConvolutionNode>(convSave->getInput()));
ConvolutionNode *conv = llvm::dyn_cast<ConvolutionNode>(convSave->getInput());
EXPECT_EQ(conv, CV);
EXPECT_TRUE(llvm::isa<BatchNormalizationNode>(ret->getInput()));
BatchNormalizationNode *batchNorm =
llvm::dyn_cast<BatchNormalizationNode>(ret->getInput());
EXPECT_EQ(batchNorm, BN);
EXPECT_EQ(batchNorm->getInput().getNode(), CV);
EXPECT_EQ(conv->getInput().getNode(), A);
}
TEST_F(GraphOptz, optimizeBatchNormAfterConvButVarReused) {
Node *A =
mod_.createPlaceholder(ElemKind::FloatTy, {1, 10, 20, 3}, "A", false);
auto *filter =
mod_.createPlaceholder(ElemKind::FloatTy, {16, 5, 5, 3}, "filter", true);
auto *bias = mod_.createPlaceholder(ElemKind::FloatTy, {16}, "bias", true);
ConvolutionNode *CV = F_->createConv(
"conv", A, filter, bias,
mod_.uniqueType(ElemKind::FloatTy, {1, 10, 20, 16}), 5, 1, 2, 1);
auto *beta = mod_.createPlaceholder(ElemKind::FloatTy, {16}, "beta", true);
auto *gamma = mod_.createPlaceholder(ElemKind::FloatTy, {16}, "gamma", true);
auto *mean = mod_.createPlaceholder(ElemKind::FloatTy, {16}, "mean", false);
auto *var = mod_.createPlaceholder(ElemKind::FloatTy, {16}, "var", false);
Node *BN = F_->createBatchNormalization("batch", CV, beta, gamma, mean, var,
3, 0.0001, 0.9);
SaveNode *ret = F_->createSave("ret", BN);
SaveNode *filterSave = F_->createSave("filterSave", CV->getFilter());
EXPECT_EQ(F_->getNodes().size(), 4);
::glow::optimize(F_, CompilationMode::Infer);
// Make sure the structure of the graph did not change.
EXPECT_EQ(F_->getNodes().size(), 4);
EXPECT_TRUE(llvm::isa<Placeholder>(filterSave->getInput()));
auto *varFilter = llvm::dyn_cast<Placeholder>(filterSave->getInput());
EXPECT_EQ(varFilter, CV->getFilter());
EXPECT_TRUE(llvm::isa<BatchNormalizationNode>(ret->getInput()));
BatchNormalizationNode *batchNorm =
llvm::dyn_cast<BatchNormalizationNode>(ret->getInput());
EXPECT_EQ(batchNorm, BN);
EXPECT_TRUE(batchNorm && batchNorm->getInput() &&
batchNorm->getInput().getNode() == CV);
}
TEST_F(GraphOptz, transposePrivateVariable) {
auto *A =
mod_.createPlaceholder(ElemKind::FloatTy, {1, 10, 20, 3}, "A", false);
ctx_.allocate(A)->getHandle().randomize(-7.0, 12.0, mod_.getPRNG());
Tensor transposedA;
ctx_.get(A)->transpose(&transposedA, {0, 3, 1, 2});
Node *T = F_->createTranspose("transpose", A, NHWC2NCHW);
SaveNode *save = F_->createSave("ret", T);
EXPECT_EQ(F_->getNodes().size(), 2);
::glow::convertPlaceholdersToConstants(F_, ctx_, {});
::glow::optimize(F_, CompilationMode::Infer);
ASSERT_EQ(F_->getNodes().size(), 1);
EXPECT_EQ(&*F_->getNodes().begin(), save);
Constant *optimizedA = llvm::dyn_cast<Constant>(save->getInput().getNode());
ASSERT_NE(optimizedA, nullptr);
// Check that A has been properly transposed.
EXPECT_TRUE(optimizedA->getPayload().isEqual(transposedA));
}
/// Check that the removing of transposes still happens when
/// predicates are involved.
TEST_F(GraphOptz, transposePrivateVariableWithPredicate) {
auto *A =
mod_.createPlaceholder(ElemKind::FloatTy, {1, 10, 20, 3}, "A", false);
auto *pred = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
ctx_.allocate(A)->getHandle().randomize(-7.0, 12.0, mod_.getPRNG());
Tensor transposedA;
ctx_.get(A)->transpose(&transposedA, {0, 3, 1, 2});
// Arguably, if the transpose doesn't happen because the predicate is false
// the value of A should be unchanged. However, the semantic of our
// predicate is that they can be ignored and the program would still
// be correct, thus this optimization is still legal.
Node *T = F_->createTranspose("transpose", A, NHWC2NCHW);
T->setPredicate(pred);
SaveNode *save = F_->createSave("ret", T);
save->setPredicate(pred);
EXPECT_EQ(F_->getNodes().size(), 2);
::glow::convertPlaceholdersToConstants(F_, ctx_, {});
::glow::optimize(F_, CompilationMode::Infer);
ASSERT_EQ(F_->getNodes().size(), 1);
EXPECT_EQ(&*F_->getNodes().begin(), save);
// We should have kept the predicate on the save node.
ASSERT_EQ(pred->getNumUsers(), 1);
EXPECT_EQ(pred->getUsers().begin()->getUser(), save);
Constant *optimizedA = llvm::dyn_cast<Constant>(save->getInput().getNode());
ASSERT_NE(optimizedA, nullptr);
// Check that A has been properly transposed.
EXPECT_TRUE(optimizedA->getPayload().isEqual(transposedA));
}
TEST_F(GraphOptz, BatchNormAfterConvNotOptimizeForTrain) {
Node *A =
mod_.createPlaceholder(ElemKind::FloatTy, {1, 10, 20, 3}, "A", false);
Node *CV = F_->createConv(ctx_, "conv", A, 16, 5, 1, 2, 1);
Node *BN = F_->createBatchNormalization(ctx_, "batch", CV, 3, 0.0001, 0.9);
F_->createSave("ret", BN);
EXPECT_EQ(F_->getNodes().size(), 3);
::glow::optimize(F_, CompilationMode::Train);
EXPECT_EQ(F_->getNodes().size(), 3);
ASSERT_EQ(A->getNumUsers(), 1);
Node *curCV = A->getUsers().begin()->getUser();
EXPECT_EQ(curCV, CV);
ASSERT_EQ(curCV->getNumUsers(), 1);
Node *curBN = curCV->getUsers().begin()->getUser();
EXPECT_EQ(curBN, BN);
ASSERT_EQ(curBN->getNumUsers(), 1);
Node *save = curBN->getUsers().begin()->getUser();
EXPECT_TRUE(llvm::isa<SaveNode>(save));
}
TEST_F(GraphOptz, batchNormAfterConvNotOptimizeWhenMoreThanOneUseOfConv) {
Node *A =
mod_.createPlaceholder(ElemKind::FloatTy, {1, 10, 20, 3}, "A", false);
Node *CV = F_->createConv(ctx_, "conv", A, 16, 5, 1, 2, 1);
Node *BN = F_->createBatchNormalization(ctx_, "batch", CV, 3, 0.0001, 0.9);
SaveNode *convSave = F_->createSave("ret", CV);
SaveNode *ret = F_->createSave("ret", BN);
EXPECT_EQ(F_->getNodes().size(), 4);
::glow::optimize(F_, CompilationMode::Infer);
// Make sure the structure of the graph did not change, since the convolution
// node is used more than once.
EXPECT_EQ(F_->getNodes().size(), 4);
ASSERT_TRUE(llvm::isa<ConvolutionNode>(convSave->getInput()));
ConvolutionNode *conv = llvm::dyn_cast<ConvolutionNode>(convSave->getInput());
EXPECT_EQ(conv, CV);
EXPECT_TRUE(llvm::isa<BatchNormalizationNode>(ret->getInput()));
BatchNormalizationNode *batchNorm =
llvm::dyn_cast<BatchNormalizationNode>(ret->getInput());
EXPECT_EQ(batchNorm, BN);
EXPECT_EQ(batchNorm->getInput().getNode(), CV);
EXPECT_EQ(conv->getInput().getNode(), A);
}
TEST_F(GraphOptz, sinkTransposeBelowOptimizeBatchNorm) {
const size_t origDims[] = {1, 5, 10, 15};
const size_t transposedDims[] = {1, 15, 5, 10};
Node *A = mod_.createPlaceholder(ElemKind::FloatTy, origDims, "input", false);
Node *T = F_->createTranspose("transpose", A, NHWC2NCHW);
Node *BN = F_->createBatchNormalization(ctx_, "batch", T, 3, 0.0001, 0.9);
SaveNode *O = F_->createSave("ret", BN);
EXPECT_EQ(F_->getNodes().size(), 3);
EXPECT_EQ(BN->dims(0), llvm::makeArrayRef(transposedDims));
::glow::optimize(F_, CompilationMode::Infer);
// Expecting Transpose->Output rather than BN->Output.
auto *transpose = llvm::dyn_cast<TransposeNode>(O->getInput());
ASSERT_NE(transpose, nullptr);
ASSERT_TRUE(llvm::isa<BatchNormalizationNode>(transpose->getInput()));
auto *bn = llvm::cast<BatchNormalizationNode>(transpose->getInput());
// Check that the dimensions of the input and output have been
// updated to compensate the absence of transpose.
EXPECT_EQ(bn->dims(0), llvm::makeArrayRef(origDims));
EXPECT_EQ(bn->getInput().dims(), llvm::makeArrayRef(origDims));
EXPECT_EQ(F_->getNodes().size(), 3);
}
/// Check that the predicates are preserved while sinking transposes
/// through batch normalization.
TEST_F(GraphOptz, sinkTransposeBelowOptimizeBatchNormWithPredicate) {
const size_t origDims[] = {1, 5, 10, 15};
const size_t transposedDims[] = {1, 15, 5, 10};
Node *A = mod_.createPlaceholder(ElemKind::FloatTy, origDims, "input", false);
Node *pred1 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *pred2 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *pred3 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *T = F_->createTranspose("transpose", A, NHWC2NCHW);
T->setPredicate(pred1);
Node *BN = F_->createBatchNormalization(ctx_, "batch", T, 3, 0.0001, 0.9);
BN->setPredicate(pred2);
SaveNode *O = F_->createSave("ret", BN);
O->setPredicate(pred3);
EXPECT_EQ(F_->getNodes().size(), 3);
EXPECT_EQ(BN->dims(0), llvm::makeArrayRef(transposedDims));
::glow::optimize(F_, CompilationMode::Infer);
EXPECT_EQ(O->getPredicate().getNode(), pred3);
// Expecting Transpose->Output rather than BN->Output.
auto *transpose = llvm::dyn_cast<TransposeNode>(O->getInput());
ASSERT_NE(transpose, nullptr);
EXPECT_EQ(transpose->getPredicate().getNode(), pred2);
ASSERT_TRUE(llvm::isa<BatchNormalizationNode>(transpose->getInput()));
auto *bn = llvm::cast<BatchNormalizationNode>(transpose->getInput());
EXPECT_EQ(bn->getPredicate().getNode(), pred2);
// Check that the dimensions of the input and output have been
// updated to compensate the absence of transpose.
EXPECT_EQ(bn->dims(0), llvm::makeArrayRef(origDims));
EXPECT_EQ(bn->getInput().dims(), llvm::makeArrayRef(origDims));
EXPECT_EQ(F_->getNodes().size(), 3);
}
TEST_F(GraphOptz, sinkTransposeBelowRELU) {
const size_t origDims[] = {1, 5, 10, 15};
const size_t transposedDims[] = {1, 15, 5, 10};
Node *A = mod_.createPlaceholder(ElemKind::FloatTy, origDims, "input", false);
Node *T = F_->createTranspose("transpose", A, NHWC2NCHW);
Node *K = F_->createRELU("relu", T);
SaveNode *O = F_->createSave("ret", K);
EXPECT_EQ(F_->getNodes().size(), 3);
EXPECT_EQ(K->dims(0), llvm::makeArrayRef(transposedDims));
::glow::optimize(F_, CompilationMode::Infer);
// Expecting Transpose->Output rather than RELU->Output.
auto *transpose = llvm::dyn_cast<TransposeNode>(O->getInput());
ASSERT_NE(transpose, nullptr);
ASSERT_TRUE(llvm::isa<ReluNode>(transpose->getInput()));
auto *relu = llvm::cast<ReluNode>(transpose->getInput());
// Check that the dimensions of the input and output have been
// updated to compensate the absence of transpose.
EXPECT_EQ(relu->dims(0), llvm::makeArrayRef(origDims));
EXPECT_EQ(relu->getInput().dims(), llvm::makeArrayRef(origDims));
EXPECT_EQ(F_->getNodes().size(), 3);
}
/// Check that the predicates are preserved while sinking transposes
/// through ReLU.
TEST_F(GraphOptz, sinkTransposeBelowRELUWithPredicate) {
const size_t origDims[] = {1, 5, 10, 15};
const size_t transposedDims[] = {1, 15, 5, 10};
Node *A = mod_.createPlaceholder(ElemKind::FloatTy, origDims, "input", false);
Node *pred1 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *pred2 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *pred3 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *T = F_->createTranspose("transpose", A, NHWC2NCHW);
T->setPredicate(pred1);
Node *K = F_->createRELU("relu", T);
K->setPredicate(pred2);
SaveNode *O = F_->createSave("ret", K);
O->setPredicate(pred3);
EXPECT_EQ(F_->getNodes().size(), 3);
EXPECT_EQ(K->dims(0), llvm::makeArrayRef(transposedDims));
::glow::optimize(F_, CompilationMode::Infer);
EXPECT_EQ(O->getPredicate().getNode(), pred3);
// Expecting Transpose->Output rather than RELU->Output.
auto *transpose = llvm::dyn_cast<TransposeNode>(O->getInput());
ASSERT_NE(transpose, nullptr);
EXPECT_EQ(transpose->getPredicate().getNode(), pred2);
ASSERT_TRUE(llvm::isa<ReluNode>(transpose->getInput()));
auto *relu = llvm::cast<ReluNode>(transpose->getInput());
EXPECT_EQ(relu->getPredicate().getNode(), pred2);
// Check that the dimensions of the input and output have been
// updated to compensate the absence of transpose.
EXPECT_EQ(relu->dims(0), llvm::makeArrayRef(origDims));
EXPECT_EQ(relu->getInput().dims(), llvm::makeArrayRef(origDims));
EXPECT_EQ(F_->getNodes().size(), 3);
}
TEST_F(GraphOptz, sinkTransposeBelowSigmoid) {
const size_t origDims[] = {1, 5, 10, 15};
const size_t transposedDims[] = {1, 15, 5, 10};
Node *A = mod_.createPlaceholder(ElemKind::FloatTy, origDims, "input", false);
Node *T = F_->createTranspose("transpose", A, NHWC2NCHW);
Node *SI = F_->createSigmoid("sigmoid", T);
SaveNode *O = F_->createSave("ret", SI);
EXPECT_EQ(F_->getNodes().size(), 3);
EXPECT_EQ(SI->dims(0), llvm::makeArrayRef(transposedDims));
::glow::optimize(F_, CompilationMode::Infer);
// Expecting Transpose->Output rather than Sigmoid->Output.
auto *transpose = llvm::dyn_cast<TransposeNode>(O->getInput());
ASSERT_NE(transpose, nullptr);
ASSERT_TRUE(llvm::isa<SigmoidNode>(transpose->getInput()));
auto *si = llvm::cast<SigmoidNode>(transpose->getInput());
// Check that the dimensions of the input and output have been
// updated to compensate the absence of transpose.
EXPECT_EQ(si->dims(0), llvm::makeArrayRef(origDims));
EXPECT_EQ(si->getInput().dims(), llvm::makeArrayRef(origDims));
EXPECT_EQ(F_->getNodes().size(), 3);
}
/// Check that the predicates are preserved while sinking transposes
/// through Sigmoid.
TEST_F(GraphOptz, sinkTransposeBelowSigmoidWithPredicate) {
const size_t origDims[] = {1, 5, 10, 15};
const size_t transposedDims[] = {1, 15, 5, 10};
Node *A = mod_.createPlaceholder(ElemKind::FloatTy, origDims, "input", false);
Node *pred1 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *pred2 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *pred3 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *T = F_->createTranspose("transpose", A, NHWC2NCHW);
T->setPredicate(pred1);
Node *SI = F_->createSigmoid("sigmoid", T);
SI->setPredicate(pred2);
SaveNode *O = F_->createSave("ret", SI);
O->setPredicate(pred3);
EXPECT_EQ(F_->getNodes().size(), 3);
EXPECT_EQ(SI->dims(0), llvm::makeArrayRef(transposedDims));
::glow::optimize(F_, CompilationMode::Infer);
EXPECT_EQ(O->getPredicate().getNode(), pred3);
// Expecting Transpose->Output rather than Sigmoid->Output.
auto *transpose = llvm::dyn_cast<TransposeNode>(O->getInput());
ASSERT_NE(transpose, nullptr);
EXPECT_EQ(transpose->getPredicate().getNode(), pred2);
ASSERT_TRUE(llvm::isa<SigmoidNode>(transpose->getInput()));
auto *si = llvm::cast<SigmoidNode>(transpose->getInput());
EXPECT_EQ(si->getPredicate().getNode(), pred2);
// Check that the dimensions of the input and output have been
// updated to compensate the absence of transpose.
EXPECT_EQ(si->dims(0), llvm::makeArrayRef(origDims));
EXPECT_EQ(si->getInput().dims(), llvm::makeArrayRef(origDims));
EXPECT_EQ(F_->getNodes().size(), 3);
}
TEST_F(GraphOptz, sinkTransposeBelowTanh) {
const size_t origDims[] = {1, 5, 10, 15};
const size_t transposedDims[] = {1, 15, 5, 10};
Node *A = mod_.createPlaceholder(ElemKind::FloatTy, origDims, "input", false);
Node *T = F_->createTranspose("transpose", A, NHWC2NCHW);
Node *TN = F_->createTanh("tanh", T);
SaveNode *O = F_->createSave("ret", TN);
EXPECT_EQ(F_->getNodes().size(), 3);
EXPECT_EQ(TN->dims(0), llvm::makeArrayRef(transposedDims));
::glow::optimize(F_, CompilationMode::Infer);
// Expecting Transpose->Output rather than Tanh->Output.
auto *transpose = llvm::dyn_cast<TransposeNode>(O->getInput());
ASSERT_NE(transpose, nullptr);
ASSERT_TRUE(llvm::isa<TanhNode>(transpose->getInput()));
auto *tn = llvm::cast<TanhNode>(transpose->getInput());
// Check that the dimensions of the input and output have been
// updated to compensate the absence of transpose.
EXPECT_EQ(tn->dims(0), llvm::makeArrayRef(origDims));
EXPECT_EQ(tn->getInput().dims(), llvm::makeArrayRef(origDims));
EXPECT_EQ(F_->getNodes().size(), 3);
}
TEST_F(GraphOptz, sinkTransposeBelowTanhWithPredicate) {
const size_t origDims[] = {1, 5, 10, 15};
const size_t transposedDims[] = {1, 15, 5, 10};
Node *A = mod_.createPlaceholder(ElemKind::FloatTy, origDims, "input", false);
Node *pred1 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *pred2 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *pred3 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *T = F_->createTranspose("transpose", A, NHWC2NCHW);
T->setPredicate(pred1);
Node *TN = F_->createTanh("tanh", T);
TN->setPredicate(pred2);
SaveNode *O = F_->createSave("ret", TN);
O->setPredicate(pred3);
EXPECT_EQ(F_->getNodes().size(), 3);
EXPECT_EQ(TN->dims(0), llvm::makeArrayRef(transposedDims));
::glow::optimize(F_, CompilationMode::Infer);
EXPECT_EQ(O->getPredicate().getNode(), pred3);
// Expecting Transpose->Output rather than Tanh->Output.
auto *transpose = llvm::dyn_cast<TransposeNode>(O->getInput());
ASSERT_NE(transpose, nullptr);
EXPECT_EQ(transpose->getPredicate().getNode(), pred2);
ASSERT_TRUE(llvm::isa<TanhNode>(transpose->getInput()));
auto *tn = llvm::cast<TanhNode>(transpose->getInput());
EXPECT_EQ(tn->getPredicate().getNode(), pred2);
// Check that the dimensions of the input and output have been
// updated to compensate the absence of transpose.
EXPECT_EQ(tn->dims(0), llvm::makeArrayRef(origDims));
EXPECT_EQ(tn->getInput().dims(), llvm::makeArrayRef(origDims));
EXPECT_EQ(F_->getNodes().size(), 3);
}
TEST_F(GraphOptz, cancelTwoTransposes) {
const size_t origDims[] = {1, 5, 10, 15};
Node *A = mod_.createPlaceholder(ElemKind::FloatTy, origDims, "input", false);
Node *T1 = F_->createTranspose("transpose", A, NCHW2NHWC);
Node *T2 = F_->createTranspose("transpose", T1, NHWC2NCHW);
ReluNode *K = F_->createRELU("relu", T2);
SaveNode *save = F_->createSave("ret", K);
EXPECT_EQ(K->getInput().dims(), llvm::makeArrayRef(origDims));
EXPECT_EQ(F_->getNodes().size(), 4);
::glow::optimize(F_, CompilationMode::Infer);
EXPECT_EQ(F_->getNodes().size(), 2);
Node *relu = save->getInput();
EXPECT_EQ(relu->dims(0), llvm::makeArrayRef(origDims));
ASSERT_TRUE(llvm::isa<ReluNode>(relu));
EXPECT_EQ(llvm::cast<ReluNode>(relu)->getInput().getNode(), A);
}
/// Make sure the predicates don't get in the way of the
/// transpose(transpose) => identity and that they are
/// preserved.
TEST_F(GraphOptz, cancelTwoTransposesWithPredicate) {
const size_t origDims[] = {1, 5, 10, 15};
Node *A = mod_.createPlaceholder(ElemKind::FloatTy, origDims, "input", false);
Node *pred1 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *pred2 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *pred3 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *pred4 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *T1 = F_->createTranspose("transpose", A, NCHW2NHWC);
T1->setPredicate(pred1);
Node *T2 = F_->createTranspose("transpose", T1, NHWC2NCHW);
T2->setPredicate(pred2);
ReluNode *K = F_->createRELU("relu", T2);
K->setPredicate(pred3);
SaveNode *save = F_->createSave("ret", K);
save->setPredicate(pred4);
EXPECT_EQ(K->getInput().dims(), llvm::makeArrayRef(origDims));
EXPECT_EQ(F_->getNodes().size(), 4);
::glow::optimize(F_, CompilationMode::Infer);
EXPECT_EQ(F_->getNodes().size(), 2);
EXPECT_EQ(save->getPredicate().getNode(), pred4);
Node *relu = save->getInput();
EXPECT_EQ(relu->getPredicate().getNode(), pred3);
EXPECT_EQ(relu->dims(0), llvm::makeArrayRef(origDims));
ASSERT_TRUE(llvm::isa<ReluNode>(relu));
EXPECT_EQ(llvm::cast<ReluNode>(relu)->getInput().getNode(), A);
}
TEST_F(GraphOptz, removeIdentityTranspose) {
const size_t origDims[] = {1, 5, 10, 15};
Placeholder *A =
mod_.createPlaceholder(ElemKind::FloatTy, origDims, "input", false);
TransposeNode *T = F_->createTranspose("transpose", A, {0, 1, 2, 3});
ReluNode *K = F_->createRELU("relu", T);
F_->createSave("ret", K);
EXPECT_EQ(F_->getNodes().size(), 3);
EXPECT_EQ(K->getInput().getNode(), T);
::glow::optimize(F_, CompilationMode::Infer);
EXPECT_EQ(F_->getNodes().size(), 2);
EXPECT_EQ(K->getInput().getNode(), A);
// Make sure we didn't mess up with the dimensions of the
// variable while eliminating the transpose.
EXPECT_EQ(A->dims(), llvm::makeArrayRef(origDims));
}
/// Check that the predicates don't get in the way of
/// the identity transpose removal, while still being
/// preserved.
TEST_F(GraphOptz, removeIdentityTransposeWithPredicate) {
const size_t origDims[] = {1, 5, 10, 15};
Placeholder *A =
mod_.createPlaceholder(ElemKind::FloatTy, origDims, "input", false);
Placeholder *pred1 =
mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Placeholder *pred2 =
mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Placeholder *pred3 =
mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
TransposeNode *T = F_->createTranspose("transpose", A, {0, 1, 2, 3});
T->setPredicate(pred1);
ReluNode *K = F_->createRELU("relu", T);
K->setPredicate(pred2);
SaveNode *save = F_->createSave("ret", K);
save->setPredicate(pred3);
EXPECT_EQ(F_->getNodes().size(), 3);
EXPECT_EQ(K->getInput().getNode(), T);
::glow::optimize(F_, CompilationMode::Infer);
EXPECT_EQ(F_->getNodes().size(), 2);
EXPECT_EQ(save->getPredicate().getNode(), pred3);
EXPECT_EQ(save->getInput().getNode(), K);
EXPECT_EQ(K->getInput().getNode(), A);
EXPECT_EQ(K->getPredicate().getNode(), pred2);
// Make sure we didn't mess up with the dimensions of the
// variable while eliminating the transpose.
EXPECT_EQ(A->dims(), llvm::makeArrayRef(origDims));
}
TEST_F(GraphOptz, dontCancelTwoTransposesIfNotMatching) {
const size_t origDims[] = {1, 5, 10, 15};
const size_t afterFirstTransposeDims[] = {1, 10, 15, 5};
const size_t afterSecondTransposeDims[] = {1, 15, 5, 10};
Node *A = mod_.createPlaceholder(ElemKind::FloatTy, origDims, "input", false);
TransposeNode *T1 = F_->createTranspose("transpose", A, NCHW2NHWC);
TransposeNode *T2 = F_->createTranspose("transpose", T1, NCHW2NHWC);
SaveNode *save = F_->createSave("ret", T2);
EXPECT_EQ(F_->getNodes().size(), 3);
::glow::optimize(F_, CompilationMode::Infer);
EXPECT_EQ(F_->getNodes().size(), 3);
// Make sure the structure of the graph did not change.
Node *secondTranspose = save->getInput();
EXPECT_EQ(secondTranspose->dims(0),
llvm::makeArrayRef(afterSecondTransposeDims));
EXPECT_EQ(secondTranspose, T2);
Node *firstTranspose = T2->getInput();
EXPECT_EQ(firstTranspose, T1);
EXPECT_EQ(T1->dims(0), llvm::makeArrayRef(afterFirstTransposeDims));
EXPECT_EQ(T1->getInput().getNode(), A);
EXPECT_EQ(A->dims(0), llvm::makeArrayRef(origDims));
}
TEST_F(GraphOptz, sinkTransposeBelowArithmeticNodes) {
const size_t origDims[] = {1, 5, 10, 15};
Node *A1 =
mod_.createPlaceholder(ElemKind::FloatTy, origDims, "input1", false);
Node *A2 =
mod_.createPlaceholder(ElemKind::FloatTy, origDims, "input2", false);
Node *T1 = F_->createTranspose("transpose1", A1, NHWC2NCHW);
Node *T2 = F_->createTranspose("transpose2", A2, NHWC2NCHW);
Node *K = F_->createAdd("arith", T1, T2);
SaveNode *O = F_->createSave("ret", K);
EXPECT_EQ(F_->getNodes().size(), 4);
::glow::optimize(F_, CompilationMode::Infer);
// Expecting Transpose->Output rather than Add->Output.
auto *transpose = llvm::dyn_cast<TransposeNode>(O->getInput());
ASSERT_NE(transpose, nullptr);
ASSERT_TRUE(llvm::isa<AddNode>(transpose->getInput()));
auto *add = llvm::cast<AddNode>(transpose->getInput());
// Check that the dimensions of the input and output have been
// updated to compensate the absence of transpose.
EXPECT_EQ(add->dims(0), llvm::makeArrayRef(origDims));
EXPECT_EQ(add->getRHS().dims(), llvm::makeArrayRef(origDims));
EXPECT_EQ(add->getLHS().dims(), llvm::makeArrayRef(origDims));
EXPECT_EQ(add->getLHS().getNode(), A1);
EXPECT_EQ(add->getRHS().getNode(), A2);
EXPECT_EQ(F_->getNodes().size(), 3);
}
/// Check that the predicates are properly preserved while doing
/// the add(transpose, transpose) => transpose(add).
TEST_F(GraphOptz, sinkTransposeBelowArithmeticNodesWithPredicate) {
const size_t origDims[] = {1, 5, 10, 15};
Node *A1 =
mod_.createPlaceholder(ElemKind::FloatTy, origDims, "input1", false);
Node *A2 =
mod_.createPlaceholder(ElemKind::FloatTy, origDims, "input2", false);
Node *pred1 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *pred2 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *pred3 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *pred4 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *T1 = F_->createTranspose("transpose1", A1, NHWC2NCHW);
T1->setPredicate(pred1);
Node *T2 = F_->createTranspose("transpose2", A2, NHWC2NCHW);
T2->setPredicate(pred2);
Node *K = F_->createAdd("arith", T1, T2);
K->setPredicate(pred3);
SaveNode *O = F_->createSave("ret", K);
O->setPredicate(pred4);
EXPECT_EQ(F_->getNodes().size(), 4);
::glow::optimize(F_, CompilationMode::Infer);
EXPECT_EQ(O->getPredicate().getNode(), pred4);
// Expecting Transpose->Output rather than Add->Output.
auto *transpose = llvm::dyn_cast<TransposeNode>(O->getInput());
ASSERT_NE(transpose, nullptr);
EXPECT_EQ(transpose->getPredicate().getNode(), pred3);
ASSERT_TRUE(llvm::isa<AddNode>(transpose->getInput()));
auto *add = llvm::cast<AddNode>(transpose->getInput());
EXPECT_EQ(add->getPredicate().getNode(), pred3);
// Check that the dimensions of the input and output have been
// updated to compensate the absence of transpose.
EXPECT_EQ(add->dims(0), llvm::makeArrayRef(origDims));
EXPECT_EQ(add->getRHS().dims(), llvm::makeArrayRef(origDims));
EXPECT_EQ(add->getLHS().dims(), llvm::makeArrayRef(origDims));
EXPECT_EQ(add->getLHS().getNode(), A1);
EXPECT_EQ(add->getRHS().getNode(), A2);
EXPECT_EQ(F_->getNodes().size(), 3);
}
TEST_F(GraphOptz, sinkReluBelowConcatNodes) {
const size_t origDims[] = {1, 5, 10, 15};
const size_t origDimsConcat[] = {1, 10, 10, 15};
Node *A1 =
mod_.createPlaceholder(ElemKind::FloatTy, origDims, "input1", false);
Node *A2 =
mod_.createPlaceholder(ElemKind::FloatTy, origDims, "input2", false);
Node *R1 = F_->createRELU("relu1", A1);
Node *R2 = F_->createRELU("relu2", A2);
Node *CN = F_->createConcat("concat", {R1, R2}, 1);
SaveNode *O = F_->createSave("ret", CN);
EXPECT_EQ(F_->getNodes().size(), 4);
::glow::optimize(F_, CompilationMode::Infer);
// Expecting RELU->Output rather than Concat->Output.
auto *relu = llvm::dyn_cast<ReluNode>(O->getInput());
ASSERT_NE(relu, nullptr);
ASSERT_TRUE(llvm::isa<ConcatNode>(relu->getInput()));
auto *concat = llvm::cast<ConcatNode>(relu->getInput());
// Check that the dimensions of the input and output have been
// updated to compensate the absence of transpose.
EXPECT_EQ(concat->dims(0), llvm::makeArrayRef(origDimsConcat));
EXPECT_EQ(concat->getInputs()[0].dims(), llvm::makeArrayRef(origDims));
EXPECT_EQ(concat->getInputs()[1].dims(), llvm::makeArrayRef(origDims));
EXPECT_EQ(concat->getInputs()[0].getNode(), A1);
EXPECT_EQ(concat->getInputs()[1].getNode(), A2);
EXPECT_EQ(F_->getNodes().size(), 3);
}
/// Check that the predicates are properly preserved while doing
/// the sinking of relu nodes.
TEST_F(GraphOptz, sinkReluBelowConcatNodesWithPredicate) {
const size_t origDims[] = {1, 5, 10, 15};
const size_t origDimsConcat[] = {1, 10, 10, 15};
Node *A1 =
mod_.createPlaceholder(ElemKind::FloatTy, origDims, "input1", false);
Node *A2 =
mod_.createPlaceholder(ElemKind::FloatTy, origDims, "input2", false);
Node *pred1 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *pred2 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *pred3 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *pred4 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *R1 = F_->createRELU("relu1", A1);
R1->setPredicate(pred1);
Node *R2 = F_->createRELU("relu2", A2);
R2->setPredicate(pred2);
Node *CN = F_->createConcat("concat", {R1, R2}, 1);
CN->setPredicate(pred3);
SaveNode *O = F_->createSave("ret", CN);
O->setPredicate(pred4);
EXPECT_EQ(F_->getNodes().size(), 4);
::glow::optimize(F_, CompilationMode::Infer);
// Expecting RELU->Output rather than Concat->Output.
EXPECT_EQ(O->getPredicate().getNode(), pred4);
auto *relu = llvm::dyn_cast<ReluNode>(O->getInput());
ASSERT_NE(relu, nullptr);
EXPECT_EQ(relu->getPredicate().getNode(), pred3);
ASSERT_TRUE(llvm::isa<ConcatNode>(relu->getInput()));
auto *concat = llvm::cast<ConcatNode>(relu->getInput());
EXPECT_EQ(concat->getPredicate().getNode(), pred3);
// Check that the dimensions of the input and output have been
// updated to compensate the absence of transpose.
EXPECT_EQ(concat->dims(0), llvm::makeArrayRef(origDimsConcat));
EXPECT_EQ(concat->getInputs()[0].dims(), llvm::makeArrayRef(origDims));
EXPECT_EQ(concat->getInputs()[1].dims(), llvm::makeArrayRef(origDims));
EXPECT_EQ(concat->getInputs()[0].getNode(), A1);
EXPECT_EQ(concat->getInputs()[1].getNode(), A2);
EXPECT_EQ(F_->getNodes().size(), 3);
}
TEST_F(GraphOptz, sinkTransposeBelowConcatNodes) {
const size_t origDims[] = {1, 5, 10, 15};
const size_t origDimsConcat[] = {1, 5, 20, 15};
Node *A1 =
mod_.createPlaceholder(ElemKind::FloatTy, origDims, "input1", false);
Node *A2 =
mod_.createPlaceholder(ElemKind::FloatTy, origDims, "input2", false);
Node *T1 = F_->createTranspose("transpose", A1, NCHW2NHWC);
Node *T2 = F_->createTranspose("transpose", A2, NCHW2NHWC);
Node *CN = F_->createConcat("concat", {T1, T2}, 1);
SaveNode *O = F_->createSave("ret", CN);
EXPECT_EQ(F_->getNodes().size(), 4);
::glow::optimize(F_, CompilationMode::Infer);
// Expecting Transpose->Output rather than Add->Output.
auto *transpose = llvm::dyn_cast<TransposeNode>(O->getInput());
ASSERT_NE(transpose, nullptr);
ASSERT_TRUE(llvm::isa<ConcatNode>(transpose->getInput()));
auto *concat = llvm::cast<ConcatNode>(transpose->getInput());
// Check that the dimensions of the input and output have been
// updated to compensate the absence of transpose.
EXPECT_EQ(concat->dims(0), llvm::makeArrayRef(origDimsConcat));
EXPECT_EQ(concat->getInputs()[0].dims(), llvm::makeArrayRef(origDims));
EXPECT_EQ(concat->getInputs()[1].dims(), llvm::makeArrayRef(origDims));
EXPECT_EQ(concat->getInputs()[0].getNode(), A1);
EXPECT_EQ(concat->getInputs()[1].getNode(), A2);
EXPECT_EQ(F_->getNodes().size(), 3);
}
/// Check that the predicates are properly preserved while doing
/// the concat(transpose, transpose) => transpose(add).
TEST_F(GraphOptz, sinkTransposeBelowConcatWithPredicate) {
const size_t origDims[] = {1, 5, 10, 15};
const size_t origDimsConcat[] = {1, 5, 20, 15};
Node *A1 =
mod_.createPlaceholder(ElemKind::FloatTy, origDims, "input1", false);
Node *A2 =
mod_.createPlaceholder(ElemKind::FloatTy, origDims, "input2", false);
Node *pred1 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *pred2 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *pred3 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *pred4 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "pred", false);
Node *T1 = F_->createTranspose("transpose", A1, NCHW2NHWC);
T1->setPredicate(pred1);
Node *T2 = F_->createTranspose("transpose", A2, NCHW2NHWC);
T2->setPredicate(pred2);
Node *CN = F_->createConcat("concat", {T1, T2}, 1);
CN->setPredicate(pred3);
SaveNode *O = F_->createSave("ret", CN);
O->setPredicate(pred4);
EXPECT_EQ(F_->getNodes().size(), 4);
::glow::optimize(F_, CompilationMode::Infer);
EXPECT_EQ(O->getPredicate().getNode(), pred4);
// Expecting Transpose->Output rather than Add->Output.
auto *transpose = llvm::dyn_cast<TransposeNode>(O->getInput());
ASSERT_NE(transpose, nullptr);
EXPECT_EQ(transpose->getPredicate().getNode(), pred3);
ASSERT_TRUE(llvm::isa<ConcatNode>(transpose->getInput()));
auto *concat = llvm::cast<ConcatNode>(transpose->getInput());
EXPECT_EQ(concat->getPredicate().getNode(), pred3);
// Check that the dimensions of the input and output have been
// updated to compensate the absence of transpose.
EXPECT_EQ(concat->dims(0), llvm::makeArrayRef(origDimsConcat));
EXPECT_EQ(concat->getInputs()[0].dims(), llvm::makeArrayRef(origDims));
EXPECT_EQ(concat->getInputs()[1].dims(), llvm::makeArrayRef(origDims));
EXPECT_EQ(concat->getInputs()[0].getNode(), A1);
EXPECT_EQ(concat->getInputs()[1].getNode(), A2);
EXPECT_EQ(F_->getNodes().size(), 3);
}
TEST_F(GraphOptz, poolBelowReluSwapped) {
Node *A =
mod_.createPlaceholder(ElemKind::FloatTy, {1, 5, 10, 15}, "input", false);
Node *R = F_->createRELU("relu", A);
Node *PL = F_->createMaxPool("pool", R, 1, 10, 20);
Node *O = F_->createSave("ret", PL);
EXPECT_EQ(F_->getNodes().size(), 3);
::glow::optimize(F_, CompilationMode::Infer);
// Expecting RELU->Output rather than Pool->Output.
EXPECT_TRUE(llvm::isa<SaveNode>(O));
EXPECT_TRUE(llvm::isa<ReluNode>(llvm::dyn_cast<SaveNode>(O)->getInput()));
EXPECT_EQ(F_->getNodes().size(), 3);
}
TEST_F(GraphOptz, poolBelowReluNotSwappedIfModeNotMax) {
Node *A =
mod_.createPlaceholder(ElemKind::FloatTy, {1, 5, 10, 15}, "input", false);
Node *R = F_->createRELU("relu", A);
Node *PL = F_->createAvgPool("pool", R, 1, 10, 20);
Node *O = F_->createSave("ret", PL);
EXPECT_EQ(F_->getNodes().size(), 3);
::glow::optimize(F_, CompilationMode::Infer);
// Expecting Pool->Output (no swap).
EXPECT_TRUE(llvm::isa<SaveNode>(O));
EXPECT_TRUE(llvm::isa<AvgPoolNode>(llvm::dyn_cast<SaveNode>(O)->getInput()));
EXPECT_EQ(F_->getNodes().size(), 3);
}
TEST_F(GraphOptz, poolBelowReluNotSwappedIfNotSingleUse) {
Node *A =
mod_.createPlaceholder(ElemKind::FloatTy, {1, 5, 10, 15}, "input", false);
Node *R = F_->createRELU("relu", A);
Node *PL = F_->createMaxPool("pool", R, 1, 10, 20);
Node *O = F_->createSave("ret", PL);
F_->createSave("ret", R);
EXPECT_EQ(F_->getNodes().size(), 4);
::glow::optimize(F_, CompilationMode::Infer);
// Expecting Pool->Output (no swap).
EXPECT_TRUE(llvm::isa<SaveNode>(O));
EXPECT_TRUE(llvm::isa<MaxPoolNode>(llvm::dyn_cast<SaveNode>(O)->getInput()));
EXPECT_EQ(F_->getNodes().size(), 4);
}
/// A helper predicate to check if the provided node has the same address as a
/// pre-defined address provided in constructor. This is useful if you need to
/// check that a given node is still in the graph. In general, it is not safe to
/// use the std::find(begin_it, end_it, value) and compare the nodes by value,
/// because the node provided as the last parameter of std::find (i.e. the value
/// reference) may have been removed by some optimizations and cannot be
/// dereferenced anymore. But comparing the addresses of the nodes should be
/// fine. Thus, one can use the following form instead:
/// std::find_if(begin_it, end_it, IsSameNodeAddress(node_address))
struct IsSameNodeAddress {
Node *nodeAddress_;
IsSameNodeAddress(Node *nodeAddress) : nodeAddress_(nodeAddress) {}
bool operator()(const Node &n) const { return &n == nodeAddress_; }
};
TEST_F(GraphOptz, mergeConcatNodes) {
Node *A1 = mod_.createPlaceholder(ElemKind::FloatTy, {1, 5, 10, 15}, "input1",
false);
Node *A2 = mod_.createPlaceholder(ElemKind::FloatTy, {1, 5, 10, 15}, "input2",
false);
Node *A3 = mod_.createPlaceholder(ElemKind::FloatTy, {1, 5, 10, 15}, "input3",
false);
Node *A4 =
mod_.createPlaceholder(ElemKind::FloatTy, {1, 1, 5, 15}, "input4", false);
Node *A5 =
mod_.createPlaceholder(ElemKind::FloatTy, {1, 1, 5, 15}, "input5", false);
Node *CN1 = F_->createConcat("concat1", {A1, A2}, 1);
Node *CN2 = F_->createConcat("concat2", {A1, CN1}, 1);
Node *CN3 = F_->createConcat("concat3", {A4, A5}, 2);
Node *CN4 = F_->createConcat("concat4", {A3, CN2, CN3}, 1);
Node *O = F_->createSave("ret", CN4);
EXPECT_EQ(F_->getNodes().size(), 5);
::glow::optimize(F_, CompilationMode::Train);
// It is expected that the optimization transforms
// concat4(1, A3, concat2(1, A1, concat1(1, A1, A2)), concat3(2, A4, A5))
// into
// concat4(1, A3, A1, A1, A2, concat3(2, A4, A5))
EXPECT_TRUE(llvm::isa<SaveNode>(O));
auto *CN =
llvm::dyn_cast<ConcatNode>(llvm::dyn_cast<SaveNode>(O)->getInput());
EXPECT_TRUE(CN);
// The merged ConcatNode should have 5 inputs.
EXPECT_EQ(CN->getInputs().size(), 5);
// CN1 should be merged into a new CN2 and later into a new CN4 and removed by
// the optimizations.
EXPECT_TRUE(std::find_if(F_->getNodes().begin(), F_->getNodes().end(),
IsSameNodeAddress(CN1)) == F_->getNodes().end());
// CN2 should be merged into a new CN4 and removed by the optimizations.
EXPECT_TRUE(std::find_if(F_->getNodes().begin(), F_->getNodes().end(),
IsSameNodeAddress(CN2)) == F_->getNodes().end());
// CN3 should not be merged into CN4 and should not be removed,
// because CN4 and CN3 have a different dimension parameter.
EXPECT_TRUE(std::find_if(F_->getNodes().begin(), F_->getNodes().end(),
IsSameNodeAddress(CN3)) != F_->getNodes().end());
// The CN4 concat node should be replaced by a merged concat node.
EXPECT_TRUE(std::find_if(F_->getNodes().begin(), F_->getNodes().end(),
IsSameNodeAddress(CN4)) == F_->getNodes().end());
EXPECT_EQ(F_->getNodes().size(), 3);
}
TEST_F(GraphOptz, CSE) {
Node *A1 = mod_.createPlaceholder(ElemKind::FloatTy, {1, 5, 10, 15}, "input1",
false);
Node *A2 = mod_.createPlaceholder(ElemKind::FloatTy, {1, 5, 10, 15}, "input2",
false);
Node *CN1 = F_->createConcat("concat1", {A1, A2}, 1);
Node *CN2 = F_->createConcat("concat2", {A1, A2}, 1);
Node *CN3 = F_->createConcat("concat3", {CN1, CN2}, 2);
Node *O = F_->createSave("ret", CN3);
EXPECT_EQ(F_->getNodes().size(), 4);
::glow::optimize(F_, CompilationMode::Train);
EXPECT_TRUE(llvm::isa<SaveNode>(O));
auto *CN =
llvm::dyn_cast<ConcatNode>(llvm::dyn_cast<SaveNode>(O)->getInput());
EXPECT_TRUE(CN);
// The merged ConcatNode should have 2 inputs.
EXPECT_EQ(CN->getInputs().size(), 2);
// CN1 should not be removed.
EXPECT_TRUE(std::find_if(F_->getNodes().begin(), F_->getNodes().end(),
IsSameNodeAddress(CN1)) != F_->getNodes().end());
// CSE should replace CN2 by CN1 and remove CN2.
EXPECT_TRUE(std::find_if(F_->getNodes().begin(), F_->getNodes().end(),
IsSameNodeAddress(CN2)) == F_->getNodes().end());
EXPECT_EQ(F_->getNodes().size(), 3);
}
TEST_F(GraphOptz, SliceOfSplatNode) {
Type t(ElemKind::FloatTy, {1000, 1000, 1000});
Node *Z = F_->createSplat("zero", &t, 0.);
Node *S = F_->createSlice("slice", Z, {5, 15, 42}, {99, 88, 77});
Node *O = F_->createSave("ret", S);
EXPECT_EQ(F_->getNodes().size(), 3);
::glow::optimize(F_, CompilationMode::Train);
EXPECT_EQ(F_->getNodes().size(), 2);
EXPECT_TRUE(llvm::isa<SaveNode>(O));
auto *CN = llvm::dyn_cast<SplatNode>(llvm::dyn_cast<SaveNode>(O)->getInput());
EXPECT_TRUE(CN);
EXPECT_TRUE(CN->getResult().getType()->dims().equals({94, 73, 35}));
}
TEST_F(GraphOptz, ZeroArithmetic) {
// Tests the identities: [0 + X = X] [0 * X = 0] [0 / X = 0] [ X - 0 = X]
auto *input =
mod_.createPlaceholder(ElemKind::FloatTy, {4, 10}, "input", true);
// This builds the expression: ((0 / I) + (0 + I) + (0 * I)) - 0
auto *zero = F_->createSplat("zero", input->getType(), 0.);
auto *div = F_->createDiv("div", zero, input); // -> zero
auto *add = F_->createAdd("add", zero, input); // -> input
auto *mul = F_->createMul("mul", zero, input); // -> zero
auto *add3 = F_->createAdd("add", div, add);
add3 = F_->createAdd("add", add3, mul);
auto *sub = F_->createSub("sub", add3, zero); // -> input
SaveNode *O = F_->createSave("ret", sub);
// The expression evaluates to "I".
EXPECT_EQ(F_->getNodes().size(), 8);
::glow::optimize(F_, CompilationMode::Infer);
EXPECT_EQ(F_->getNodes().size(), 1);
EXPECT_EQ(O->getInput().getNode(), input);
}
/// A test that verifies that arithmetic simplification works correctly when
/// the parents need to be simplified prior to the node itself.
TEST_F(GraphOptz, ZeroArithmeticParentsMustBeSimplifiedFirst) {
auto *input1 =
mod_.createPlaceholder(ElemKind::FloatTy, {4, 10}, "input1", true);
auto *input2 =
mod_.createPlaceholder(ElemKind::FloatTy, {4, 10}, "input2", true);
// This builds the expression: ((0 * I1) * (0 * I2)) = 0
// It should be simplified to simply the splat zero node being saved.
SplatNode *zero = F_->createSplat("zero", input1->getType(), 0.);
MulNode *mul1 = F_->createMul("mul1", zero, input1); // -> 0
MulNode *mul2 = F_->createMul("mul2", zero, input2); // -> 0
MulNode *mul3 = F_->createMul("mul3", mul1, mul2); // -> 0
SaveNode *O = F_->createSave("ret", mul3);
// Expect 1 splat, 3 muls, 1 save.
EXPECT_EQ(F_->getNodes().size(), 5);
::glow::optimize(F_, CompilationMode::Infer);
// Expect all muls to be optimized away, with 1 splat and 1 save left.
EXPECT_EQ(F_->getNodes().size(), 2);
EXPECT_TRUE(std::find_if(F_->getNodes().begin(), F_->getNodes().end(),
IsSameNodeAddress(O)) != F_->getNodes().end());
EXPECT_TRUE(std::find_if(F_->getNodes().begin(), F_->getNodes().end(),
IsSameNodeAddress(zero)) != F_->getNodes().end());
EXPECT_EQ(O->getInput().getNode(), zero);
}
/// Tests opts for the identities: [1 * X = X] [X / 1 = X]
TEST_F(GraphOptz, ArithmeticIdentitiesOne) {
auto *input =
mod_.createPlaceholder(ElemKind::FloatTy, {4, 10}, "input", true);
// This builds the expression: (I / 1) * 1:
SplatNode *one = F_->createSplat("one", input->getType(), 1.);
DivNode *div = F_->createDiv("div", input, one);
MulNode *mul = F_->createMul("mul", div, one);
SaveNode *SN = F_->createSave("ret", mul);
// Splat, Div, Mul, Save.
EXPECT_EQ(F_->getNodes().size(), 4);
::glow::optimize(F_, CompilationMode::Infer);
// The expression evaluates to "I", so Save is only node left.
EXPECT_EQ(F_->getNodes().size(), 1);
ASSERT_TRUE(std::find_if(F_->getNodes().begin(), F_->getNodes().end(),
IsSameNodeAddress(SN)) != F_->getNodes().end());
// Save node should just save the input.
EXPECT_TRUE(SN->getInput().getNode() == input);
}
/// Reverse the intrusive list of nodes. This custom implementation is required,
/// because std::reverse cannot be used with LLVM's intrusive lists.
static void reverse(NodesList &L) {
if (L.empty())
return;
// Last element of the list before reversal.
auto &last = L.back();
// Take element from the beginning and move it right after the old last
// element. Do it until the old last element becomes the first element.
while (true) {
auto &first = L.front();
// Finish when the old last element becomes the new front element.
if (&first == &last) {
break;
}
L.remove(first);
L.insert(++last.getIterator(), &first);
}
}
TEST(GraphOptzTest, SliceOfSplatNodeChain) {
for (int shouldReverse = 0; shouldReverse <= 1; shouldReverse++) {
Module mod;
Function *F = mod.createFunction("foo");
Context ctx;
Type t(ElemKind::FloatTy, {1000, 1000, 1000});
Node *Z = F->createSplat("zero", &t, 0.);
Node *S1 = F->createSlice("slice1", Z, {5, 15, 42}, {99, 88, 77});
Node *S2 = F->createSlice("slice2", S1, {1, 1, 1}, {2, 3, 4});
F->createSave("ret", S2);
if (shouldReverse) {
auto &nodes = F->getNodes();
reverse(nodes);
}
EXPECT_EQ(F->getNodes().size(), 4);
::glow::optimize(F, CompilationMode::Train);
// This test illustrates some inconsistency in the optimization.
// Chain splats are not guaranteed to be optimized.
EXPECT_EQ(F->getNodes().size(), shouldReverse ? 3 : 2);
}
}
TEST_F(GraphOptz, ReshapeNoop) {
const size_t shape[] = {10, 20, 30};
Type t(ElemKind::FloatTy, shape);
auto *Z = F_->createSplat("zero", &t, 0.);
auto *R = F_->createReshape("reshape", Z, shape);
auto *O = F_->createSave("ret", R);
EXPECT_EQ(F_->getNodes().size(), 3);
::glow::optimize(F_, CompilationMode::Train);
EXPECT_EQ(F_->getNodes().size(), 2);
auto *SN = llvm::dyn_cast<SplatNode>(llvm::dyn_cast<SaveNode>(O)->getInput());
EXPECT_TRUE(SN);
EXPECT_TRUE(SN->getResult().getType()->dims().equals(shape));
}
/// Test the Reshape(Splat(args)) -> Splat(args') transformation.
/// Including a positive and a negative test case. In the positive case,
/// the optimization will take place for the splat node (Z2) that has only one
/// use. In the negative case, the optimization will not happen as the splat
/// node (Z1) has more than one use.
TEST_F(GraphOptz, ReshapeAfterSplat) {
const size_t shape[] = {10, 20, 30};
const size_t reshape[] = {1, 6000};
Type t1(ElemKind::FloatTy, shape);
Type t2(ElemKind::FloatTy, reshape);
Node *input = F_->getParent()->createPlaceholder(ElemKind::FloatTy, shape,
"input", true);
auto *Z1 = F_->createSplat("zero1", &t1, 1.5);
auto *A1 = F_->createAdd("add1", Z1->getResult().getType(), input, Z1);
auto *R1 = F_->createReshape("reshape1", Z1, reshape);
// Z1 is used by R1 and A1.
// The reshape optimization will thus NOT be able to remove this reshape node
// (R1).
auto *R2 = F_->createReshape("reshape2", A1, reshape);
auto *A2 = F_->createAdd("add", R1->getResult().getType(), R1, R2);
auto *Z2 = F_->createSplat("zero2", &t1, 2.5);
auto *R3 = F_->createReshape("reshape3", Z2, reshape);
// Z2 is only used by R3.
// The Z2,R3 nodes will be replaced by a new splat node with the shape of R3.
auto *A3 = F_->createAdd("add", A2->getResult().getType(), A2, R3);
auto *O = F_->createSave("ret", A3);
// Before optimization, we have 9 nodes in the graph.
EXPECT_EQ(F_->getNodes().size(), 9);
::glow::optimize(F_, CompilationMode::Infer);
// After optimization, we expect to see only 8 nodes, as Z2,R2 would be
// replace by a new splat node.
EXPECT_EQ(F_->getNodes().size(), 8);
// The second input of A3 shoule be a splat node with a shape of R3.
auto *newA3 = llvm::dyn_cast<AddNode>(O->getInput());
ASSERT_TRUE(newA3);
auto *SN = llvm::dyn_cast<SplatNode>(newA3->getRHS());
EXPECT_TRUE(SN);
EXPECT_TRUE(SN->getResult().getType()->dims().equals(reshape));
// R1 should still be in the graph.
EXPECT_TRUE(std::find_if(F_->getNodes().begin(), F_->getNodes().end(),
IsSameNodeAddress(R1)) != F_->getNodes().end());
// R3 and Z2 should not be in the graph any more.
EXPECT_TRUE(std::find_if(F_->getNodes().begin(), F_->getNodes().end(),
IsSameNodeAddress(R3)) == F_->getNodes().end());
EXPECT_TRUE(std::find_if(F_->getNodes().begin(), F_->getNodes().end(),
IsSameNodeAddress(Z2)) == F_->getNodes().end());
}
/// Test the Reshape(Reshape(x)) -> Reshape(x) transformation.
TEST_F(GraphOptz, ReshapeReshapeOpt) {
const size_t shape[] = {10, 20};
const size_t reshape1[] = {200, 1};
const size_t reshape2[] = {200};
Node *input = F_->getParent()->createPlaceholder(ElemKind::FloatTy, shape,
"input", true);
auto *R1 = F_->createReshape("reshape1", input, reshape1);
auto *R2 = F_->createReshape("reshape2", R1, reshape2);
auto *O = F_->createSave("ret", R2);
// Before optimization, we have 2 Reshapes and a Save.
EXPECT_EQ(F_->getNodes().size(), 3);
::glow::optimize(F_, CompilationMode::Infer);
// After optimization, we expect to see only 1 Reshape and a Save.
EXPECT_EQ(F_->getNodes().size(), 2);
// Save should have the new Reshape as input.
auto *RN = llvm::dyn_cast<ReshapeNode>(O->getInput());
ASSERT_TRUE(RN);
// The new Reshape should have the same shape as the original second Reshape.
EXPECT_TRUE(RN->getResult().getType()->dims().equals(reshape2));
// R1 and R2 should not be in the graph any more; they were replaced by a
// single new reshape.
EXPECT_TRUE(std::find_if(F_->getNodes().begin(), F_->getNodes().end(),
IsSameNodeAddress(R1)) == F_->getNodes().end());
EXPECT_TRUE(std::find_if(F_->getNodes().begin(), F_->getNodes().end(),
IsSameNodeAddress(R2)) == F_->getNodes().end());
}
TEST_F(GraphOptz, DCEPublicVars) {
mod_.createPlaceholder(ElemKind::FloatTy, {4, 320, 200, 3}, "input", true);
EXPECT_EQ(mod_.getPlaceholders().size(), 1);
// Optimize all of the dead code.
::glow::optimize(F_, CompilationMode::Infer);
// Public nodes should not be deleted.
EXPECT_EQ(mod_.getPlaceholders().size(), 1);
}
TEST_F(GraphOptz, foldQuantizeIntoVar) {
auto *input = mod_.createPlaceholder(ElemKind::FloatTy, {4}, "input", true);
*ctx_.allocate(input) = {10, 10, 10, 10};
auto qType = mod_.uniqueType(ElemKind::Int8QTy, {4}, 2, 0);
auto Q = F_->createQuantize("quantize", input, qType);
auto S = F_->createSave("save", Q);
EXPECT_EQ(2, F_->getNodes().size());
::glow::convertPlaceholdersToConstants(F_, ctx_, {S->getPlaceholder()});
::glow::optimize(F_, CompilationMode::Infer);
// Quantization node was merged into input var.
EXPECT_EQ(1, F_->getNodes().size());
auto quantizedInput = llvm::cast<Constant>(S->getInput());
auto quantizedValues = quantizedInput->getHandle<int8_t>();
for (unsigned i = 0; i < 4; ++i) {
EXPECT_EQ(5, quantizedValues.raw(i));
}
}
TEST_F(GraphOptz, foldQuantizeIntoVarMultipleUsages) {
auto *input = mod_.createPlaceholder(ElemKind::FloatTy, {4}, "input", true);
*ctx_.allocate(input) = {10, 10, 10, 10};
auto qType = mod_.uniqueType(ElemKind::Int8QTy, {4}, 2, 0);
auto Q = F_->createQuantize("quantize", input, qType);
F_->createSave("save", Q);
auto clonedF = F_->clone("cloned");
EXPECT_EQ(2, clonedF->getNodes().size());
::glow::convertPlaceholdersToConstants(clonedF, ctx_, {});
::glow::optimize(clonedF, CompilationMode::Infer);
// F_ function should not be affected.
EXPECT_EQ(2, F_->getNodes().size());
// Check original var.
for (unsigned i = 0; i < 4; ++i) {
EXPECT_EQ(10, ctx_.get(input)->getHandle().raw(i));
}
// Quantization node was merged into input var.
EXPECT_EQ(1, clonedF->getNodes().size());
auto *save = llvm::dyn_cast<SaveNode>(&clonedF->getNodes().front());
ASSERT_TRUE(save);
auto quantizedInput = llvm::cast<Constant>(save->getInput());
auto quantizedValues = quantizedInput->getHandle<int8_t>();
for (unsigned i = 0; i < 4; ++i) {
EXPECT_EQ(5, quantizedValues.raw(i));
}
}
/// Check that rescale gets correctly merged into a following dequantize node
TEST_F(GraphOptz, mergeRescaleIntoDequantize) {
// Check that we are combining quantization-dequantization pairs.
auto *input = mod_.createPlaceholder(ElemKind::Int8QTy, {4, 10}, 0.5, 11,
"input", true);
auto *qType = mod_.uniqueType(ElemKind::Int8QTy, {4, 10}, 0.03f, 5);
auto *R = F_->createRescaleQuantized("rescale", input, qType);
auto *D = F_->createDequantize("dequantize", R);
F_->createSave("ret", D);
EXPECT_EQ(F_->getNodes().size(), 3);
::glow::optimize(F_, CompilationMode::Infer);
// Only 2 nodes should remain (Dequantize -> Save)
EXPECT_EQ(F_->getNodes().size(), 2);
// Check the graph structure
auto *SN = F_->getNodeByName("ret");
EXPECT_NE(nullptr, SN);
auto *S = llvm::dyn_cast<SaveNode>(SN);
EXPECT_NE(nullptr, S);
auto *newDN = S->getInput().getNode();
EXPECT_NE(nullptr, newDN);
EXPECT_NE(nullptr, llvm::dyn_cast<DequantizeNode>(newDN));
}
TEST_F(GraphOptz, quantizeToRescale) {
// Check that we are combining quantization-dequantization pairs.
auto *input = mod_.createPlaceholder(ElemKind::Int8QTy, {4, 10}, 0.5, 11,
"input", true);
auto *D = F_->createDequantize("dequantize", input);
auto qType = mod_.uniqueType(ElemKind::Int8QTy, {4, 10}, 0.03, 5);
auto *Q = F_->createQuantize("quantize", D, qType);
F_->createSave("ret", Q);
EXPECT_EQ(F_->getNodes().size(), 3);
::glow::optimize(F_, CompilationMode::Infer);
EXPECT_EQ(F_->getNodes().size(), 2);
}
TEST_F(GraphOptz, MaxOfQuantizedSplat) {
const size_t size = 5;
const float scale = 1;
// offset == -128 guarantees that fp range has values which are not less than
// 0.
const int32_t offset = -128;
auto splatTy = mod_.uniqueType(ElemKind::Int8QTy, {size}, scale, offset);
auto *splat = F_->createSplat("splat", splatTy, 0.0);
auto *input = mod_.createPlaceholder(ElemKind::Int8QTy, {size}, scale, offset,
"input", true);
auto *max = F_->createMax("max", splat, input);
F_->createSave("save", max);
EXPECT_EQ(F_->getNodes().size(), 3);
::glow::optimize(F_, CompilationMode::Infer);
// Splat and Max should be gone.
EXPECT_EQ(F_->getNodes().size(), 1);
}
TEST_F(GraphOptz, FuseRescaleIntoArithmetic) {
// This test ensures the fact that fusing of rescale is done.
auto opOutTy = mod_.uniqueType(ElemKind::Int8QTy, {10}, 1, 0);
auto rescaleOutTy = mod_.uniqueType(ElemKind::Int8QTy, {10}, 2, 1);
Placeholder *LHS =
mod_.createPlaceholder(ElemKind::Int8QTy, {10}, 0.4, 0, "LHS", true);
Placeholder *RHS =
mod_.createPlaceholder(ElemKind::Int8QTy, {10}, 0.3, 0, "RHS", true);
AddNode *add = F_->createAdd("qAdd", opOutTy, LHS, RHS);
RescaleQuantizedNode *rescaleAdd =
F_->createRescaleQuantized("rsAdd", add, rescaleOutTy);
SaveNode *addSave = F_->createSave("saveAdd", rescaleAdd);
SubNode *sub = F_->createSub("qSub", opOutTy, LHS, RHS);
RescaleQuantizedNode *rescaleSub =
F_->createRescaleQuantized("rsSub", sub, rescaleOutTy);
SaveNode *subSave = F_->createSave("saveSub", rescaleSub);
DivNode *div = F_->createDiv("qDiv", opOutTy, LHS, RHS);
RescaleQuantizedNode *rescaleDiv =
F_->createRescaleQuantized("rsDiv", div, rescaleOutTy);
SaveNode *divSave = F_->createSave("saveDiv", rescaleDiv);
MulNode *mul = F_->createMul("qMul", opOutTy, LHS, RHS);
RescaleQuantizedNode *rescaleMul =
F_->createRescaleQuantized("rsMul", mul, rescaleOutTy);
SaveNode *mulSave = F_->createSave("saveMul", rescaleMul);
MinNode *min = F_->createMin("qMin", opOutTy, LHS, RHS);
RescaleQuantizedNode *rescaleMin =
F_->createRescaleQuantized("rsMin", min, rescaleOutTy);
SaveNode *minSave = F_->createSave("saveMin", rescaleMin);
MaxNode *max = F_->createMax("qMax", opOutTy, LHS, RHS);
RescaleQuantizedNode *rescaleMax =
F_->createRescaleQuantized("rsMax", max, rescaleOutTy);
SaveNode *maxSave = F_->createSave("saveMax", rescaleMax);
// All rescales must be fused into arithmetic operations above.
::glow::optimize(F_, CompilationMode::Infer);
EXPECT_EQ(F_->getNodes().size(), 12);
EXPECT_EQ(addSave->getInput().getType(), rescaleOutTy);
EXPECT_EQ(subSave->getInput().getType(), rescaleOutTy);
EXPECT_EQ(mulSave->getInput().getType(), rescaleOutTy);
EXPECT_EQ(divSave->getInput().getType(), rescaleOutTy);
EXPECT_EQ(minSave->getInput().getType(), rescaleOutTy);
EXPECT_EQ(maxSave->getInput().getType(), rescaleOutTy);
}
TEST_F(GraphOptz, fuseRescaleIntoConv) {
// This test ensures the fact that fusing of rescale is done.
auto *input = mod_.createPlaceholder(ElemKind::Int8QTy, {1, 10, 20, 3}, 0.5,
10, "input", true);
auto *filter = mod_.createPlaceholder(ElemKind::Int8QTy, {16, 5, 5, 3}, 0.5,
10, "filter", true);
auto *bias =
mod_.createPlaceholder(ElemKind::Int8QTy, {16}, 0.5, 10, "bias", true);
auto *rInput = F_->createRescaleQuantized(
"rescale", input,
mod_.uniqueType(ElemKind::Int8QTy, {1, 10, 20, 3}, 0.1, -25));
auto *rFilter = F_->createRescaleQuantized(
"rescale", filter,
mod_.uniqueType(ElemKind::Int8QTy, {16, 5, 5, 3}, 0.2, 0));
auto *rBias = F_->createRescaleQuantized(
"rescale", bias, mod_.uniqueType(ElemKind::Int8QTy, {16}, 0.3, 25));
auto *CV = F_->createConv(
"conv", rInput, rFilter, rBias,
mod_.uniqueType(ElemKind::Int8QTy, {1, 10, 20, 16}, 0.7, -3), 5, 1, 2, 1);
auto *rCV = F_->createRescaleQuantized(
"rescale", CV,
mod_.uniqueType(ElemKind::Int8QTy, {1, 10, 20, 16}, 0.4, 37));
F_->createSave("save", rCV);
// All rescales must be fused into convolution.
EXPECT_EQ(F_->getNodes().size(), 6);
::glow::optimize(F_, CompilationMode::Infer);
EXPECT_EQ(F_->getNodes().size(), 2);
}
/// This test ensures that if there is a RescaleNode whose input has multiple
/// users that the input is not cloned, as this duplicates the node.
TEST_F(GraphOptz, MultipleUsersRescaleCombineNoOpt) {
auto opOutTy = mod_.uniqueType(ElemKind::Int8QTy, {10}, 1, 0);
auto rescaleOutTy = mod_.uniqueType(ElemKind::Int8QTy, {10}, 2, 1);
Node *LHS =
mod_.createPlaceholder(ElemKind::Int8QTy, {10}, 0.4, 0, "LHS", true);
Node *RHS =
mod_.createPlaceholder(ElemKind::Int8QTy, {10}, 0.3, 0, "RHS", true);
AddNode *AN = F_->createAdd("qAdd", opOutTy, LHS, RHS);
RescaleQuantizedNode *RQN =
F_->createRescaleQuantized("rsAdd", AN, rescaleOutTy);
SaveNode *saveRQN = F_->createSave("saveRQN", RQN);
SaveNode *saveAN = F_->createSave("saveAN", AN);
EXPECT_EQ(F_->getNodes().size(), 4);
::glow::optimize(F_, CompilationMode::Infer);
// The graph should be unchanged.
EXPECT_EQ(F_->getNodes().size(), 4);
EXPECT_EQ(saveRQN->getInput().getNode(), RQN);
EXPECT_EQ(RQN->getInput().getNode(), AN);
EXPECT_EQ(saveAN->getInput().getNode(), AN);
EXPECT_EQ(AN->getLHS().getNode(), LHS);
EXPECT_EQ(AN->getRHS().getNode(), RHS);
}
/// This test ensures that fusing of rescale into MatMul is done.
TEST_F(GraphOptz, FuseRescaleIntoMatMul) {
auto opOutTy = mod_.uniqueType(ElemKind::Int8QTy, {10}, 1, 0);
auto rescaleOutTy = mod_.uniqueType(ElemKind::Int8QTy, {10}, 2, 1);
Placeholder *LHS =
mod_.createPlaceholder(ElemKind::Int8QTy, {10}, 0.4, 0, "LHS", true);
Placeholder *RHS =
mod_.createPlaceholder(ElemKind::Int8QTy, {10}, 0.3, 0, "RHS", true);
RescaleQuantizedNode *LHSR =
F_->createRescaleQuantized("rs1", LHS, rescaleOutTy);
RescaleQuantizedNode *RHSR =
F_->createRescaleQuantized("rs2", RHS, rescaleOutTy);
MatMulNode *MN = F_->createMatMul("qMatMul", opOutTy, LHSR, RHSR);
SaveNode *SN = F_->createSave("save", MN);
// All rescales must be fused into arithmetic operations above.
::glow::optimize(F_, CompilationMode::Infer);
// Only the MatMul and Save should be left.
EXPECT_EQ(F_->getNodes().size(), 2);
EXPECT_EQ(countNodeKind(F_, Kinded::Kind::RescaleQuantizedNodeKind), 0);
MatMulNode *newMN = llvm::dyn_cast<MatMulNode>(SN->getInput());
ASSERT_TRUE(newMN);
Placeholder *LPH = llvm::dyn_cast<Placeholder>(newMN->getLHS());
EXPECT_EQ(LPH, LHS);
Placeholder *RPH = llvm::dyn_cast<Placeholder>(newMN->getRHS());
EXPECT_EQ(RPH, RHS);
}
TEST_F(GraphOptz, sinkRescaledQuantizedNode) {
// Check that we eliminate rescale nodes by sinking them into other operators.
auto *input = mod_.createPlaceholder(ElemKind::Int8QTy, {4, 10}, 0.5, 11,
"input", true);
// slice -> rescale -> reshape -> rescale -> transpose -> maxpool -> save.
auto *slice = F_->createSlice("slice", input, {0, 0}, {3, 3});
auto *rescale = F_->createRescaleQuantized(
"rescale", slice, mod_.uniqueType(ElemKind::Int8QTy, {3, 3}, 0.4, 10));
auto *reshape = F_->createReshape("reshape", rescale, {1, 1, 3, 3});
auto *rescale2 = F_->createRescaleQuantized(
"rescale", reshape,
mod_.uniqueType(ElemKind::Int8QTy, {1, 1, 3, 3}, 0.3, 9));
auto *transpose = F_->createTranspose("transpose", rescale2, {0, 2, 3, 1});
auto *maxpool =
F_->createMaxPool("maxpool", transpose, {3, 3}, {1, 1}, {0, 0, 0, 0});
auto *save = F_->createSave("ret", maxpool);
EXPECT_EQ(F_->getNodes().size(), 7);
::glow::optimize(F_, CompilationMode::Infer);
EXPECT_EQ(F_->getNodes().size(), 6);
// Check that rescale sank all the way down to the save node.
EXPECT_TRUE(llvm::dyn_cast<RescaleQuantizedNode>(save->getInput()));
}
TEST_F(GraphOptz, mergeRescaleWithArithmeticNode) {
// Check that Arithmetic operations can be merged with the Rescale.
auto *input = mod_.createPlaceholder(ElemKind::Int8QTy, {4, 10}, 0.5, 11,
"input", true);
auto *rescale1 = F_->createRescaleQuantized(
"rescale", input, mod_.uniqueType(ElemKind::Int8QTy, {4, 10}, 0.4, 11));
auto *add = F_->createAdd("add", rescale1, rescale1);
auto *rescale2 = F_->createRescaleQuantized(
"rescale", add, mod_.uniqueType(ElemKind::Int8QTy, {4, 10}, 0.3, 11));
auto *sub = F_->createSub("sub", rescale2, rescale2);
auto *rescale3 = F_->createRescaleQuantized(
"rescale", sub, mod_.uniqueType(ElemKind::Int8QTy, {4, 10}, 0.2, 11));
auto *mul = F_->createMul("mul", rescale3, rescale3);
auto *rescale4 = F_->createRescaleQuantized(
"rescale", mul, mod_.uniqueType(ElemKind::Int8QTy, {4, 10}, 0.1, 11));
auto *div = F_->createDiv("div", rescale4, rescale4);
F_->createSave("save", div);
EXPECT_EQ(F_->getNodes().size(), 9);
::glow::optimize(F_, CompilationMode::Infer);
EXPECT_EQ(F_->getNodes().size(), 5);
}
/// Check that Relu can be merged with Rescale.
TEST_F(GraphOptz, mergeRescaleWithRelu) {
auto *input = mod_.createPlaceholder(ElemKind::Int8QTy, {4, 10}, 0.5, 11,
"input", false);
auto *rescale1 = F_->createRescaleQuantized(
"rescale", input, mod_.uniqueType(ElemKind::Int8QTy, {4, 10}, 0.4, 11));
auto *relu = F_->createRELU("relu", rescale1);
F_->createSave("save", relu);
// Rescale, RELU, Save nodes.
EXPECT_EQ(F_->getNodes().size(), 3);
::glow::optimize(F_, CompilationMode::Infer);
// RELU, Save nodes left; Rescale merged into RELU.
EXPECT_EQ(F_->getNodes().size(), 2);
EXPECT_EQ(countNodeKind(F_, Kinded::Kind::RescaleQuantizedNodeKind), 0);
EXPECT_EQ(countNodeKind(F_, Kinded::Kind::ReluNodeKind), 1);
}
// Check that we are able to merge some small matmuls into a larger one.
TEST_F(GraphOptz, mergeMatMulNodes) {
Node *input =
mod_.createPlaceholder(ElemKind::FloatTy, {10, 10, 10}, "input", true);
Node *weight =
mod_.createPlaceholder(ElemKind::FloatTy, {10, 10}, "weight", true);
// Split the input to a bunch of small slices.
std::vector<NodeValue> inputs;
for (size_t i = 0; i < 10; i++) {
auto *K = F_->createSlice("extract", input, {i, 0, 0}, {i + 1, 10, 10});
auto *R = F_->createReshape("reshape", K, {10, 10});
auto *MM = F_->createMatMul("mm", R, weight);
inputs.push_back(MM);
}
auto *cc = F_->createConcat("merge", inputs, 0);
F_->createSave("save", cc);
EXPECT_EQ(countNodeKind(F_, Kinded::Kind::MatMulNodeKind), 10);
::glow::optimize(F_, CompilationMode::Infer);
// Check that all of the matmuls are merged into a single matmul node.
EXPECT_EQ(countNodeKind(F_, Kinded::Kind::MatMulNodeKind), 1);
}
// Check that we are able to merge batched adds.
TEST_F(GraphOptz, mergeBANodes) {
Node *input =
mod_.createPlaceholder(ElemKind::FloatTy, {10, 10, 10}, "input", true);
Node *slice =
mod_.createPlaceholder(ElemKind::FloatTy, {10, 10}, "weight", true);
// Split the input to a bunch of small slices.
std::vector<NodeValue> inputs;
for (size_t i = 0; i < 10; i++) {
auto *K = F_->createSlice("extract", input, {i, 0, 0}, {i + 1, 10, 10});
auto *MM = F_->createBatchedAdd("BA", K, slice);
inputs.push_back(MM);
}
auto *cc = F_->createConcat("merge", inputs, 0);
F_->createSave("save", cc);
EXPECT_EQ(countNodeKind(F_, Kinded::Kind::BatchedAddNodeKind), 10);
::glow::optimize(F_, CompilationMode::Infer);
// Check that all of the batched-adds are merged into a single node.
EXPECT_EQ(countNodeKind(F_, Kinded::Kind::BatchedAddNodeKind), 1);
}
// Check that we are able to eliminate concat nodes.
TEST_F(GraphOptz, concatElim) {
Node *input =
mod_.createPlaceholder(ElemKind::FloatTy, {10, 10, 10}, "input", true);
// Split the input to a bunch of small slices.
std::vector<NodeValue> inputs;
for (size_t i = 0; i < 10; i++) {
auto *K = F_->createSlice("extract", input, {i, 0, 0}, {i + 1, 10, 10});
// Insert the nodes in reverse order to make sure that we can catch
// non-consecutive graph-order slices.
inputs.insert(inputs.begin(), K);
}
auto *cc = F_->createConcat("merge", inputs, 0);
F_->createSave("save", cc);
EXPECT_EQ(countNodeKind(F_, Kinded::Kind::SliceNodeKind), 10);
::glow::optimize(F_, CompilationMode::Infer);
// Check that the concat node is gone.
EXPECT_EQ(countNodeKind(F_, Kinded::Kind::ConcatNodeKind), 0);
}
// Check the transformation Concat(Reshape(x) * N) -> Reshape(Concat(x * N)).
TEST_F(GraphOptz, concatReshapes) {
const size_t shape1[] = {2, 5, 2, 1, 20};
const size_t shape2[] = {10, 2, 2, 10};
const size_t shape3[] = {5, 80};
llvm::SmallVector<NodeValue, 10> inputs1;
llvm::SmallVector<NodeValue, 10> inputs2;
for (size_t i = 0; i < 10; i++) {
// 10 reshape nodes that transform from {2,5,2,1,20} to {10,2,2,10}.
// And a ConcatNode concatenates the outputs of reshape at 2nd dim.
// The optimization would kick in, as the size of trailing dimensions of
// original ConcatNode (before opt) is 20, and the size of leading
// dimensions of original ConcatNode (before opt) is 10.
Node *var = F_->getParent()->createPlaceholder(
ElemKind::FloatTy, shape1, "input" + std::to_string(i), true);
auto *RN = F_->createReshape("reshape" + std::to_string(i), var, shape2);
inputs1.push_back(RN);
}
auto *concatNode1 = F_->createConcat("concat", inputs1, 1);
for (size_t i = 0; i < 10; i++) {
// 10 reshape nodes that transform from {5,80} to {10,1,2,10}.
// And a ConcatNode concatenates the outputs of reshape at 2nd dim.
// The optimization would NOT kick in, as we cannot find the dim that
// makes the leading/trailing dims same as in the case of the original
// concat node.
Node *var = F_->getParent()->createPlaceholder(
ElemKind::FloatTy, shape3, "input" + std::to_string(i), true);
auto *RN = F_->createReshape("reshape" + std::to_string(i), var, shape2);
inputs2.push_back(RN);
}
auto *concatNode2 = F_->createConcat("concat", inputs2, 1);
auto outputShape = concatNode1->getResult().dims();
// Need to dereference the RN vectors, otherwise the user number of those
// nodes would always be positive, making them unable to be removed by DCE.
inputs1.clear();
inputs2.clear();
auto *addNode = F_->createAdd("add", concatNode1, concatNode2);
auto *O = F_->createSave("ret", addNode);
EXPECT_EQ(F_->getNodes().size(), 24);
::glow::optimize(F_, CompilationMode::Infer);
// After optimization, we expect to see only 15 nodes. All 10 of the reshapes
// that were the inputs to the first original concat node (concatNode1) are
// removed, and a single new reshape is added after the new concat.
EXPECT_EQ(F_->getNodes().size(), 15);
// concatNode1 should not exist any more.
EXPECT_TRUE(std::find_if(F_->getNodes().begin(), F_->getNodes().end(),
IsSameNodeAddress(concatNode1)) ==
F_->getNodes().end());
// concatNode2 should still exist.
EXPECT_TRUE(std::find_if(F_->getNodes().begin(), F_->getNodes().end(),
IsSameNodeAddress(concatNode2)) !=
F_->getNodes().end());
// The first input of addNode should be a Reshape node now, with the same
// result shape of concatNode1.
auto *newAddNode = llvm::dyn_cast<AddNode>(O->getInput());
ASSERT_TRUE(newAddNode);
auto *newRN = llvm::dyn_cast<ReshapeNode>(newAddNode->getLHS());
ASSERT_TRUE(newRN);
EXPECT_TRUE(newRN->getResult().getType()->dims().equals(outputShape));
// The input of newRN should be a ConcatNode now.
auto *newCN = llvm::dyn_cast<ConcatNode>(newRN->getInput());
ASSERT_TRUE(newCN);
}
/// Check that Variable CSE works correctly, combining small Variables that have
/// the same data.
TEST_F(GraphOptz, VarsCSE) {
// Create three variables that are Private, are not trainable, and have no
// writers. The first two variables have the same data, and so should be
// combined via variable CSE. The third variable differs by the last value,
// and so should not be combined.
auto *input1 = mod_.createConstant(ElemKind::FloatTy, {10}, "input1");
auto *input2 = mod_.createConstant(ElemKind::FloatTy, {10}, "input2");
auto *input3 = mod_.createConstant(ElemKind::FloatTy, {10}, "input3");
input1->getHandle() = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
input2->getHandle() = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
input3->getHandle() = {0, 1, 2, 3, 4, 5, 6, 7, 8, -1};
// Input them each to different nodes, so node CSE does not change them.
auto *TN = F_->createTanh("tanh", input1);
auto *SN = F_->createSigmoid("sigmoid", input2);
auto *RN = F_->createRELU("relu", input3);
auto *CN = F_->createConcat("concat", {TN, SN, RN}, /* axis */ 0);
F_->createSave("ret", CN);
// Initially there are three variables: inputs 1, 2, and 3 (the save uses a
// placeholder).
EXPECT_EQ(mod_.getConstants().size(), 3);
::glow::optimize(F_, CompilationMode::Infer);
// Now only two variables are left; input1 and input2 have been combined,
// but input3 has not.
EXPECT_EQ(mod_.getConstants().size(), 2);
// Verify that only one of input1 and input2 exists, and that input3 still
// exists.
Constant *varOneOrTwo = nullptr;
bool foundVarThree = false;
for (auto *V : mod_.getConstants()) {
if (V == input1 || V == input2) {
EXPECT_TRUE(varOneOrTwo == nullptr);
varOneOrTwo = V;
} else if (V == input3) {
foundVarThree = true;
}
}
EXPECT_TRUE(varOneOrTwo != nullptr);
EXPECT_TRUE(foundVarThree);
// Verify that the users of the inputs are updated correctly.
EXPECT_TRUE(TN->getInput().getNode() == varOneOrTwo);
EXPECT_TRUE(SN->getInput().getNode() == varOneOrTwo);
EXPECT_TRUE(RN->getInput().getNode() == input3);
// Verify that whichever input1/input2 is left over has two users TN and SN.
EXPECT_TRUE(varOneOrTwo->getUsers().size() == 2);
for (auto &U : varOneOrTwo->getUsers()) {
auto *N = U.getUser();
EXPECT_TRUE(N == TN || N == SN);
}
// Verify that input3 only has a single user RN.
ASSERT_TRUE(input3->getUsers().size() == 1);
EXPECT_TRUE(input3->getUsers().begin()->getUser() == RN);
}
// Verify that constant input canonicalization works correctly when the
// arithmetic nodes have multiple users.
TEST_F(GraphOptz, simplifyArithmeticMultipleUsers) {
Node *I1 =
mod_.createPlaceholder(ElemKind::FloatTy, {10, 10, 10}, "input1", false);
Type t(ElemKind::FloatTy, {10, 10, 10});
Node *SN = F_->createSplat("one", &t, 1.0);
// The splat is a constant input to add1 and add2, and is their LHS input. We
// expect canonicalization to occur during optimization, moving the splat
// to the RHS for both. Note that add1 has multiple users: add2 and save1.
Node *AN1 = F_->createAdd("add1", SN, I1);
Node *AN2 = F_->createAdd("add2", SN, AN1);
SaveNode *SN1 = F_->createSave("save1", AN1);
SaveNode *SN2 = F_->createSave("save2", AN2);
// Five nodes in total: one splat, two adds, and two saves.
EXPECT_EQ(F_->getNodes().size(), 5);
EXPECT_EQ(countNodeKind(F_, Kinded::Kind::SplatNodeKind), 1);
EXPECT_EQ(countNodeKind(F_, Kinded::Kind::AddNodeKind), 2);
EXPECT_EQ(countNodeKind(F_, Kinded::Kind::SaveNodeKind), 2);
// input1 has a single user before optimization.
EXPECT_EQ(I1->getUsers().size(), 1);
// Simplify nodes will canonicalize add1 and add2, and should replace all
// their users, without otherwise adding new nodes to the graph/changing the
// overall structure.
::glow::optimize(F_, CompilationMode::Infer);
// We should have the same five nodes: one splat, two adds, and two saves.
EXPECT_EQ(F_->getNodes().size(), 5);
EXPECT_EQ(countNodeKind(F_, Kinded::Kind::SplatNodeKind), 1);
EXPECT_EQ(countNodeKind(F_, Kinded::Kind::AddNodeKind), 2);
EXPECT_EQ(countNodeKind(F_, Kinded::Kind::SaveNodeKind), 2);
// Verify that both add nodes were canonicalized, and that the graph's shape
// is the same as prior to optimization other than canonicalization.
AddNode *newAN1 = llvm::dyn_cast<AddNode>(SN1->getInput().getNode());
ASSERT_TRUE(newAN1 != nullptr);
EXPECT_TRUE(llvm::isa<Placeholder>(newAN1->getLHS()));
EXPECT_TRUE(llvm::isa<SplatNode>(newAN1->getRHS()));
AddNode *newAN2 = llvm::dyn_cast<AddNode>(SN2->getInput().getNode());
ASSERT_TRUE(newAN2 != nullptr);
EXPECT_TRUE(llvm::isa<AddNode>(newAN2->getLHS()));
EXPECT_TRUE(llvm::isa<SplatNode>(newAN2->getRHS()));
EXPECT_EQ(newAN1, newAN2->getLHS());
// input1 should still have a single user after optimization.
EXPECT_EQ(I1->getUsers().size(), 1);
}
/// Test that a concat with a single input is replaced by the input.
TEST_F(GraphOptz, eliminateSingleConcat) {
Node *input = mod_.createPlaceholder(ElemKind::FloatTy, {10}, "input", false);
ConcatNode *CN = F_->createConcat("concat1", {input}, 0);
SaveNode *SN = F_->createSave("ret", CN);
// The ConcatNode and SaveNode.
EXPECT_EQ(F_->getNodes().size(), 2);
::glow::optimize(F_, CompilationMode::Infer);
// Just the SaveNode should be left.
EXPECT_EQ(F_->getNodes().size(), 1);
ASSERT_TRUE(std::find_if(F_->getNodes().begin(), F_->getNodes().end(),
IsSameNodeAddress(SN)) != F_->getNodes().end());
// Save node should just save the input.
EXPECT_TRUE(SN->getInput().getNode() == input);
}
/// Test that a reshape of a private variable with one use has the reshape
/// merged into the variable.
TEST_F(GraphOptz, ReshapePrivateVarOneUse) {
const size_t shape[] = {10, 20};
const size_t reshape1[] = {200, 1};
const size_t reshape2[] = {200};
auto *input = F_->getParent()->createPlaceholder(ElemKind::FloatTy, shape,
"input", true);
ctx_.allocate(input);
auto *R1 = F_->createReshape("reshape1", input, reshape1);
auto *R2 = F_->createReshape("reshape2", R1, reshape2);
auto *O = F_->createSave("ret", R2);
// Before optimization, we have 2 Reshapes and a Save.
EXPECT_EQ(F_->getNodes().size(), 3);
::glow::convertPlaceholdersToConstants(F_, ctx_, {});
::glow::optimize(F_, CompilationMode::Infer);
// After optimization, we expect to see just a Save.
EXPECT_EQ(F_->getNodes().size(), 1);
// Save should have the new Variable as input.
auto *V = llvm::dyn_cast<Constant>(O->getInput());
ASSERT_TRUE(V);
// The new Variable should have the same shape as the original second Reshape.
EXPECT_TRUE(V->getType()->dims().equals(reshape2));
}
/// Test that transpose is merged into matmul.
TEST_F(GraphOptz, mergeTransposeIntoMatMul) {
auto *input =
mod_.createPlaceholder(ElemKind::FloatTy, {1, 1, 2, 3}, "input", false);
auto *weights =
F_->getParent()->createConstant(ElemKind::FloatTy, {6, 1}, "weights");
weights->getHandle() = {0, 1, 2, 3, 4, 5};
float newWeightsRef[] = {0, 2, 4, 1, 3, 5};
auto *TN = F_->createTranspose("transpose", input, NHWC2NCHW);
auto *RN = F_->createReshape("reshape", TN, {1, 6});
auto *MMN = F_->createMatMul("matmul", RN, weights);
auto *SN = F_->createSave("ret", MMN);
// Transpose + Reshape + MatMul + Save.
EXPECT_EQ(F_->getNodes().size(), 4);
::glow::optimize(F_, CompilationMode::Infer);
// Reshape + MatMul + Save.
EXPECT_EQ(F_->getNodes().size(), 3);
// Check reordered weights.
auto *newMMN = llvm::dyn_cast<MatMulNode>(SN->getInput());
ASSERT_TRUE(newMMN != nullptr);
auto *newW = llvm::dyn_cast<Constant>(newMMN->getRHS());
ASSERT_TRUE(newW != nullptr);
for (unsigned i = 0; i < 6; ++i) {
EXPECT_EQ(newWeightsRef[i], newW->getHandle().raw(i));
}
}
TEST_F(GraphOptz, ConvertPlaceholdersToConstants) {
auto *input1 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "input1", true);
auto *input2 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "input2", true);
auto *input3 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "input3", true);
auto *save1 = F_->createSave("save1", input1);
auto *save2 = F_->createSave("save2", input2);
auto *save3 = F_->createSave("save3", input3);
// No variables, six PHs (3 inputs, 3 saves).
EXPECT_EQ(mod_.getConstants().size(), 0);
EXPECT_EQ(mod_.getPlaceholders().size(), 6);
// Allocate two of the three inputs, but mark input2 of them as non-constant.
ctx_.allocate(input1);
ctx_.allocate(input2);
// Don't allocate input3; keep it as a placeholder instead.
::glow::convertPlaceholdersToConstants(F_, ctx_, {input2});
// input1 becomes a variable.
EXPECT_EQ(mod_.getConstants().size(), 1);
EXPECT_EQ(mod_.getPlaceholders().size(), 6);
EXPECT_TRUE(llvm::isa<Constant>(save1->getInput()));
EXPECT_TRUE(llvm::isa<Placeholder>(save2->getInput()));
EXPECT_TRUE(llvm::isa<Placeholder>(save3->getInput()));
}
TEST_F(GraphOptz, optimizeSameTypeConversions) {
auto *input1 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "input1", true);
auto *input2 = mod_.createPlaceholder(ElemKind::FloatTy, {1}, "input2", true);
auto *conv1 = F_->createConvertTo("cast1", input1, input1->getType());
auto *conv2 = F_->createConvertTo(
"cast2", input2, mod_.uniqueType(ElemKind::Float16Ty, input2->dims()));
auto *save1 = F_->createSave("save1", conv1);
auto *save2 = F_->createSave("save1", conv2);
// convert_to1 + save1 + convert_to2 + save2 nodes.
EXPECT_EQ(F_->getNodes().size(), 4);
EXPECT_TRUE(llvm::isa<ConvertToNode>(save1->getInput()));
::glow::optimize(F_, CompilationMode::Infer);
// save1 + convert_to2 + save2 nodes.
EXPECT_EQ(F_->getNodes().size(), 3);
// convert_to1 node should be eliminated, because it converts the node into
// the same type.
EXPECT_TRUE(llvm::isa<Placeholder>(save1->getInput()));
// convert_to1 node should not be eliminated, because it converts the node
// into a different type.
EXPECT_TRUE(llvm::isa<ConvertToNode>(save2->getInput()));
EXPECT_EQ(save2->getInput(), NodeValue(conv2));
}
TEST_F(GraphOptz, dceBeforeOptimizeTranpose) {
auto *input1 = mod_.createConstant(ElemKind::FloatTy, {5, 10}, "input1");
// Create an unused node.
F_->createAdd("add", input1, input1);
auto *transposedInput1 = F_->createTranspose("transpose", input1, {1, 0});
auto *save1 = F_->createSave("save1", transposedInput1);
// add + transpose + save.
EXPECT_EQ(F_->getNodes().size(), 3);
::glow::optimize(F_, CompilationMode::Infer);
// A single node: save.
EXPECT_EQ(F_->getNodes().size(), 1);
// transpose should be eliminated and replaced by the transposed constant.
EXPECT_TRUE(llvm::isa<Constant>(save1->getInput()));
}
/// Test that Transpose is sunk below ChannelShuffle and cancels with an inverse
/// transpose below the ChannelShuffle. This test is models a pattern that has
/// has been observed in shufflenet during graph optimization.
TEST_F(GraphOptz, sinkTransposeBelowChannelShuffleNodesAndEliminate) {
const size_t inputDims[] = {3, 28, 28, 136};
Node *K =
mod_.createPlaceholder(ElemKind::FloatTy, inputDims, "input", false);
K = F_->createTranspose("unnecessary_transpose_1", K, {0, 3, 1, 2});
K = F_->createChannelShuffle("channel_shuffle", K, 4, 1);
K = F_->createTranspose("unnecessary_transpose_2", K, {0, 2, 3, 1});
auto *save = F_->createSave("ret", K);
EXPECT_EQ(F_->getNodes().size(), 6);
// Optimize away the unnecessary transposes.
optimize(F_, CompilationMode::Infer);
// Ensure the two unnecessary transposes are gone.
ASSERT_EQ(F_->getNodes().size(), 4);
// Check that the channel shuffle nodes are still there.
auto *postShuffleRN = llvm::dyn_cast<ReshapeNode>(save->getInput().getNode());
ASSERT_NE(nullptr, postShuffleRN);
auto *shuffleTR =
llvm::dyn_cast<TransposeNode>(postShuffleRN->getInput().getNode());
ASSERT_NE(nullptr, shuffleTR);
auto *preShuffleRN =
llvm::dyn_cast<ReshapeNode>(shuffleTR->getInput().getNode());
ASSERT_NE(nullptr, preShuffleRN);
// Ensure last reshape has the same dimensions as the input.
EXPECT_EQ(postShuffleRN->getDims(), llvm::makeArrayRef(inputDims));
// Ensure the transpose in the middle of the reshapes shuffles the last
// dimension of the input.
const unsigned_t expectedShuffleTRShuffle[] = {0, 1, 2, 4, 3};
EXPECT_EQ(shuffleTR->getShuffle(),
llvm::makeArrayRef(expectedShuffleTRShuffle));
// Ensure the first reshape expands the last dimension of the input.
const size_t expectedPreShuffleRNDims[] = {3, 28, 28, 4, 34};
EXPECT_EQ(preShuffleRN->getDims(),
llvm::makeArrayRef(expectedPreShuffleRNDims));
}
|
#include "drawboard.h"
#include "configuration.h"
#include "tetrisboard.h"
#include "game/player.h"
#include <sdl/graphic.h>
#include <sdl/imguiauxiliary.h>
#include <spdlog/spdlog.h>
#include <vector>
namespace mwetris::graphic {
namespace {
Vec2 calculateCenterOfMass(const tetris::Block& block) {
Vec2 pos{};
for (const auto& sq : block) {
pos += Vec2{sq.column, sq.row};
}
return 1.f / block.getSize() * pos;
}
void addRectangle(sdl::Graphic& graphic, float x, float y, float w, float h, Color color) {
graphic.addRectangle({x, y}, {w, h}, color);
}
void addSquare(sdl::Graphic& graphic, float x, float y, float size, Color color) {
graphic.addRectangle({x, y}, {size, size}, color);
}
void addSquare(sdl::Graphic& graphic, float x, float y, float size, const sdl::TextureView& sprite, Color color = color::White) {
graphic.addRectangleImage({x, y}, {size, size}, sprite, color);
}
void addText(sdl::Graphic& graphic, float x, float y, const sdl::Sprite& text) {
auto view = text.getTextureView();
graphic.addRectangleImage(Vec2{x, y} + view.getPosition(), 0.5f * text.getSize(), view);
}
constexpr float middleDistance = 5.f;
constexpr float rightDistance = 5.f;
}
DrawBoard::DrawBoard(game::Player& player)
: tetrisBoard_{player.getTetrisBoard()}
, tmp_{tetrisBoard_} {
spriteZ_ = Configuration::getInstance().getSprite(tetris::BlockType::Z);
spriteS_ = Configuration::getInstance().getSprite(tetris::BlockType::S);
spriteJ_ = Configuration::getInstance().getSprite(tetris::BlockType::J);
spriteI_ = Configuration::getInstance().getSprite(tetris::BlockType::I);
spriteL_ = Configuration::getInstance().getSprite(tetris::BlockType::L);
spriteT_ = Configuration::getInstance().getSprite(tetris::BlockType::T);
spriteO_ = Configuration::getInstance().getSprite(tetris::BlockType::O);
squareSize_ = Configuration::getInstance().getTetrisSquareSize();
borderSize_ = Configuration::getInstance().getTetrisBorderSize();
infoSize_ = squareSize_ * 5.f;
name_ = sdl::Sprite{"Test", Configuration::getInstance().getDefaultFont(50)};
name_.bindTexture();
width_ = squareSize_ * tetrisBoard_.getColumns() + infoSize_ + borderSize_ * 2 + middleDistance + rightDistance;
height_ = squareSize_ * (tetrisBoard_.getRows() - 2) + borderSize_ * 2;
}
Vec2 DrawBoard::getSize() const {
return {width_, height_};
}
void DrawBoard::drawBlock(sdl::Graphic& graphic, const tetris::Block& block, Vec2 pos, bool center, Color color) {
Vec2 delta{};
if (center) {
delta = (-Vec2{0.5f, 0.5f} - calculateCenterOfMass(block)) * squareSize_;
}
for (const auto& sq : block) {
const int columns = tetrisBoard_.getColumns();
auto x = pos.x + borderSize_ + squareSize_ * sq.column + delta.x;
auto y = pos.y + borderSize_ + squareSize_ * sq.row + delta.y;
if (sq.row < tetrisBoard_.getRows() - 2) {
addSquare(graphic,
x, y,
squareSize_,
getSprite(block.getBlockType()),
color);
}
}
}
void DrawBoard::draw(sdl::Graphic& graphic) {
const int columns = tetrisBoard_.getColumns();
const int rows = tetrisBoard_.getRows();
const float boardWidth = squareSize_ * columns;
//restart(player); // Must be called after variables are defined.
// Draw the player area.
float x = borderSize_;
float y = borderSize_;
addRectangle(graphic,
x, y,
boardWidth + infoSize_ + middleDistance + rightDistance, squareSize_ * (rows - 2),
Configuration::getInstance().getPlayerAreaColor());
// Draw the outer square.
x = borderSize_;
y = borderSize_;
addRectangle(graphic,
x, y,
squareSize_ * columns, squareSize_ * (rows - 2),
Configuration::getInstance().getOuterSquareColor());
// Draw the inner squares.
for (int row = 0; row < rows - 2; ++row) {
for (int column = 0; column < columns; ++column) {
x = borderSize_ + squareSize_ * column + squareSize_ * 0.1f;
y = borderSize_ + squareSize_ * row + squareSize_ * 0.1f;
addRectangle(graphic,
x, y,
squareSize_ * 0.8f, squareSize_ * 0.8f,
Configuration::getInstance().getInnerSquareColor());
}
}
// Draw the block start area.
x = borderSize_;
y = borderSize_ + squareSize_ * (rows - 4);
addRectangle(graphic,
x, y,
squareSize_ * columns, squareSize_ * 2,
Configuration::getInstance().getStartAreaColor());
// Draw the preview block area.
x = borderSize_ + boardWidth + middleDistance;
y = borderSize_ + squareSize_ * (rows - 4) - (squareSize_ * 5 + middleDistance);
addSquare(graphic,
x, y,
infoSize_,
Configuration::getInstance().getStartAreaColor());
drawBlock(graphic, tetris::Block{tetrisBoard_.getNextBlockType(), 0, 0}, Vec2{x, y} + squareSize_ * 2.5f, true);
const auto borderColor = Configuration::getInstance().getBorderColor();
// Add border.
// Left-up corner.
x = 0.f;
y = height_ - borderSize_;
addSquare(graphic,
x, y,
borderSize_,
borderColor);
// Right-up corner.
x = width_ - borderSize_;
y = height_ - borderSize_;
addSquare(graphic,
x, y,
borderSize_,
borderColor);
// Left-down corner.
x = 0.f;
y = 0.f;
addSquare(graphic,
x, y,
borderSize_,
borderColor);
// Right-down corner.
x = width_ - borderSize_;
y = 0.f;
addSquare(graphic,
x, y,
borderSize_,
borderColor);
// Up.
x = borderSize_;
y = height_ - borderSize_;
addRectangle(graphic,
x, y,
width_ - 2 * borderSize_, borderSize_,
borderColor);
// Down.
x = borderSize_;
y = 0.f;
addRectangle(graphic,
x, y,
width_ - 2 * borderSize_, borderSize_,
borderColor);
// Left.
x = 0.f;
y = borderSize_;
addRectangle(graphic,
x, y,
borderSize_, height_ - 2 * borderSize_,
borderColor);
// Right.
x = width_ - borderSize_;
y = borderSize_;
addRectangle(graphic,
x, y,
borderSize_, height_ - 2 * borderSize_,
borderColor);
tmp_ = tetrisBoard_;
tmp_.update(tetris::Move::DownGround);
drawBlock(graphic, tmp_.getBlock(), {}, false, Color(1.f, 1.f, 1, 0.3f));
drawBlock(graphic, tetrisBoard_.getBlock());
for (int i = 0; i < tetrisBoard_.getRows() - 2; ++i) {
for (int j = 0; j < tetrisBoard_.getColumns(); ++j) {
x = borderSize_ + squareSize_ * j;
y = borderSize_ + squareSize_ * i;
auto blockType = tetrisBoard_.getBlockType(j, i);
if (blockType != tetris::BlockType::Empty
&& blockType != tetris::BlockType::Wall) {
addSquare(graphic,
x, y,
squareSize_,
getSprite(blockType));
}
}
}
addText(graphic, 100, 100, name_);
}
void DrawBoard::callback(tetris::BoardEvent gameEvent, const tetris::TetrisBoard& tetrisBoard) {
/*
for (auto& row : rows_) {
row->handleEvent(gameEvent, tetrisBoard);
}
rows_.remove_if([&](const DrawRowPtr& row) {
if (!row->isAlive()) {
freeRows_.push_front(row);
return true;
}
return false;
});
switch (gameEvent) {
case BoardEvent::GAME_OVER:
break;
case BoardEvent::BLOCK_COLLISION:
break;
case BoardEvent::RESTARTED:
break;
case BoardEvent::EXTERNAL_ROWS_ADDED:
{
int rows = tetrisBoard.getNbrExternalRowsAdded();
for (int row = 0; row < rows; ++row) {
addDrawRowBottom(tetrisBoard, rows - row - 1);
}
int highestRow = tetrisBoard.getBoardVector().size() / tetrisBoard.getColumns();
assert(rows_.size() - highestRow >= 0); // Something is wrong. Should not be posssible.
for (int i = 0; i < (int) rows_.size() - highestRow; ++i) { // Remove unneeded empty rows at the top.
rows_.pop_back();
}
}
break;
case BoardEvent::NEXT_BLOCK_UPDATED:
nextBlock_.update(Block(tetrisBoard.getNextBlockType(), 0, 0));
break;
case BoardEvent::CURRENT_BLOCK_UPDATED:
// Fall through!
case BoardEvent::PLAYER_MOVES_BLOCK_ROTATE:
// Fall through!
case BoardEvent::PLAYER_MOVES_BLOCK_LEFT:
// Fall through!
case BoardEvent::PLAYER_MOVES_BLOCK_RIGHT:
currentBlock_.update(tetrisBoard.getBlock());
{
TetrisBoard board = tetrisBoard;
board.update(Move::DOWN_GROUND);
downBlock_.update(board.getBlock());
}
break;
case BoardEvent::PLAYER_MOVES_BLOCK_DOWN_GROUND:
blockDownGround_ = true;
latestBlockDownGround_ = tetrisBoard.getBlock();
break;
case BoardEvent::PLAYER_MOVES_BLOCK_DOWN:
if (blockDownGround_) {
currentBlock_.updateDown(tetrisBoard.getBlock());
blockDownGround_ = false;
}
// Fall through!
case BoardEvent::GRAVITY_MOVES_BLOCK:
currentBlock_.update(tetrisBoard.getBlock());
break;
case BoardEvent::ROW_TO_BE_REMOVED:
textClearedRows_.update("Rows " + std::to_string(tetrisBoard.getRemovedRows()));
break;
case BoardEvent::ONE_ROW_REMOVED:
addDrawRowAtTheTop(tetrisBoard, 1);
break;
case BoardEvent::TWO_ROW_REMOVED:
addDrawRowAtTheTop(tetrisBoard, 2);
break;
case BoardEvent::THREE_ROW_REMOVED:
addDrawRowAtTheTop(tetrisBoard, 3);
break;
case BoardEvent::FOUR_ROW_REMOVED:
addDrawRowAtTheTop(tetrisBoard, 4);
break;
}
*/
}
sdl::TextureView DrawBoard::getSprite(tetris::BlockType blockType) const {
switch (blockType) {
case tetris::BlockType::I:
return spriteI_;
case tetris::BlockType::J:
return spriteJ_;
case tetris::BlockType::L:
return spriteL_;
case tetris::BlockType::O:
return spriteO_;
case tetris::BlockType::S:
return spriteS_;
case tetris::BlockType::T:
return spriteT_;
case tetris::BlockType::Z:
return spriteZ_;
}
return spriteI_;
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Network Embedded Systems - 2016/2017 (second semester)
// Interconnecting "mbeds" by a CAN
//
// Code for the MBED1 - Master
//
// Work done by:
// Joao Belfo - 78913
// Joao Girao - 78761
// Luis Rei - 78486
//
// Rev: 1.7 (26/05/2017)
//
////////////////////////////////////////////////////////////////////////////////
#include "stdio.h"
#include "mbed.h"
#include "CAN.h" //allows the sending/receiving of messages through a CAN bus
#include "C12832.h" //allows the use of LCD
#include "cstdlib"
#include "string"
#include "PinDetect.h"
#include "stdlib.h"
#include "PowerControl/PowerControl.h"
///////////////////////////////////////////////////////////////////////////////
// DECLARING GLOBAL VARIABLES //
///////////////////////////////////////////////////////////////////////////////
//Redefinition of LEDS
DigitalOut led1(LED1);
DigitalOut led2(LED2);
DigitalOut led3(LED3);
DigitalOut led4(LED4);
PinDetect OnOff( p7, PullUp ); //on/off switch
PinDetect alarm( p8, PullDown ); //opens menu
AnalogIn pot1(p19); //Potentiometers
AnalogIn pot2(p20);
//Definition of receiver and trasmitter pins
CAN can1(p30, p29);
CANMessage msg; //Defines buffer to handle communications
//Buttons for Joystick use (and hexadecimal code for reference)
BusIn joy(p15,p12,p13,p16); //up (0x1), left (0x4), down (0x2), right (0x8)
PinDetect fire(p14); //Middle click (0xf)
BusOut leds(LED1,LED2,LED3,LED4);
C12832 lcd(p5, p7, p6, p8, p11); //LCD manipulation
Timeout ticker; //Timed event
Timer temp1; //program runtime
Timer debounce1, debounce2, debounce3; //button debounce
char counter = 0; //Counter of messages sent
char select = '1'; //Predefined mode of functionality is mode 1
char shuttingDown = 0; //1 if it's the program is close to shutting down
char usedpass[5]; //Keeps the correct password for comparison
char pass[5]; //Keeps the password from the joystick
char c[7];
float period = 3.0; //periodicity of sensor information
//thresholds
float temp_threshold = 34;
float hum_threshold = 50;
float light_threshold = 500;
float threshold, hum_aux, temp_aux, light_aux;
float light_threshold2, hum_threshold2, temp_threshold2;
volatile int pressed_OnOff = 0, pressed_alarm = 0, pressed_fnc=0; //check if the button was pressed
int JoyIn; //Number of Joystick movements
bool on = false; //Defines system state
bool info = false, alarmed = false, menu, popmenu = false;
LocalFileSystem local("local"); // Create the local filesystem under the name "local"
FILE * fp; //file with the current password
///////////////////////////////////////////////////////////////////////////////
// DECLARING FUNCTIONS //
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// FUNCTION THAT //
// Sends message to a node informing he needs to start sending info //
///////////////////////////////////////////////////////////////////////////////
//Sends message to a node informing he needs to start sending info
void sendMode() {
sprintf(c, "%c", select);
if(can1.write(CANMessage(5, c, 1))){}
else{
lcd.cls();
lcd.locate(0,10); lcd.printf("Error sending message");
}
}
///////////////////////////////////////////////////////////////////////////////
// FUNCTION THAT PUTS EVERYONE TO SLEEP //
///////////////////////////////////////////////////////////////////////////////
void sleepAll(){
//Puts everyone to sleep
if(can1.write(CANMessage(0000, "1",1))){
}else{
lcd.cls();
lcd.locate(0,10); lcd.printf("Error sending message");
}
temp1.reset();
temp1.stop();
pressed_OnOff = 0;
pressed_alarm = 0;
pressed_fnc = 0;
lcd.cls(); lcd.locate(0,0); lcd.printf("A desligar...");
wait_us(2000000);
lcd.cls();
}
///////////////////////////////////////////////////////////////////////////////
// FUNCTION THAT Stores the password in memory //
///////////////////////////////////////////////////////////////////////////////
void savepass(){
fp = fopen("/local/pass.txt", "w"); // Write to "pass.txt"
fprintf(fp, "%s", pass);
fclose(fp);
}
///////////////////////////////////////////////////////////////////////////////
// FUNCTION THAT Reads password from local file //
///////////////////////////////////////////////////////////////////////////////
void readpass(){
fp = fopen("/local/pass.txt", "r"); // Read "pass.txt"
//if there's a file to read, read it and update 'usedpass' variable
if(fp){
fscanf(fp, "%s", usedpass);
fclose(fp);
//if there isn't, create a file and give 'usedpass' a default value
}else{
fp = fopen("/local/pass.txt", "w");
fprintf(fp, "uldr");
strcpy(usedpass, "uldr"); //default password
fclose(fp);
}
}
///////////////////////////////////////////////////////////////////////////////
// FUNCTION THAT Handles CAN interrupts //
///////////////////////////////////////////////////////////////////////////////
void receive() {
if(can1.read(msg)){
if( msg.id == 2 || msg.id == 3 || msg.id == 4 ){
alarmed = true;
temp1.stop();
}
else if( msg.id == 6 || msg.id == 7 || msg.id == 8){
lcd.locate(0,10); lcd.printf("Reading %s from node %d", msg.data, msg.id);
}
}
temp1.reset();
}
///////////////////////////////////////////////////////////////////////////////
// FUNCTION THAT Saves the password from the Joystick movements //
///////////////////////////////////////////////////////////////////////////////
void check_JoyIn_pass(){
JoyIn = 0;
while(JoyIn < 4 && on){
if( joy==0x1 || joy==0x4 || joy==0x2 || joy==0x8){
temp1.reset();
lcd.locate(0,20); lcd.printf(" ");
JoyIn++; //increment number of joystick movements
if (JoyIn == 1){
led1 = 1;
if( joy == 0x1 ){ pass[0]='u';}
else if( joy == 0x2 ){ pass[0]='d';}
else if( joy == 0x4 ){ pass[0]='l';}
else if( joy == 0x8 ){ pass[0]='r';}
}else if (JoyIn == 2){
led2 = 1;
if( joy == 0x1 ){ pass[1]='u';}
else if( joy == 0x2 ){ pass[1]='d';}
else if( joy == 0x4 ){ pass[1]='l';}
else if( joy == 0x8 ){ pass[1]='r';}
}else if (JoyIn == 3){
led3 = 1;
if( joy == 0x1 ){ pass[2]='u';}
else if( joy == 0x2 ){ pass[2]='d';}
else if( joy == 0x4 ){ pass[2]='l';}
else if( joy == 0x8 ){ pass[2]='r';}
}else if (JoyIn == 4){
led4 = 1;
if( joy == 0x1 ){ pass[3]='u'; }
else if( joy == 0x2 ){ pass[3]='d'; }
else if( joy == 0x4 ){ pass[3]='l'; }
else if( joy == 0x8 ){ pass[3]='r'; }
}
wait_us(500000);
}
}
}
///////////////////////////////////////////////////////////////////////////////
// FUNCTION THAT Chooses the mode from the Joystick movements //
///////////////////////////////////////////////////////////////////////////////
void check_JoyIn_mode(){
while(!fire && on){
//Selection of the modes
//Press right or left to choose the intended functionality
if (joy == 0x8){
temp1.reset();
lcd.locate(0,20); lcd.printf(" ");
if(led1){
select = '2';
led1 = 0;
led2 = 1;
lcd.cls(); lcd.locate(0,0); lcd.printf("Select Mode:");
lcd.locate(0,10); lcd.printf("Mode 2: Temperature");
}else if (led2){
select = '3';
led2 = 0;
led3 = 1;
lcd.cls(); lcd.locate(0,0); lcd.printf("Select Mode:");
lcd.locate(0,10); lcd.printf("Mode 3: Luminosity");
}else if (led3){
select = '4';
led3 = 0;
led4 = 1;
lcd.cls(); lcd.locate(0,0); lcd.printf("Select Mode:");
lcd.locate(0,10); lcd.printf("Mode 4: Change password");
}else{
lcd.cls(); lcd.locate(0,0);
lcd.printf("Numero de modos excedido!");
wait_us(2000000);
lcd.cls(); lcd.locate(0,0); lcd.printf("Select Mode:");
lcd.locate(0,10); lcd.printf("Mode 4: Change password");
}
wait_us(500000);
}else if (joy == 0x4){
temp1.reset();
lcd.locate(0,20); lcd.printf(" ");
if(led1){
lcd.cls(); lcd.locate(0,0);
lcd.printf("Numero de modos excedido!");
wait_us(2000000);
lcd.cls(); lcd.locate(0,0); lcd.printf("Select Mode:");
lcd.locate(0,10); lcd.printf("Mode 1: Humidity");
}else if (led2){
select = '1';
led2 = 0;
led1 = 1;
lcd.cls(); lcd.locate(0,0); lcd.printf("Select Mode:");
lcd.locate(0,10); lcd.printf("Mode 1: Humidity");
}else if (led3){
select = '2';
led3 = 0;
led2 = 1;
lcd.cls(); lcd.locate(0,0); lcd.printf("Select Mode:");
lcd.locate(0,10); lcd.printf("Mode 2: Temperature");
}else if (led4){
select = '3';
led4 = 0;
led3 = 1;
lcd.cls(); lcd.locate(0,0); lcd.printf("Select Mode:");
lcd.locate(0,10); lcd.printf("Mode 3: Luminosity");
}
wait_us(500000);
}
}
}
///////////////////////////////////////////////////////////////////////////////
// FUNCTION THAT Implements password system //
///////////////////////////////////////////////////////////////////////////////
void passInsert(){
menu = true;
led1 = led2 = led3 = led4 = 0;
readpass();
//Writes a message in a certain location (in this case position (0,0))
lcd.cls(); lcd.locate(0,0); lcd.printf("WELCOME!");
wait_us(1000000);
lcd.locate(0,10); lcd.printf("INSERT PASSWORD, PLEASE");
temp1.start();
while(on){
check_JoyIn_pass();
if(!on){
info = false;
alarmed = false;
menu = false;
break;
}
//If it doesn't, ask to reinsert password
if(strcmp(pass, usedpass)){
lcd.locate(0,20); lcd.printf("PASSWORD INCORRECT");
wait_us(1000000);
led1 = led2 = led3 = led4 = 0;
lcd.cls(); lcd.locate(0,0); lcd.printf("REINSERT PASSWORD");
}else{
//If it does, unlock the system. You can now proceed
lcd.cls(); lcd.locate(0,10); lcd.printf("PASSWORD CORRECT");
led1 = led2 = led3 = led4 = 0;
// wakes up everybody
if(can1.write(CANMessage(0000, "0", 1))){
}else{
lcd.cls();
lcd.locate(0,10); lcd.printf("Error sending message");
}
wait_us(1000000);
menu = false;
break;
}
}
}
///////////////////////////////////////////////////////////////////////////////
// FUNCTION THAT Implements mode selection //
// The password was correct. You can now choose from a variety of modes. //
// To do so, choose the mode use the joystick once again. //
// The number of the mode is the amount of leds turned on. The modes are: //
// //
// Mode 1: Selects Humidity mode //
// Mode 2: Selects Temperature mode //
// Mode 3: Selects Luminosity mode //
// Mode 4: Change password //
///////////////////////////////////////////////////////////////////////////////
void modeSelect(){
temp1.reset();
wait_us(100000);
menu = true;
while(on){
led1 = 1;
select = '1';
lcd.cls(); lcd.locate(0,0); lcd.printf("Select Mode:");
lcd.locate(0,10); lcd.printf("Mode 1: Humidity");
check_JoyIn_mode();
if(!on){
info = false;
alarmed = false;
menu = false;
break;
}
lcd.cls(); lcd.locate(0,0); lcd.printf("Mode selected successfully");
led1 = led2 = led3 = led4 = 0;
wait_us(1000000);
//if the forth mode was picked, choose the new password
//if not, wake up the respective node and proceed
if (select == '4'){
lcd.cls(); lcd.locate(0,0); lcd.printf("Select New Pass");
check_JoyIn_pass();
if(!on){
info = false;
alarmed = false;
menu = false;
break;
}
strcpy(usedpass, pass); //updates password
savepass(); //Stores the password in memory
lcd.cls(); lcd.locate(0,0); lcd.printf("Password reselected: %s", pass);
wait_us(1000000);
led1 = led2 = led3 = led4 = 0;
}else{
shuttingDown = 0;
break;
}
}
if(on){
lcd.cls();
lcd.locate(0,0); lcd.printf("Press fire for more actions");
wait_us(1000000);
menu = false;
pressed_fnc = 0;
}
}
///////////////////////////////////////////////////////////////////////////////
// FUNCTION THAT Chooses threshold //
///////////////////////////////////////////////////////////////////////////////
void choose_threshold(){
temp1.stop();
lcd.cls(); lcd.locate(0,0); lcd.printf("Entered Threshold mode!");
lcd.locate(0,10); lcd.printf("Left/right to change");
lcd.locate(0,20); lcd.printf(" ");
wait_us(500000);
while(!fire && on){
//Calculates new humidity threshold
if(select == '1'){
hum_aux = hum_threshold;
hum_threshold2 = 2*(pot1.read())*hum_aux - 1.5*(pot2.read())*hum_aux;
lcd.locate(0,0); lcd.printf(" ");
lcd.locate(0,10); lcd.printf(" ");
lcd.locate(0,20); lcd.printf(" ");
lcd.locate(0,0);
lcd.printf("Humidity threshold: %.2f", hum_threshold2);
wait_us(300000);
}
//Calculates new temperature threshold
else if(select == '2'){
temp_aux = temp_threshold;
temp_threshold2 = 2*(pot1.read())*temp_aux - 1.5*(pot2.read())*temp_aux;
lcd.locate(0,0); lcd.printf(" ");
lcd.locate(0,10); lcd.printf(" ");
lcd.locate(0,20); lcd.printf(" ");
lcd.locate(0,0);
lcd.printf("Temperature threshold: %.2f", temp_threshold2);
wait_us(300000);
}
//Calculates new light threshold
else if(select == '3'){
light_aux = light_threshold;
light_threshold2 = 2*(pot1.read())*light_aux - 1.5*(pot2.read())*light_aux;
lcd.locate(0,0); lcd.printf(" ");
lcd.locate(0,10); lcd.printf(" ");
lcd.locate(0,20); lcd.printf(" ");
lcd.locate(0,0);
lcd.printf("Light threshold: %.2f", light_threshold2);
wait_us(300000);
}
wait_us(500000);
}
light_threshold = light_threshold2;
temp_threshold = temp_threshold2;
hum_threshold = hum_threshold2;
temp1.start();
}
///////////////////////////////////////////////////////////////////////////////
// FUNCTION THAT Chooses node information periodicity //
///////////////////////////////////////////////////////////////////////////////
void choose_period_info(){
lcd.cls(); lcd.locate(0,0); lcd.printf("Entered Period mode!");
lcd.locate(0,10); lcd.printf("Current period: %.2f", period);
lcd.locate(0,20); lcd.printf("Left/right to change");
while(!fire && on){
//Joystick to the right
if (joy == 0x8){
temp1.reset();
//Superor limit
if(period <= 9.9){
period = period + 0.2;
lcd.locate(0,0); lcd.printf(" ");
lcd.locate(0,10); lcd.printf(" ");
lcd.locate(0,20); lcd.printf(" ");
lcd.locate(0,0); lcd.printf("New period: %.2f", period);
lcd.locate(0,10); lcd.printf("Left/right to change");
wait_us(300000);
}else{
lcd.locate(0,10); lcd.printf("Can't go above 9.9 secs");
lcd.locate(0,20); lcd.printf(" ");
wait_us(1000000);
lcd.locate(0,10); lcd.printf(" ");
wait_us(300000);
}
}
//Joystick to the left
else if (joy == 0x4){
temp1.reset();
//Inferior limit
if(period >= 2.1){
period = period - 0.1;
lcd.locate(0,0); lcd.printf(" ");
lcd.locate(0,10); lcd.printf(" ");
lcd.locate(0,20); lcd.printf(" ");
lcd.locate(0,0); lcd.printf("New period: %.2f", period);
lcd.locate(0,10); lcd.printf("Left/right to change");
wait_us(300000);
}else{
lcd.locate(0,10); lcd.printf("Can't go lower than 2 secs");
lcd.locate(0,20); lcd.printf(" ");
wait_us(1000000);
lcd.locate(0,10); lcd.printf(" ");
wait_us(300000);
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
// FUNCTION THAT //
// Chooses several functionalities through Joystick commands //
// Up to choose a new threshold //
// Right to select a new period //
// Down to toggle messages //
// Left to open the menu //
///////////////////////////////////////////////////////////////////////////////
void options(){
menu = true;
temp1.reset();
lcd.cls();
lcd.locate(0,0); lcd.printf("Up: Threshold, Right: Period");
lcd.locate(0,10); lcd.printf("Left open menu");
lcd.locate(0,20); lcd.printf("Down to toggle messages");
while(on){
//Joystick right
if (joy == 0x8){
temp1.reset();
wait_us(300000);
choose_period_info();
if(!on){
info = false;
alarmed = false;
menu = false;
break;
}
sprintf(c, "%.2f", period);
if(can1.write(CANMessage(12, c, 7))){}
else{
lcd.cls();
lcd.locate(0,0); lcd.printf("Error sending message");
}
wait_us(200000);
break;
}
//Joystick up
else if (joy == 0x1){
temp1.reset();
wait_us(300000);
choose_threshold();
if(!on){
info = false;
alarmed = false;
menu = false;
break;
}
if(select == '1'){
sprintf(c, "%.2f", hum_threshold);
if(can1.write(CANMessage(9, c, 7))){}
else{
lcd.cls();
lcd.locate(0,0); lcd.printf("Error sending message");
}
wait_us(200000);
}
else if (select == '2'){
sprintf(c, "%.2f", temp_threshold);
if(can1.write(CANMessage(10, c, 7))){}
else{
lcd.cls();
lcd.locate(0,0); lcd.printf("Error sending message");
}
wait_us(200000);
}
else if(select == '3'){
sprintf(c, "%.2f", light_threshold);
if(can1.write(CANMessage(11, c, 7))){}
else{
lcd.cls();
lcd.locate(0,0); lcd.printf("Error sending message");
}
wait_us(200000);
}
break;
}
//Joystick down
else if (joy == 0x2){
temp1.reset();
wait_us(300000);
info = !info;
if(info){
sendMode();
wait_us(100000);
break;
}else {
if(can1.write(CANMessage(5, "0", 1))){}
else{
lcd.cls();
lcd.locate(0,0); lcd.printf("Error sending message");
}
wait_us(100000);
break;
}
}
//Joystick left
else if (joy == 0x4){
temp1.reset();
wait_us(300000);
//Stops receiving info
if(can1.write(CANMessage(5, "0" ,1))){
info = false;
}
else{
lcd.cls();
lcd.locate(0,0); lcd.printf("Error sending message");
}
wait_us(1000000);
modeSelect();
if(!on){
info = false;
alarmed = false;
menu = false;
break;
}
popmenu = true;
break;
}
}
if(on && !popmenu){
lcd.cls();
lcd.locate(0,0); lcd.printf("Press fire for more actions");
wait_us(1000000);
menu = false;
}
pressed_fnc = 0;
popmenu = false;
}
///////////////////////////////////////////////////////////////////////////////
// FUNCTION THAT Deals with switch bouncing on the on/off button //
///////////////////////////////////////////////////////////////////////////////
void onIn( void ) {
if (debounce1.read_us() > 200000) {
on = !on;
pressed_OnOff++;
temp1.reset();
debounce1.reset();
led1 = led2 = led3 = led4 = 0;
}
}
///////////////////////////////////////////////////////////////////////////////
// FUNCTION THAT //
// Verifies program run time //
///////////////////////////////////////////////////////////////////////////////
void verifyTimer(){
if( temp1.read_us() > 10000000 && temp1.read_us() < 20000000 && shuttingDown == 0){
shuttingDown = 1;
lcd.locate(0,20); lcd.printf(" ");
lcd.locate(0,20); lcd.printf("Vamos desligar em breve");
}
else if (temp1.read_us() < 10000000){
shuttingDown = 0;
}
else if(temp1.read_us() > 20000000 ){
on = false;
}
if(on) ticker.attach(&verifyTimer, 2.0);
}
///////////////////////////////////////////////////////////////////////////////
// FUNCTION THAT Deals with switch bouncing on the alarm button! //
///////////////////////////////////////////////////////////////////////////////
void alarmOff( void ) {
if (debounce2.read_us() > 200000) {
if(alarmed){
temp1.start();
//Makes nodes stop alarm
if(can1.write(CANMessage(1, "1" ,1))){}
else{
lcd.cls();
lcd.locate(0,0); lcd.printf("Error sending message");
}
alarmed = false;
}
lcd.locate(0,20); lcd.printf(" ");
temp1.reset();
debounce2.reset();
}
}
///////////////////////////////////////////////////////////////////////////////
// FUNCTION THAT Deals with switch bouncing on the options button! //
///////////////////////////////////////////////////////////////////////////////
void fnc(){
if (debounce3.read_us() > 200000) {
pressed_fnc++;
temp1.reset();
debounce3.reset();
}
}
///////////////////////////////////////////////////////////////////////////////
// MAIN //
///////////////////////////////////////////////////////////////////////////////
int main() {
can1.attach(&receive);
//Defines button interrupt
debounce1.start(); //Allows us to manage button debouncing problems
debounce2.start();
debounce3.start();
temp1.start();
OnOff.setSampleFrequency(10000);
alarm.setSampleFrequency(20000);
fire.setSampleFrequency(30000);
OnOff.setSamplesTillAssert(3);
alarm.setSamplesTillAssert(3);
fire.setSamplesTillAssert(3);
OnOff.attach_asserted( &onIn );
alarm.attach_asserted( &alarmOff );
fire.attach_asserted( &fnc );
while(1){
Sleep();
while(on){
//Pressing the button turns on/off the system
if( pressed_OnOff > 0){
pressed_OnOff = -1;
ticker.attach(&verifyTimer, 2.0);
//Insert password and choose a mode for the program to function
passInsert();
if(!on){
info = false;
alarmed = false;
menu = false;
sleepAll();
break;
}
//everyone is already checking for sensor values
//select mode
modeSelect();
if(!on){
info = false;
alarmed = false;
menu = false;
sleepAll();
break;
}
}
//Check for the options menu button
if( pressed_fnc > 0){
pressed_fnc = 0;
//Master stops receiving info
if(can1.write(CANMessage(5, "0" ,1))){}
else{
lcd.cls();
lcd.locate(0,0); lcd.printf("Error sending message");
}
options();
}
if(!on){
info = false;
alarmed = false;
menu = false;
sleepAll();
}
}
}
}
|
/*
* Copyright (c) 2020, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cassert>
#include <cmath>
#include <functional>
#include <iostream>
#include <limits>
//! `fixed_point` and supporting types
namespace numeric {
/** \cond HIDDEN_SYMBOLS */
// This is a wrapper struct that enforces "strong typing"
// at the construction site of the type. No implicit
// conversions will be allowed and you will need to use the
// name of the type alias (i.e. scale_type{0})
template <typename T>
struct strong_typedef {
T _t;
CUDA_HOST_DEVICE_CALLABLE explicit strong_typedef(T t) : _t(t) {}
CUDA_HOST_DEVICE_CALLABLE operator T() const { return _t; }
};
/** \endcond */
using scale_type = strong_typedef<int32_t>;
/**
* @brief Scoped enumerator to use when constructing `fixed_point`
*
* Examples:
* ```cpp
* using decimal32 = fixed_point<int32_t, Radix::BASE_10>;
* using binary64 = fixed_point<int64_t, Radix::BASE_2>;
* ```
*/
enum class Radix : int32_t { BASE_2 = 2, BASE_10 = 10 };
template <typename T>
constexpr inline auto is_supported_representation_type()
{
return std::is_same<T, int32_t>::value || std::is_same<T, int64_t>::value;
}
template <typename T>
constexpr inline auto is_supported_construction_value_type()
{
return std::is_integral<T>::value || std::is_floating_point<T>::value;
}
// Helper functions for `fixed_point` type
namespace detail {
/**
* @brief A function for integer exponentiation by squaring
*
* https://simple.wikipedia.org/wiki/Exponentiation_by_squaring <br>
* Note: this is the iterative equivalent of the recursive definition (faster) <br>
* Quick-bench: http://quick-bench.com/Wg7o7HYQC9FW5M0CO0wQAjSwP_Y <br>
* `exponent` comes from `using scale_type = strong_typedef<int32_t>` <br>
*
* @tparam Rep Representation type for return type
* @tparam Base The base to be exponentiated
* @param exponent The exponent to be used for exponentiation
* @return Result of `Base` to the power of `exponent` of type `Rep`
*/
template <typename Rep,
Radix Base,
typename T,
typename std::enable_if_t<(std::is_same<int32_t, T>::value &&
is_supported_representation_type<Rep>())>* = nullptr>
CUDA_HOST_DEVICE_CALLABLE Rep ipow(T exponent)
{
if (exponent == 0) return static_cast<Rep>(Base);
auto extra = static_cast<Rep>(1);
auto square = static_cast<Rep>(Base);
while (exponent > 1) {
if (exponent & 1 /* odd */) {
extra *= square;
exponent -= 1;
}
exponent /= 2;
square *= square;
}
return square * extra;
}
/** @brief Helper function to negate strongly typed scale_type
*
* @param scale The scale to be negated
* @return The negated scale
*/
CUDA_HOST_DEVICE_CALLABLE
auto negate(scale_type const& scale) { return scale_type{-scale}; }
/** @brief Function that performs a `right shift` scale "times" on the `val`
*
* Note: perform this operation when constructing with positive scale
*
* @tparam Rep Representation type needed for integer exponentiation
* @tparam Rad The radix which will act as the base in the exponentiation
* @tparam T Type for value `val` being shifted and the return type
* @param val The value being shifted
* @param scale The amount to shift the value by
* @return Shifted value of type T
*/
template <typename Rep, Radix Rad, typename T>
CUDA_HOST_DEVICE_CALLABLE constexpr T right_shift(T const& val, scale_type const& scale)
{
return val / ipow<Rep, Rad>(scale._t);
}
/** @brief Function that performs a `left shift` scale "times" on the `val`
*
* Note: perform this operation when constructing with negative scale
*
* @tparam Rep Representation type needed for integer exponentiation
* @tparam Rad The radix which will act as the base in the exponentiation
* @tparam T Type for value `val` being shifted and the return type
* @param val The value being shifted
* @param scale The amount to shift the value by
* @return Shifted value of type T
*/
template <typename Rep, Radix Rad, typename T>
CUDA_HOST_DEVICE_CALLABLE constexpr T left_shift(T const& val, scale_type const& scale)
{
return val * ipow<Rep, Rad>(-scale._t);
}
/** @brief Function that performs a `right` or `left shift`
* scale "times" on the `val`
*
* Note: Function will call the correct right or left shift based
* on the sign of `val`
*
* @tparam Rep Representation type needed for integer exponentiation
* @tparam Rad The radix which will act as the base in the exponentiation
* @tparam T Type for value `val` being shifted and the return type
* @param val The value being shifted
* @param scale The amount to shift the value by
* @return Shifted value of type T
*/
template <typename Rep, Radix Rad, typename T>
CUDA_HOST_DEVICE_CALLABLE constexpr T shift(T const& val, scale_type const& scale)
{
if (scale == 0)
return val;
else if (scale > 0)
return right_shift<Rep, Rad>(val, scale);
else
return left_shift<Rep, Rad>(val, scale);
}
/** @brief Function that performs precise shift to avoid "lossiness"
* inherent in floating point values
*
* Example: `auto n = fixed_point<int32_t, Radix::BASE_10>{1.001, scale_type{-3}}`
* will construct n to have a value of 1 without the precise shift
*
* @tparam Rep Representation type needed for integer exponentiation
* @tparam Rad The radix which will act as the base in the exponentiation
* @tparam T Type for value `val` being shifted and the return type
* @param value The value being shifted
* @param scale The amount to shift the value by
* @return Shifted value of type T
*/
template <typename Rep,
Radix Rad,
typename T,
typename std::enable_if_t<is_supported_construction_value_type<T>()>* = nullptr>
CUDA_HOST_DEVICE_CALLABLE auto shift_with_precise_round(T const& value, scale_type const& scale)
-> int64_t
{
if (scale == 0) return value;
int64_t const base = static_cast<int64_t>(Rad);
int64_t const factor = ipow<int64_t, Rad>(std::abs(scale));
int64_t const temp = scale <= 0 ? value * (factor * base) : value / (factor / base);
return std::roundf(static_cast<double>(temp) / base);
}
} // namespace detail
/**
* @addtogroup fixed_point_classes
* @{
*/
/**
* @brief Helper struct for constructing `fixed_point` when value is already shifted
*
* Example:
* ```cpp
* using decimal32 = fixed_point<int32_t, Radix::BASE_10>;
* auto n = decimal32{scaled_integer{1001, 3}}; // n = 1.001
* ```
*
* @tparam Rep The representation type (either `int32_t` or `int64_t`)
*/
template <typename Rep,
typename std::enable_if_t<is_supported_representation_type<Rep>()>* = nullptr>
struct scaled_integer {
Rep value;
scale_type scale;
CUDA_HOST_DEVICE_CALLABLE explicit scaled_integer(Rep v, scale_type s) : value(v), scale(s) {}
};
/**
* @brief A type for representing a number with a fixed amount of precision
*
* Currently, only binary and decimal `fixed_point` numbers are supported.
* Binary operations can only be performed with other `fixed_point` numbers
*
* @tparam Rep The representation type (either `int32_t` or `int64_t`)
* @tparam Rad The radix/base (either `Radix::BASE_2` or `Radix::BASE_10`)
*/
template <typename Rep, Radix Rad>
class fixed_point {
Rep _value;
scale_type _scale;
public:
/**
* @brief Constructor that will perform shifting to store value appropriately
*
* @tparam T The type that you are constructing from (integral or floating)
* @param value The value that will be constructed from
* @param scale The exponent that is applied to Rad to perform shifting
*/
template <typename T,
typename std::enable_if_t<is_supported_construction_value_type<T>() &&
is_supported_representation_type<Rep>()>* = nullptr>
CUDA_HOST_DEVICE_CALLABLE explicit fixed_point(T const& value, scale_type const& scale)
: _value{static_cast<Rep>(detail::shift_with_precise_round<Rep, Rad>(value, scale))},
_scale{scale}
{
}
/**
* @brief Constructor that will not perform shifting (assumes value already
* shifted)
*
* @param s scaled_integer that contains scale and already shifted value
*/
CUDA_HOST_DEVICE_CALLABLE
explicit fixed_point(scaled_integer<Rep> s) : _value{s.value}, _scale{s.scale} {}
/**
* @brief Default constructor that constructs `fixed_point` number with a
* value and scale of zero
*/
CUDA_HOST_DEVICE_CALLABLE
fixed_point() : _value{0}, _scale{scale_type{0}} {}
/**
* @brief Explicit conversion operator
*
* @tparam U The type that is being explicitly converted to (integral or floating)
* @return The `fixed_point` number in base 10 (aka human readable format)
*/
template <typename U,
typename std::enable_if_t<is_supported_construction_value_type<U>()>* = nullptr>
CUDA_HOST_DEVICE_CALLABLE explicit constexpr operator U() const
{
return detail::shift<Rep, Rad>(static_cast<U>(_value), detail::negate(_scale));
}
/**
* @brief operator +=
*
* @tparam Rep1 Representation type of number being added to `this`
* @tparam Rad1 Radix (base) type of number being added to `this`
* @return The sum
*/
template <typename Rep1, Radix Rad1>
CUDA_HOST_DEVICE_CALLABLE fixed_point<Rep1, Rad1>& operator+=(fixed_point<Rep1, Rad1> const& rhs)
{
*this = *this + rhs;
return *this;
}
/**
* @brief operator *=
*
* @tparam Rep1 Representation type of number being added to `this`
* @tparam Rad1 Radix (base) type of number being added to `this`
* @return The product
*/
template <typename Rep1, Radix Rad1>
CUDA_HOST_DEVICE_CALLABLE fixed_point<Rep1, Rad1>& operator*=(fixed_point<Rep1, Rad1> const& rhs)
{
*this = *this * rhs;
return *this;
}
/**
* @brief operator -=
*
* @tparam Rep1 Representation type of number being added to `this`
* @tparam Rad1 Radix (base) type of number being added to `this`
* @return The difference
*/
template <typename Rep1, Radix Rad1>
CUDA_HOST_DEVICE_CALLABLE fixed_point<Rep1, Rad1>& operator-=(fixed_point<Rep1, Rad1> const& rhs)
{
*this = *this - rhs;
return *this;
}
/**
* @brief operator /=
*
* @tparam Rep1 Representation type of number being added to `this`
* @tparam Rad1 Radix (base) type of number being added to `this`
* @return The quotient
*/
template <typename Rep1, Radix Rad1>
CUDA_HOST_DEVICE_CALLABLE fixed_point<Rep1, Rad1>& operator/=(fixed_point<Rep1, Rad1> const& rhs)
{
*this = *this / rhs;
return *this;
}
/**
* @brief operator ++ (post-increment)
*
* @return The incremented result
*/
CUDA_HOST_DEVICE_CALLABLE
fixed_point<Rep, Rad>& operator++()
{
*this = *this + fixed_point<Rep, Rad>{1, scale_type{_scale}};
return *this;
}
/**
* @brief operator + (for adding two `fixed_point` numbers)
*
* If `_scale`s are equal, `_value`s are added <br>
* If `_scale`s are not equal, number with smaller `_scale` is shifted to the
* greater `_scale`, and then `_value`s are added
*
* @tparam Rep1 Representation type of number being added to `this`
* @tparam Rad1 Radix (base) type of number being added to `this`
* @return The resulting `fixed_point` sum
*/
template <typename Rep1, Radix Rad1>
CUDA_HOST_DEVICE_CALLABLE friend fixed_point<Rep1, Rad1> operator+(
fixed_point<Rep1, Rad1> const& lhs, fixed_point<Rep1, Rad1> const& rhs);
/**
* @brief operator - (for subtracting two `fixed_point` numbers)
*
* If `_scale`s are equal, `_value`s are substracted <br>
* If `_scale`s are not equal, number with smaller `_scale` is shifted to the
* greater `_scale`, and then `_value`s are substracted
*
* @tparam Rep1 Representation type of number being added to `this`
* @tparam Rad1 Radix (base) type of number being added to `this`
* @return The resulting `fixed_point` difference
*/
template <typename Rep1, Radix Rad1>
CUDA_HOST_DEVICE_CALLABLE friend fixed_point<Rep1, Rad1> operator-(
fixed_point<Rep1, Rad1> const& lhs, fixed_point<Rep1, Rad1> const& rhs);
/**
* @brief operator * (for multiplying two `fixed_point` numbers)
*
* `_scale`s are added and `_value`s are multiplied
*
* @tparam Rep1 Representation type of number being added to `this`
* @tparam Rad1 Radix (base) type of number being added to `this`
* @return The resulting `fixed_point` product
*/
template <typename Rep1, Radix Rad1>
CUDA_HOST_DEVICE_CALLABLE friend fixed_point<Rep1, Rad1> operator*(
fixed_point<Rep1, Rad1> const& lhs, fixed_point<Rep1, Rad1> const& rhs);
/**
* @brief operator / (for dividing two `fixed_point` numbers)
*
* `_scale`s are substracted and `_value`s are divided
*
* @tparam Rep1 Representation type of number being added to `this`
* @tparam Rad1 Radix (base) type of number being added to `this`
* @return The resulting `fixed_point` quotient
*/
template <typename Rep1, Radix Rad1>
CUDA_HOST_DEVICE_CALLABLE friend fixed_point<Rep1, Rad1> operator/(
fixed_point<Rep1, Rad1> const& lhs, fixed_point<Rep1, Rad1> const& rhs);
/**
* @brief operator == (for comparing two `fixed_point` numbers)
*
* If `_scale`s are equal, `_value`s are compared <br>
* If `_scale`s are not equal, number with smaller `_scale` is shifted to the
* greater `_scale`, and then `_value`s are compared
*
* @tparam Rep1 Representation type of number being added to `this`
* @tparam Rad1 Radix (base) type of number being added to `this`
* @return true if `lhs` and `rhs` are equal, false if not
*/
template <typename Rep1, Radix Rad1>
CUDA_HOST_DEVICE_CALLABLE friend bool operator==(fixed_point<Rep1, Rad1> const& lhs,
fixed_point<Rep1, Rad1> const& rhs);
};
/** @brief Function that converts Rep to `std::string`
*
* @tparam Rep Representation type
* @return String-ified Rep
*/
template <typename Rep>
std::string print_rep()
{
if (std::is_same<Rep, int32_t>::value)
return "int32_t";
else if (std::is_same<Rep, int64_t>::value)
return "int64_t";
else
return "unknown type";
}
/** @brief Function for identifying integer overflow when adding
*
* @tparam Rep Type of integer to check for overflow on
* @tparam T Types of lhs and rhs (ensures they are the same type)
* @param lhs Left hand side of addition
* @param rhs Right hand side of addition
* @return true if addition causes overflow, false otherwise
*/
template <typename Rep, typename T>
CUDA_HOST_DEVICE_CALLABLE auto addition_overflow(T lhs, T rhs)
{
return rhs > 0 ? lhs > std::numeric_limits<Rep>::max() - rhs
: lhs < std::numeric_limits<Rep>::min() - rhs;
}
/** @brief Function for identifying integer overflow when subtracting
*
* @tparam Rep Type of integer to check for overflow on
* @tparam T Types of lhs and rhs (ensures they are the same type)
* @param lhs Left hand side of subtraction
* @param rhs Right hand side of subtraction
* @return true if subtraction causes overflow, false otherwise
*/
template <typename Rep, typename T>
CUDA_HOST_DEVICE_CALLABLE auto subtraction_overflow(T lhs, T rhs)
{
return rhs > 0 ? lhs < std::numeric_limits<Rep>::min() + rhs
: lhs > std::numeric_limits<Rep>::max() + rhs;
}
/** @brief Function for identifying integer overflow when dividing
*
* @tparam Rep Type of integer to check for overflow on
* @tparam T Types of lhs and rhs (ensures they are the same type)
* @param lhs Left hand side of division
* @param rhs Right hand side of division
* @return true if division causes overflow, false otherwise
*/
template <typename Rep, typename T>
CUDA_HOST_DEVICE_CALLABLE auto division_overflow(T lhs, T rhs)
{
return lhs == std::numeric_limits<Rep>::min() && rhs == -1;
}
/** @brief Function for identifying integer overflow when multiplying
*
* @tparam Rep Type of integer to check for overflow on
* @tparam T Types of lhs and rhs (ensures they are the same type)
* @param lhs Left hand side of multiplication
* @param rhs Right hand side of multiplication
* @return true if multiplication causes overflow, false otherwise
*/
template <typename Rep, typename T>
CUDA_HOST_DEVICE_CALLABLE auto multiplication_overflow(T lhs, T rhs)
{
auto const min = std::numeric_limits<Rep>::min();
auto const max = std::numeric_limits<Rep>::max();
if (rhs > 0)
return lhs > max / rhs || lhs < min / rhs;
else if (rhs < -1)
return lhs > min / rhs || lhs < max / rhs;
else
return rhs == -1 && lhs == min;
}
// PLUS Operation
template <typename Rep1, Radix Rad1>
CUDA_HOST_DEVICE_CALLABLE fixed_point<Rep1, Rad1> operator+(fixed_point<Rep1, Rad1> const& lhs,
fixed_point<Rep1, Rad1> const& rhs)
{
auto const rhsv = lhs._scale > rhs._scale ? detail::shift_with_precise_round<Rep1, Rad1>(
rhs._value, scale_type{lhs._scale - rhs._scale})
: rhs._value;
auto const lhsv = lhs._scale < rhs._scale ? detail::shift_with_precise_round<Rep1, Rad1>(
lhs._value, scale_type{rhs._scale - lhs._scale})
: lhs._value;
auto const scale = lhs._scale > rhs._scale ? lhs._scale : rhs._scale;
#if defined(__CUDACC_DEBUG__)
assert(!addition_overflow<Rep1>(lhsv, rhsv) &&
"fixed_point overflow of underlying representation type " + print_rep<Rep1>());
#endif
return fixed_point<Rep1, Rad1>{scaled_integer<Rep1>(lhsv + rhsv, scale)};
}
// MINUS Operation
template <typename Rep1, Radix Rad1>
CUDA_HOST_DEVICE_CALLABLE fixed_point<Rep1, Rad1> operator-(fixed_point<Rep1, Rad1> const& lhs,
fixed_point<Rep1, Rad1> const& rhs)
{
auto const rhsv = lhs._scale > rhs._scale ? detail::shift_with_precise_round<Rep1, Rad1>(
rhs._value, scale_type{lhs._scale - rhs._scale})
: rhs._value;
auto const lhsv = lhs._scale < rhs._scale ? detail::shift_with_precise_round<Rep1, Rad1>(
lhs._value, scale_type{rhs._scale - lhs._scale})
: lhs._value;
auto const scale = lhs._scale > rhs._scale ? lhs._scale : rhs._scale;
#if defined(__CUDACC_DEBUG__)
assert(!subtraction_overflow<Rep1>(lhsv, rhsv) &&
"fixed_point overflow of underlying representation type " + print_rep<Rep1>());
#endif
return fixed_point<Rep1, Rad1>{scaled_integer<Rep1>(lhsv - rhsv, scale)};
}
// MULTIPLIES Operation
template <typename Rep1, Radix Rad1>
CUDA_HOST_DEVICE_CALLABLE fixed_point<Rep1, Rad1> operator*(fixed_point<Rep1, Rad1> const& lhs,
fixed_point<Rep1, Rad1> const& rhs)
{
#if defined(__CUDACC_DEBUG__)
assert(!multiplication_overflow<Rep1>(lhs._value, rhs._value) &&
"fixed_point overflow of underlying representation type " + print_rep<Rep1>());
#endif
return fixed_point<Rep1, Rad1>{
scaled_integer<Rep1>(lhs._value * rhs._value, scale_type{lhs._scale + rhs._scale})};
}
// DIVISION Operation
template <typename Rep1, Radix Rad1>
CUDA_HOST_DEVICE_CALLABLE fixed_point<Rep1, Rad1> operator/(fixed_point<Rep1, Rad1> const& lhs,
fixed_point<Rep1, Rad1> const& rhs)
{
#if defined(__CUDACC_DEBUG__)
assert(!division_overflow<Rep1>(lhs._value, rhs._value) &&
"fixed_point overflow of underlying representation type " + print_rep<Rep1>());
#endif
return fixed_point<Rep1, Rad1>{scaled_integer<Rep1>(std::roundf(lhs._value * 1.0 / rhs._value),
scale_type{lhs._scale - rhs._scale})};
}
// EQUALITY COMPARISON Operation
template <typename Rep1, Radix Rad1>
CUDA_HOST_DEVICE_CALLABLE bool operator==(fixed_point<Rep1, Rad1> const& lhs,
fixed_point<Rep1, Rad1> const& rhs)
{
auto const rhsv = lhs._scale > rhs._scale ? detail::shift_with_precise_round<Rep1, Rad1>(
rhs._value, scale_type{lhs._scale - rhs._scale})
: rhs._value;
auto const lhsv = lhs._scale < rhs._scale ? detail::shift_with_precise_round<Rep1, Rad1>(
lhs._value, scale_type{rhs._scale - lhs._scale})
: lhs._value;
return rhsv == lhsv;
}
/**
* @brief ostream operator for outputting `fixed_point` number
*
* @tparam Rep Representation type of number being output
* @tparam Rad Radix (base) type of number being output
* @param os target ostream
* @return fp `fixed_point` number being output
*/
template <typename Rep, Radix Radix>
std::ostream& operator<<(std::ostream& os, fixed_point<Rep, Radix> const& fp)
{
return os << static_cast<double>(fp);
}
/** @} */ // end of group
} // namespace numeric
|
/*
* Copyright (c) 2021, NVIDIA CORPORATION. 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.
*/
//!
//! sampleUffMNIST.cpp
//! This file contains the implementation of the Uff MNIST sample.
//! It creates the network using the MNIST model converted to uff.
//!
//! It can be run with the following command line:
//! Command: ./sample_uff_mnist [-h or --help] [-d or --datadir=<path to data directory>] [--useDLACore=<int>]
//!
#include "argsParser.h"
#include "buffers.h"
#include "common.h"
#include "logger.h"
#include "NvInfer.h"
#include "NvUffParser.h"
#include <cuda_runtime_api.h>
#include <algorithm>
#include <chrono>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <sys/stat.h>
#include <unordered_map>
#include <vector>
using samplesCommon::SampleUniquePtr;
const std::string gSampleName = "TensorRT.sample_uff_mnist";
//!
//! \brief The SampleUffMNIST class implements the UffMNIST sample
//!
//! \details It creates the network using a Uff model
//!
class SampleUffMNIST
{
public:
SampleUffMNIST(const samplesCommon::UffSampleParams& params)
: mParams(params)
{
}
//!
//! \brief Builds the network engine
//!
bool build();
//!
//! \brief Runs the TensorRT inference engine for this sample
//!
bool infer();
//!
//! \brief Used to clean up any state created in the sample class
//!
bool teardown();
private:
//!
//! \brief Parses a Uff model for MNIST and creates a TensorRT network
//!
void constructNetwork(
SampleUniquePtr<nvuffparser::IUffParser>& parser, SampleUniquePtr<nvinfer1::INetworkDefinition>& network);
//!
//! \brief Reads the input and mean data, preprocesses, and stores the result
//! in a managed buffer
//!
bool processInput(
const samplesCommon::BufferManager& buffers, const std::string& inputTensorName, int inputFileIdx) const;
//!
//! \brief Verifies that the output is correct and prints it
//!
bool verifyOutput(
const samplesCommon::BufferManager& buffers, const std::string& outputTensorName, int groundTruthDigit) const;
std::shared_ptr<nvinfer1::ICudaEngine> mEngine{nullptr}; //!< The TensorRT engine used to run the network
samplesCommon::UffSampleParams mParams;
nvinfer1::Dims mInputDims;
const int kDIGITS{10};
};
//!
//! \brief Creates the network, configures the builder and creates the network engine
//!
//! \details This function creates the MNIST network by parsing the Uff model
//! and builds the engine that will be used to run MNIST (mEngine)
//!
//! \return Returns true if the engine was created successfully and false otherwise
//!
bool SampleUffMNIST::build()
{
auto builder = SampleUniquePtr<nvinfer1::IBuilder>(nvinfer1::createInferBuilder(sample::gLogger.getTRTLogger()));
if (!builder)
{
return false;
}
auto network = SampleUniquePtr<nvinfer1::INetworkDefinition>(builder->createNetworkV2(0));
if (!network)
{
return false;
}
auto config = SampleUniquePtr<nvinfer1::IBuilderConfig>(builder->createBuilderConfig());
if (!config)
{
return false;
}
auto parser = SampleUniquePtr<nvuffparser::IUffParser>(nvuffparser::createUffParser());
if (!parser)
{
return false;
}
constructNetwork(parser, network);
builder->setMaxBatchSize(mParams.batchSize);
config->setMaxWorkspaceSize(16_MiB);
config->setFlag(BuilderFlag::kGPU_FALLBACK);
if (mParams.fp16)
{
config->setFlag(BuilderFlag::kFP16);
}
if (mParams.int8)
{
config->setFlag(BuilderFlag::kINT8);
}
samplesCommon::enableDLA(builder.get(), config.get(), mParams.dlaCore);
// CUDA stream used for profiling by the builder.
auto profileStream = samplesCommon::makeCudaStream();
if (!profileStream)
{
return false;
}
config->setProfileStream(*profileStream);
SampleUniquePtr<IHostMemory> plan{builder->buildSerializedNetwork(*network, *config)};
if (!plan)
{
return false;
}
SampleUniquePtr<IRuntime> runtime{createInferRuntime(sample::gLogger.getTRTLogger())};
if (!runtime)
{
return false;
}
mEngine = std::shared_ptr<nvinfer1::ICudaEngine>(
runtime->deserializeCudaEngine(plan->data(), plan->size()), samplesCommon::InferDeleter());
if (!mEngine)
{
return false;
}
ASSERT(network->getNbInputs() == 1);
mInputDims = network->getInput(0)->getDimensions();
ASSERT(mInputDims.nbDims == 3);
return true;
}
//!
//! \brief Uses a Uff parser to create the MNIST Network and marks the output layers
//!
//! \param network Pointer to the network that will be populated with the MNIST network
//!
//! \param builder Pointer to the engine builder
//!
void SampleUffMNIST::constructNetwork(
SampleUniquePtr<nvuffparser::IUffParser>& parser, SampleUniquePtr<nvinfer1::INetworkDefinition>& network)
{
// There should only be one input and one output tensor
ASSERT(mParams.inputTensorNames.size() == 1);
ASSERT(mParams.outputTensorNames.size() == 1);
// Register tensorflow input
parser->registerInput(
mParams.inputTensorNames[0].c_str(), nvinfer1::Dims3(1, 28, 28), nvuffparser::UffInputOrder::kNCHW);
parser->registerOutput(mParams.outputTensorNames[0].c_str());
parser->parse(mParams.uffFileName.c_str(), *network, nvinfer1::DataType::kFLOAT);
if (mParams.int8)
{
samplesCommon::setAllDynamicRanges(network.get(), 127.0f, 127.0f);
}
}
//!
//! \brief Reads the input data, preprocesses, and stores the result in a managed buffer
//!
bool SampleUffMNIST::processInput(
const samplesCommon::BufferManager& buffers, const std::string& inputTensorName, int inputFileIdx) const
{
const int inputH = mInputDims.d[1];
const int inputW = mInputDims.d[2];
std::vector<uint8_t> fileData(inputH * inputW);
readPGMFile(locateFile(std::to_string(inputFileIdx) + ".pgm", mParams.dataDirs), fileData.data(), inputH, inputW);
// Print ASCII representation of digit
sample::gLogInfo << "Input:\n";
for (int i = 0; i < inputH * inputW; i++)
{
sample::gLogInfo << (" .:-=+*#%@"[fileData[i] / 26]) << (((i + 1) % inputW) ? "" : "\n");
}
sample::gLogInfo << std::endl;
float* hostInputBuffer = static_cast<float*>(buffers.getHostBuffer(inputTensorName));
for (int i = 0; i < inputH * inputW; i++)
{
hostInputBuffer[i] = 1.0 - float(fileData[i]) / 255.0;
}
return true;
}
//!
//! \brief Verifies that the inference output is correct
//!
bool SampleUffMNIST::verifyOutput(
const samplesCommon::BufferManager& buffers, const std::string& outputTensorName, int groundTruthDigit) const
{
const float* prob = static_cast<const float*>(buffers.getHostBuffer(outputTensorName));
sample::gLogInfo << "Output:\n";
float val{0.0f};
int idx{0};
// Determine index with highest output value
for (int i = 0; i < kDIGITS; i++)
{
if (val < prob[i])
{
val = prob[i];
idx = i;
}
}
// Print output values for each index
for (int j = 0; j < kDIGITS; j++)
{
sample::gLogInfo << j << "=> " << std::setw(10) << prob[j] << "\t : ";
// Emphasize index with highest output value
if (j == idx)
{
sample::gLogInfo << "***";
}
sample::gLogInfo << "\n";
}
sample::gLogInfo << std::endl;
return (idx == groundTruthDigit);
}
//!
//! \brief Runs the TensorRT inference engine for this sample
//!
//! \details This function is the main execution function of the sample.
//! It allocates the buffer, sets inputs, executes the engine, and verifies the output.
//!
bool SampleUffMNIST::infer()
{
// Create RAII buffer manager object
samplesCommon::BufferManager buffers(mEngine, mParams.batchSize);
auto context = SampleUniquePtr<nvinfer1::IExecutionContext>(mEngine->createExecutionContext());
if (!context)
{
return false;
}
bool outputCorrect = true;
float total = 0;
// Try to infer each digit 0-9
for (int digit = 0; digit < kDIGITS; digit++)
{
if (!processInput(buffers, mParams.inputTensorNames[0], digit))
{
return false;
}
// Copy data from host input buffers to device input buffers
buffers.copyInputToDevice();
const auto t_start = std::chrono::high_resolution_clock::now();
// Execute the inference work
if (!context->execute(mParams.batchSize, buffers.getDeviceBindings().data()))
{
return false;
}
const auto t_end = std::chrono::high_resolution_clock::now();
const float ms = std::chrono::duration<float, std::milli>(t_end - t_start).count();
total += ms;
// Copy data from device output buffers to host output buffers
buffers.copyOutputToHost();
// Check and print the output of the inference
outputCorrect &= verifyOutput(buffers, mParams.outputTensorNames[0], digit);
}
total /= kDIGITS;
sample::gLogInfo << "Average over " << kDIGITS << " runs is " << total << " ms." << std::endl;
return outputCorrect;
}
//!
//! \brief Used to clean up any state created in the sample class
//!
bool SampleUffMNIST::teardown()
{
nvuffparser::shutdownProtobufLibrary();
return true;
}
//!
//! \brief Initializes members of the params struct
//! using the command line args
//!
samplesCommon::UffSampleParams initializeSampleParams(const samplesCommon::Args& args)
{
samplesCommon::UffSampleParams params;
if (args.dataDirs.empty()) //!< Use default directories if user hasn't provided paths
{
params.dataDirs.push_back("data/mnist/");
params.dataDirs.push_back("data/samples/mnist/");
}
else //!< Use the data directory provided by the user
{
params.dataDirs = args.dataDirs;
}
params.uffFileName = locateFile("lenet5.uff", params.dataDirs);
params.inputTensorNames.push_back("in");
params.batchSize = 1;
params.outputTensorNames.push_back("out");
params.dlaCore = args.useDLACore;
params.int8 = args.runInInt8;
params.fp16 = args.runInFp16;
return params;
}
//!
//! \brief Prints the help information for running this sample
//!
void printHelpInfo()
{
std::cout << "Usage: ./sample_uff_mnist [-h or --help] [-d or "
"--datadir=<path to data directory>] [--useDLACore=<int>]\n";
std::cout << "--help Display help information\n";
std::cout << "--datadir Specify path to a data directory, overriding "
"the default. This option can be used multiple times to add "
"multiple directories. If no data directories are given, the "
"default is to use (data/samples/mnist/, data/mnist/)"
<< std::endl;
std::cout << "--useDLACore=N Specify a DLA engine for layers that support "
"DLA. Value can range from 0 to n-1, where n is the number of "
"DLA engines on the platform."
<< std::endl;
std::cout << "--int8 Run in Int8 mode.\n";
std::cout << "--fp16 Run in FP16 mode." << std::endl;
}
int main(int argc, char** argv)
{
samplesCommon::Args args;
bool argsOK = samplesCommon::parseArgs(args, argc, argv);
if (!argsOK)
{
sample::gLogError << "Invalid arguments" << std::endl;
printHelpInfo();
return EXIT_FAILURE;
}
if (args.help)
{
printHelpInfo();
return EXIT_SUCCESS;
}
auto sampleTest = sample::gLogger.defineTest(gSampleName, argc, argv);
sample::gLogger.reportTestStart(sampleTest);
samplesCommon::UffSampleParams params = initializeSampleParams(args);
SampleUffMNIST sample(params);
sample::gLogInfo << "Building and running a GPU inference engine for Uff MNIST" << std::endl;
if (!sample.build())
{
return sample::gLogger.reportFail(sampleTest);
}
if (!sample.infer())
{
return sample::gLogger.reportFail(sampleTest);
}
if (!sample.teardown())
{
return sample::gLogger.reportFail(sampleTest);
}
return sample::gLogger.reportPass(sampleTest);
}
|
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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.
#include <string>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <vector>
#include <google/protobuf/test_util.h>
#include <google/protobuf/unittest.pb.h>
#include <google/protobuf/unittest_proto3_arena.pb.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
namespace google {
using proto3_arena_unittest::TestAllTypes;
namespace protobuf {
namespace {
// We selectively set/check a few representative fields rather than all fields
// as this test is only expected to cover the basics of arena support.
void SetAllFields(TestAllTypes* m) {
m->set_optional_int32(100);
m->set_optional_string("asdf");
m->set_optional_bytes("jkl;");
m->mutable_optional_nested_message()->set_bb(42);
m->mutable_optional_foreign_message()->set_c(43);
m->set_optional_nested_enum(
proto3_arena_unittest::TestAllTypes_NestedEnum_BAZ);
m->set_optional_foreign_enum(
proto3_arena_unittest::FOREIGN_BAZ);
m->mutable_optional_lazy_message()->set_bb(45);
m->add_repeated_int32(100);
m->add_repeated_string("asdf");
m->add_repeated_bytes("jkl;");
m->add_repeated_nested_message()->set_bb(46);
m->add_repeated_foreign_message()->set_c(47);
m->add_repeated_nested_enum(
proto3_arena_unittest::TestAllTypes_NestedEnum_BAZ);
m->add_repeated_foreign_enum(
proto3_arena_unittest::FOREIGN_BAZ);
m->add_repeated_lazy_message()->set_bb(49);
m->set_oneof_uint32(1);
m->mutable_oneof_nested_message()->set_bb(50);
m->set_oneof_string("test"); // only this one remains set
}
void ExpectAllFieldsSet(const TestAllTypes& m) {
EXPECT_EQ(100, m.optional_int32());
EXPECT_EQ("asdf", m.optional_string());
EXPECT_EQ("jkl;", m.optional_bytes());
EXPECT_EQ(true, m.has_optional_nested_message());
EXPECT_EQ(42, m.optional_nested_message().bb());
EXPECT_EQ(true, m.has_optional_foreign_message());
EXPECT_EQ(43, m.optional_foreign_message().c());
EXPECT_EQ(proto3_arena_unittest::TestAllTypes_NestedEnum_BAZ,
m.optional_nested_enum());
EXPECT_EQ(proto3_arena_unittest::FOREIGN_BAZ,
m.optional_foreign_enum());
EXPECT_EQ(true, m.has_optional_lazy_message());
EXPECT_EQ(45, m.optional_lazy_message().bb());
EXPECT_EQ(1, m.repeated_int32_size());
EXPECT_EQ(100, m.repeated_int32(0));
EXPECT_EQ(1, m.repeated_string_size());
EXPECT_EQ("asdf", m.repeated_string(0));
EXPECT_EQ(1, m.repeated_bytes_size());
EXPECT_EQ("jkl;", m.repeated_bytes(0));
EXPECT_EQ(1, m.repeated_nested_message_size());
EXPECT_EQ(46, m.repeated_nested_message(0).bb());
EXPECT_EQ(1, m.repeated_foreign_message_size());
EXPECT_EQ(47, m.repeated_foreign_message(0).c());
EXPECT_EQ(1, m.repeated_nested_enum_size());
EXPECT_EQ(proto3_arena_unittest::TestAllTypes_NestedEnum_BAZ,
m.repeated_nested_enum(0));
EXPECT_EQ(1, m.repeated_foreign_enum_size());
EXPECT_EQ(proto3_arena_unittest::FOREIGN_BAZ,
m.repeated_foreign_enum(0));
EXPECT_EQ(1, m.repeated_lazy_message_size());
EXPECT_EQ(49, m.repeated_lazy_message(0).bb());
EXPECT_EQ(proto3_arena_unittest::TestAllTypes::kOneofString,
m.oneof_field_case());
EXPECT_EQ("test", m.oneof_string());
}
// In this file we only test some basic functionalities of arena support in
// proto3 and expect the arena support to be fully tested in proto2 unittests
// because proto3 shares most code with proto2.
TEST(Proto3ArenaTest, Parsing) {
TestAllTypes original;
SetAllFields(&original);
Arena arena;
TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
arena_message->ParseFromString(original.SerializeAsString());
ExpectAllFieldsSet(*arena_message);
}
TEST(Proto3ArenaTest, UnknownFields) {
TestAllTypes original;
SetAllFields(&original);
Arena arena;
TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
arena_message->ParseFromString(original.SerializeAsString());
ExpectAllFieldsSet(*arena_message);
// In proto3 we can still get a pointer to the UnknownFieldSet through
// reflection API.
UnknownFieldSet* unknown_fields =
arena_message->GetReflection()->MutableUnknownFields(arena_message);
// We can modify this UnknownFieldSet.
unknown_fields->AddVarint(1, 2);
// But the change will never will serialized back.
ASSERT_EQ(original.ByteSize(), arena_message->ByteSize());
ASSERT_TRUE(
arena_message->GetReflection()->GetUnknownFields(*arena_message).empty());
}
TEST(Proto3ArenaTest, Swap) {
Arena arena1;
Arena arena2;
// Test Swap().
TestAllTypes* arena1_message = Arena::CreateMessage<TestAllTypes>(&arena1);
TestAllTypes* arena2_message = Arena::CreateMessage<TestAllTypes>(&arena2);
arena1_message->Swap(arena2_message);
EXPECT_EQ(&arena1, arena1_message->GetArena());
EXPECT_EQ(&arena2, arena2_message->GetArena());
}
TEST(Proto3ArenaTest, SetAllocatedMessage) {
Arena arena;
TestAllTypes *arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
TestAllTypes::NestedMessage* nested = new TestAllTypes::NestedMessage;
nested->set_bb(118);
arena_message->set_allocated_optional_nested_message(nested);
EXPECT_EQ(118, arena_message->optional_nested_message().bb());
}
TEST(Proto3ArenaTest, ReleaseMessage) {
Arena arena;
TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
arena_message->mutable_optional_nested_message()->set_bb(118);
google::protobuf::scoped_ptr<TestAllTypes::NestedMessage> nested(
arena_message->release_optional_nested_message());
EXPECT_EQ(118, nested->bb());
}
TEST(Proto3ArenaTest, MessageFieldClear) {
// GitHub issue #310: https://github.com/google/protobuf/issues/310
Arena arena;
TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
arena_message->mutable_optional_nested_message()->set_bb(118);
// This should not crash, but prior to the bugfix, it tried to use `operator
// delete` the nested message (which is on the arena):
arena_message->Clear();
}
TEST(Proto3ArenaTest, MessageFieldClearViaReflection) {
Arena arena;
TestAllTypes* message = Arena::CreateMessage<TestAllTypes>(&arena);
const Reflection* r = message->GetReflection();
const Descriptor* d = message->GetDescriptor();
const FieldDescriptor* msg_field = d->FindFieldByName(
"optional_nested_message");
message->mutable_optional_nested_message()->set_bb(1);
r->ClearField(message, msg_field);
EXPECT_FALSE(message->has_optional_nested_message());
EXPECT_EQ(0, message->optional_nested_message().bb());
}
} // namespace
} // namespace protobuf
} // namespace google
|
// Copyright (c) 2014 Dropbox, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <cstdio>
#include <cstdlib>
#include <cxxabi.h>
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "Usage: %s IDENTIFIER\n", argv[0]);
exit(1);
}
int status;
char* demangled = abi::__cxa_demangle(argv[1], NULL, NULL, &status);
if (demangled) {
printf("%s\n", demangled);
} else {
fprintf(stderr, "Error: unable to demangle\n");
exit(1);
}
return 0;
}
|
class Solution {
public:
int missingNumber(vector<int> &nums) {
int n = nums.size();
for (int i = 0; i < n; i++) {
if (nums[i] < n && nums[i] != i) {
int t = nums[nums[i]];
nums[nums[i]] = nums[i];
nums[i] = t;
i--;
}
}
for (int i = 0; i < n; i++)
if (nums[i] != i)
return i;
return n;
}
};
|
/**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file physxConvexMesh.cxx
* @author enn0x
* @date 2009-10-13
*/
#include "physxConvexMesh.h"
#include "physxMeshPool.h"
TypeHandle PhysxConvexMesh::_type_handle;
/**
*
*/
void PhysxConvexMesh::
link(NxConvexMesh *meshPtr) {
// Link self
PhysxManager::get_global_ptr()->_convex_meshes.add(this);
_ptr = meshPtr;
_error_type = ET_ok;
}
/**
*
*/
void PhysxConvexMesh::
unlink() {
// Unlink self
_error_type = ET_released;
PhysxManager::get_global_ptr()->_convex_meshes.remove(this);
}
/**
*
*/
void PhysxConvexMesh::
release() {
nassertv(_error_type == ET_ok);
unlink();
NxGetPhysicsSDK()->releaseConvexMesh(*_ptr);
_ptr = nullptr;
PhysxMeshPool::release_convex_mesh(this);
}
/**
* Returns the reference count for shared meshes.
*/
unsigned int PhysxConvexMesh::
get_reference_count() const {
nassertr(_error_type == ET_ok, 0);
return _ptr->getReferenceCount();
}
|
/*******************************************************************************
* Filename : fpucpacrregisters.hpp
*
* Details : Floating point unit CPACR. This header file is auto-generated
* for STM32F411 device.
*
*
*******************************************************************************/
#if !defined(FPUCPACRREGISTERS_HPP)
#define FPUCPACRREGISTERS_HPP
#include "fpucpacrfieldvalues.hpp" //for Bits Fields defs
#include "registerbase.hpp" //for RegisterBase
#include "register.hpp" //for Register
#include "accessmode.hpp" //for ReadMode, WriteMode, ReadWriteMode
struct FPU_CPACR
{
struct FPU_CPACRCPACRBase {} ;
struct CPACR : public RegisterBase<0xE000ED88, 32, ReadWriteMode>
{
using CP = FPU_CPACR_CPACR_CP_Values<FPU_CPACR::CPACR, 20, 4, ReadWriteMode, FPU_CPACRCPACRBase> ;
using FieldValues = FPU_CPACR_CPACR_CP_Values<FPU_CPACR::CPACR, 0, 0, NoAccess, NoAccess> ;
} ;
template<typename... T>
using CPACRPack = Register<0xE000ED88, 32, ReadWriteMode, FPU_CPACRCPACRBase, T...> ;
} ;
#endif //#if !defined(FPUCPACRREGISTERS_HPP)
|
// @@@ START COPYRIGHT @@@
//
// 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.
//
// @@@ END COPYRIGHT @@@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/time.h>
#include <signal.h>
#include "seabed/trace.h"
#include "dtm/tm_util.h"
#include "tmtxkey.h"
#include "tmlogging.h"
#include "hbasetm.h"
#include "javaobjectinterfacetm.h"
// Externals
using namespace std;
// Globals
CHbaseTM gv_HbaseTM;
HBASETM_TraceMask gv_HBASETM_traceMask; // HBase TM tracing Mask. 0 = no tracing (default)
#define SQ_LIO_SIGNAL_REQUEST_REPLY (SIGRTMAX - 4)
static int tm_rtsigblock_proc() {
sigset_t lv_sig_set;
// Setup signal handling
sigemptyset(&lv_sig_set);
sigaddset(&lv_sig_set, SQ_LIO_SIGNAL_REQUEST_REPLY);
int err = pthread_sigmask(SIG_BLOCK, &lv_sig_set, NULL);
if (err)
abort();
return 0;
}
short HBasetoTxnError(short pv_HBerr)
{
switch (pv_HBerr)
{
case RET_OK: return FEOK;
case RET_NOTX: return FENOTRANSID;
case RET_READONLY: return FEOK; //Read-only reply is ok
case RET_ADD_PARAM: return FEBOUNDSERR;
case RET_EXCEPTION: return FETRANSEXCEPTION;
case RET_HASCONFLICT: return FELOCKED; //Change to FEHASCONFLICT?
case RET_IOEXCEPTION: return FETRANSIOEXCEPTION;
case RET_NOCOMMITEX: return FEABORTEDTRANSID;
default: return FETRANSERRUNKNOWN;
}
}
// ---------------------------------------------------------------
// HbaseTM_initialize
// Purpose - Initialize HBase-trx in a client.
// ---------------------------------------------------------------
int HbaseTM_initialize (short pv_nid)
{
int lv_error = gv_HbaseTM.initialize(pv_nid);
return lv_error;
}
// ---------------------------------------------------------------
// HbaseTM_initialize (2)
// Purpose - Initialize the HBase-trx TM Library.
// ---------------------------------------------------------------
int HbaseTM_initialize (bool pp_tracing, bool pv_tm_stats, CTmTimer *pp_tmTimer, short pv_nid)
{
int lv_error = 0;
union {
HBASETM_TraceMask lv_traceMask;
int lv_traceMaskInt;
} u;
//initialize trace file
char * lp_traceString = (char *) ms_getenv_str("HBASETM_TRACE");
char * lp_traceStringEnd;
if (pp_tracing != 0 && lp_traceString)
{
lp_traceStringEnd = lp_traceString + strlen(lp_traceString);
if (lp_traceStringEnd == NULL)
{
// tm_log_event(DTM_XMAPI_INVALID_STRING_SIZE, SQ_LOG_CRIT, "DTM_XMAPI_INVALID_STRING_SIZE");
// Make sure the lp_traceStringEnd pointer points to the null terminator.
abort();
}
//Convert hexadecimal string to int
unsigned long lv_traceMaskul = strtoul(lp_traceString, &lp_traceStringEnd, 16);
u.lv_traceMaskInt = (int) lv_traceMaskul;
}
else
u.lv_traceMask = HBASETM_TraceOff;
lv_error = gv_HbaseTM.initialize(u.lv_traceMask, pv_tm_stats, pp_tmTimer, pv_nid);
HBASETrace((lv_error?HBASETM_TraceAPIExitError:HBASETM_TraceAPIExit),
(HDR ": HbaseTM_initialize EXIT returning %d\n", lv_error));
return lv_error;
} // HbaseTM_initialize
//----------------------------------------------------------------
// HbaseTM_initiate_cp
// Purpose - Initiate control point
//----------------------------------------------------------------
void HbaseTM_initiate_cp()
{
gv_HbaseTM.addControlPoint();
}
//----------------------------------------------------------------
// HbaseTM_initiate_stall
// Purpose - Initiate stall in phase 2
//----------------------------------------------------------------
void HbaseTM_initiate_stall(int where)
{
cout << "HbaseTM_initiate_stall called with parameter " << where << "\n";
gv_HbaseTM.stall(where);
}
//----------------------------------------------------------------
// HbaseTM_process_request_regions_info
// Purpose: Retrieve region info for dtmci
//---------------------------------------------------------------
HashMapArray* HbaseTM_process_request_regions_info()
{
cout << "Start HBaseTM_process_request_regions\n";
HashMapArray* mapArrayRegions = gv_HbaseTM.requestRegionInfo();
return mapArrayRegions;
}
// =============================================================
// ===== Class CHbaseTM
// =============================================================
jclass CHbaseTM::javaClass_ = 0;
// CHbaseTM Methods
// TM Default Constructor
// CHbaseTM Methods
// TM Default Constructor
CHbaseTM::CHbaseTM() : JavaObjectInterfaceTM()
{
tm_rtsigblock_proc();
// cout << "CHbaseTM::CHbaseTM() called\n";
// Mutex attributes: Recursive = true, ErrorCheck=false
// ip_mutex = new TM_Mutex(true, false);
iv_tm_stats = false;
lock();
iv_initialized = false;
my_nid(-1); // Indicates that the node hasn't been set yet.
iv_traceMask = HBASETM_TraceOff;
ip_tmTimer = NULL;
iv_next_msgNum = 1;
// Need to check return and handle error
int lv_result = initJVM();
if(lv_result != JOI_OK) {
tm_log_write(DTM_SEA_SOFT_FAULT, SQ_LOG_CRIT, (char *)"CHbaseTM::CHbaseTM()-1", (char *) _tlp_error_msg->c_str(), -1LL);
abort();
}
unlock();
}
// TM Destructor
CHbaseTM::~CHbaseTM()
{
//delete ip_mutex;
HBASETrace(HBASETM_TraceExit, (HDR ": CHbaseTM::~CHbaseTM Exit.\n"));
}
int CHbaseTM::initJVM()
{
JavaMethods_[JM_CTOR ].jm_name = "<init>";
JavaMethods_[JM_CTOR ].jm_signature = "()V";
JavaMethods_[JM_INIT1 ].jm_name = "init";
JavaMethods_[JM_INIT1 ].jm_signature = "(S)Z";
JavaMethods_[JM_BEGIN ].jm_name = "beginTransaction";
JavaMethods_[JM_BEGIN ].jm_signature = "(J)J";
JavaMethods_[JM_ABORT ].jm_name = "abortTransaction";
JavaMethods_[JM_ABORT ].jm_signature = "(J)S";
JavaMethods_[JM_PRECOMMIT ].jm_name = "prepareCommit";
JavaMethods_[JM_PRECOMMIT ].jm_signature = "(J)S";
JavaMethods_[JM_DOCOMMIT ].jm_name = "doCommit";
JavaMethods_[JM_DOCOMMIT ].jm_signature = "(J)S";
JavaMethods_[JM_TRYCOMMIT ].jm_name = "tryCommit";
JavaMethods_[JM_TRYCOMMIT ].jm_signature = "(J)S";
JavaMethods_[JM_COMPLETEREQUEST].jm_name = "completeRequest";
JavaMethods_[JM_COMPLETEREQUEST].jm_signature = "(J)S";
JavaMethods_[JM_REGREGION ].jm_name = "callRegisterRegion";
JavaMethods_[JM_REGREGION ].jm_signature = "(JJI[BJ[B)S";
JavaMethods_[JM_PARREGION ].jm_name = "participatingRegions";
JavaMethods_[JM_PARREGION ].jm_signature = "(J)I";
JavaMethods_[JM_CNTPOINT ].jm_name = "addControlPoint";
JavaMethods_[JM_CNTPOINT ].jm_signature = "()J";
JavaMethods_[JM_STALL ].jm_name = "stall";
JavaMethods_[JM_STALL ].jm_signature = "(I)S";
JavaMethods_[JM_NODEDOWN ].jm_name = "nodeDown";
JavaMethods_[JM_NODEDOWN ].jm_signature = "(I)V";
JavaMethods_[JM_NODEUP ].jm_name = "nodeUp";
JavaMethods_[JM_NODEUP ].jm_signature = "(I)V";
JavaMethods_[JM_CREATETABLE ].jm_name = "callCreateTable";
JavaMethods_[JM_CREATETABLE ].jm_signature = "(J[B[Ljava/lang/Object;)S";
JavaMethods_[JM_ALTERTABLE ].jm_name = "callAlterTable";
JavaMethods_[JM_ALTERTABLE ].jm_signature = "(J[B[Ljava/lang/Object;)S";
JavaMethods_[JM_REGTRUNCABORT].jm_name = "callRegisterTruncateOnAbort";
JavaMethods_[JM_REGTRUNCABORT].jm_signature = "(J[B)S";
JavaMethods_[JM_DROPTABLE ].jm_name = "callDropTable";
JavaMethods_[JM_DROPTABLE ].jm_signature = "(J[B)S";
JavaMethods_[JM_RQREGINFO ].jm_name = "callRequestRegionInfo";
JavaMethods_[JM_RQREGINFO ].jm_signature = "()Lorg/trafodion/dtm/HashMapArray;";
char className[]="org/trafodion/dtm/HBaseTxClient";
return (HBTM_RetCode)JavaObjectInterfaceTM::init(className, javaClass_, (JavaMethodInit*)&JavaMethods_, (int)JM_LAST, false);
}
//////////////////////////////////////////////
// JNI Methods //
//////////////////////////////////////////////
short CHbaseTM::initConnection(short pv_nid)
{
jshort jdtmid = pv_nid;
jboolean jresult = _tlp_jenv->CallBooleanMethod(javaObj_, JavaMethods_[JM_INIT1].methodID, jdtmid);
if (getExceptionDetails(NULL)) {
tm_log_write(DTM_SEA_SOFT_FAULT, SQ_LOG_CRIT, (char *)"CHbaseTM::initConnection()", (char *) _tlp_error_msg->c_str(), -1LL);
return RET_EXCEPTION;
}
if (jresult == false)
{
return RET_LAST;
}
return RET_OK;
}
short CHbaseTM::addControlPoint() {
JOI_RetCode lv_joi_retcode = JOI_OK;
lv_joi_retcode = initJNIEnv();
if (lv_joi_retcode != JOI_OK) {
tm_log_write(DTM_SEA_SOFT_FAULT, SQ_LOG_CRIT, (char *)"CHbaseTM::addControlPoint()", (char *)_tlp_error_msg->c_str(), -1LL);
abort();
}
jlong jresult = _tlp_jenv->CallLongMethod(javaObj_, JavaMethods_[JM_CNTPOINT].methodID);
if (getExceptionDetails(NULL)) {
tm_log_write(DTM_SEA_SOFT_FAULT, SQ_LOG_CRIT, (char *)"CHbaseTM::addControlPoint()", (char *)_tlp_error_msg->c_str(), -1LL);
_tlp_jenv->PopLocalFrame(NULL);
return RET_EXCEPTION;
}
_tlp_jenv->PopLocalFrame(NULL);
if (jresult == 0L) {
return RET_EXCEPTION;
}
return RET_OK;
}
short CHbaseTM::beginTransaction(int64 *pp_transid) {
jlong jlv_transid = *pp_transid;
JOI_RetCode lv_joi_retcode = JOI_OK;
lv_joi_retcode = initJNIEnv();
if (lv_joi_retcode != JOI_OK) {
tm_log_write(DTM_SEA_SOFT_FAULT, SQ_LOG_CRIT, (char *)"CHbaseTM::beginTransaction()", (char *)_tlp_error_msg->c_str(), -1LL);
abort();
}
jlong jresult = _tlp_jenv->CallLongMethod(javaObj_, JavaMethods_[JM_BEGIN].methodID, jlv_transid);
if (getExceptionDetails(NULL)) {
tm_log_write(DTM_TM_JNI_ERROR, SQ_LOG_ERR, (char *)"CHbaseTM::beginTransaction()", (char *)_tlp_error_msg->c_str(), *pp_transid);
_tlp_jenv->PopLocalFrame(NULL);
return RET_EXCEPTION;
}
*pp_transid = (long)jresult;
_tlp_jenv->PopLocalFrame(NULL);
return RET_OK;
}
short CHbaseTM::abortTransaction(int64 pv_transid) {
jlong jlv_transid = pv_transid;
JOI_RetCode lv_joi_retcode = JOI_OK;
lv_joi_retcode = initJNIEnv();
if (lv_joi_retcode != JOI_OK) {
tm_log_write(DTM_SEA_SOFT_FAULT, SQ_LOG_CRIT, (char *)"CHbaseTM::abortTransaction()", (char *)_tlp_error_msg->c_str(), -1LL);
abort();
}
jshort jresult = _tlp_jenv->CallShortMethod(javaObj_, JavaMethods_[JM_ABORT].methodID, jlv_transid);
if (getExceptionDetails(NULL)) {
tm_log_write(DTM_TM_JNI_ERROR, SQ_LOG_ERR, (char *)"CHbaseTM::abortTransaction()", (char *)_tlp_error_msg->c_str(), pv_transid);
_tlp_jenv->PopLocalFrame(NULL);
return RET_EXCEPTION;
}
_tlp_jenv->PopLocalFrame(NULL);
// RET_NOTX means the transaction wasn't found by the HBase client code (trx). This is ok here, it
// simply means the transaction hasn't been seen by the HBase client code, so no work was done on it.
if (jresult == RET_NOTX)
{
return RET_OK;
}
return jresult;
}
short CHbaseTM::prepareCommit(int64 pv_transid , char *errstr, int &errstrlen) {
jlong jlv_transid = pv_transid;
JOI_RetCode lv_joi_retcode = JOI_OK;
lv_joi_retcode = initJNIEnv();
if (lv_joi_retcode != JOI_OK) {
tm_log_write(DTM_SEA_SOFT_FAULT, SQ_LOG_CRIT, (char *)"CHbaseTM::prepareCommit()", (char *)_tlp_error_msg->c_str(), -1LL);
abort();
}
jshort jresult = _tlp_jenv->CallShortMethod(javaObj_, JavaMethods_[JM_PRECOMMIT].methodID, jlv_transid);
if (getExceptionDetails(NULL, (short*)&lv_joi_retcode)) {
int errMsgLen = (int)_tlp_error_msg->length();
errstrlen = ((errMsgLen < errstrlen) && (errMsgLen > 0)) ? errMsgLen : errstrlen -1;
strncpy(errstr, _tlp_error_msg->c_str(), errstrlen);
errstr[errstrlen] = '\0';
tm_log_write(DTM_TM_JNI_ERROR, SQ_LOG_ERR,(char*)"CHbaseTM::prepareCommit()", (char *)_tlp_error_msg->c_str(), pv_transid);
//If an exception is received, it is only due to some issue.
//Exception can come back with error code set or not set.
//If there is an error code passed as part of exception, pass this
//back to my caller. Else return RET_EXCEPTION;
if(lv_joi_retcode != JOI_OK)
jresult = lv_joi_retcode;
else
{
_tlp_jenv->PopLocalFrame(NULL);
return RET_EXCEPTION;
}
}
_tlp_jenv->PopLocalFrame(NULL);
if (jresult <= RET_LAST) {
return jresult;
}
// For building
if(pv_transid)
return RET_OK;
return RET_OK;
}
short CHbaseTM::doCommit(int64 pv_transid) {
jlong jlv_transid = pv_transid;
JOI_RetCode lv_joi_retcode = JOI_OK;
lv_joi_retcode = initJNIEnv();
if (lv_joi_retcode != JOI_OK) {
tm_log_write(DTM_SEA_SOFT_FAULT, SQ_LOG_CRIT, (char *)"CHbaseTM::doCommit()", (char *)_tlp_error_msg->c_str(), -1LL);
abort();
}
jshort jresult = _tlp_jenv->CallShortMethod(javaObj_, JavaMethods_[JM_DOCOMMIT].methodID, jlv_transid);
if (getExceptionDetails(NULL)) {
tm_log_write(DTM_TM_JNI_ERROR, SQ_LOG_ERR, (char *)"CHbaseTM::doCommit()", (char *)_tlp_error_msg->c_str(), pv_transid);
_tlp_jenv->PopLocalFrame(NULL);
return RET_EXCEPTION;
}
_tlp_jenv->PopLocalFrame(NULL);
if (jresult == 1)
{
// jresult from abort java method - 1 is error
return RET_ADD_PARAM;
}
// For building
if(pv_transid) {
return RET_OK;
}
return RET_OK;
}
short CHbaseTM::tryCommit(int64 pv_transid) {
jlong jlv_transid = pv_transid;
JOI_RetCode lv_joi_retcode = JOI_OK;
lv_joi_retcode = initJNIEnv();
if (lv_joi_retcode != JOI_OK) {
tm_log_write(DTM_SEA_SOFT_FAULT, SQ_LOG_CRIT, (char *)"CHbaseTM::tryCommit()", (char *)_tlp_error_msg->c_str(), -1LL);
abort();
}
jshort jresult = _tlp_jenv->CallShortMethod(javaObj_, JavaMethods_[JM_TRYCOMMIT].methodID, jlv_transid);
if (getExceptionDetails(NULL)) {
tm_log_write(DTM_TM_JNI_ERROR, SQ_LOG_ERR, (char *)"CHbaseTM::tryCommit()", (char *)_tlp_error_msg->c_str(), pv_transid);
return RET_EXCEPTION;
}
_tlp_jenv->PopLocalFrame(NULL);
// RET_NOTX means the transaction wasn't found by the HBase client code (trx). This is ok here, it
// simply means the transaction hasn't been seen by the HBase client code, so no work was done on it.
if (jresult == RET_NOTX)
{
return RET_OK;
}
return jresult;
}
short CHbaseTM::completeRequest(int64 pv_transid) {
jlong jlv_transid = pv_transid;
JOI_RetCode lv_joi_retcode = JOI_OK;
lv_joi_retcode = initJNIEnv();
if (lv_joi_retcode != JOI_OK) {
tm_log_write(DTM_SEA_SOFT_FAULT, SQ_LOG_CRIT, (char *)"CHbaseTM::completeRequest()", (char *)_tlp_error_msg->c_str(), -1LL);
abort();
}
jshort jresult = _tlp_jenv->CallShortMethod(javaObj_, JavaMethods_[JM_COMPLETEREQUEST].methodID, jlv_transid);
if (getExceptionDetails(NULL)) {
tm_log_write(DTM_TM_JNI_ERROR, SQ_LOG_ERR, (char *)"CHbaseTM::completeRequest()", (char *)_tlp_error_msg->c_str(), pv_transid);
_tlp_jenv->PopLocalFrame(NULL);
return RET_EXCEPTION;
}
_tlp_jenv->PopLocalFrame(NULL);
if (jresult == 1)
{
// jresult from abort java method - 1 is error
return RET_ADD_PARAM;
}
// For building
if(pv_transid) {
return RET_OK;
}
return RET_OK;
}
// TM lock semaphore
void CHbaseTM::lock()
{
/*
HBASETrace(HBASETM_TraceLock, (HDR ": CHbaseTM::lock, count %d, owner %ld\n",
ip_mutex->lock_count(), ip_mutex->lock_owner()));
int lv_error = ip_mutex->lock();
if (lv_error)
{
//HBASETrace(HBASETM_TraceError, (HDR ": CHbaseTM::lock returned error %d.\n", lv_error));
//::abort();
}
*/
}
// CHbaseTM::setAndGetNid
// Get the node number
// The first time this is called it will retrieve the value from
// the Monitor.
inline int CHbaseTM::setAndGetNid()
{
lock();
if (my_nid() == -1)
{
msg_mon_get_process_info(NULL, &iv_my_nid, &iv_my_pid);
}
unlock();
return my_nid();
} //setAndGetNid
// CHbaseTM::initialize
// Initialize the CHbaseTM object
//
int CHbaseTM::initialize(short pv_nid)
{
return initialize(HBASETM_TraceOff, false, NULL, pv_nid);
}
// CHbaseTM::initialize
// Initialize the CHbaseTM object
//
int CHbaseTM::initialize(HBASETM_TraceMask pv_traceMask, bool pv_tm_stats, CTmTimer *pp_tmTimer, short pv_nid)
{
int lv_error = 0;
setTrace(pv_traceMask);
lock();
// gv_HbaseTM.setTrace(pv_traceMask);
iv_tm_stats = pv_tm_stats;
if (pp_tmTimer != NULL)
{
ip_tmTimer = pp_tmTimer;
//gv_startTime = ip_tmTimer->startTime();
}
else
{
ip_tmTimer = NULL;
//gv_startTime = Ctimeval::now();
}
lv_error = initConnection(pv_nid);
if (lv_error)
{
printf("CHbaseTM::initialize: CHbaseTM::initConnection failed with error %d.\n", lv_error);
HBASETrace(HBASETM_TraceError,
(HDR "CHbaseTM::initialize: CHbaseTM::initConnection failed with error %d.\n", lv_error));
//tm_log_event(DTM_HBASE_INIT_FAILED, SQ_LOG_CRIT, "DTM_HBASE_INIT_FAILED", lv_error);
abort();
}
else
HBASETrace(HBASETM_TraceDetail,
(HDR "CHbaseTM::initialize: CHbaseTM::initConnection succeeded.\n"));
if (lv_error)
abort();
else
iv_initialized = true;
unlock();
HBASETrace(HBASETM_TraceExitError,
(HDR "CHbaseTM::initialize EXIT returning %d.\n", lv_error));
return lv_error;
} //CHbase::initialize
// TM unlock semaphore
void CHbaseTM::unlock()
{
/*
HBASETrace(HBASETM_TraceLock, (HDR ": CHbaseTM::unlock, count %d, owner %ld\n",
ip_mutex->lock_count(), ip_mutex->lock_owner()));
int lv_error = ip_mutex->unlock();
if (lv_error)
{
HBASETrace(HBASETM_TraceError, (HDR ": CHbaseTM::unlock returned error %d.\n", lv_error));
abort();
}
*/
}
// TM Trace
// Returns the value of iv_trace.
bool CHbaseTM::Trace(HBASETM_TraceMask pv_traceMask)
{
return ((pv_traceMask & iv_traceMask)? true: false);
}
// TM setTrace
// Sets the value of iv_traceMask.
// Note that because this is a mask it is concatenated to the mask unless
// set to 0. Ie:
// If pv_traceMask == 0, set iv_traceMask = 0
// If pv_traceMask > 0, iv_traceMask |= pv_traceMask; (bit-wise OR)
void CHbaseTM::setTrace(HBASETM_TraceMask pv_traceMask)
{
HBASETM_TraceMask iv_OldMask = iv_traceMask;
lock();
if (pv_traceMask == HBASETM_TraceOff)
iv_traceMask = HBASETM_TraceOff;
else
iv_traceMask = (HBASETM_TraceMask) (iv_traceMask | pv_traceMask);
gv_HBASETM_traceMask = iv_traceMask;
unlock();
// Don't use HBASETrace here as we always want to write the trace record.
if (iv_OldMask != HBASETM_TraceOff && pv_traceMask == HBASETM_TraceOff)
trace_printf(HDR ":Tracing off.\n");
else
if (pv_traceMask != HBASETM_TraceOff)
trace_printf(HDR ": Tracing on, Mask=0x%x.\n", iv_traceMask);
} //Trace
//----------------------------------------------------------------------------
// CHbaseTM::registerRegion
// Purpose : Register a region for the specified transaction.
//----------------------------------------------------------------------------
int CHbaseTM::registerRegion(int64 pv_transid,
int64 pv_startid,
int pv_port,
const char pa_hostname[],
int pv_hostname_Length,
long pv_startcode,
const char *pa_regionInfo,
int pv_regionInfo_Length)
{
int lv_error = FEOK;
jlong jlv_transid = pv_transid;
jlong jlv_startid = pv_startid;
jint jiv_port = pv_port;
CTmTxKey lv_tid(pv_transid);
HBASETrace(HBASETM_TraceAPI, (HDR "CHbaseTM::registerRegion : Txn ID (%d,%d), startid %ld, hostname: %s.\n",
lv_tid.node(), lv_tid.seqnum(), jlv_startid, pa_hostname));
JOI_RetCode lv_joi_retcode = JOI_OK;
lv_joi_retcode = initJNIEnv();
if (lv_joi_retcode != JOI_OK) {
tm_log_write(DTM_SEA_SOFT_FAULT, SQ_LOG_CRIT, (char *)"CHbaseTM::registerRegion()", (char *)_tlp_error_msg->c_str(), -1LL);
abort();
}
jbyteArray jba_hostname = _tlp_jenv->NewByteArray(pv_hostname_Length+1);
if (jba_hostname == NULL) {
_tlp_jenv->PopLocalFrame(NULL);
return RET_ADD_PARAM;
}
_tlp_jenv->SetByteArrayRegion(jba_hostname, 0, pv_hostname_Length, (const jbyte*) pa_hostname);
jbyteArray jba_regionInfo = _tlp_jenv->NewByteArray(pv_regionInfo_Length);
if (jba_regionInfo == NULL) {
_tlp_jenv->PopLocalFrame(NULL);
return RET_ADD_PARAM;
}
_tlp_jenv->SetByteArrayRegion(jba_regionInfo, 0, pv_regionInfo_Length, (const jbyte*)pa_regionInfo);
// printf("JavaObjectInterfaceTM::registerRegion calling client callRegisterRegion with trans: %ld and startid: %ld\n", jlv_transid, jlv_startid);
lv_error = _tlp_jenv->CallShortMethod(javaObj_,
JavaMethods_[JM_REGREGION].methodID,
jlv_transid,
jlv_startid,
jiv_port,
jba_hostname,
pv_startcode,
jba_regionInfo);
if (getExceptionDetails(NULL)) {
tm_log_write(DTM_TM_JNI_ERROR, SQ_LOG_ERR, (char *)"CHbaseTM::registerRegion()", (char *)_tlp_error_msg->c_str(), pv_transid);
_tlp_jenv->PopLocalFrame(NULL);
return RET_EXCEPTION;
}
HBASETrace(HBASETM_TraceExit, (HDR "CHbaseTM::registerRegion : Error %d, Txn ID (%d,%d), hostname %s.\n",
lv_error, lv_tid.node(), lv_tid.seqnum(), pa_hostname));
_tlp_jenv->PopLocalFrame(NULL);
return lv_error;
} //CHbaseTM::registerRegion
//----------------------------------------------------------------------------
// CHbaseTM::recoverRegion
// Purpose : Recover a region for the specified transaction.
// pp_count :input Maximum number of transids to be returned in a single reply
// :output Number of transids returned
// Replies will contain transaction lists for a single region only. It is assumed that all transactions for a region will be contained
// within the array pointed to by pp_transidList.
// pp_flags as per xa_recover flags:
// TMSTARTRSCAN 0x01000000LL /* start a recovery scan */
// TMENDRSCAN 0x00800000LL /* end a recovery scan */
// TMRESENDRSCAN 0x00010000LL
// TMRMFAILRSCAN 0x00001000LL
// When TMRESENDRSCAN is specified pp_region must contain a valid region name. This is used to retrieve indoubt transactions
// for a specific region following a region failure.
//----------------------------------------------------------------------------
int CHbaseTM::recoverRegion(int64 *pp_count, int64 *pp_transidList[], int64 *pp_flags)
{
int lv_error = FEOK;
HBASETrace(HBASETM_TraceAPI, (HDR "CHbaseTM::recoverRegion : Count " PFLL ", flags " PFLLX ".\n",
*pp_count, *pp_flags));
//!@# TODO
HBASETrace(HBASETM_TraceExit, (HDR "CHbaseTM::recoverRegion : Error %d, Count " PFLL ", flags " PFLLX ".\n",
lv_error, *pp_count, *pp_flags));
return lv_error;
} //CHbaseTM::recoverRegion
//----------------------------------------------------------------------------
// CHbaseTM::failedRegions
// Purpose : Returns the number of failed regions for
// the specified transaction.
// Currently not supported.
//----------------------------------------------------------------------------
int CHbaseTM::failedRegions(int64 pv_transid)
{
int lv_failedCount = 0;
CTmTxKey lv_transid(pv_transid);
HBASETrace(HBASETM_TraceAPI, (HDR "CHbaseTM::failedRegions : Txn ID (%d,%d).\n", lv_transid.node(), lv_transid.seqnum()));
HBASETrace(HBASETM_TraceExit, (HDR "CHbaseTM::failedRegions : Count %d.\n", lv_failedCount));
return lv_failedCount;
} //CHbaseTM::failedRegions
//----------------------------------------------------------------------------
// CHbaseTM::participatingRegions
// Purpose : Returns the number of failed regions for
// the specified transaction.
// Currently yet supported.
//----------------------------------------------------------------------------
int CHbaseTM::participatingRegions(int64 pv_transid)
{
jlong lv_transid_j = pv_transid;
jint lv_participating = 0;
int lv_participatingCount = 0;
CTmTxKey lv_transid(pv_transid);
HBASETrace(HBASETM_TraceAPI, (HDR "CHbaseTM::participatingRegions : Txn ID (%d,%d).\n", lv_transid.node(), lv_transid.seqnum()));
JOI_RetCode lv_joi_retcode = JOI_OK;
lv_joi_retcode = initJNIEnv();
if (lv_joi_retcode != JOI_OK) {
tm_log_write(DTM_SEA_SOFT_FAULT, SQ_LOG_CRIT, (char *)"CHbaseTM::participatingRegions()", (char *)_tlp_error_msg->c_str(), -1LL);
abort();
}
lv_participating = _tlp_jenv->CallIntMethod(javaObj_, JavaMethods_[JM_PARREGION].methodID, lv_transid_j);
if (getExceptionDetails(NULL)) {
tm_log_write(DTM_TM_JNI_ERROR, SQ_LOG_ERR, (char *)"CHbaseTM::participatingRegions()", (char *)_tlp_error_msg->c_str(), pv_transid);
lv_participatingCount = -1;
}
_tlp_jenv->PopLocalFrame(NULL);
lv_participatingCount = lv_participating;
HBASETrace(HBASETM_TraceExit, (HDR "CHbaseTM::participatingRegions : Count %d.\n", lv_participatingCount));
return lv_participatingCount;
} //CHbaseTM::participatingRegions
//----------------------------------------------------------------------------
// CHbaseTM::unresolvedRegions
// Purpose : Returns the number of failed regions for
// the specified transaction.
// Currently yet supported.
//----------------------------------------------------------------------------
int CHbaseTM::unresolvedRegions(int64 pv_transid)
{
int lv_unresolvedCount = 0;
CTmTxKey lv_transid(pv_transid);
HBASETrace(HBASETM_TraceAPI, (HDR "CHbaseTM::unresolvedRegions : Txn ID (%d,%d).\n", lv_transid.node(), lv_transid.seqnum()));
HBASETrace(HBASETM_TraceExit, (HDR "CHbaseTM::unresolvedRegions : Count %d.\n", lv_unresolvedCount));
return lv_unresolvedCount;
} //CHbaseTM::unresolvedRegions
short CHbaseTM::stall(int where){
jint jiv_where = where;
JOI_RetCode lv_joi_retcode = JOI_OK;
lv_joi_retcode = initJNIEnv();
if (lv_joi_retcode != JOI_OK) {
tm_log_write(DTM_SEA_SOFT_FAULT, SQ_LOG_CRIT, (char *)"CHbaseTM::stall()", (char *)_tlp_error_msg->c_str(), -1LL);
abort();
}
cout << "CHbaseTM::stall called with: " << jiv_where << "\n";
_tlp_jenv->CallShortMethod(javaObj_, JavaMethods_[JM_STALL].methodID, jiv_where);
if (getExceptionDetails(NULL)) {
tm_log_write(DTM_TM_JNI_ERROR, SQ_LOG_ERR, (char *)"CHbaseTM::stall()", (char *)_tlp_error_msg->c_str(), -1LL);
_tlp_jenv->PopLocalFrame(NULL);
return RET_EXCEPTION;
}
_tlp_jenv->PopLocalFrame(NULL);
return RET_OK;
}
short CHbaseTM::nodeDown(int32 nid){
jint jiv_nid = nid;
JOI_RetCode lv_joi_retcode = JOI_OK;
lv_joi_retcode = initJNIEnv();
if (lv_joi_retcode != JOI_OK) {
tm_log_write(DTM_SEA_SOFT_FAULT, SQ_LOG_CRIT, (char *)"CHbaseTM::nodeDown()", (char *)_tlp_error_msg->c_str(), -1LL);
abort();
}
cout << "CHbaseTM::nodeDown called with nodeId " << jiv_nid << "\n";
_tlp_jenv->CallShortMethod(javaObj_, JavaMethods_[JM_NODEDOWN].methodID, jiv_nid);
if (getExceptionDetails(NULL)) {
tm_log_write(DTM_TM_JNI_ERROR, SQ_LOG_ERR, (char *)"CHbaseTM::nodeDown()", (char *)_tlp_error_msg->c_str(), -1LL);
_tlp_jenv->PopLocalFrame(NULL);
return RET_EXCEPTION;
}
_tlp_jenv->PopLocalFrame(NULL);
return RET_OK;
}
short CHbaseTM::nodeUp(int32 nid){
jint jiv_nid = nid;
JOI_RetCode lv_joi_retcode = JOI_OK;
lv_joi_retcode = initJNIEnv();
if (lv_joi_retcode != JOI_OK) {
tm_log_write(DTM_SEA_SOFT_FAULT, SQ_LOG_CRIT, (char *)"CHbaseTM::nodeUp()", (char *)_tlp_error_msg->c_str(), -1LL);
abort();
}
cout << "CHbaseTM::nodeUp called with: " << jiv_nid << "\n";
_tlp_jenv->CallShortMethod(javaObj_, JavaMethods_[JM_NODEUP].methodID, jiv_nid);
if (getExceptionDetails(NULL)) {
tm_log_write(DTM_TM_JNI_ERROR, SQ_LOG_ERR, (char *)"CHbaseTM::nodeUp()", (char *)_tlp_error_msg->c_str(), -1LL);
_tlp_jenv->PopLocalFrame(NULL);
return RET_EXCEPTION;
}
_tlp_jenv->PopLocalFrame(NULL);
return RET_OK;
}
//----------------------------------------------------------------------------
// CHbaseTM: createTable
// Purpose: To handle create table transactional requests
//----------------------------------------------------------------------------
int CHbaseTM::createTable(int64 pv_transid,
const char* pa_tbldesc,
int pv_tbldesc_len,
char** pv_keys,
int pv_numsplits,
int pv_keylen,
char *errstr,
int &errstrlen)
{
int lv_error = FEOK;
jlong jlv_transid = pv_transid;
CTmTxKey lv_tid(pv_transid);
HBASETrace(HBASETM_TraceExitError,
(HDR "CHbaseTM::createTable returning %d.\n", lv_error));
JOI_RetCode lv_joi_retcode = JOI_OK;
lv_joi_retcode = initJNIEnv();
if (lv_joi_retcode != JOI_OK) {
tm_log_write(DTM_SEA_SOFT_FAULT, SQ_LOG_CRIT, (char *)"CHbaseTM::createTable()", (char *)_tlp_error_msg->c_str(), -1LL);
abort();
}
jbyteArray jba_tbldesc = _tlp_jenv->NewByteArray(pv_tbldesc_len);
if (jba_tbldesc == NULL) {
_tlp_jenv->PopLocalFrame(NULL);
return RET_ADD_PARAM;
}
_tlp_jenv->SetByteArrayRegion(jba_tbldesc, 0, pv_tbldesc_len, (const jbyte*) pa_tbldesc);
jobjectArray j_keys = NULL;
if (pv_numsplits > 0)
{
j_keys = convertToByteArrayObjectArray(pv_keys, pv_numsplits, pv_keylen);
}
lv_error = _tlp_jenv->CallShortMethod(javaObj_,
JavaMethods_[JM_CREATETABLE].methodID,
jlv_transid,
jba_tbldesc,
j_keys);
if (getExceptionDetails(NULL)) {
int errMsgLen = (int)_tlp_error_msg->length();
errstrlen = ((errMsgLen < errstrlen) && (errMsgLen > 0)) ? errMsgLen : errstrlen -1;
strncpy(errstr, _tlp_error_msg->c_str(), errstrlen);
errstr[errstrlen] = '\0';
tm_log_write(DTM_TM_JNI_ERROR, SQ_LOG_ERR, (char *)"CHbaseTM::createTable()", (char *)_tlp_error_msg->c_str(), pv_transid);
_tlp_jenv->PopLocalFrame(NULL);
return RET_EXCEPTION;
}
HBASETrace(HBASETM_TraceExit, (HDR "CHbaseTM::createTable : Error %d, Txn ID (%d,%d), hostname %s.\n",
lv_error, lv_tid.node(), lv_tid.seqnum(), pa_tbldesc));
_tlp_jenv->PopLocalFrame(NULL);
return lv_error;
}
//----------------------------------------------------------------------------
// CHbaseTM: alterTable
// Purpose: To handle alter table requests for hbase
//---------------------------------------------------------------------------
int CHbaseTM::alterTable(int64 pv_transid,
const char* pa_tblname,
int pv_tblname_len,
char ** buffer_tblopts,
int pv_numtblopts,
int pv_tbloptslen,
char *errstr,
int &errstrlen)
{
int lv_error = FEOK;
jlong jlv_transid = pv_transid;
CTmTxKey lv_tid(pv_transid);
HBASETrace(HBASETM_TraceExitError,
(HDR "CHbaseTM::alterTable returning %d.\n", lv_error));
JOI_RetCode lv_joi_retcode = JOI_OK;
lv_joi_retcode = initJNIEnv();
if (lv_joi_retcode != JOI_OK) {
tm_log_write(DTM_SEA_SOFT_FAULT, SQ_LOG_CRIT, (char *)"CHbaseTM::alterTable()", (char *)_tlp_error_msg->c_str(), -1LL);
abort();
}
jbyteArray jba_tblname = _tlp_jenv->NewByteArray(pv_tblname_len);
if (jba_tblname == NULL) {
_tlp_jenv->PopLocalFrame(NULL);
return RET_ADD_PARAM;
}
_tlp_jenv->SetByteArrayRegion(jba_tblname, 0, pv_tblname_len, (const jbyte*) pa_tblname);
jobjectArray j_tblopts = NULL;
j_tblopts = convertToStringObjectArray((const char **) buffer_tblopts, pv_numtblopts);
lv_error = _tlp_jenv->CallShortMethod(javaObj_,
JavaMethods_[JM_ALTERTABLE].methodID,
jlv_transid,
jba_tblname,
j_tblopts);
if (getExceptionDetails(NULL)) {
int errMsgLen = (int)_tlp_error_msg->length();
errstrlen = ((errMsgLen < errstrlen) && (errMsgLen > 0)) ? errMsgLen : errstrlen -1;
strncpy(errstr, _tlp_error_msg->c_str(), errstrlen);
errstr[errstrlen] = '\0';
tm_log_write(DTM_TM_JNI_ERROR, SQ_LOG_ERR, (char *)"CHbaseTM::alterTable()", (char *)_tlp_error_msg->c_str(), pv_transid);
_tlp_jenv->PopLocalFrame(NULL);
return RET_EXCEPTION;
}
_tlp_jenv->PopLocalFrame(NULL);
HBASETrace(HBASETM_TraceExit, (HDR "CHbaseTM::createTable : Error %d, Txn ID (%d,%d), hostname %s.\n",
lv_error, lv_tid.node(), lv_tid.seqnum(), pa_tblname));
return lv_error;
}
//----------------------------------------------------------------------------
// CHbaseTM: regTruncateOnAbort
// Purpose: To handle registration of truncate table during upsert using load
// ---------------------------------------------------------------------------
int CHbaseTM::regTruncateOnAbort(int64 pv_transid,
const char* pa_tblname,
int pv_tblname_len,
char *errstr,
int &errstrlen)
{
int lv_error = FEOK;
jlong jlv_transid = pv_transid;
CTmTxKey lv_tid(pv_transid);
HBASETrace(HBASETM_TraceExitError,
(HDR "CHbaseTM::regTruncateOnAbort returning %d.\n", lv_error));
JOI_RetCode lv_joi_retcode = JOI_OK;
lv_joi_retcode = initJNIEnv();
if (lv_joi_retcode != JOI_OK) {
tm_log_write(DTM_SEA_SOFT_FAULT, SQ_LOG_CRIT, (char *)"CHbaseTM::regTruncateAbort()", (char *)_tlp_error_msg->c_str(), -1LL);
abort();
}
jbyteArray jba_tblname = _tlp_jenv->NewByteArray(pv_tblname_len);
if (jba_tblname == NULL) {
_tlp_jenv->PopLocalFrame(NULL);
return RET_ADD_PARAM;
}
_tlp_jenv->SetByteArrayRegion(jba_tblname, 0, pv_tblname_len, (const jbyte*) pa_tblname);
lv_error = _tlp_jenv->CallShortMethod(javaObj_,
JavaMethods_[JM_REGTRUNCABORT].methodID,
jlv_transid,
jba_tblname);
if (getExceptionDetails(NULL)) {
int errMsgLen = (int)_tlp_error_msg->length();
errstrlen = ((errMsgLen < errstrlen) && (errMsgLen > 0)) ? errMsgLen : errstrlen -1;
strncpy(errstr, _tlp_error_msg->c_str(), errstrlen);
errstr[errstrlen] = '\0';
tm_log_write(DTM_TM_JNI_ERROR, SQ_LOG_ERR, (char *)"CHbaseTM::regTruncateOnAbort()", (char *)_tlp_error_msg->c_str(), pv_transid);
_tlp_jenv->PopLocalFrame(NULL);
return RET_EXCEPTION;
}
_tlp_jenv->PopLocalFrame(NULL);
HBASETrace(HBASETM_TraceExit, (HDR "CHbaseTM::regTruncateOnAbort : Error %d, Txn ID (%d,%d), hostname %s.\n",
lv_error, lv_tid.node(), lv_tid.seqnum(), pa_tblname));
return lv_error;
}
//----------------------------------------------------------------------------
// CHbaseTM: dropTable
// Purpose: To handle drop table transactional requests
// ---------------------------------------------------------------------------
int CHbaseTM::dropTable(int64 pv_transid,
const char* pa_tblname,
int pv_tblname_len,
char *errstr,
int &errstrlen)
{
int lv_error = FEOK;
jlong jlv_transid = pv_transid;
CTmTxKey lv_tid(pv_transid);
HBASETrace(HBASETM_TraceExitError,
(HDR "CHbaseTM::dropTable returning %d.\n", lv_error));
JOI_RetCode lv_joi_retcode = JOI_OK;
lv_joi_retcode = initJNIEnv();
if (lv_joi_retcode != JOI_OK) {
tm_log_write(DTM_SEA_SOFT_FAULT, SQ_LOG_CRIT, (char *)"CHbaseTM::dropTable()", (char *)_tlp_error_msg->c_str(), -1LL);
abort();
}
jbyteArray jba_tblname = _tlp_jenv->NewByteArray(pv_tblname_len);
if (jba_tblname == NULL) {
_tlp_jenv->PopLocalFrame(NULL);
return RET_ADD_PARAM;
}
_tlp_jenv->SetByteArrayRegion(jba_tblname, 0, pv_tblname_len, (const jbyte*) pa_tblname);
lv_error = _tlp_jenv->CallShortMethod(javaObj_,
JavaMethods_[JM_DROPTABLE].methodID,
jlv_transid,
jba_tblname);
if (getExceptionDetails(NULL)) {
int errMsgLen = (int)_tlp_error_msg->length();
errstrlen = ((errMsgLen < errstrlen) && (errMsgLen > 0)) ? errMsgLen : errstrlen -1;
strncpy(errstr, _tlp_error_msg->c_str(), errstrlen);
errstr[errstrlen] = '\0';
tm_log_write(DTM_TM_JNI_ERROR, SQ_LOG_ERR, (char *)"CHbaseTM::dropTable()", (char *)_tlp_error_msg->c_str(), pv_transid);
_tlp_jenv->PopLocalFrame(NULL);
return RET_EXCEPTION;
}
_tlp_jenv->PopLocalFrame(NULL);
HBASETrace(HBASETM_TraceExit, (HDR "CHbaseTM::dropTable : Error %d, Txn ID (%d,%d), hostname %s.\n",
lv_error, lv_tid.node(), lv_tid.seqnum(), pa_tblname));
return lv_error;
}
jobjectArray CHbaseTM::convertToStringObjectArray(const char **textArray, int arrayLen)
{
int i = 0;
jobjectArray j_objArray = NULL;
for ( i = 0; i < arrayLen ; i++)
{
jstring j_obj = _tlp_jenv->NewStringUTF(textArray[i]);
if (_tlp_jenv->ExceptionCheck())
{
if (j_objArray != NULL)
_tlp_jenv->DeleteLocalRef(j_objArray);
return NULL;
}
if (j_objArray == NULL)
{
j_objArray = _tlp_jenv->NewObjectArray(arrayLen,
_tlp_jenv->GetObjectClass(j_obj), NULL);
if (_tlp_jenv->ExceptionCheck())
{
_tlp_jenv->DeleteLocalRef(j_obj);
return NULL;
}
}
_tlp_jenv->SetObjectArrayElement(j_objArray, i, (jobject)j_obj);
_tlp_jenv->DeleteLocalRef(j_obj);
}
return j_objArray;
}
jobjectArray CHbaseTM::convertToByteArrayObjectArray(char **array,
int numElements, int elementLen)
{
int i = 0;
jobjectArray j_objArray = NULL;
for (i = 0; i < numElements; i++)
{
jbyteArray j_obj = _tlp_jenv->NewByteArray(elementLen);
if (_tlp_jenv->ExceptionCheck())
{
if (j_objArray != NULL)
_tlp_jenv->DeleteLocalRef(j_objArray);
return NULL;
}
_tlp_jenv->SetByteArrayRegion(j_obj, 0, elementLen,
(const jbyte *)(array[i]));
if (j_objArray == NULL)
{
j_objArray = _tlp_jenv->NewObjectArray(numElements,
_tlp_jenv->GetObjectClass(j_obj), NULL);
if (_tlp_jenv->ExceptionCheck())
{
_tlp_jenv->DeleteLocalRef(j_obj);
return NULL;
}
}
_tlp_jenv->SetObjectArrayElement(j_objArray, i, (jobject)j_obj);
_tlp_jenv->DeleteLocalRef(j_obj);
}
return j_objArray;
}
//----------------------------------------------------------------------------
// CHbaseTM::shutdown
// Purpose : Informs the HBase TM Library to shutdown
// Currently yet supported.
//----------------------------------------------------------------------------
void CHbaseTM::shutdown()
{
HBASETrace(HBASETM_TraceAPI, (HDR "CHbaseTM::shutdown ENTRY.\n"));
HBASETrace(HBASETM_TraceExit, (HDR "CHbaseTM::shutdown EXIT.\n"));
} //CHbaseTM::shutdown
//-------------------------------------------------------------------------------------
// requestRegionInfo
// Purpose: request region information to the hbase regions api's via hbase-trx client
//------------------------------------------------------------------------------------
HashMapArray* CHbaseTM::requestRegionInfo(){
JOI_RetCode lv_joi_retcode = JOI_OK;
lv_joi_retcode = initJNIEnv();
if (lv_joi_retcode != JOI_OK) {
tm_log_write(DTM_SEA_SOFT_FAULT, SQ_LOG_CRIT, (char *)"CHbaseTM::requestRegionInfo()", (char *)_tlp_error_msg->c_str(), -1LL);
abort();
}
jobject jHashMapArray = _tlp_jenv->CallObjectMethod(javaObj_, JavaMethods_[JM_RQREGINFO].methodID);
if (getExceptionDetails(NULL)) {
tm_log_write(DTM_TM_JNI_ERROR, SQ_LOG_ERR, (char *)"CHbaseTM::requestRegionInfo()", (char *)_tlp_error_msg->c_str(), -1LL);
_tlp_jenv->PopLocalFrame(NULL);
return NULL;
}
if (jHashMapArray == NULL) {
_tlp_jenv->PopLocalFrame(NULL);
return NULL;
}
HashMapArray* regionMap = new HashMapArray(jvm_, _tlp_jenv, jHashMapArray);
regionMap->init();
_tlp_jenv->PopLocalFrame(NULL);
return regionMap;
}
// ===========================================================================
// ===== Class HashMapArray
// ===========================================================================
JavaMethodInit* HashMapArray::JavaMethods_ = NULL;
jclass HashMapArray::javaClass_ = 0;
HashMapArray::~HashMapArray()
{
}
HMN_RetCode HashMapArray::init()
{
static char className[]="org/trafodion/dtm/HashMapArray";
if (isInitialized())
return HMN_OK;
if (JavaMethods_)
return (HMN_RetCode)JavaObjectInterfaceTM::init(className, javaClass_, JavaMethods_, (int32)JM_LAST, true);
else
{
JavaMethods_ = new JavaMethodInit[JM_LAST];
JavaMethods_[JM_CTOR ].jm_name = "<init>";
JavaMethods_[JM_CTOR ].jm_signature = "()V";
JavaMethods_[JM_GET ].jm_name = "getElement";
JavaMethods_[JM_GET ].jm_signature = "(I)Ljava/lang/String;";
JavaMethods_[JM_GET_TNAME ].jm_name = "getTableName";
JavaMethods_[JM_GET_TNAME ].jm_signature = "(I)Ljava/lang/String;";
JavaMethods_[JM_GET_ENCREGNAME ].jm_name = "getEncodedRegionName";
JavaMethods_[JM_GET_ENCREGNAME ].jm_signature = "(I)Ljava/lang/String;";
JavaMethods_[JM_GET_REGNAME ].jm_name = "getRegionName";
JavaMethods_[JM_GET_REGNAME ].jm_signature = "(I)Ljava/lang/String;";
JavaMethods_[JM_GET_OFFLINE ].jm_name = "getRegionOfflineStatus";
JavaMethods_[JM_GET_OFFLINE ].jm_signature = "(I)Ljava/lang/String;";
JavaMethods_[JM_GET_REGID ].jm_name = "getRegionId";
JavaMethods_[JM_GET_REGID ].jm_signature = "(I)Ljava/lang/String;";
JavaMethods_[JM_GET_HOSTNAME ].jm_name = "getHostName";
JavaMethods_[JM_GET_HOSTNAME ].jm_signature = "(I)Ljava/lang/String;";
JavaMethods_[JM_GET_PORT ].jm_name = "getPort";
JavaMethods_[JM_GET_PORT ].jm_signature = "(I)Ljava/lang/String;";
JavaMethods_[JM_GET_REGINFO ].jm_name = "getRegionInfo";
JavaMethods_[JM_GET_REGINFO ].jm_signature = "(J)Ljava/lang/String;";
return (HMN_RetCode)JavaObjectInterfaceTM::init(className, javaClass_, JavaMethods_, (int32)JM_LAST, false);
}
}
char* HashMapArray::get(int tid)
{
jstring js_val = (jstring)(_tlp_jenv->CallObjectMethod(javaObj_, JavaMethods_[JM_GET].methodID, tid));
if (getExceptionDetails(NULL)) {
tm_log_write(DTM_TM_JNI_ERROR, SQ_LOG_ERR, (char *)"HashMapArray::get()", (char *)_tlp_error_msg->c_str(), -1LL);
return NULL;
}
if(js_val == NULL){
printf("hbasetm::HashMapArray::get - js_val is NULL");
return NULL;
}
const jbyte* jb_val = (jbyte*)_tlp_jenv->GetStringUTFChars(js_val, NULL);
char* cp_val = (char *)jb_val;
return cp_val;
}
char* HashMapArray::getRegionInfo(int64 tid)
{
jstring js_val = (jstring)(_tlp_jenv->CallObjectMethod(javaObj_, JavaMethods_[JM_GET_REGINFO].methodID, tid));
if (getExceptionDetails(NULL)) {
tm_log_write(DTM_TM_JNI_ERROR, SQ_LOG_ERR, (char *)"HashMapArray::getRegionInfo()", (char *)_tlp_error_msg->c_str(), -1LL);
return NULL;
}
if(js_val == NULL){
return NULL;
}
const jbyte* jb_val = (jbyte*)_tlp_jenv->GetStringUTFChars(js_val, NULL);
char* cp_val = (char *)jb_val;
return cp_val;
}
char* HashMapArray::getTableName(int tid)
{
jstring js_val = (jstring)(_tlp_jenv->CallObjectMethod(javaObj_, JavaMethods_[JM_GET_TNAME].methodID, tid));
if (getExceptionDetails(NULL)) {
tm_log_write(DTM_TM_JNI_ERROR, SQ_LOG_ERR, (char *)"HashMapArray::getTableName()", (char *)_tlp_error_msg->c_str(), -1LL);
return NULL;
}
if(js_val == NULL){
printf("hbasetm::HashMapArray::getTableName - js_val is NULL");
return NULL;
}
const jbyte* jb_val = (jbyte*)_tlp_jenv->GetStringUTFChars(js_val, NULL);
char* cp_val = (char *)jb_val;
return cp_val;
}
char* HashMapArray::getEncodedRegionName(int tid)
{
jstring js_val = (jstring)(_tlp_jenv->CallObjectMethod(javaObj_, JavaMethods_[JM_GET_ENCREGNAME].methodID, tid));
if (getExceptionDetails(NULL)) {
tm_log_write(DTM_TM_JNI_ERROR, SQ_LOG_ERR, (char *)"HashMapArray::getEncodedRegionName()", (char *)_tlp_error_msg->c_str(), -1LL);
return NULL;
}
if(js_val == NULL){
printf("hbasetm.cpp::HashMapArray::getEncodedRegionName - js_val is NULL");
return NULL;
}
const jbyte* jb_val = (jbyte*)_tlp_jenv->GetStringUTFChars(js_val, NULL);
char* cp_val = (char *)jb_val;
return cp_val;
}
char* HashMapArray::getRegionName(int tid)
{
jstring js_val = (jstring)(_tlp_jenv->CallObjectMethod(javaObj_, JavaMethods_[JM_GET_REGNAME].methodID, tid));
if (getExceptionDetails(NULL)) {
tm_log_write(DTM_TM_JNI_ERROR, SQ_LOG_ERR, (char *)"HashMapArray::getRegionName()", (char *)_tlp_error_msg->c_str(), -1LL);
return NULL;
}
if(js_val == NULL){
printf("hbasetm.cpp::HashMapArray::getRegionName - js_val is NULL");
return NULL;
}
const jbyte* jb_val = (jbyte*)_tlp_jenv->GetStringUTFChars(js_val, NULL);
char* cp_val = (char *)jb_val;
return cp_val;
}
char* HashMapArray::getRegionOfflineStatus(int tid)
{
jstring js_val = (jstring)(_tlp_jenv->CallObjectMethod(javaObj_, JavaMethods_[JM_GET_OFFLINE].methodID, tid));
if (getExceptionDetails(NULL)) {
tm_log_write(DTM_TM_JNI_ERROR, SQ_LOG_ERR, (char *)"HashMapArray::getRegionOfflineStatus()", (char *)_tlp_error_msg->c_str(), -1LL);
return NULL;
}
if(js_val == NULL){
printf("hbasetm.cpp::HashMapArray::getRegionOfflineStatus - js_val is NULL");
return NULL;
}
const jbyte* jb_val = (jbyte*)_tlp_jenv->GetStringUTFChars(js_val, NULL);
char* cp_val = (char *)jb_val;
return cp_val;
}
char* HashMapArray::getRegionId(int tid)
{
jstring js_val = (jstring)(_tlp_jenv->CallObjectMethod(javaObj_, JavaMethods_[JM_GET_REGID].methodID, tid));
if (getExceptionDetails(NULL)) {
tm_log_write(DTM_TM_JNI_ERROR, SQ_LOG_ERR, (char *)"HashMaparray::getRegionId()", (char *)_tlp_error_msg->c_str(), -1LL);
return NULL;
}
if(js_val == NULL){
printf("hbasetm.cpp::HashMapArray::getRegionId - js_val is NULL");
return NULL;
}
const jbyte* jb_val = (jbyte*)_tlp_jenv->GetStringUTFChars(js_val, NULL);
char* cp_val = (char *)jb_val;
return cp_val;
}
char* HashMapArray::getHostName(int tid)
{
jstring js_val = (jstring)(_tlp_jenv->CallObjectMethod(javaObj_, JavaMethods_[JM_GET_HOSTNAME].methodID, tid));
if (getExceptionDetails(NULL)) {
tm_log_write(DTM_TM_JNI_ERROR, SQ_LOG_ERR, (char *)"HashMapArray::getHostName()", (char *)_tlp_error_msg->c_str(), -1LL);
return NULL;
}
if(js_val == NULL){
printf("hbasetm.cpp::HashMapArray::getHostName - js_val is NULL");
return NULL;
}
const jbyte* jb_val = (jbyte*)_tlp_jenv->GetStringUTFChars(js_val, NULL);
char* cp_val = (char *)jb_val;
return cp_val;
}
char* HashMapArray::getPort(int tid)
{
jstring js_val = (jstring)(_tlp_jenv->CallObjectMethod(javaObj_, JavaMethods_[JM_GET_PORT].methodID, tid));
if (getExceptionDetails(NULL)) {
tm_log_write(DTM_TM_JNI_ERROR, SQ_LOG_ERR, (char *)"HashMapArrray::getPort()", (char *)_tlp_error_msg->c_str(), -1LL);
return NULL;
}
if(js_val == NULL){
printf("hbasetm.cpp::HashMapArray::getPort - js_val is NULL");
return NULL;
}
const jbyte* jb_val = (jbyte*)_tlp_jenv->GetStringUTFChars(js_val, NULL);
char* cp_val = (char *)jb_val;
return cp_val;
}
|
#include <PnC/Scorpio2PnC/CtrlSet/OSCPosCtrl.hpp>
#include <PnC/Scorpio2PnC/TestSet/OSCTest.hpp>
OSCTest::OSCTest(RobotSystem* robot) : Test(robot) {
myUtils::pretty_constructor(1, "Scoprio2 OSC Test");
cfg_ = YAML::LoadFile(THIS_COM "Config/Scorpio/TEST/OSC_TEST.yaml");
phase_ = 0;
state_list_.clear();
osc_pos_ctrl_ = new OSCPosCtrl(robot);
//osc_ori_ctrl_ = new OSCOriCtrl(robot);
state_list_.push_back(osc_pos_ctrl_);
//state_list_.push_back(osc_ori_ctrl_);
_ParameterSetting();
}
OSCTest::~OSCTest() {
delete osc_pos_ctrl_;
//delete osc_ori_ctrl_;
}
void OSCTest::TestInitialization() {
osc_pos_ctrl_->ctrlInitialization(
cfg_["control_configuration"]["osc_position_ctrl"]);
//osc_ori_ctrl_->ctrlInitialization(
//cfg_["control_configuration"]["osc_orientation_ctrl"]);
}
int OSCTest::_NextPhase(const int& phase) {
int nx_phase = phase + 1;
printf("[OSC TEST] next phase: %d\n", nx_phase);
//if (phase == NUM_OSC_TEST) {
//nx_phase = OSC_POS_TEST;
//}
//return nx_phase;
return 0;
}
void OSCTest::_ParameterSetting() {
try {
YAML::Node test_cfg = cfg_["test_configuration"];
Eigen::VectorXd tmp_vec;
double tmp_val;
myUtils::readParameter(test_cfg, "xyz_duration", tmp_val);
((OSCPosCtrl*)osc_pos_ctrl_)->setEndTime(tmp_val);
myUtils::readParameter(test_cfg, "end_effector_target_pos", tmp_vec);
((OSCPosCtrl*)osc_pos_ctrl_)->setTargetPosition(tmp_vec);
myUtils::readParameter(test_cfg, "end_effector_target_ori", tmp_vec);
((OSCPosCtrl*)osc_pos_ctrl_)->setTargetOrientation(tmp_vec);
//myUtils::readParameter(test_cfg, "ori_duration", tmp_val);
//((OSCOriCtrl*)osc_ori_ctrl_)->setEndTime(tmp_val);
//myUtils::readParameter(test_cfg, "head_target_pos", tmp_vec);
//((OSCOriCtrl*)osc_ori_ctrl_)->setTargetPosition(tmp_vec);
} catch (std::runtime_error& e) {
std::cout << "Error reading parameter [" << e.what() << "] at file: ["
<< __FILE__ << "]" << std::endl
<< std::endl;
exit(0);
}
}
|
///////////////////////////////////////////////////////////////////////
// File: unicharmap.cpp
// Description: Unicode character/ligature to integer id class.
// Author: Thomas Kielbus
//
// (C) Copyright 2006, Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////
#include "unicharmap.h"
#include <tesseract/unichar.h>
#include <cassert>
namespace tesseract {
UNICHARMAP::UNICHARMAP() : nodes(nullptr) {}
UNICHARMAP::~UNICHARMAP() {
delete[] nodes;
}
// Search the given unichar representation in the tree, using length characters
// from it maximum. Each character in the string is interpreted as an index in
// an array of nodes.
UNICHAR_ID UNICHARMAP::unichar_to_id(const char *const unichar_repr, int length) const {
UNICHARMAP_NODE *current_nodes = nodes;
assert(*unichar_repr != '\0');
assert(length > 0 && length <= UNICHAR_LEN);
int index = 0;
if (length <= 0 || unichar_repr[index] == '\0') {
return INVALID_UNICHAR_ID;
}
do {
if (index + 1 >= length || unichar_repr[index + 1] == '\0') {
return current_nodes[static_cast<unsigned char>(unichar_repr[index])].id;
}
current_nodes = current_nodes[static_cast<unsigned char>(unichar_repr[index])].children;
++index;
} while (true);
}
// Search the given unichar representation in the tree, creating the possibly
// missing nodes. Once the right place has been found, insert the given id and
// update the inserted flag to keep track of the insert. Each character in the
// string is interpreted as an index in an array of nodes.
void UNICHARMAP::insert(const char *const unichar_repr, UNICHAR_ID id) {
const char *current_char = unichar_repr;
if (*current_char == '\0') {
return;
}
UNICHARMAP_NODE **current_nodes_pointer = &nodes;
do {
if (*current_nodes_pointer == nullptr) {
*current_nodes_pointer = new UNICHARMAP_NODE[256];
}
if (current_char[1] == '\0') {
(*current_nodes_pointer)[static_cast<unsigned char>(*current_char)].id = id;
return;
}
current_nodes_pointer =
&((*current_nodes_pointer)[static_cast<unsigned char>(*current_char)].children);
++current_char;
} while (true);
}
// Search the given unichar representation in the tree, using length characters
// from it maximum. Each character in the string is interpreted as an index in
// an array of nodes. Stop once the tree does not have anymore nodes or once we
// found the right unichar_repr.
bool UNICHARMAP::contains(const char *const unichar_repr, int length) const {
if (unichar_repr == nullptr || *unichar_repr == '\0') {
return false;
}
if (length <= 0 || length > UNICHAR_LEN) {
return false;
}
int index = 0;
if (unichar_repr[index] == '\0') {
return false;
}
UNICHARMAP_NODE *current_nodes = nodes;
while (current_nodes != nullptr && index + 1 < length && unichar_repr[index + 1] != '\0') {
current_nodes = current_nodes[static_cast<unsigned char>(unichar_repr[index])].children;
++index;
}
return current_nodes != nullptr && (index + 1 >= length || unichar_repr[index + 1] == '\0') &&
current_nodes[static_cast<unsigned char>(unichar_repr[index])].id >= 0;
}
// Return the minimum number of characters that must be used from this string
// to obtain a match in the UNICHARMAP.
int UNICHARMAP::minmatch(const char *const unichar_repr) const {
const char *current_char = unichar_repr;
if (*current_char == '\0') {
return 0;
}
UNICHARMAP_NODE *current_nodes = nodes;
while (current_nodes != nullptr && *current_char != '\0') {
if (current_nodes[static_cast<unsigned char>(*current_char)].id >= 0) {
return current_char + 1 - unichar_repr;
}
current_nodes = current_nodes[static_cast<unsigned char>(*current_char)].children;
++current_char;
}
return 0;
}
void UNICHARMAP::clear() {
delete[] nodes;
nodes = nullptr;
}
UNICHARMAP::UNICHARMAP_NODE::UNICHARMAP_NODE() : children(nullptr), id(-1) {}
// Recursively delete the children
UNICHARMAP::UNICHARMAP_NODE::~UNICHARMAP_NODE() {
delete[] children;
}
} // namespace tesseract
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/extensions/context_menus_custom_bindings.h"
#include "base/bind.h"
#include "chrome/common/extensions/extension_messages.h"
#include "content/public/renderer/render_thread.h"
#include "grit/renderer_resources.h"
#include "v8/include/v8.h"
namespace {
void GetNextContextMenuId(const v8::FunctionCallbackInfo<v8::Value>& args) {
int context_menu_id = -1;
content::RenderThread::Get()->Send(
new ExtensionHostMsg_GenerateUniqueID(&context_menu_id));
args.GetReturnValue().Set(static_cast<int32_t>(context_menu_id));
}
} // namespace
namespace extensions {
ContextMenusCustomBindings::ContextMenusCustomBindings(
Dispatcher* dispatcher, ChromeV8Context* context)
: ChromeV8Extension(dispatcher, context) {
RouteFunction("GetNextContextMenuId", base::Bind(&GetNextContextMenuId));
}
} // extensions
|
// Copyright (C) 2019 Internet Systems Consortium, Inc. ("ISC")
//
// 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/.
#include <config.h>
#include <cc/server_tag.h>
#include <exceptions/exceptions.h>
#include <util/strutil.h>
#include <boost/algorithm/string.hpp>
namespace isc {
namespace data {
std::string ServerTag::ALL = "all";
ServerTag::ServerTag()
: tag_(ALL) {
}
ServerTag::ServerTag(const std::string& tag)
: tag_(util::str::trim(tag)) {
if (tag_.empty()) {
isc_throw(BadValue, "server-tag must not be empty");
} else if (tag_.length() > 256) {
isc_throw(BadValue, "server-tag must not be longer than 256 characters");
}
boost::algorithm::to_lower(tag_);
// ANY has a defined meaning for server selector and must not be used as
// a server tag.
if (tag_ == "any") {
isc_throw(BadValue, "'any' is reserved and must not be used as a server-tag");
}
}
bool
ServerTag::amAll() const {
return (tag_ == ALL);
}
std::ostream&
operator<<(std::ostream& os, const ServerTag& server_tag) {
os << server_tag.get();
return (os);
}
} // end of namespace isc::data
} // end of namespace isc
|
/**
* 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.
*/
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/prctl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <list>
#include <ostream>
#include <tuple>
#include <vector>
#include <process/clock.hpp>
#include <process/collect.hpp>
#include <process/defer.hpp>
#include <process/io.hpp>
#include <process/process.hpp>
#include <process/subprocess.hpp>
#include <stout/strings.hpp>
#include <stout/unreachable.hpp>
#include <stout/os/signals.hpp>
#include "common/status_utils.hpp"
#include "linux/perf.hpp"
using namespace process;
using process::await;
using std::list;
using std::ostringstream;
using std::set;
using std::string;
using std::tuple;
using std::vector;
namespace perf {
// Delimiter for fields in perf stat output.
static const char PERF_DELIMITER[] = ",";
namespace internal {
// Normalize a perf event name. After normalization the event name
// should match an event field in the PerfStatistics protobuf.
inline string normalize(const string& s)
{
string lower = strings::lower(s);
return strings::replace(lower, "-", "_");
}
// Executes the 'perf' command using the supplied arguments, and
// returns stdout as the value of the future or a failure if calling
// the command fails or the command returns a non-zero exit code.
//
// TODO(bmahler): Add a process::os::shell to generalize this.
class Perf : public Process<Perf>
{
public:
Perf(const vector<string>& _argv) : argv(_argv)
{
// The first argument should be 'perf'. Note that this is
// a bit hacky because this class is specialized to only
// execute the 'perf' binary. Ultimately, this should be
// generalized to something like process::os::shell.
if (argv.empty() || argv.front() != "perf") {
argv.insert(argv.begin(), "perf");
}
}
virtual ~Perf() {}
Future<string> output()
{
return promise.future();
}
protected:
virtual void initialize()
{
// Stop when no one cares.
promise.future().onDiscard(lambda::bind(
static_cast<void(*)(const UPID&, bool)>(terminate), self(), true));
execute();
}
virtual void finalize()
{
// Kill the perf process (if it's still running) by sending
// SIGTERM to the signal handler which will then SIGKILL the
// perf process group created by setupChild.
if (perf.isSome() && perf->status().isPending()) {
kill(perf->pid(), SIGTERM);
}
promise.discard();
}
private:
static void signalHandler(int signal)
{
// Send SIGKILL to every process in the process group of the
// calling process. This will terminate both the perf process
// (including its children) and the bookkeeping process.
kill(0, SIGKILL);
abort();
}
// This function is invoked right before each 'perf' is exec'ed.
// Note that this function needs to be async signal safe. In fact,
// all the library functions we used in this function are async
// signal safe.
static int setupChild()
{
// Send SIGTERM to the current process if the parent (i.e., the
// slave) exits. Note that this function should always succeed
// because we are passing in a valid signal.
prctl(PR_SET_PDEATHSIG, SIGTERM);
// Put the current process into a separate process group so that
// we can kill it and all its children easily.
if (setpgid(0, 0) != 0) {
abort();
}
// Install a SIGTERM handler which will kill the current process
// group. Since we already setup the death signal above, the
// signal handler will be triggered when the parent (i.e., the
// slave) exits.
if (os::signals::install(SIGTERM, &signalHandler) != 0) {
abort();
}
pid_t pid = fork();
if (pid == -1) {
abort();
} else if (pid == 0) {
// Child. This is the process that is going to exec the perf
// process if zero is returned.
// We setup death signal for the perf process as well in case
// someone, though unlikely, accidentally kill the parent of
// this process (the bookkeeping process).
prctl(PR_SET_PDEATHSIG, SIGKILL);
// NOTE: We don't need to clear the signal handler explicitly
// because the subsequent 'exec' will clear them.
return 0;
} else {
// Parent. This is the bookkeeping process which will wait for
// the perf process to finish.
// Close the files to prevent interference on the communication
// between the slave and the perf process.
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
// Block until the perf process finishes.
int status = 0;
if (waitpid(pid, &status, 0) == -1) {
abort();
}
// Forward the exit status if the perf process exits normally.
if (WIFEXITED(status)) {
_exit(WEXITSTATUS(status));
}
abort();
UNREACHABLE();
}
}
void execute()
{
Try<Subprocess> _perf = subprocess(
"perf",
argv,
Subprocess::PIPE(),
Subprocess::PIPE(),
Subprocess::PIPE(),
None(),
None(),
setupChild);
if (_perf.isError()) {
promise.fail("Failed to launch perf process: " + _perf.error());
terminate(self());
return;
}
perf = _perf.get();
// Wait for the process to exit.
await(perf->status(),
io::read(perf->out().get()),
io::read(perf->err().get()))
.onReady(defer(self(), [this](const tuple<
Future<Option<int>>,
Future<string>,
Future<string>>& results) {
Future<Option<int>> status = std::get<0>(results);
Future<string> output = std::get<1>(results);
Option<Error> error = None();
if (!status.isReady()) {
error = Error("Failed to execute perf: " +
(status.isFailed() ? status.failure() : "discarded"));
} else if (status->isNone()) {
error = Error("Failed to execute perf: failed to reap");
} else if (status->get() != 0) {
error = Error("Failed to execute perf: " +
WSTRINGIFY(status->get()));
} else if (!output.isReady()) {
error = Error("Failed to read perf output: " +
(output.isFailed() ? output.failure() : "discarded"));
}
if (error.isSome()) {
promise.fail(error->message);
terminate(self());
return;
}
promise.set(output.get());
terminate(self());
return;
}));
}
vector<string> argv;
Promise<string> promise;
Option<Subprocess> perf;
};
} // namespace internal {
Future<Version> version()
{
internal::Perf* perf = new internal::Perf({"--version"});
Future<string> output = perf->output();
spawn(perf, true);
return output
.then([](const string& output) -> Future<Version> {
// Trim off the leading 'perf version ' text to convert.
return Version::parse(strings::remove(
output, "perf version ", strings::PREFIX));
});
};
bool supported(const Version& version)
{
// Require perf version >= 2.6.39 to support cgroups and formatting.
return version >= Version(2, 6, 39);
}
bool supported()
{
Future<Version> version = perf::version();
// If perf does not respond in a reasonable time, mark as unsupported.
version.await(Seconds(5));
if (!version.isReady()) {
if (version.isFailed()) {
LOG(ERROR) << "Failed to get perf version: " << version.failure();
} else {
LOG(ERROR) << "Failed to get perf version: timeout of 5secs exceeded";
}
version.discard();
return false;
}
return supported(version.get());
}
Future<hashmap<string, mesos::PerfStatistics>> sample(
const set<string>& events,
const set<string>& cgroups,
const Duration& duration)
{
// Is this a no-op?
if (cgroups.empty()) {
return hashmap<string, mesos::PerfStatistics>();
}
vector<string> argv = {
"stat",
// System-wide collection from all CPUs.
"--all-cpus",
// Print counts using a CSV-style output to make it easy to import
// directly into spreadsheets. Columns are separated by the string
// specified in PERF_DELIMITER.
"--field-separator", PERF_DELIMITER,
// Ensure all output goes to stdout.
"--log-fd", "1"
};
// Add all pairwise combinations of event and cgroup.
foreach (const string& event, events) {
foreach (const string& cgroup, cgroups) {
argv.push_back("--event");
argv.push_back(event);
argv.push_back("--cgroup");
argv.push_back(cgroup);
}
}
argv.push_back("--");
argv.push_back("sleep");
argv.push_back(stringify(duration.secs()));
Time start = Clock::now();
internal::Perf* perf = new internal::Perf(argv);
Future<string> output = perf->output();
spawn(perf, true);
auto parse = [start, duration](
const tuple<Version, string> values) ->
Future<hashmap<string, mesos::PerfStatistics>> {
const Version& version = std::get<0>(values);
const string& output = std::get<1>(values);
// Check that the version is supported.
if (!supported(version)) {
return Failure("Perf " + stringify(version) + " is not supported");
}
Try<hashmap<string, mesos::PerfStatistics>> result =
perf::parse(output, version);
if (result.isError()) {
return Failure("Failed to parse perf sample: " + result.error());
}
foreachvalue (mesos::PerfStatistics& statistics, result.get()) {
statistics.set_timestamp(start.secs());
statistics.set_duration(duration.secs());
}
return result.get();
};
// TODO(pbrett): Don't wait for these forever!
return process::collect(perf::version(), output)
.then(parse);
}
bool valid(const set<string>& events)
{
ostringstream command;
// Log everything to stderr which is then redirected to /dev/null.
command << "perf stat --log-fd 2";
foreach (const string& event, events) {
command << " --event " << event;
}
command << " true 2>/dev/null";
return (os::system(command.str()) == 0);
}
struct Sample
{
const string value;
const string event;
const string cgroup;
// Convert a single line of perf output in CSV format (using
// PERF_DELIMITER as a separator) to a sample.
static Try<Sample> parse(const string& line, const Version& version)
{
// We use strings::split to separate the tokens
// because the unit field can be empty.
vector<string> tokens = strings::split(line, PERF_DELIMITER);
if (version >= Version(4, 0, 0)) {
// Optional running time and ratio were introduced in Linux v4.0,
// which make the format either:
// value,unit,event,cgroup
// value,unit,event,cgroup,running,ratio
if ((tokens.size() == 4) || (tokens.size() == 6)) {
return Sample({tokens[0], internal::normalize(tokens[2]), tokens[3]});
}
} else if (version >= Version(3, 13, 0)) {
// Unit was added in Linux v3.13, making the format:
// value,unit,event,cgroup
if (tokens.size() == 4) {
return Sample({tokens[0], internal::normalize(tokens[2]), tokens[3]});
}
} else {
// Expected format for Linux kernel <= 3.12 is:
// value,event,cgroup
if (tokens.size() == 3) {
return Sample({tokens[0], internal::normalize(tokens[1]), tokens[2]});
}
}
return Error("Unexpected number of fields");
}
};
Try<hashmap<string, mesos::PerfStatistics>> parse(
const string& output,
const Version& version)
{
hashmap<string, mesos::PerfStatistics> statistics;
foreach (const string& line, strings::tokenize(output, "\n")) {
Try<Sample> sample = Sample::parse(line, version);
if (sample.isError()) {
return Error("Failed to parse perf sample line '" + line + "': " +
sample.error());
}
if (!statistics.contains(sample->cgroup)) {
statistics.put(sample->cgroup, mesos::PerfStatistics());
}
const google::protobuf::Reflection* reflection =
statistics[sample->cgroup].GetReflection();
const google::protobuf::FieldDescriptor* field =
statistics[sample->cgroup].GetDescriptor()->FindFieldByName(
sample->event);
if (field == NULL) {
return Error("Unexpected event '" + sample->event + "'"
" in perf output at line: " + line);
}
if (sample->value == "<not supported>") {
LOG(WARNING) << "Unsupported perf counter, ignoring: " << line;
continue;
}
switch (field->type()) {
case google::protobuf::FieldDescriptor::TYPE_DOUBLE: {
Try<double> number = (sample->value == "<not counted>")
? 0
: numify<double>(sample->value);
if (number.isError()) {
return Error("Unable to parse perf value at line: " + line);
}
reflection->SetDouble(&(
statistics[sample->cgroup]), field, number.get());
break;
}
case google::protobuf::FieldDescriptor::TYPE_UINT64: {
Try<uint64_t> number = (sample->value == "<not counted>")
? 0
: numify<uint64_t>(sample->value);
if (number.isError()) {
return Error("Unable to parse perf value at line: " + line);
}
reflection->SetUInt64(&(
statistics[sample->cgroup]), field, number.get());
break;
}
default:
return Error("Unsupported perf field type at line: " + line);
}
}
return statistics;
}
} // namespace perf {
|
#include "pch.h"
#include "AppDelegate.h"
#include "ClassManage.h"
#include "util.h"
USING_NS_CC;
AppDelegate::AppDelegate() {
}
AppDelegate::~AppDelegate()
{
}
//if you want a different context,just modify the value of glContextAttrs
//it will takes effect on all platforms
void AppDelegate::initGLContextAttrs()
{
//set OpenGL context attributions,now can only set six attributions:
//red,green,blue,alpha,depth,stencil
GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};
GLView::setGLContextAttrs(glContextAttrs);
}
bool AppDelegate::applicationDidFinishLaunching() {
// initialize director
auto director = Director::getInstance();
auto glview = director->getOpenGLView();
if(!glview) {
glview = GLViewImpl::createWithRect("ClassManagement",
cocos2d::Rect(0, 0, WINSIZE_WIDTH, WINSIZE_HEIGHT));
director->setOpenGLView(glview);
}
// turn on display FPS
director->setDisplayStats(false);
// set FPS. the default value is 1.0/60 if you don't call this
director->setAnimationInterval(1.0 / 60);
// create a scene. it's an autorelease object
auto scene = ClassManage::createScene();
// run
director->runWithScene(scene);
return true;
}
void AppDelegate::applicationDidEnterBackground()
{
}
void AppDelegate::applicationWillEnterForeground()
{
}
|
/*
* Copyright (c) 2015, 2016, 2017, 2018, 2019, Intel Corporation
*
* 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 Intel Corporation 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 LOG OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cstdio>
#include <limits.h>
#include <fstream>
#include <string>
#include <vector>
#include "gtest/gtest.h"
#include "ModelParse.hpp"
#include "Exception.hpp"
#include "Helper.hpp"
using geopm::model_parse_config;
using geopm::Exception;
class ModelApplicationTest : public ::testing::Test
{
protected:
virtual void TearDown();
std::string m_filename = "model_application_test.json";
// variables for output
uint64_t m_loop_count = 0;
std::vector<std::string> m_region_name;
std::vector<double> m_big_o;
};
void ModelApplicationTest::TearDown()
{
std::remove(m_filename.c_str());
}
TEST_F(ModelApplicationTest, parse_config_errors)
{
// no file, empty file
EXPECT_THROW(model_parse_config(m_filename, m_loop_count, m_region_name, m_big_o),
Exception);
std::ofstream empty_file(m_filename);
empty_file.close();
EXPECT_THROW(model_parse_config(m_filename, m_loop_count, m_region_name, m_big_o),
Exception);
// malformed file
std::ofstream bad_json(m_filename);
bad_json << "{[\"test\"]" << std::endl;
bad_json.close();
EXPECT_THROW(model_parse_config(m_filename, m_loop_count, m_region_name, m_big_o),
Exception);
// unknown key
std::ofstream unknown_key(m_filename);
unknown_key << "{\"unknown\":1}" << std::endl;
unknown_key.close();
EXPECT_THROW(model_parse_config(m_filename, m_loop_count, m_region_name, m_big_o),
Exception);
// loop count must be integer
std::ofstream bad_loop_count(m_filename);
bad_loop_count << "{\"loop-count\":\"one\"}" << std::endl;
bad_loop_count.close();
EXPECT_THROW(model_parse_config(m_filename, m_loop_count, m_region_name, m_big_o),
Exception);
std::ofstream bad_loop_count2(m_filename);
bad_loop_count2 << "{\"loop-count\":22.2}" << std::endl;
bad_loop_count2.close();
EXPECT_THROW(model_parse_config(m_filename, m_loop_count, m_region_name, m_big_o),
Exception);
// region must be array
std::ofstream bad_region(m_filename);
bad_region << "{\"region\":\"myregion\"}" << std::endl;
bad_region.close();
EXPECT_THROW(model_parse_config(m_filename, m_loop_count, m_region_name, m_big_o),
Exception);
// region array items must be string
std::ofstream bad_region_item(m_filename);
bad_region_item << "{\"region\":[22]}" << std::endl;
bad_region_item.close();
EXPECT_THROW(model_parse_config(m_filename, m_loop_count, m_region_name, m_big_o),
Exception);
// big-o must be array
std::ofstream bad_bigo(m_filename);
bad_bigo << "{\"big-o\":\"biggo\"}" << std::endl;
bad_bigo.close();
EXPECT_THROW(model_parse_config(m_filename, m_loop_count, m_region_name, m_big_o),
Exception);
// big-o items must be double
std::ofstream bad_bigo_item(m_filename);
bad_bigo_item << "{\"big-o\":[\"number\"]}" << std::endl;
bad_bigo_item.close();
EXPECT_THROW(model_parse_config(m_filename, m_loop_count, m_region_name, m_big_o),
Exception);
// hostname must be array
std::ofstream bad_hostname(m_filename);
bad_hostname << "{\"hostname\":\"myhost\"}" << std::endl;
bad_hostname.close();
EXPECT_THROW(model_parse_config(m_filename, m_loop_count, m_region_name, m_big_o),
Exception);
// hostname items must be string
std::ofstream bad_hostname_item(m_filename);
bad_hostname_item << "{\"hostname\":[123]}" << std::endl;
bad_hostname_item.close();
EXPECT_THROW(model_parse_config(m_filename, m_loop_count, m_region_name, m_big_o),
Exception);
// imbalance must be array
std::ofstream bad_imbalance(m_filename);
bad_imbalance << "{\"imbalance\":\"ecnalabmi\"}" << std::endl;
bad_imbalance.close();
EXPECT_THROW(model_parse_config(m_filename, m_loop_count, m_region_name, m_big_o),
Exception);
// imbalance values must be double, non-negative
std::ofstream bad_imbalance_item(m_filename);
bad_imbalance_item << "{\"imbalance\":[\"hello\"]}" << std::endl;
bad_imbalance_item.close();
EXPECT_THROW(model_parse_config(m_filename, m_loop_count, m_region_name, m_big_o),
Exception);
std::ofstream bad_imbalance_item2(m_filename);
bad_imbalance_item2 << "{\"imbalance\":[-20.2], \"hostname\":[\""
<< geopm::hostname() << "\"]}" << std::endl;
bad_imbalance_item2.close();
EXPECT_THROW(model_parse_config(m_filename, m_loop_count, m_region_name, m_big_o),
Exception);
// region, big-o, hostname, and imbalance arrays must be same length
std::ofstream mismatch_region_length(m_filename);
mismatch_region_length << "{\"region\":[\"one\", \"two\"], \"big-o\":[2.2]}" << std::endl;
mismatch_region_length.close();
EXPECT_THROW(model_parse_config(m_filename, m_loop_count, m_region_name, m_big_o),
Exception);
std::ofstream mismatch_hostname_length(m_filename);
mismatch_hostname_length << "{\"hostname\":[\"one\", \"two\"], \"imbalance\":[2.2]}" << std::endl;
mismatch_hostname_length.close();
EXPECT_THROW(model_parse_config(m_filename, m_loop_count, m_region_name, m_big_o),
Exception);
}
|
#include <windows.h>
#include <GL/glew.h>
#include <GL/freeglut.h>
#include <GL/gl.h>
#include <GL/glext.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <iostream>
#include "InitShader.h"
#include "imgui_impl_glut.h"
#include "VideoMux.h"
#include "DebugCallback.h"
//names of the shader files to load
static const std::string vertex_shader("tfb_vs.glsl");
static const std::string fragment_shader("tfb_fs.glsl");
GLuint shader_program = -1;
//Ping-pong pairs of objects and buffers since we don't have simultaneous read/write access to VBOs.
GLuint vao[2] = {-1, -1};
GLuint vbo[2] = {-1, -1};
const int num_particles = 10000;
GLuint tfo[2] = { -1, -1 }; //transform feedback objects
//These indices get swapped every frame to perform the ping-ponging
int Read_Index = 0; //initially read from VBO_ID[0]
int Write_Index = 1; //initially write to VBO_ID[1]
float time_sec = 0.0f;
float angle = 0.0f;
bool recording = false;
void reload_shader()
{
GLuint new_shader = InitShader(vertex_shader.c_str(), fragment_shader.c_str());
if (new_shader == -1) // loading failed
{
glClearColor(1.0f, 0.0f, 1.0f, 0.0f);
}
else
{
//glClearColor(0.35f, 0.35f, 0.35f, 0.0f);
glClearColor(1.0f, 0.95f, 0.9f, 0.0f);
if (shader_program != -1)
{
glDeleteProgram(shader_program);
}
shader_program = new_shader;
//You need to specify which varying variables will capture transform feedback values.
const char *vars[] = { "pos_out", "vel_out", "age_out" };
glTransformFeedbackVaryings(shader_program, 3, vars, GL_INTERLEAVED_ATTRIBS);
//Must relink the program after specifying transform feedback varyings.
glLinkProgram(shader_program);
int status;
glGetProgramiv(shader_program, GL_LINK_STATUS, &status);
if (status == GL_FALSE)
{
printProgramLinkError(shader_program);
}
}
}
//Draw the user interface using ImGui
void draw_gui()
{
ImGui_ImplGlut_NewFrame();
if (ImGui::Button("Reload Shader"))
{
reload_shader();
}
const int filename_len = 256;
static char video_filename[filename_len] = "capture.mp4";
ImGui::InputText("Video filename", video_filename, filename_len);
ImGui::SameLine();
if (recording == false)
{
if (ImGui::Button("Start Recording"))
{
const int w = glutGet(GLUT_WINDOW_WIDTH);
const int h = glutGet(GLUT_WINDOW_HEIGHT);
recording = true;
start_encoding(video_filename, w, h); //Uses ffmpeg
}
}
else
{
if (ImGui::Button("Stop Recording"))
{
recording = false;
finish_encoding(); //Uses ffmpeg
}
}
//create a slider to change the angle variables
ImGui::SliderFloat("View angle", &angle, -3.141592f, +3.141592f);
static float slider = 0.5f;
if(ImGui::SliderFloat("Slider", &slider, 0.0f, 1.0f))
{
glUniform1f(2, slider);
}
//static bool show = false;
//ImGui::ShowTestWindow(&show);
ImGui::Render();
}
// glut display callback function.
// This function gets called every time the scene gets redisplayed
void display()
{
//clear the screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(shader_program);
const int w = glutGet(GLUT_WINDOW_WIDTH);
const int h = glutGet(GLUT_WINDOW_HEIGHT);
const float aspect_ratio = float(w) / float(h);
glm::mat4 M = glm::rotate(angle, glm::vec3(0.0f, 1.0f, 0.0f))*glm::scale(glm::vec3(0.4f,0.4f,0.4f));
glm::mat4 V = glm::lookAt(glm::vec3(0.0f, 1.0f, 2.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
glm::mat4 P = glm::perspective(3.141592f / 4.0f, aspect_ratio, 0.1f, 100.0f);
int PVM_loc = glGetUniformLocation(shader_program, "PVM");
if (PVM_loc != -1)
{
glm::mat4 PVM = P*V*M;
glUniformMatrix4fv(PVM_loc, 1, false, glm::value_ptr(PVM));
}
const bool TFO_SUPPORTED = true;
if(TFO_SUPPORTED == true)
{
//Bind the current write transform feedback object.
glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, tfo[Write_Index]);
}
else
{
//Binding the transform feedback object recalls the buffer range state shown below. If
//your system does not support transform feedback objects you can uncomment the following lines.
const GLint pos_varying = 0;
const GLint vel_varying = 1;
const GLint age_varying = 2;
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, pos_varying, vbo[Write_Index]);
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, vel_varying, vbo[Write_Index]);
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, age_varying, vbo[Write_Index]);
}
glDepthMask(GL_FALSE);
//Prepare the pipeline for transform feedback
glBeginTransformFeedback(GL_POINTS);
glBindVertexArray(vao[Read_Index]);
glDrawArrays(GL_POINTS, 0, num_particles);
glEndTransformFeedback();
if(TFO_SUPPORTED == true)
{
//Bind the current write transform feedback object.
glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, 0);
}
//Ping-pong the buffers.
Read_Index = 1 - Read_Index;
Write_Index = 1 - Write_Index;
glDepthMask(GL_TRUE);
if (recording == true)
{
glFinish();
glReadBuffer(GL_BACK);
read_frame_to_encode(&rgb, &pixels, w, h);
encode_frame(rgb);
}
draw_gui();
glutSwapBuffers();
}
// glut idle callback.
//This function gets called between frames
void idle()
{
glutPostRedisplay();
const int time_ms = glutGet(GLUT_ELAPSED_TIME);
time_sec = 0.001f*time_ms;
glUniform1f(1, time_sec);
}
// Display info about the OpenGL implementation provided by the graphics driver.
// Your version should be > 4.0 for CGT 521
void printGlInfo()
{
std::cout << "Vendor: " << glGetString(GL_VENDOR) << std::endl;
std::cout << "Renderer: " << glGetString(GL_RENDERER) << std::endl;
std::cout << "Version: " << glGetString(GL_VERSION) << std::endl;
std::cout << "GLSL Version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
}
#define BUFFER_OFFSET( offset ) ((GLvoid*) (offset))
void initOpenGl()
{
//Initialize glew so that new OpenGL function names can be used
glewInit();
RegisterCallback();
glEnable(GL_DEPTH_TEST);
//Enable alpha blending
glEnable(GL_BLEND);
//glBlendFunc(GL_SRC_ALPHA, GL_ONE); //additive alpha blending
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //semitransparent alpha blending
//Allow setting point size in fragment shader
glEnable(GL_PROGRAM_POINT_SIZE);
//reload shader is modified to specify transform feedback varyings
reload_shader();
//create TFOs
glGenTransformFeedbacks(2, tfo);
//all attribs are initially zero
float zeros[7*num_particles] = {0.0f}; //particle positions, velocities, ages
const int stride = 7*sizeof(float);
const int pos_offset = 0;
const int vel_offset = sizeof(glm::vec3);
const int age_offset = 2*sizeof(glm::vec3);
const int pos_size = num_particles * sizeof(glm::vec3);
const int vel_size = num_particles * sizeof(glm::vec3);
const int age_size = num_particles * sizeof(float);
//These are the indices in the array passed to glTransformFeedbackVaryings (const char *vars[] = { "pos_out", "vel_out", "age_out" };)
const GLint pos_varying = 0;
const GLint vel_varying = 1;
const GLint age_varying = 2;
//create VAOs and VBOs
glGenVertexArrays(2, vao);
glGenBuffers(2, vbo);
//These are the attribute locations we specify in the shader.
const GLint pos_loc = 0;
const GLint vel_loc = 1;
const GLint age_loc = 2;
for(int i=0; i<2; i++)
{
//Create VAO and VBO with interleaved attributes
glBindVertexArray(vao[i]);
glBindBuffer(GL_ARRAY_BUFFER, vbo[i]);
glBufferData(GL_ARRAY_BUFFER, sizeof(zeros), zeros, GL_DYNAMIC_COPY);
glEnableVertexAttribArray(pos_loc);
glVertexAttribPointer(pos_loc, 3, GL_FLOAT, false, stride, BUFFER_OFFSET(pos_offset));
glEnableVertexAttribArray(vel_loc);
glVertexAttribPointer(vel_loc, 3, GL_FLOAT, false, stride, BUFFER_OFFSET(vel_offset));
glEnableVertexAttribArray(age_loc);
glVertexAttribPointer(age_loc, 1, GL_FLOAT, false, stride, BUFFER_OFFSET(age_offset));
//Tell the TFO where each varying variable should be written in the VBO.
glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, tfo[i]);
//Specify VBO to write into
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, pos_varying, vbo[i]);
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, vel_varying, vbo[i]);
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, age_varying, vbo[i]);
glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, 0);
glBindVertexArray(0); //unbind vao
glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind vbo
}
}
// glut callbacks need to send keyboard and mouse events to imgui
void keyboard(unsigned char key, int x, int y)
{
ImGui_ImplGlut_KeyCallback(key);
std::cout << "key : " << key << ", x: " << x << ", y: " << y << std::endl;
switch(key)
{
case 'r':
case 'R':
reload_shader();
break;
}
}
void keyboard_up(unsigned char key, int x, int y)
{
ImGui_ImplGlut_KeyUpCallback(key);
}
void special_up(int key, int x, int y)
{
ImGui_ImplGlut_SpecialUpCallback(key);
}
void passive(int x, int y)
{
ImGui_ImplGlut_PassiveMouseMotionCallback(x,y);
}
void special(int key, int x, int y)
{
ImGui_ImplGlut_SpecialCallback(key);
}
void motion(int x, int y)
{
ImGui_ImplGlut_MouseMotionCallback(x, y);
}
void mouse(int button, int state, int x, int y)
{
ImGui_ImplGlut_MouseButtonCallback(button, state);
}
int main (int argc, char **argv)
{
//Configure initial window state using freeglut
#if _DEBUG
glutInitContextFlags(GLUT_DEBUG);
#endif
glutInitContextVersion(4, 3);
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowPosition (5, 5);
glutInitWindowSize (1280, 720);
int win = glutCreateWindow ("Transform Feedback Demo");
printGlInfo();
//Register callback functions with glut.
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
glutSpecialFunc(special);
glutKeyboardUpFunc(keyboard_up);
glutSpecialUpFunc(special_up);
glutMouseFunc(mouse);
glutMotionFunc(motion);
glutPassiveMotionFunc(motion);
glutIdleFunc(idle);
initOpenGl();
ImGui_ImplGlut_Init(); // initialize the imgui system
//Enter the glut event loop.
glutMainLoop();
glutDestroyWindow(win);
return 0;
}
|
/*
File: InputParser.cpp
Authors:
Indranil Saha (isaha@cse.iitk.ac.in)
Ankush Desai(ankush@eecs.berkeley.edu)
This file is used for parsing the inputs to complan.
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <math.h>
#include <stdlib.h>
#include "MotionPrimitives.h"
#include "InputParser.h"
using namespace std;
void ReadMotionPrimitives(MotionPrimitive_Vector &primitives)
{
ifstream ifp;
string line;
string str;
int location, location1, location2, location3;
RobotPosition pos_tmp;
int xmin, ymin, xmax, ymax;
RobotState q_i, q_f;
RobotPosition pos_f;
string fls;
float cost;
RobotPosition_Vector swath;
RobotPosition pos_min;
RobotPosition pos_max;
ifp.open("2d_template.txt");
if (ifp.is_open())
{
while (getline(ifp, line))
{
//cout << line << endl;
location = line.find(":");
if (line.substr(0, location) == "q_i")
{
istringstream (line.substr(location+2, 1)) >> q_i.velocity;
}
if (line.substr(0, location) == "q_f")
{
istringstream (line.substr(location+2, 1)) >> q_f.velocity;
}
if (line.substr(0, location) == "pos_f")
{
location1 = line.find('[');
location2 = line.find(',');
location3 = line.find(']');
istringstream (line.substr(location1 + 1, location2 - location1 - 1)) >> pos_f.x;
istringstream (line.substr(location2 + 2, location3 - location2 - 2)) >> pos_f.y;
}
if (line.substr(0, location) == "cost")
{
fls = line.substr(location + 1);
istringstream (fls) >> cost;
}
if (line.substr(0, location) == "swath")
{
str = line.substr(location+1);
xmin = 10000; ymin = 10000; xmax = -10000; ymax = -10000;
location = str.find(';');
while (location != -1)
{
location1 = str.find('[');
location2 = str.find(',');
location3 = str.find(']');
istringstream (str.substr(location1 + 1, location2 - location1 - 1)) >> pos_tmp.x;
istringstream (str.substr(location2 + 2, location3 - location2 - 2)) >> pos_tmp.y;
swath.push_back(pos_tmp);
if (pos_tmp.x < xmin)
xmin = pos_tmp.x;
if (pos_tmp.y < ymin)
ymin = pos_tmp.y;
if (pos_tmp.x > xmax)
xmax = pos_tmp.x;
if (pos_tmp.y > ymax)
ymax = pos_tmp.y;
str = str.substr(location+1);
location = str.find(';');
//cout << pos_tmp.x << " --- " << pos_tmp.y << endl;
}
location1 = str.find('[');
location2 = str.find(',');
location3 = str.find(']');
istringstream (str.substr(location1 + 1, location2 - location1 - 1)) >> pos_tmp.x;
istringstream (str.substr(location2 + 2, location3 - location2 - 2)) >> pos_tmp.y;
//cout << pos_tmp.x << " --- " << pos_tmp.y << endl;
swath.push_back(pos_tmp);
if (pos_tmp.x < xmin)
xmin = pos_tmp.x;
if (pos_tmp.y < ymin)
ymin = pos_tmp.y;
if (pos_tmp.x > xmax)
xmax = pos_tmp.x;
if (pos_tmp.y > ymax)
ymax = pos_tmp.y;
pos_min.x = xmin;
pos_min.y = ymin;
pos_max.x = xmax;
pos_max.y = ymax;
MotionPrimitive prim(q_i, q_f, pos_f, cost, swath, pos_min, pos_max);
primitives.push_back(prim);
swath.erase (swath.begin(), swath.end());
}
}
ifp.close();
}
}
void WriteMotionPrimitives(MotionPrimitive_Vector primitives)
{
unsigned int count1, count2;
RobotState q_i, q_f;
RobotPosition pos_f;
string cost;
RobotPosition_Vector swath;
RobotPosition pos_min;
RobotPosition pos_max;
//cout << endl << "PRIMITIVES:" << endl << endl;
for(count1 = 0; count1 < primitives.size(); count1++)
{
cout << "Primitive " << count1 << endl;
q_i = primitives[count1].get_q_i();
cout << "q_i: " << q_i.velocity << endl;
q_f = primitives[count1].get_q_f();
cout << "q_f: " << q_f.velocity << endl;
pos_f = primitives[count1].get_pos_f();
cout << "pos_f: " << pos_f.x << " " << pos_f.y << endl;
cost = primitives[count1].get_cost();
cout << "cost: " << cost << endl;
swath = primitives[count1].get_swath();
cout << "swath: ";
for(count2 = 0; count2 < swath.size(); count2++)
{
cout << swath[count2].x << " " << swath[count2].y << " | ";
}
cout << endl;
pos_min = primitives[count1].get_pos_min();
cout << "pos_min: " << pos_min.x << " " << pos_min.y << endl;
pos_max = primitives[count1].get_pos_max();
cout << "pos_max: " << pos_max.x << " " << pos_max.y << endl;
cout << endl;
}
}
void GetMotionPrimitiveCost(MotionPrimitive_Vector primitives, MotionPrimitive_Cost & prim_cost)
{
unsigned int count1, count2;
float str1, str2;
prim_cost.max_cost = 0;
prim_cost.min_cost = 100000;
prim_cost.min_cost_diff = 100000;
for (count1 = 0; count1 < primitives.size(); count1++)
{
str1 = primitives[count1].get_cost();
if (str1 > prim_cost.max_cost)
prim_cost.max_cost = str1;
if (str1 < prim_cost.min_cost)
prim_cost.min_cost = str1;
for (count2 = count1 + 1; count2 < primitives.size(); count2++)
{
str2 = primitives[count2].get_cost();
if (fabs(str1 - str2) > 0.0001 && fabs(str1 - str2) < prim_cost.min_cost_diff)
prim_cost.min_cost_diff = fabs(str1 - str2);
}
}
}
void WriteMotionPrimitiveCost(MotionPrimitive_Cost prim_cost)
{
cout << endl << "PRIMITIVE COST INFORMATION:" << endl << endl;
cout << "prim_max_cost = " << prim_cost.max_cost << endl;
cout << "prim_min_cost = " << prim_cost.min_cost << endl;
cout << "prim_min_cost_diff = " << prim_cost.min_cost_diff << endl;
}
void ReadDimension(Dimension &dimension)
{
ifstream ifp;
string line;
ifp.open("dimension.txt");
if (ifp.is_open())
{
getline(ifp, line);
istringstream (line) >> dimension.length_x;
getline(ifp, line);
istringstream (line) >> dimension.length_y;
}
else
{
cout << "dimension.txt file cannot be opened.." << endl;
exit(0);
}
}
void WriteDimension(Dimension dimension)
{
cout << endl << "DIMENSION:" << endl << endl;
cout << dimension.length_x << endl;
cout << dimension.length_y << endl;
cout << endl;
}
void FindLocation(Dimension dimension, int id, int &x, int &y)
{
//cout << "dimx = " << dimension.length_x << endl;
//cout << "dimy = " << dimension.length_y << endl;
//cout << "id = " << id << endl;
x = (id - 1) / dimension.length_x;
y = (id - 1) % dimension.length_x;
//cout << "x = " << x << " " << "y = " << y << endl;
if (((id - 1) / dimension.length_x) %2 == 1)
{
y = dimension.length_y - y - 1;
}
}
void FindIndex(Dimension dimension, int x, int y, int &id)
{
if (x % 2 == 0 )
{
id = dimension.length_x * x + y + 1;
}
else
{
id = dimension.length_x * x + (dimension.length_y - y);
}
}
|
#include <iostream>
#include <vector>
#include <array>
#include <math.h>
#include "consts.hpp"
#include "ensemble.hpp"
#include "MT.h"
using namespace std;
//コンストラクタ
Ens::Ens(){
int i, ix, iy;
div_t div_i;
double sum_ux=0, sum_uy=0, r1, r2;
init_genrand(1);
for(i=0; i<NAtom; i++){
div_i = div(i, NInitConfig);
ix = div_i.quot;
iy = div_i.rem;
x[i] = ((double)ix+0.5)*LBox/((double)NInitConfig);
y[i] = ((double)iy+0.5)*LBox/((double)NInitConfig);
x_ref[i] = x[i];
y_ref[i] = y[i];
r1=genrand_real3();
r2=genrand_real3();
ux[i]=sqrt(-2.0*log(r1))*cos(2.0*M_PI*r2);
uy[i]=sqrt(-2.0*log(r1))*sin(2.0*M_PI*r2);
sum_ux += ux[i];
sum_uy += uy[i];
}
//系全体の運動量をゼロにする
for(i=0; i<NAtom; i++){
ux[i] -= sum_ux/(double)NAtom;
uy[i] -= sum_ux/(double)NAtom;
}
}
bool Ens::apply_pbc(){
int i;
for(i=0;i<NAtom;i++){
if(x[i]<0.0){
x[i] += LBox;
}else if(x[i]>=LBox){
x[i] -= LBox;
}
if(y[i]<0.0){
y[i] += LBox;
}else if(y[i]>=LBox){
y[i] -= LBox;
}
}
return true;
}
void Ens::calcu(double T1){
int i;
for(i=0;i<NAtom;i++){
ux[i] += T1*Fx[i];
uy[i] += T1*Fy[i];
}
}
void Ens::calcr(double T1){
int i;
for(i=0;i<NAtom;i++){
x[i] += T1*ux[i];
y[i] += T1*uy[i];
}
}
double Ens::pbc_dist(double r){
double result;
if(r >= LHalf){
result = r - LBox;
}else if(r < -LHalf){
result = r + LBox;
}else{
result = r;
}
return result;
}
void Ens::give_label(){
int i,im;
for(im=0;im<MCell*MCell;im++){
LinkedList[im].clear();
LinkedList[im].shrink_to_fit();
}
for(i=0;i<NAtom;i++){
//粒子iがどのセルに属するかを調べる →コメントでは、簡単にセル(ix,iy)と表す
label_x[i] = floor(MCell/LBox*x[i]);
label_y[i] = floor(MCell/LBox*y[i]);
//セル(ix,iy)を番号ix+iy*Mで指定
//LinkedListを(ix, iy)に入っている粒子の一覧にするため、LinkedListに番号iを追加
LinkedList[label_x[i]+label_y[i]*MCell].push_back(i);
}
}
void Ens::make_VNL(){
NeighborList_i.clear();
NeighborList_i.shrink_to_fit();
NeighborList_j.clear();
NeighborList_j.shrink_to_fit();
pot=0.0;
int i,ix,iy,i_delta,jx,jy,j_cell,k,j;
double xij, yij, rij, Eij, Fij;
for(i=0;i<NAtom;i++){
Fx[i]=0.0;
Fy[i]=0.0;
}
give_label();
array<int, 5> delta_ix={0, 0, 1, 1, 1};
array<int, 5> delta_iy={0, -1, -1, 0, 1}; //順に、同じセル、上、右上、右、右下を指定する
for(i=0;i<NAtom;i++){
ix=label_x[i];
iy=label_y[i];
for(i_delta=0;i_delta<5;i_delta++){
jx = floored_mod((ix+delta_ix[i_delta]) , MCell); //近接するセルを指定
jy = floored_mod((iy+delta_iy[i_delta]) , MCell);
j_cell=jx+jy*MCell;
for(k=0;k<LinkedList[j_cell].size();k++){
j=LinkedList[j_cell][k];
if((i_delta==0) && (j<=i)){
continue;
}
xij = pbc_dist(x[j] - x[i]);
yij = pbc_dist(y[j] - y[i]);
rij=sqrt(pow(xij,2)+pow(yij,2));
Eij=0.0;
Fij=0.0;
if(rij<RList){
NeighborList_i.push_back(i);
NeighborList_j.push_back(j);
if(rij<Rcut){
Eij=4.0*(pow(rij,-12)-pow(rij,-6));
Fij=24.0*(-2.0*pow(rij,-13)+pow(rij,-7));
Fx[i] += Fij*xij/rij;
Fy[i] += Fij*yij/rij;
Fx[j] -= Fij*xij/rij;
Fy[j] -= Fij*yij/rij;
pot += Eij/(double)NAtom;
}
}
}
}
}
cout << "update VNL" <<endl;
}
/*
void Ens::make_VNL2(){
NeighborList_i.clear();
NeighborList_i.shrink_to_fit();
NeighborList_j.clear();
NeighborList_j.shrink_to_fit();
pot=0.0;
int i,j;
double xij, yij, rij, Eij, Fij;
for(i=0;i<NAtom;i++){
Fx[i]=0.0;
Fy[i]=0.0;
}
for(i=0;i<NAtom;i++){
for(j=i+1;j<NAtom;j++){
xij = pbc_dist(x[j] - x[i]);
yij = pbc_dist(y[j] - y[i]);
rij=sqrt(pow(xij,2)+pow(yij,2));
Eij=0.0;
Fij=0.0;
if(rij<RList){
NeighborList_i.push_back(i);
NeighborList_j.push_back(j);
if(rij<Rcut){
Eij=4.0*(pow(rij,-12)-pow(rij,-6));
Fij=24.0*(-2.0*pow(rij,-13)+pow(rij,-7));
Fx[i] += Fij*xij/rij;
Fy[i] += Fij*yij/rij;
Fx[j] -= Fij*xij/rij;
Fy[j] -= Fij*yij/rij;
pot += Eij/(double)NAtom;
}
}
}
}
cout << "update VNL" <<endl;
}*/
bool Ens::check_update_VNL(){
double diff,diffmax; //i番目の粒子がrefと比べてどれくらいの距離離れたか
int i;
diffmax=0.0;
for(i=0;i<NAtom;i++){
diff=sqrt(pow((x[i]-x_ref[i]),2)+pow((y[i]-y_ref[i]),2));
if(diff>diffmax){
diffmax=diff;
}
}
if(diffmax > Skin/2.0){
return true;
}else{
return false;
}
}
void Ens::use_VNL(){
pot=0.0;
int i,j,k,i_F;
for(i_F=0;i_F<NAtom;i_F++){
Fx[i_F]=0.0;
Fy[i_F]=0.0;
}
double xij,yij,rij,Eij,Fij;
for(k=0;k<NeighborList_i.size();k++){
i=NeighborList_i[k];
j=NeighborList_j[k];
xij = pbc_dist(x[j] - x[i]);
yij = pbc_dist(y[j] - y[i]);
rij=sqrt(pow(xij,2)+pow(yij,2));
if(rij<Rcut){
Eij=4.0*(pow(rij,-12)-pow(rij,-6));
Fij=24.0*(-2.0*pow(rij,-13)+pow(rij,-7));
Fx[i] += Fij*xij/rij;
Fy[i] += Fij*yij/rij;
Fx[j] -= Fij*xij/rij;
Fy[j] -= Fij*yij/rij;
pot += Eij/(double)NAtom;
}
}
}
void Ens::calcF(){
if(check_update_VNL()){
make_VNL(); //!
int i;
for(i=0;i<NAtom;i++){
x_ref[i]=(x[i]*1.0);
y_ref[i]=(y[i]*1.0);
}
}else{
use_VNL();
}
}
void Ens::VVcycle(){
calcu(dT/2.0);
calcr(dT);
apply_pbc();
calcF();
calcu(dT/2.0);
temp = 0;
int i;
for(i=0;i<NAtom;i++){
temp += ((pow(ux[i],2)+pow(uy[i],2))/2.0)/double(NAtom);
}
energy = temp + pot;
}
array<double,NAtom> Ens::getx(){
return x;
}
array<double,NAtom> Ens::gety(){
return y;
}
array<double,NAtom> Ens::getux(){
return ux;
}
array<double,NAtom> Ens::getuy(){
return uy;
}
array<double,NAtom> Ens::getFx(){
return Fx;
}
array<double,NAtom> Ens::getFy(){
return Fy;
}
double Ens::get_energy(){
return energy;
}
double Ens::get_pot(){
return pot;
}
double Ens::get_temp(){
return temp;
}
//-------------------------------------
//切り捨て割り算(余りの符号はbの符号と一致)
int floored_mod(int a, int b){
return a-floor((double)a/(double)b)*b;
}
|
bonsai_function u32
GetWorkerThreadCount()
{
u32 LogicalCoreCount = PlatformGetLogicalCoreCount();
u32 Bias = 1 + DEBUG_THREAD_COUNT_BIAS; // +1 because we already have a main thread
if (Bias >= LogicalCoreCount)
{
Bias = LogicalCoreCount - 1;
}
u32 ThreadCount = LogicalCoreCount - Bias;
return ThreadCount;
}
bonsai_function u32
GetTotalThreadCount()
{
u32 Result = GetWorkerThreadCount() + 1;
return Result;
}
inline void
SuspendWorkerThreads()
{
TIMED_FUNCTION();
MainThreadBlocksWorkerThreads = True;
u32 WorkerThreadCount = GetWorkerThreadCount();
while (WorkerThreadsWaiting < WorkerThreadCount);
return;
}
inline void
ResumeWorkerThreads()
{
TIMED_FUNCTION();
MainThreadBlocksWorkerThreads = False;
return;
}
|
#include <Python.h>
#include <QDir>
#include <QMessageBox>
#include <QCloseEvent>
#include "app/app.h"
#include "window/base.h"
// Initialize global window count (used to detect when last window closes)
int BaseWindow::window_count = 0;
BaseWindow::BaseWindow(QString type)
: QMainWindow(), window_type(type), ui(new Ui::BaseWindow)
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
connectActions(App::instance());
setShortcuts();
window_count++;
}
BaseWindow::~BaseWindow()
{
window_count--;
}
void BaseWindow::connectActions(App* app)
{
// File menu
connect(ui->actionSave, &QAction::triggered,
app, &App::onSave);
connect(ui->actionSaveAs, &QAction::triggered,
app, &App::onSaveAs);
connect(ui->actionNew, &QAction::triggered,
app, &App::onNew);
connect(ui->actionOpen, &QAction::triggered,
app, &App::onOpen);
connect(ui->actionQuit, &QAction::triggered,
app, &App::onQuit);
connect(ui->actionClose, &QAction::triggered,
this, &BaseWindow::tryClose);
// Add undo / redo to edit menu
ui->menuEdit->addAction(App::instance()->getUndoAction());
ui->menuEdit->addAction(App::instance()->getRedoAction());
// View window
connect(ui->actionNewCanvas, &QAction::triggered,
app, &App::newCanvasWindow);
connect(ui->actionNewViewport, &QAction::triggered,
app, &App::newViewportWindow);
connect(ui->actionNewQuad, &QAction::triggered,
app, &App::newQuadWindow);
// Help menu
connect(ui->actionAbout, &QAction::triggered,
app, &App::onAbout);
connect(ui->actionCheckUpdate, &QAction::triggered,
app, &App::onUpdateCheck);
// Connect to the App-level signals that adjust window titles
connect(app, &App::filenameChanged,
this, &BaseWindow::setFilename);
connect(app, &App::cleanChanged,
this, &BaseWindow::setClean);
// Ask the app to emit those signals to set our title
App::instance()->onNewWindow();
}
////////////////////////////////////////////////////////////////////////////////
void BaseWindow::setFilename(QString f)
{
filename = f;
updateTitle();
}
void BaseWindow::setClean(bool c)
{
clean = c;
updateTitle();
}
void BaseWindow::setSub(QString s)
{
sub = s;
updateTitle();
}
void BaseWindow::updateTitle()
{
auto title = window_type + " [";
if (filename.isEmpty())
{
title += "untitled";
}
else
{
// Use a shorter version of the filename if we're in a subgraph
title += sub.isEmpty()
? filename
: filename.split(QDir::separator()).last().replace(".sb", "");
}
if (!sub.isEmpty())
{
title += "." + sub;
}
title += "]";
if (!clean)
{
title += "*";
}
setWindowTitle(title);
}
////////////////////////////////////////////////////////////////////////////////
void BaseWindow::setShortcuts()
{
ui->actionNew->setShortcuts(QKeySequence::New);
ui->actionOpen->setShortcuts(QKeySequence::Open);
ui->actionSave->setShortcuts(QKeySequence::Save);
ui->actionSaveAs->setShortcuts(QKeySequence::SaveAs);
ui->actionClose->setShortcuts(QKeySequence::Close);
ui->actionQuit->setShortcuts(QKeySequence::Quit);
ui->actionCut->setShortcuts(QKeySequence::Cut);
ui->actionCopy->setShortcuts(QKeySequence::Copy);
ui->actionPaste->setShortcuts(QKeySequence::Paste);
}
////////////////////////////////////////////////////////////////////////////////
bool BaseWindow::askClose()
{
if(window_count <= 1 && !App::instance()->isUndoStackClean())
{
auto res = QMessageBox::question(
this, "Antimony", "There are unsaved changes!\n"
"Do you still want to close this window?\n",
QMessageBox::No | QMessageBox::Yes, QMessageBox::Yes);
return (res == QMessageBox::Yes);
}
return true;
}
void BaseWindow::closeEvent(QCloseEvent* event)
{
if (!askClose())
{
event->ignore();
}
}
void BaseWindow::tryClose()
{
if (askClose())
{
deleteLater();
}
}
|
//-----------------------------------------------------------------------------
// Copyright (c) 2015 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "platform/platform.h"
#include "gfx/D3D11/gfxD3D11Shader.h"
#include "core/frameAllocator.h"
#include "core/stream/fileStream.h"
#include "core/util/safeDelete.h"
#include "console/console.h"
extern bool gDisassembleAllShaders;
#pragma comment(lib, "d3dcompiler.lib")
gfxD3DIncludeRef GFXD3D11Shader::smD3DInclude = NULL;
class gfxD3D11Include : public ID3DInclude, public StrongRefBase
{
private:
Vector<String> mLastPath;
public:
void setPath(const String &path)
{
mLastPath.clear();
mLastPath.push_back(path);
}
gfxD3D11Include() {}
virtual ~gfxD3D11Include() {}
STDMETHOD(Open)(THIS_ D3D_INCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes);
STDMETHOD(Close)(THIS_ LPCVOID pData);
};
HRESULT gfxD3D11Include::Open(THIS_ D3D_INCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes)
{
using namespace Torque;
// First try making the path relative to the parent.
Torque::Path path = Torque::Path::Join( mLastPath.last(), '/', pFileName );
path = Torque::Path::CompressPath( path );
if ( !Torque::FS::ReadFile( path, (void *&)*ppData, *pBytes, true ) )
{
// Ok... now try using the path as is.
path = String( pFileName );
path = Torque::Path::CompressPath( path );
if ( !Torque::FS::ReadFile( path, (void *&)*ppData, *pBytes, true ) )
{
AssertISV(false, avar( "Failed to open include '%s'.", pFileName));
return E_FAIL;
}
}
// If the data was of zero size then we cannot recurse
// into this file and DX won't call Close() below.
//
// So in this case don't push on the path.
if ( *pBytes > 0 )
mLastPath.push_back( path.getRootAndPath() );
return S_OK;
}
HRESULT gfxD3D11Include::Close( THIS_ LPCVOID pData )
{
// Free the data file and pop its path off the stack.
delete [] (U8*)pData;
mLastPath.pop_back();
return S_OK;
}
GFXD3D11ShaderConstHandle::GFXD3D11ShaderConstHandle()
{
clear();
}
const String& GFXD3D11ShaderConstHandle::getName() const
{
if ( mVertexConstant )
return mVertexHandle.name;
else
return mPixelHandle.name;
}
GFXShaderConstType GFXD3D11ShaderConstHandle::getType() const
{
if ( mVertexConstant )
return mVertexHandle.constType;
else
return mPixelHandle.constType;
}
U32 GFXD3D11ShaderConstHandle::getArraySize() const
{
if ( mVertexConstant )
return mVertexHandle.arraySize;
else
return mPixelHandle.arraySize;
}
S32 GFXD3D11ShaderConstHandle::getSamplerRegister() const
{
if ( !mValid || !isSampler() )
return -1;
// We always store sampler type and register index in the pixelHandle,
// sampler registers are shared between vertex and pixel shaders anyway.
return mPixelHandle.offset;
}
GFXD3D11ConstBufferLayout::GFXD3D11ConstBufferLayout()
{
mSubBuffers.reserve(CBUFFER_MAX);
}
bool GFXD3D11ConstBufferLayout::set(const ParamDesc& pd, const GFXShaderConstType constType, const U32 inSize, const void* data, U8* basePointer)
{
PROFILE_SCOPE(GenericConstBufferLayout_set);
S32 size = inSize;
// Shader compilers like to optimize float4x4 uniforms into float3x3s.
// So long as the real paramater is a matrix of-some-type and the data
// passed in is a MatrixF ( which is will be ), we DO NOT have a
// mismatched const type.
AssertFatal(pd.constType == constType ||
(
(pd.constType == GFXSCT_Float2x2 ||
pd.constType == GFXSCT_Float3x3 ||
pd.constType == GFXSCT_Float4x3 ||
pd.constType == GFXSCT_Float4x4) &&
(constType == GFXSCT_Float2x2 ||
constType == GFXSCT_Float3x3 ||
constType == GFXSCT_Float4x3 ||
constType == GFXSCT_Float4x4)
), "Mismatched const type!");
// This "cute" bit of code allows us to support 2x3 and 3x3 matrices in shader constants but use our MatrixF class. Yes, a hack. -BTR
switch (pd.constType)
{
case GFXSCT_Float2x2:
case GFXSCT_Float3x3:
case GFXSCT_Float4x3:
case GFXSCT_Float4x4:
return setMatrix(pd, constType, size, data, basePointer);
break;
// TODO add other AlignedVector here
case GFXSCT_Float2:
if (size > sizeof(Point2F))
size = pd.size;
default:
break;
}
AssertFatal(pd.size >= size, "Not enough room in the buffer for this data!");
// Ok, we only set data if it's different than the data we already have, this maybe more expensive than just setting the data, but
// we'll have to do some timings to see. For example, the lighting shader constants rarely change, but we can't assume that at the
// renderInstMgr level, but we can check down here. -BTR
if (dMemcmp(basePointer + pd.offset, data, size) != 0)
{
dMemcpy(basePointer + pd.offset, data, size);
return true;
}
return false;
}
bool GFXD3D11ConstBufferLayout::setMatrix(const ParamDesc& pd, const GFXShaderConstType constType, const U32 size, const void* data, U8* basePointer)
{
PROFILE_SCOPE(GFXD3D11ConstBufferLayout_setMatrix);
if (pd.constType == GFXSCT_Float4x4)
{
// Special case, we can just blast this guy.
AssertFatal(pd.size >= size, "Not enough room in the buffer for this data!");
if (dMemcmp(basePointer+pd.offset, data, size) != 0)
{
dMemcpy(basePointer+pd.offset, data, size);
return true;
}
return false;
}
else
{
PROFILE_SCOPE(GFXD3D11ConstBufferLayout_setMatrix_not4x4);
// Figure out how big of a chunk we are copying. We're going to copy 4 columns by N rows of data
U32 csize;
switch (pd.constType)
{
case GFXSCT_Float2x2 :
csize = 24; //this takes up 16+8
break;
case GFXSCT_Float3x3 :
csize = 44; //This takes up 16+16+12
break;
case GFXSCT_Float4x3:
csize = 48;
break;
default:
AssertFatal(false, "Unhandled case!");
return false;
break;
}
// Loop through and copy
bool ret = false;
U8* currDestPointer = basePointer+pd.offset;
const U8* currSourcePointer = static_cast<const U8*>(data);
const U8* endData = currSourcePointer + size;
while (currSourcePointer < endData)
{
if (dMemcmp(currDestPointer, currSourcePointer, csize) != 0)
{
dMemcpy(currDestPointer, currSourcePointer, csize);
ret = true;
}
else if (pd.constType == GFXSCT_Float4x3)
{
ret = true;
}
currDestPointer += csize;
currSourcePointer += sizeof(MatrixF);
}
return ret;
}
}
//------------------------------------------------------------------------------
GFXD3D11ShaderConstBuffer::GFXD3D11ShaderConstBuffer( GFXD3D11Shader* shader,
GFXD3D11ConstBufferLayout* vertexLayout,
GFXD3D11ConstBufferLayout* pixelLayout)
{
AssertFatal( shader, "GFXD3D11ShaderConstBuffer() - Got a null shader!" );
// We hold on to this so we don't have to call
// this virtual method during activation.
mShader = shader;
for (U32 i = 0; i < CBUFFER_MAX; ++i)
{
mConstantBuffersV[i] = NULL;
mConstantBuffersP[i] = NULL;
}
// TODO: Remove buffers and layouts that don't exist for performance?
//Mandatory
mVertexConstBufferLayout = vertexLayout;
mVertexConstBuffer = new GenericConstBuffer(vertexLayout);
mPixelConstBufferLayout = pixelLayout;
mPixelConstBuffer = new GenericConstBuffer(pixelLayout);
mDeviceContext = D3D11DEVICECONTEXT;
_createBuffers();
}
GFXD3D11ShaderConstBuffer::~GFXD3D11ShaderConstBuffer()
{
// release constant buffer
for (U32 i = 0; i < CBUFFER_MAX; ++i)
{
SAFE_RELEASE(mConstantBuffersP[i]);
SAFE_RELEASE(mConstantBuffersV[i]);
}
SAFE_DELETE(mVertexConstBuffer);
SAFE_DELETE(mPixelConstBuffer);
if ( mShader )
mShader->_unlinkBuffer( this );
}
void GFXD3D11ShaderConstBuffer::_createBuffers()
{
HRESULT hr;
// Create a vertex constant buffer
if (mVertexConstBufferLayout->getBufferSize() > 0)
{
const Vector<ConstSubBufferDesc> &subBuffers = mVertexConstBufferLayout->getSubBufferDesc();
for (U32 i = 0; i < subBuffers.size(); ++i)
{
D3D11_BUFFER_DESC cbDesc;
cbDesc.ByteWidth = subBuffers[i].size;
cbDesc.Usage = D3D11_USAGE_DEFAULT;
cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbDesc.CPUAccessFlags = 0;
cbDesc.MiscFlags = 0;
cbDesc.StructureByteStride = 0;
hr = D3D11DEVICE->CreateBuffer(&cbDesc, NULL, &mConstantBuffersV[i]);
if (FAILED(hr))
{
AssertFatal(false, "can't create constant mConstantBuffersV!");
}
}
}
// Create a pixel constant buffer
if (mPixelConstBufferLayout->getBufferSize())
{
const Vector<ConstSubBufferDesc> &subBuffers = mPixelConstBufferLayout->getSubBufferDesc();
for (U32 i = 0; i < subBuffers.size(); ++i)
{
// Create a pixel float constant buffer
D3D11_BUFFER_DESC cbDesc;
cbDesc.ByteWidth = subBuffers[i].size;
cbDesc.Usage = D3D11_USAGE_DEFAULT;
cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbDesc.CPUAccessFlags = 0;
cbDesc.MiscFlags = 0;
cbDesc.StructureByteStride = 0;
hr = D3D11DEVICE->CreateBuffer(&cbDesc, NULL, &mConstantBuffersP[i]);
if (FAILED(hr))
{
AssertFatal(false, "can't create constant mConstantBuffersP!");
}
}
}
}
GFXShader* GFXD3D11ShaderConstBuffer::getShader()
{
return mShader;
}
// This is kind of cheesy, but I don't think templates would work well here because
// these functions potentially need to be handled differently by other derived types
template<class T>
inline void GFXD3D11ShaderConstBuffer::SET_CONSTANT( GFXShaderConstHandle* handle, const T& fv,
GenericConstBuffer *vBuffer, GenericConstBuffer *pBuffer )
{
AssertFatal(static_cast<const GFXD3D11ShaderConstHandle*>(handle), "Incorrect const buffer type!");
const GFXD3D11ShaderConstHandle* h = static_cast<const GFXD3D11ShaderConstHandle*>(handle);
AssertFatal(h, "Handle is NULL!" );
AssertFatal(h->isValid(), "Handle is not valid!" );
AssertFatal(!h->isSampler(), "Handle is sampler constant!" );
AssertFatal(!mShader.isNull(), "Buffer's shader is null!" );
AssertFatal(!h->mShader.isNull(), "Handle's shader is null!" );
AssertFatal(h->mShader.getPointer() == mShader.getPointer(), "Mismatched shaders!");
if ( h->mInstancingConstant )
{
dMemcpy( mInstPtr+h->mPixelHandle.offset, &fv, sizeof( fv ) );
return;
}
if (h->mVertexConstant)
vBuffer->set(h->mVertexHandle, fv);
if (h->mPixelConstant)
pBuffer->set(h->mPixelHandle, fv);
}
void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const F32 fv)
{
SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
}
void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point2F& fv)
{
SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
}
void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point3F& fv)
{
SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
}
void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point4F& fv)
{
SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
}
void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const PlaneF& fv)
{
SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
}
void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const LinearColorF& fv)
{
SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
}
void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const S32 f)
{
// This is the only type that is allowed to be used
// with a sampler shader constant type, but it is only
// allowed to be set from GLSL.
//
// So we ignore it here... all other cases will assert.
//
if ( ((GFXD3D11ShaderConstHandle*)handle)->isSampler() )
return;
SET_CONSTANT(handle, f, mVertexConstBuffer, mPixelConstBuffer);
}
void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point2I& fv)
{
SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
}
void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point3I& fv)
{
SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
}
void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point4I& fv)
{
SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
}
void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<F32>& fv)
{
SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
}
void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<Point2F>& fv)
{
SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
}
void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<Point3F>& fv)
{
SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
}
void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<Point4F>& fv)
{
SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
}
void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<S32>& fv)
{
SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
}
void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<Point2I>& fv)
{
SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
}
void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<Point3I>& fv)
{
SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
}
void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray<Point4I>& fv)
{
SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer);
}
#undef SET_CONSTANT
void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const MatrixF& mat, const GFXShaderConstType matrixType)
{
AssertFatal(handle, "Handle is NULL!" );
AssertFatal(handle->isValid(), "Handle is not valid!" );
AssertFatal(static_cast<const GFXD3D11ShaderConstHandle*>(handle), "Incorrect const buffer type!");
const GFXD3D11ShaderConstHandle* h = static_cast<const GFXD3D11ShaderConstHandle*>(handle);
AssertFatal(!h->isSampler(), "Handle is sampler constant!" );
AssertFatal(h->mShader == mShader, "Mismatched shaders!");
MatrixF transposed;
if (matrixType == GFXSCT_Float4x3)
{
transposed = mat;
}
else
{
mat.transposeTo(transposed);
}
if (h->mInstancingConstant)
{
if ( matrixType == GFXSCT_Float4x4 )
dMemcpy( mInstPtr+h->mPixelHandle.offset, mat, sizeof( mat ) );
// TODO: Support 3x3 and 2x2 matricies?
return;
}
if (h->mVertexConstant)
mVertexConstBuffer->set(h->mVertexHandle, transposed, matrixType);
if (h->mPixelConstant)
mPixelConstBuffer->set(h->mPixelHandle, transposed, matrixType);
}
void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const MatrixF* mat, const U32 arraySize, const GFXShaderConstType matrixType)
{
AssertFatal(handle, "Handle is NULL!" );
AssertFatal(handle->isValid(), "Handle is not valid!" );
AssertFatal(static_cast<const GFXD3D11ShaderConstHandle*>(handle), "Incorrect const buffer type!");
const GFXD3D11ShaderConstHandle* h = static_cast<const GFXD3D11ShaderConstHandle*>(handle);
AssertFatal(!h->isSampler(), "Handle is sampler constant!" );
AssertFatal(h->mShader == mShader, "Mismatched shaders!");
static Vector<MatrixF> transposed;
if (arraySize > transposed.size())
transposed.setSize(arraySize);
if (matrixType == GFXSCT_Float4x3)
{
dMemcpy(transposed.address(), mat, arraySize * sizeof(MatrixF));
}
else
{
for (U32 i = 0; i < arraySize; i++)
mat[i].transposeTo(transposed[i]);
}
// TODO: Maybe support this in the future?
if (h->mInstancingConstant)
return;
if (h->mVertexConstant)
mVertexConstBuffer->set(h->mVertexHandle, transposed.begin(), arraySize, matrixType);
if (h->mPixelConstant)
mPixelConstBuffer->set(h->mPixelHandle, transposed.begin(), arraySize, matrixType);
}
const String GFXD3D11ShaderConstBuffer::describeSelf() const
{
String ret;
ret = String(" GFXD3D11ShaderConstBuffer\n");
for (U32 i = 0; i < mVertexConstBufferLayout->getParameterCount(); i++)
{
GenericConstBufferLayout::ParamDesc pd;
mVertexConstBufferLayout->getDesc(i, pd);
ret += String::ToString(" Constant name: %s", pd.name.c_str());
}
return ret;
}
void GFXD3D11ShaderConstBuffer::zombify()
{
}
void GFXD3D11ShaderConstBuffer::resurrect()
{
}
bool GFXD3D11ShaderConstBuffer::isDirty()
{
bool ret = mVertexConstBuffer->isDirty();
ret |= mPixelConstBuffer->isDirty();
return ret;
}
void GFXD3D11ShaderConstBuffer::activate( GFXD3D11ShaderConstBuffer *prevShaderBuffer )
{
PROFILE_SCOPE(GFXD3D11ShaderConstBuffer_activate);
// NOTE: This is a really critical function as it gets
// called between every draw call to update the constants.
//
// Alot of the calls here are inlined... be careful
// what you change.
// If the buffer has changed we need to compare it
// with the new buffer to see if we can skip copying
// equal buffer content.
//
// If the buffer hasn't changed then we only will
// be copying the changes that have occured since
// the last activate call.
if ( prevShaderBuffer != this )
{
// If the previous buffer is dirty, than we can't compare
// against it, because it hasn't sent its contents to the
// card yet and must be copied.
if ( prevShaderBuffer && !prevShaderBuffer->isDirty() )
{
PROFILE_SCOPE(GFXD3D11ShaderConstBuffer_activate_dirty_check_1);
// If the buffer content is equal then we set the dirty
// flag to false knowing the current state of the card matches
// the new buffer.
//
// If the content is not equal we set the dirty flag to
// true which causes the full content of the buffer to be
// copied to the card.
//
mVertexConstBuffer->setDirty( !prevShaderBuffer->mVertexConstBuffer->isEqual( mVertexConstBuffer ) );
mPixelConstBuffer->setDirty( !prevShaderBuffer->mPixelConstBuffer->isEqual( mPixelConstBuffer ) );
}
else
{
// This happens rarely... but it can happen.
// We copy the entire dirty state to the card.
PROFILE_SCOPE(GFXD3D11ShaderConstBuffer_activate_dirty_check_2);
mVertexConstBuffer->setDirty( true );
mPixelConstBuffer->setDirty( true );
}
}
D3D11_MAPPED_SUBRESOURCE pConstData;
ZeroMemory(&pConstData, sizeof(D3D11_MAPPED_SUBRESOURCE));
const U8* buf;
U32 nbBuffers = 0;
if(mVertexConstBuffer->isDirty())
{
const Vector<ConstSubBufferDesc> &subBuffers = mVertexConstBufferLayout->getSubBufferDesc();
// TODO: This is not very effecient updating the whole lot, re-implement the dirty system to work with multiple constant buffers.
// TODO: Implement DX 11.1 UpdateSubresource1 which supports updating ranges with constant buffers
buf = mVertexConstBuffer->getEntireBuffer();
for (U32 i = 0; i < subBuffers.size(); ++i)
{
const ConstSubBufferDesc &desc = subBuffers[i];
mDeviceContext->UpdateSubresource(mConstantBuffersV[i], 0, NULL, buf + desc.start, desc.size, 0);
nbBuffers++;
}
mDeviceContext->VSSetConstantBuffers(0, nbBuffers, mConstantBuffersV);
}
nbBuffers = 0;
if(mPixelConstBuffer->isDirty())
{
const Vector<ConstSubBufferDesc> &subBuffers = mPixelConstBufferLayout->getSubBufferDesc();
// TODO: This is not very effecient updating the whole lot, re-implement the dirty system to work with multiple constant buffers.
// TODO: Implement DX 11.1 UpdateSubresource1 which supports updating ranges with constant buffers
buf = mPixelConstBuffer->getEntireBuffer();
for (U32 i = 0; i < subBuffers.size(); ++i)
{
const ConstSubBufferDesc &desc = subBuffers[i];
mDeviceContext->UpdateSubresource(mConstantBuffersP[i], 0, NULL, buf + desc.start, desc.size, 0);
nbBuffers++;
}
mDeviceContext->PSSetConstantBuffers(0, nbBuffers, mConstantBuffersP);
}
#ifdef TORQUE_DEBUG
// Make sure all the constants for this buffer were assigned.
if(mWasLost)
{
mVertexConstBuffer->assertUnassignedConstants( mShader->getVertexShaderFile().c_str() );
mPixelConstBuffer->assertUnassignedConstants( mShader->getPixelShaderFile().c_str() );
}
#endif
// Clear the lost state.
mWasLost = false;
}
void GFXD3D11ShaderConstBuffer::onShaderReload( GFXD3D11Shader *shader )
{
AssertFatal( shader == mShader, "GFXD3D11ShaderConstBuffer::onShaderReload is hosed!" );
// release constant buffers
for (U32 i = 0; i < CBUFFER_MAX; ++i)
{
SAFE_RELEASE(mConstantBuffersP[i]);
SAFE_RELEASE(mConstantBuffersV[i]);
}
SAFE_DELETE( mVertexConstBuffer );
SAFE_DELETE( mPixelConstBuffer );
AssertFatal( mVertexConstBufferLayout == shader->mVertexConstBufferLayout, "GFXD3D11ShaderConstBuffer::onShaderReload is hosed!" );
AssertFatal( mPixelConstBufferLayout == shader->mPixelConstBufferLayout, "GFXD3D11ShaderConstBuffer::onShaderReload is hosed!" );
mVertexConstBuffer = new GenericConstBuffer( mVertexConstBufferLayout );
mPixelConstBuffer = new GenericConstBuffer( mPixelConstBufferLayout );
_createBuffers();
// Set the lost state.
mWasLost = true;
}
//------------------------------------------------------------------------------
GFXD3D11Shader::GFXD3D11Shader()
{
VECTOR_SET_ASSOCIATION( mShaderConsts );
AssertFatal(D3D11DEVICE, "Invalid device for shader.");
mVertShader = NULL;
mPixShader = NULL;
mVertexConstBufferLayout = NULL;
mPixelConstBufferLayout = NULL;
if( smD3DInclude == NULL )
smD3DInclude = new gfxD3D11Include;
}
//------------------------------------------------------------------------------
GFXD3D11Shader::~GFXD3D11Shader()
{
for (HandleMap::Iterator i = mHandles.begin(); i != mHandles.end(); i++)
delete i->value;
// delete const buffer layouts
SAFE_DELETE(mVertexConstBufferLayout);
SAFE_DELETE(mPixelConstBufferLayout);
// release shaders
SAFE_RELEASE(mVertShader);
SAFE_RELEASE(mPixShader);
//maybe add SAFE_RELEASE(mVertexCode) ?
}
bool GFXD3D11Shader::_init()
{
PROFILE_SCOPE( GFXD3D11Shader_Init );
SAFE_RELEASE(mVertShader);
SAFE_RELEASE(mPixShader);
// Create the macro array including the system wide macros.
const U32 macroCount = smGlobalMacros.size() + mMacros.size() + 2;
FrameTemp<D3D_SHADER_MACRO> d3dMacros( macroCount );
for ( U32 i=0; i < smGlobalMacros.size(); i++ )
{
d3dMacros[i].Name = smGlobalMacros[i].name.c_str();
d3dMacros[i].Definition = smGlobalMacros[i].value.c_str();
}
for ( U32 i=0; i < mMacros.size(); i++ )
{
d3dMacros[i+smGlobalMacros.size()].Name = mMacros[i].name.c_str();
d3dMacros[i+smGlobalMacros.size()].Definition = mMacros[i].value.c_str();
}
d3dMacros[macroCount - 2].Name = "TORQUE_SM";
d3dMacros[macroCount - 2].Definition = D3D11->getShaderModel().c_str();
memset(&d3dMacros[macroCount - 1], 0, sizeof(D3D_SHADER_MACRO));
if ( !mVertexConstBufferLayout )
mVertexConstBufferLayout = new GFXD3D11ConstBufferLayout();
else
mVertexConstBufferLayout->clear();
if ( !mPixelConstBufferLayout )
mPixelConstBufferLayout = new GFXD3D11ConstBufferLayout();
else
mPixelConstBufferLayout->clear();
mSamplerDescriptions.clear();
mShaderConsts.clear();
String vertTarget = D3D11->getVertexShaderTarget();
String pixTarget = D3D11->getPixelShaderTarget();
if ( !Con::getBoolVariable( "$shaders::forceLoadCSF", false ) )
{
if (!mVertexFile.isEmpty() && !_compileShader( mVertexFile, vertTarget, d3dMacros, mVertexConstBufferLayout, mSamplerDescriptions ) )
return false;
if (!mPixelFile.isEmpty() && !_compileShader( mPixelFile, pixTarget, d3dMacros, mPixelConstBufferLayout, mSamplerDescriptions ) )
return false;
}
else
{
if ( !_loadCompiledOutput( mVertexFile, vertTarget, mVertexConstBufferLayout, mSamplerDescriptions ) )
{
if ( smLogErrors )
Con::errorf( "GFXD3D11Shader::init - Unable to load precompiled vertex shader for '%s'.", mVertexFile.getFullPath().c_str() );
return false;
}
if ( !_loadCompiledOutput( mPixelFile, pixTarget, mPixelConstBufferLayout, mSamplerDescriptions ) )
{
if ( smLogErrors )
Con::errorf( "GFXD3D11Shader::init - Unable to load precompiled pixel shader for '%s'.", mPixelFile.getFullPath().c_str() );
return false;
}
}
// Existing handles are resored to an uninitialized state.
// Those that are found when parsing the layout parameters
// will then be re-initialized.
HandleMap::Iterator iter = mHandles.begin();
for ( ; iter != mHandles.end(); iter++ )
(iter->value)->clear();
_buildShaderConstantHandles(mVertexConstBufferLayout, true);
_buildShaderConstantHandles(mPixelConstBufferLayout, false);
_buildSamplerShaderConstantHandles( mSamplerDescriptions );
_buildInstancingShaderConstantHandles();
// Notify any existing buffers that the buffer
// layouts have changed and they need to update.
Vector<GFXShaderConstBuffer*>::iterator biter = mActiveBuffers.begin();
for ( ; biter != mActiveBuffers.end(); biter++ )
((GFXD3D11ShaderConstBuffer*)(*biter))->onShaderReload( this );
return true;
}
bool GFXD3D11Shader::_compileShader( const Torque::Path &filePath,
const String& target,
const D3D_SHADER_MACRO *defines,
GenericConstBufferLayout* bufferLayout,
Vector<GFXShaderConstDesc> &samplerDescriptions )
{
PROFILE_SCOPE( GFXD3D11Shader_CompileShader );
using namespace Torque;
HRESULT res = E_FAIL;
ID3DBlob* code = NULL;
ID3DBlob* errorBuff = NULL;
ID3D11ShaderReflection* reflectionTable = NULL;
#ifdef TORQUE_GFX_VISUAL_DEBUG //for use with NSight, GPU Perf studio, VS graphics debugger
U32 flags = D3DCOMPILE_DEBUG | D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_PREFER_FLOW_CONTROL | D3DCOMPILE_SKIP_OPTIMIZATION;
#elif defined(TORQUE_DEBUG) //debug build
U32 flags = D3DCOMPILE_DEBUG | D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_WARNINGS_ARE_ERRORS;
#else //release build
U32 flags = D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_OPTIMIZATION_LEVEL3;
#endif
#ifdef D3D11_DEBUG_SPEW
Con::printf( "Compiling Shader: '%s'", filePath.getFullPath().c_str() );
#endif
// Is it an HLSL shader?
if(filePath.getExtension().equal("hlsl", String::NoCase))
{
// Set this so that the D3DInclude::Open will have this
// information for relative paths.
smD3DInclude->setPath(filePath.getRootAndPath());
FileStream s;
if (!s.open(filePath, Torque::FS::File::Read))
{
AssertISV(false, avar("GFXD3D11Shader::initShader - failed to open shader '%s'.", filePath.getFullPath().c_str()));
if ( smLogErrors )
Con::errorf( "GFXD3D11Shader::_compileShader - Failed to open shader file '%s'.", filePath.getFullPath().c_str() );
return false;
}
// Convert the path which might have virtualized
// mount paths to a real file system path.
Torque::Path realPath;
if (!FS::GetFSPath( filePath, realPath))
realPath = filePath;
U32 bufSize = s.getStreamSize();
FrameAllocatorMarker fam;
char *buffer = NULL;
buffer = (char*)fam.alloc(bufSize + 1);
s.read(bufSize, buffer);
buffer[bufSize] = 0;
res = D3DCompile(buffer, bufSize, realPath.getFullPath().c_str(), defines, smD3DInclude, "main", target, flags, 0, &code, &errorBuff);
}
// Is it a precompiled obj shader?
else if(filePath.getExtension().equal("obj", String::NoCase))
{
FileStream s;
if(!s.open(filePath, Torque::FS::File::Read))
{
AssertISV(false, avar("GFXD3D11Shader::initShader - failed to open shader '%s'.", filePath.getFullPath().c_str()));
if ( smLogErrors )
Con::errorf( "GFXD3D11Shader::_compileShader - Failed to open shader file '%s'.", filePath.getFullPath().c_str() );
return false;
}
res = D3DCreateBlob(s.getStreamSize(), &code);
AssertISV(SUCCEEDED(res), "Unable to create buffer!");
s.read(s.getStreamSize(), code->GetBufferPointer());
}
else
{
if (smLogErrors)
Con::errorf("GFXD3D11Shader::_compileShader - Unsupported shader file type '%s'.", filePath.getFullPath().c_str());
return false;
}
if(errorBuff)
{
// remove \n at end of buffer
U8 *buffPtr = (U8*) errorBuff->GetBufferPointer();
U32 len = dStrlen( (const char*) buffPtr );
buffPtr[len-1] = '\0';
if(FAILED(res))
{
if(smLogErrors)
Con::errorf("failed to compile shader: %s", buffPtr);
}
else
{
if(smLogWarnings)
Con::errorf("shader compiled with warning(s): %s", buffPtr);
}
}
else if (code == NULL && smLogErrors)
Con::errorf( "GFXD3D11Shader::_compileShader - no compiled code produced; possibly missing file '%s'.", filePath.getFullPath().c_str() );
AssertISV(SUCCEEDED(res), "Unable to compile shader!");
if(code != NULL)
{
#ifndef TORQUE_SHIPPING
if(gDisassembleAllShaders)
{
ID3DBlob* disassem = NULL;
D3DDisassemble(code->GetBufferPointer(), code->GetBufferSize(), 0, NULL, &disassem);
mDissasembly = (const char*)disassem->GetBufferPointer();
String filename = filePath.getFullPath();
filename.replace( ".hlsl", "_dis.txt" );
FileStream *fstream = FileStream::createAndOpen( filename, Torque::FS::File::Write );
if ( fstream )
{
fstream->write( mDissasembly );
fstream->close();
delete fstream;
}
SAFE_RELEASE(disassem);
}
#endif
if (target.compare("ps_", 3) == 0)
res = D3D11DEVICE->CreatePixelShader(code->GetBufferPointer(), code->GetBufferSize(), NULL, &mPixShader);
else if (target.compare("vs_", 3) == 0)
res = D3D11DEVICE->CreateVertexShader(code->GetBufferPointer(), code->GetBufferSize(), NULL, &mVertShader);
if (FAILED(res))
{
AssertFatal(false, "D3D11Shader::_compilershader- failed to create shader");
}
if(res == S_OK){
HRESULT reflectionResult = D3DReflect(code->GetBufferPointer(), code->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&reflectionTable);
if(FAILED(reflectionResult))
AssertFatal(false, "D3D11Shader::_compilershader - Failed to get shader reflection table interface");
}
if(res == S_OK)
_getShaderConstants(reflectionTable, bufferLayout, samplerDescriptions);
#ifdef TORQUE_ENABLE_CSF_GENERATION
// Ok, we've got a valid shader and constants, let's write them all out.
if (!_saveCompiledOutput(filePath, code, bufferLayout) && smLogErrors)
Con::errorf( "GFXD3D11Shader::_compileShader - Unable to save shader compile output for: %s",
filePath.getFullPath().c_str());
#endif
if(FAILED(res) && smLogErrors)
Con::errorf("GFXD3D11Shader::_compileShader - Unable to create shader for '%s'.", filePath.getFullPath().c_str());
}
//bool result = code && SUCCEEDED(res) && HasValidConstants;
bool result = code && SUCCEEDED(res);
#ifdef TORQUE_DEBUG
if (target.compare("vs_", 3) == 0)
{
String vertShader = mVertexFile.getFileName();
mVertShader->SetPrivateData(WKPDID_D3DDebugObjectName, vertShader.size(), vertShader.c_str());
}
else if (target.compare("ps_", 3) == 0)
{
String pixelShader = mPixelFile.getFileName();
mPixShader->SetPrivateData(WKPDID_D3DDebugObjectName, pixelShader.size(), pixelShader.c_str());
}
#endif
SAFE_RELEASE(code);
SAFE_RELEASE(reflectionTable);
SAFE_RELEASE(errorBuff);
return result;
}
void GFXD3D11Shader::_getShaderConstants( ID3D11ShaderReflection *refTable,
GenericConstBufferLayout *bufferLayoutIn,
Vector<GFXShaderConstDesc> &samplerDescriptions )
{
PROFILE_SCOPE( GFXD3D11Shader_GetShaderConstants );
AssertFatal(refTable, "NULL constant table not allowed, is this an assembly shader?");
GFXD3D11ConstBufferLayout *bufferLayout = (GFXD3D11ConstBufferLayout*)bufferLayoutIn;
Vector<ConstSubBufferDesc> &subBuffers = bufferLayout->getSubBufferDesc();
subBuffers.clear();
D3D11_SHADER_DESC tableDesc;
HRESULT hr = refTable->GetDesc(&tableDesc);
if (FAILED(hr))
{
AssertFatal(false, "Shader Reflection table unable to be created");
}
//offset for sub constant buffers
U32 bufferOffset = 0;
for (U32 i = 0; i < tableDesc.ConstantBuffers; i++)
{
ID3D11ShaderReflectionConstantBuffer* constantBuffer = refTable->GetConstantBufferByIndex(i);
D3D11_SHADER_BUFFER_DESC constantBufferDesc;
if (constantBuffer->GetDesc(&constantBufferDesc) == S_OK)
{
#ifdef TORQUE_DEBUG
AssertFatal(constantBufferDesc.Type == D3D_CT_CBUFFER, "Only scalar cbuffers supported for now.");
if (dStrcmp(constantBufferDesc.Name, "$Globals") != 0 && dStrcmp(constantBufferDesc.Name, "$Params") != 0)
AssertFatal(false, "Only $Global and $Params cbuffer supported for now.");
#endif
#ifdef D3D11_DEBUG_SPEW
Con::printf("Constant Buffer Name: %s", constantBufferDesc.Name);
#endif
for(U32 j =0; j< constantBufferDesc.Variables; j++)
{
GFXShaderConstDesc desc;
ID3D11ShaderReflectionVariable* variable = constantBuffer->GetVariableByIndex(j);
D3D11_SHADER_VARIABLE_DESC variableDesc;
D3D11_SHADER_TYPE_DESC variableTypeDesc;
variable->GetDesc(&variableDesc);
ID3D11ShaderReflectionType* variableType =variable->GetType();
variableType->GetDesc(&variableTypeDesc);
desc.name = String(variableDesc.Name);
// Prepend a "$" if it doesn't exist. Just to make things consistent.
if (desc.name.find("$") != 0)
desc.name = String::ToString("$%s", desc.name.c_str());
bool unusedVar = variableDesc.uFlags & D3D_SVF_USED ? false : true;
if (variableTypeDesc.Elements == 0)
desc.arraySize = 1;
else
desc.arraySize = variableTypeDesc.Elements;
#ifdef D3D11_DEBUG_SPEW
Con::printf("Variable Name %s:, offset: %d, size: %d, constantDesc.Elements: %d", desc.name.c_str(), variableDesc.StartOffset, variableDesc.Size, desc.arraySize);
#endif
if (_convertShaderVariable(variableTypeDesc, desc))
{
//The HLSL compiler for 4.0 and above doesn't strip out unused registered constants. We'll have to do it manually
if (!unusedVar)
{
mShaderConsts.push_back(desc);
U32 alignBytes = getAlignmentValue(desc.constType);
U32 paramSize = variableDesc.Size;
bufferLayout->addParameter( desc.name,
desc.constType,
variableDesc.StartOffset + bufferOffset,
paramSize,
desc.arraySize,
alignBytes);
} //unusedVar
} //_convertShaderVariable
} //constantBufferDesc.Variables
// fill out our const sub buffer sizes etc
ConstSubBufferDesc subBufferDesc;
subBufferDesc.size = constantBufferDesc.Size;
subBufferDesc.start = bufferOffset;
subBuffers.push_back(subBufferDesc);
// increase our bufferOffset by the constant buffer size
bufferOffset += constantBufferDesc.Size;
}
else
AssertFatal(false, "Unable to get shader constant description! (may need more elements of constantDesc");
}
// Set buffer size to the aligned size
bufferLayout->setSize(bufferOffset);
//get the sampler descriptions from the resource binding description
U32 resourceCount = tableDesc.BoundResources;
for (U32 i = 0; i < resourceCount; i++)
{
GFXShaderConstDesc desc;
D3D11_SHADER_INPUT_BIND_DESC bindDesc;
refTable->GetResourceBindingDesc(i, &bindDesc);
switch (bindDesc.Type)
{
case D3D_SIT_SAMPLER:
// Prepend a "$" if it doesn't exist. Just to make things consistent.
desc.name = String(bindDesc.Name);
if (desc.name.find("$") != 0)
desc.name = String::ToString("$%s", desc.name.c_str());
desc.constType = GFXSCT_Sampler;
desc.arraySize = bindDesc.BindPoint;
samplerDescriptions.push_back(desc);
break;
}
}
}
bool GFXD3D11Shader::_convertShaderVariable(const D3D11_SHADER_TYPE_DESC &typeDesc, GFXShaderConstDesc &desc)
{
switch (typeDesc.Type)
{
case D3D_SVT_INT:
{
switch (typeDesc.Class)
{
case D3D_SVC_SCALAR:
desc.constType = GFXSCT_Int;
break;
case D3D_SVC_VECTOR:
{
switch (typeDesc.Columns)
{
case 1:
desc.constType = GFXSCT_Int;
break;
case 2:
desc.constType = GFXSCT_Int2;
break;
case 3:
desc.constType = GFXSCT_Int3;
break;
case 4:
desc.constType = GFXSCT_Int4;
break;
}
}
break;
}
break;
}
case D3D_SVT_FLOAT:
{
switch (typeDesc.Class)
{
case D3D_SVC_SCALAR:
desc.constType = GFXSCT_Float;
break;
case D3D_SVC_VECTOR:
{
switch (typeDesc.Columns)
{
case 1:
desc.constType = GFXSCT_Float;
break;
case 2:
desc.constType = GFXSCT_Float2;
break;
case 3:
desc.constType = GFXSCT_Float3;
break;
case 4:
desc.constType = GFXSCT_Float4;
break;
}
}
break;
case D3D_SVC_MATRIX_ROWS:
case D3D_SVC_MATRIX_COLUMNS:
{
switch (typeDesc.Rows)
{
case 3:
desc.constType = typeDesc.Columns == 4 ? GFXSCT_Float3x4 : GFXSCT_Float3x3;
break;
case 4:
desc.constType = typeDesc.Columns == 3 ? GFXSCT_Float4x3 : GFXSCT_Float4x4;
break;
}
}
break;
case D3D_SVC_OBJECT:
case D3D_SVC_STRUCT:
return false;
}
}
break;
default:
AssertFatal(false, "Unknown shader constant class enum");
break;
}
return true;
}
const U32 GFXD3D11Shader::smCompiledShaderTag = MakeFourCC('t','c','s','f');
bool GFXD3D11Shader::_saveCompiledOutput( const Torque::Path &filePath,
ID3DBlob *buffer,
GenericConstBufferLayout *bufferLayout,
Vector<GFXShaderConstDesc> &samplerDescriptions )
{
Torque::Path outputPath(filePath);
outputPath.setExtension("csf"); // "C"ompiled "S"hader "F"ile (fancy!)
FileStream f;
if (!f.open(outputPath, Torque::FS::File::Write))
return false;
if (!f.write(smCompiledShaderTag))
return false;
// We could reverse engineer the structure in the compiled output, but this
// is a bit easier because we can just read it into the struct that we want.
if (!bufferLayout->write(&f))
return false;
U32 bufferSize = buffer->GetBufferSize();
if (!f.write(bufferSize))
return false;
if (!f.write(bufferSize, buffer->GetBufferPointer()))
return false;
// Write out sampler descriptions.
f.write( samplerDescriptions.size() );
for ( U32 i = 0; i < samplerDescriptions.size(); i++ )
{
f.write( samplerDescriptions[i].name );
f.write( (U32)(samplerDescriptions[i].constType) );
f.write( samplerDescriptions[i].arraySize );
}
f.close();
return true;
}
bool GFXD3D11Shader::_loadCompiledOutput( const Torque::Path &filePath,
const String &target,
GenericConstBufferLayout *bufferLayout,
Vector<GFXShaderConstDesc> &samplerDescriptions )
{
Torque::Path outputPath(filePath);
outputPath.setExtension("csf"); // "C"ompiled "S"hader "F"ile (fancy!)
FileStream f;
if (!f.open(outputPath, Torque::FS::File::Read))
return false;
U32 fileTag;
if (!f.read(&fileTag))
return false;
if (fileTag != smCompiledShaderTag)
return false;
if (!bufferLayout->read(&f))
return false;
U32 bufferSize;
if (!f.read(&bufferSize))
return false;
U32 waterMark = FrameAllocator::getWaterMark();
DWORD* buffer = static_cast<DWORD*>(FrameAllocator::alloc(bufferSize));
if (!f.read(bufferSize, buffer))
return false;
// Read sampler descriptions.
U32 samplerCount;
f.read( &samplerCount );
for ( U32 i = 0; i < samplerCount; i++ )
{
GFXShaderConstDesc samplerDesc;
f.read( &(samplerDesc.name) );
f.read( (U32*)&(samplerDesc.constType) );
f.read( &(samplerDesc.arraySize) );
samplerDescriptions.push_back( samplerDesc );
}
f.close();
HRESULT res;
if (target.compare("ps_", 3) == 0)
res = D3D11DEVICE->CreatePixelShader(buffer, bufferSize, NULL, &mPixShader);
else
res = D3D11DEVICE->CreateVertexShader(buffer, bufferSize, NULL, &mVertShader);
AssertFatal(SUCCEEDED(res), "Unable to load shader!");
FrameAllocator::setWaterMark(waterMark);
return SUCCEEDED(res);
}
void GFXD3D11Shader::_buildShaderConstantHandles(GenericConstBufferLayout* layout, bool vertexConst)
{
for (U32 i = 0; i < layout->getParameterCount(); i++)
{
GenericConstBufferLayout::ParamDesc pd;
layout->getDesc(i, pd);
GFXD3D11ShaderConstHandle* handle;
HandleMap::Iterator j = mHandles.find(pd.name);
if (j != mHandles.end())
{
handle = j->value;
handle->mShader = this;
handle->setValid( true );
}
else
{
handle = new GFXD3D11ShaderConstHandle();
handle->mShader = this;
mHandles[pd.name] = handle;
handle->setValid( true );
}
if (vertexConst)
{
handle->mVertexConstant = true;
handle->mVertexHandle = pd;
}
else
{
handle->mPixelConstant = true;
handle->mPixelHandle = pd;
}
}
}
void GFXD3D11Shader::_buildSamplerShaderConstantHandles( Vector<GFXShaderConstDesc> &samplerDescriptions )
{
Vector<GFXShaderConstDesc>::iterator iter = samplerDescriptions.begin();
for ( ; iter != samplerDescriptions.end(); iter++ )
{
const GFXShaderConstDesc &desc = *iter;
AssertFatal( desc.constType == GFXSCT_Sampler ||
desc.constType == GFXSCT_SamplerCube ||
desc.constType == GFXSCT_SamplerCubeArray,
"GFXD3D11Shader::_buildSamplerShaderConstantHandles - Invalid samplerDescription type!" );
GFXD3D11ShaderConstHandle *handle;
HandleMap::Iterator j = mHandles.find(desc.name);
if ( j != mHandles.end() )
handle = j->value;
else
{
handle = new GFXD3D11ShaderConstHandle();
mHandles[desc.name] = handle;
}
handle->mShader = this;
handle->setValid( true );
handle->mPixelConstant = true;
handle->mPixelHandle.name = desc.name;
handle->mPixelHandle.constType = desc.constType;
handle->mPixelHandle.offset = desc.arraySize;
}
}
void GFXD3D11Shader::_buildInstancingShaderConstantHandles()
{
// If we have no instancing than just return
if (!mInstancingFormat)
return;
U32 offset = 0;
for ( U32 i=0; i < mInstancingFormat->getElementCount(); i++ )
{
const GFXVertexElement &element = mInstancingFormat->getElement( i );
String constName = String::ToString( "$%s", element.getSemantic().c_str() );
GFXD3D11ShaderConstHandle *handle;
HandleMap::Iterator j = mHandles.find( constName );
if ( j != mHandles.end() )
handle = j->value;
else
{
handle = new GFXD3D11ShaderConstHandle();
mHandles[ constName ] = handle;
}
handle->mShader = this;
handle->setValid( true );
handle->mInstancingConstant = true;
// We shouldn't have an instancing constant that is also
// a vertex or pixel constant! This means the shader features
// are confused as to what is instanced.
//
AssertFatal( !handle->mVertexConstant &&
!handle->mPixelConstant,
"GFXD3D11Shader::_buildInstancingShaderConstantHandles - Bad instanced constant!" );
// HACK: The GFXD3D11ShaderConstHandle will check mVertexConstant then
// fall back to reading the mPixelHandle values. We depend on this here
// and store the data we need in the mPixelHandle constant although its
// not a pixel shader constant.
//
handle->mPixelHandle.name = constName;
handle->mPixelHandle.offset = offset;
// If this is a matrix we will have 2 or 3 more of these
// semantics with the same name after it.
for ( ; i < mInstancingFormat->getElementCount(); i++ )
{
const GFXVertexElement &nextElement = mInstancingFormat->getElement( i );
if ( nextElement.getSemantic() != element.getSemantic() )
{
i--;
break;
}
offset += nextElement.getSizeInBytes();
}
}
}
GFXShaderConstBufferRef GFXD3D11Shader::allocConstBuffer()
{
if (mVertexConstBufferLayout && mPixelConstBufferLayout)
{
GFXD3D11ShaderConstBuffer* buffer = new GFXD3D11ShaderConstBuffer(this, mVertexConstBufferLayout, mPixelConstBufferLayout);
mActiveBuffers.push_back( buffer );
buffer->registerResourceWithDevice(getOwningDevice());
return buffer;
}
return NULL;
}
/// Returns a shader constant handle for name, if the variable doesn't exist NULL is returned.
GFXShaderConstHandle* GFXD3D11Shader::getShaderConstHandle(const String& name)
{
HandleMap::Iterator i = mHandles.find(name);
if ( i != mHandles.end() )
{
return i->value;
}
else
{
GFXD3D11ShaderConstHandle *handle = new GFXD3D11ShaderConstHandle();
handle->setValid( false );
handle->mShader = this;
mHandles[name] = handle;
return handle;
}
}
GFXShaderConstHandle* GFXD3D11Shader::findShaderConstHandle(const String& name)
{
HandleMap::Iterator i = mHandles.find(name);
if(i != mHandles.end())
return i->value;
else
{
return NULL;
}
}
const Vector<GFXShaderConstDesc>& GFXD3D11Shader::getShaderConstDesc() const
{
return mShaderConsts;
}
U32 GFXD3D11Shader::getAlignmentValue(const GFXShaderConstType constType) const
{
const U32 mRowSizeF = 16;
const U32 mRowSizeI = 16;
switch (constType)
{
case GFXSCT_Float :
case GFXSCT_Float2 :
case GFXSCT_Float3 :
case GFXSCT_Float4 :
return mRowSizeF;
break;
// Matrices
case GFXSCT_Float2x2 :
return mRowSizeF * 2;
break;
case GFXSCT_Float3x3 :
return mRowSizeF * 3;
break;
case GFXSCT_Float4x3:
return mRowSizeF * 3;
break;
case GFXSCT_Float4x4 :
return mRowSizeF * 4;
break;
//// Scalar
case GFXSCT_Int :
case GFXSCT_Int2 :
case GFXSCT_Int3 :
case GFXSCT_Int4 :
return mRowSizeI;
break;
default:
AssertFatal(false, "Unsupported type!");
return 0;
break;
}
}
void GFXD3D11Shader::zombify()
{
// Shaders don't need zombification
}
void GFXD3D11Shader::resurrect()
{
// Shaders are never zombies, and therefore don't have to be brought back.
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.