text
stringlengths 5
1.04M
|
|---|
#include<iostream>
using namespace std;
int main()
{
int age;
cout<<"Enter Age of a user:";
cin>>age;
if(age>=18)
{
cout<<"\n you are eligible for voting";
}
else
{
cout<<"\n you are not eligible for voting";
return 0;
}
}
|
/******************************************************************************
- domain: Codeforces
- contest: 1144
- problem: A
- title: Diverse Strings
- link: https://codeforces.com/contest/1144/problem/A
- hash: CF_1144_A
- author: Vitor SRG
- version: 1.0 23/03/2019
- tags: tests implementation string online
- language: C++17
******************************************************************************/
/* Please contact for the solution */
/******************************************************************************
- time: 1s
- memory: 256mb
- test:
input: |
8
fced
xyz
r
dabcef
az
aa
bad
babc
output: |
Yes
Yes
Yes
Yes
No
No
No
No
******************************************************************************/
|
static int __=[](){std::ios::sync_with_stdio(false);return 1000;}();
class Solution {
public:
bool uniqueOccurrences(vector<int>& arr) {
map<int , int > m ;
set<int> o , s ;
for(int i = 0; i< arr.size() ; i++){
m[arr[i]]++;
s.insert(arr[i]);
}
for(auto i : m )
o.insert(i.second);
return o.size() == s.size() ;
}
};
|
/**************************************************************************\
* Copyright (c) Kongsberg Oil & Gas Technologies AS
* 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 the copyright holder 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
* 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.
\**************************************************************************/
/*!
\class SbTime SbTime.h Inventor/SbTime.h
\brief The SbTime class instances represents time values.
\ingroup base
SbTime is a convenient way of doing system independent
representation and calculations on time values of high resolution.
*/
// *************************************************************************
#include <Inventor/SbTime.h>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <cerrno>
#include <cmath>
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif // HAVE_CONFIG_H
#ifdef HAVE_TIME_H
#include <ctime> // struct timeval (Linux)
#endif // HAVE_TIME_H
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h> // struct timeval (IRIX)
#endif // HAVE_SYS_TIME_H
#ifdef HAVE_WINDOWS_H
#include <windows.h>
#endif // HAVE_WINDOWS_H
#include <Inventor/errors/SoDebugError.h>
#include <Inventor/C/base/time.h>
#include <Inventor/C/tidbits.h>
#include <Inventor/C/threads/thread.h>
#include "coindefs.h"
#ifndef COIN_WORKAROUND_NO_USING_STD_FUNCS
using std::strlen;
#endif // !COIN_WORKAROUND_NO_USING_STD_FUNCS
// *************************************************************************
// FIXME: I don't agree with this willy-nilly, "gut feeling"
// constant. As far as I can tell from a quick look, the exceptions in
// the code using this should be handled in other ways.
//
// E.g. this:
//
// if (s==0.0) { this->dtime /= s + SMALLEST_DOUBLE_TIMEUNIT; }
//
// ..could better be written as
//
// if (s==0.0) { this->dtime = DBL_MAX; }
//
// If there are no protests, I'll take care of removing this constant.
//
// 20050526 mortene.
static const double SMALLEST_DOUBLE_TIMEUNIT = 1.0/1000000.0;
// *************************************************************************
/*!
The default constructor sets up a time instance of 0 seconds.
*/
SbTime::SbTime(void)
{
this->setValue(0.0);
}
/*!
Construct and initialize an SbTime instance to a time specified
as \a sec seconds.
*/
SbTime::SbTime(const double sec)
{
this->setValue(sec);
}
/*!
Construct and initialize an SbTime instance to a date and time
\a sec number of seconds and \a usec number of microseconds.
*/
SbTime::SbTime(const int32_t sec, const long usec)
{
this->setValue(sec, usec);
}
/*!
Construct and initialize an SbTime instance to the date and time
given by the \a struct \a timeval. For information on the \a timeval
structure, please consult your system developer documentation.
*/
SbTime::SbTime(const struct timeval * const tv)
{
this->setValue(tv);
}
/*!
Returns an SbTime instance with the current clock time. The current
time will be given as a particular number of seconds and
microseconds since 00:00:00 January 1, 1970, in Coordinated
Universal Time (UTC).
\sa setToTimeOfDay().
*/
SbTime
SbTime::getTimeOfDay(void)
{
SbTime t(cc_time_gettimeofday());
return t;
}
/*!
Set this SbTime to be the current clock time. The current time
will be given as a particular number of seconds and microseconds since
00:00:00.00 1st January 1970.
\sa getTimeOfDay().
*/
void
SbTime::setToTimeOfDay(void)
{
(*this) = SbTime::getTimeOfDay();
}
/*!
Returns an SbTime instance representing zero time.
\sa zero().
*/
SbTime
SbTime::zero(void)
{
return SbTime(0.0);
}
/*!
Returns an SbTime instance representing the maximum representable
time/date.
\sa zero().
*/
SbTime
SbTime::maxTime(void)
{
return SbTime(static_cast<double>(INT_MAX) + 0.999999);
}
// This is needed because of the hackery in SbTime.h to avoid problems
// with the Microsoft Visual C++ header files, see comment in
// SbTime.h for additional information.
#ifdef max
#undef max
#endif // max
/*!
Returns an SbTime instance representing the maximum representable
time/date.
This method is not available under MSWindows, as max() crashes with
a define macro Microsoft has polluted the global namespace with.
\sa zero().
*/
SbTime
SbTime::max(void)
{
return SbTime::maxTime();
}
/*!
Suspends the current thread for \a msec milliseconds.
\sa cc_sleep().
\since Coin 3.0
*/
void
SbTime::sleep(int msec)
{
cc_sleep(msec/1000.0f);
}
/*!
Reset an SbTime instance to \a sec number of seconds.
\sa getValue().
*/
void
SbTime::setValue(const double sec)
{
this->dtime = sec;
}
/*!
Reset an SbTime instance to \a sec number of seconds
and \a usec number of microseconds.
\sa getValue().
*/
void
SbTime::setValue(const int32_t sec, const long usec)
{
this->dtime = static_cast<double>(sec) + static_cast<double>(usec)/1000000.0;
}
/*!
Reset an SbTime instance to the date and time given by the \a timeval
struct. For information on the \a timeval struct, please consult your
developer system documentation.
\sa getValue().
*/
void
SbTime::setValue(const struct timeval * const tv)
{
this->dtime = tv->tv_sec;
this->dtime += static_cast<double>(tv->tv_usec)/1000000.0;
}
/*!
Set the time by \a msec number of milliseconds.
\sa getMsecValue().
*/
void
SbTime::setMsecValue(const unsigned long msec)
{
this->setValue(static_cast<double>(msec) / 1000.0);
}
/*!
Return time as number of seconds.
\sa setValue().
*/
double
SbTime::getValue(void) const
{
return this->dtime;
}
/*!
Return number of seconds and microseconds which the SbTime
instance represents.
\sa setValue().
*/
void
SbTime::getValue(time_t & sec, long & usec) const
{
sec = static_cast<time_t>(this->dtime);
double us = fmod(this->dtime, 1.0) * 1000000.0;
usec = static_cast<long>(us + (us < 0.0 ? -0.5 : 0.5));
}
/*!
Returns the time as a \a timeval structure. For information on the \a timeval
structure, please consult your system developer documentation.
\sa setValue().
*/
void
SbTime::getValue(struct timeval * tv) const
{
tv->tv_sec = static_cast<SIM_TIMEVAL_TV_SEC_T>(this->dtime);
double us = fmod(this->dtime, 1.0) * 1000000.0;
tv->tv_usec = static_cast<SIM_TIMEVAL_TV_USEC_T>(us + (us < 0.0 ? -0.5 : 0.5));
}
/*!
Return number of milliseconds which the SbTime instance represents.
Important note: you should in general avoid using this function, as
it has an inherent API design flaw (from the original SGI Open
Inventor design). The problem is that an unsigned long wraps around
in a fairly short time when used for counting milliseconds: in less
than 50 days. (And since SbTime instances are often initialized to
be the time since the start of the epoch (ie 1970-01-01 00:00), the
value will have wrapped around many, many times.)
You are probably better off using the getValue() method which
returns a double for the number of seconds, then multiply by 1000.0
if you need to know the current number of milliseconds of the SbTime
instance.
\sa setMsecValue()
*/
unsigned long
SbTime::getMsecValue(void) const
{
double d = this->dtime * 1000.0;
// Check for overflow in the double->ulong cast at return.
if (d > static_cast<double>(ULONG_MAX)) {
#if COIN_DEBUG
static SbBool first = TRUE;
if (first) {
SoDebugError::postWarning("SbTime::getMsecValue",
"timer overflow -- consider using "
"SbTime::getValue() instead");
first = FALSE;
}
#endif // COIN_DEBUG
// Wrap the value. This actually happens automatically on x86
// Linux, MIPS IRIX, x86 MSWin etc when casting from a too large
// double to an unsigned long -- but not on for instance Mac OS X
// when the endianness is most significant byte first. And indeed,
// Kernighan & Ritchie's "The C Programming Language", 2nd edition
// says: "[...] if the resulting value [of a conversion from a
// floating type to an integral type] cannot be represented in the
// integral type, the behavior is undefined."
//
// So we do the modulo explicitly to be guaranteed to get the same
// behavior on every platform. (And the reason we do a modulo
// instead of for instance a clamp or just ignore the problem and
// return garbage, is that it is likely that there is application
// code already written for Coin / SGI/TGS Inventor which depends
// on the modulo behavior.)
d = fmod(d, ULONG_MAX);
}
return static_cast<unsigned long>(d);
}
/*!
Uses the formatting specified below to return a string representation
of the stored date/time. Any format specifiers must be prefixed with
a '%' symbol, any other text in the format string \a fmt will be
copied directly to the resultant SbString.
%% - insert a single '%'.<BR>
%D - number of days.<BR>
%H - number of hours.<BR>
%h - remaining hours after subtracting number of days.<BR>
%M - number of minutes.<BR>
%m - remaining minutes after subtracting the total number of hours.<BR>
%S - number of seconds.<BR>
%s - remaining seconds after subtracting the total number of minutes.<BR>
%I - number of milliseconds.<BR>
%i - remaining milliseconds after subtracting the total number of seconds.<BR>
%U - number of microseconds.<BR>
%u - remaining microseconds after subtracting the total number of mseconds.<BR>
The result shows UTC time, not corrected for local time zone
nor daylight savings time.
\sa formatDate().
*/
SbString
SbTime::format(const char * const fmt) const
{
#if COIN_DEBUG
if (fmt==NULL) {
SoDebugError::postWarning("SbTime::format",
"Format string is NULL.");
return SbString("");
}
#endif // COIN_DEBUG
SbString str("");
double dtmp;
int idx = 0;
char c;
while ((c = fmt[idx]) != '\0') {
if (c != '%') str += c;
else {
char m = fmt[++idx];
switch (m) {
case '%':
str += m;
break;
case 'D':
this->addToString(str, this->dtime / 60.0 / 60.0 / 24.0);
break;
case 'H':
this->addToString(str, this->dtime / 60.0 / 60.0);
break;
case 'M':
this->addToString(str, this->dtime / 60.0);
break;
case 'S':
this->addToString(str, this->dtime);
break;
case 'I':
this->addToString(str, this->dtime * 1000.0);
break;
case 'U':
this->addToString(str, this->dtime * 1000000.0);
break;
case 'h':
dtmp = this->dtime / 60.0 / 60.0 / 24.0;
dtmp = this->dtime - floor(dtmp) * 60.0 * 60.0 * 24.0;
dtmp = dtmp / 60.0 / 60.0;
dtmp = floor(dtmp);
if (dtmp < 10.0) str += '0';
str.addIntString(static_cast<int>(dtmp));
break;
case 'm':
dtmp = this->dtime / 60.0 / 60.0;
dtmp = this->dtime - floor(dtmp) * 60.0 * 60.0;
dtmp = dtmp / 60.0;
dtmp = floor(dtmp);
if (dtmp < 10.0) str += '0';
str.addIntString(static_cast<int>(dtmp));
break;
case 's':
dtmp = this->dtime / 60.0;
dtmp = this->dtime - floor(dtmp) * 60.0;
dtmp = floor(dtmp);
if (dtmp < 10.0) str += '0';
str.addIntString(static_cast<int>(dtmp));
break;
case 'i':
dtmp = fmod(this->dtime, 1.0);
dtmp *= 1000.0;
dtmp = floor(dtmp);
if (dtmp < 100.0) str += '0';
if (dtmp < 10.0) str += '0';
str.addIntString(static_cast<int>(dtmp));
break;
case 'u':
dtmp = fmod(this->dtime, 1.0);
dtmp *= 1000000.0;
dtmp = floor(dtmp);
if (dtmp < 100000.0) str += '0';
if (dtmp < 10000.0) str += '0';
if (dtmp < 1000.0) str += '0';
if (dtmp < 100.0) str += '0';
if (dtmp < 10.0) str += '0';
str.addIntString(static_cast<int>(dtmp));
break;
default:
#if COIN_DEBUG
SoDebugError::postWarning("SbTime::format",
"Unknown formatting char '%c'.", m);
#endif // COIN_DEBUG
break;
}
}
idx++;
}
return str;
}
/*!
Accepts the formatting identifiers specified by the POSIX strftime()
function to return a string representation of the stored date. Check
your reference documentation for strftime() for information on the
format modifiers available.
Default formatting is used if \a fmt is \c NULL. Note that the
default formatting is different on Microsoft Windows systems versus
all other systems. For Windows, it is \c "%#c", for other systems it
is \c "%A, %D %r" (again, see system documentation on strftime() for
more information).
The value of SbTime will be interpreted as seconds since 00:00:00
1970-01-01.
The result shows local time, according to local time zone and
daylight savings time (if and when applicable).
\sa format().
*/
SbString
SbTime::formatDate(const char * const fmt) const
{
const char * format = fmt;
if (format == NULL) {
#ifdef HAVE_WIN32_API
format = "%#c";
#else // ! HAVE_WIN32_API
format = "%A, %D %r";
#endif // ! HAVE_WIN32_API
}
if (strlen(format) == 0) return SbString("");
const size_t buffersize = 256;
char buffer[buffersize];
char * bufferpt = buffer;
time_t secs = static_cast<time_t>(this->dtime);
size_t currentsize = buffersize;
struct tm * ts = localtime(&secs);
size_t ret = strftime(bufferpt, currentsize, format, ts);
if ((ret == 0) || (ret == currentsize)) {
bufferpt = NULL;
// The resulting string was too large, so we will allocate
// a subsequently larger buffer until the date string fits.
do {
delete[] bufferpt;
currentsize *= 2;
bufferpt = new char[currentsize];
ret = strftime(bufferpt, currentsize, format, ts);
} while ((ret == 0) || (ret == currentsize));
}
if (bufferpt == buffer) {
return SbString(bufferpt);
}
else {
SbString s(bufferpt);
delete[] bufferpt;
return s;
}
}
// FIXME: write a few examples for the following doc.
/*!
This method takes a date string and converts it to the internal
SbTime format. The date string must conform to one of three
formats, namely the RFC 822 / RFC 1123 format (Wkd, DD Mnth YYYY
HH:MM:SS GMT), the RFC 850 / RFC 1036 format (Weekday, DD-Mnth-YY
HH:MM:SS GMT), or the asctime() format (Wkdy Mnth D HH:MM:SS YYYY).
Feeding an invalid date string to this method will make it return
\a FALSE.
*/
SbBool
SbTime::parsedate(const char * const date)
{
// FIXME: make method 100% robust for erroneous date strings.
// 19981001 mortene.
// FIXME: ditto -- 20020916 larsa
// FIXME: accept datestrings conforming to ISO 8601. 20000331 mortene.
#if COIN_DEBUG
if (!date) {
SoDebugError::postWarning("SbTime::parsedate",
"date string is NULL.");
return FALSE;
}
#endif // COIN_DEBUG
#if 0 // debug
SoDebugError::postInfo("SbTime::parseDate", "date string: '%s'", date);
#endif // debug
struct tm time;
char months[12][4] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
const char * dateptr = date;
while (*dateptr != ' ' && *dateptr != '\t' && *dateptr != '\0')
dateptr++; // we don't care if it's wednesday
if (*dateptr == '\0') return FALSE;
dateptr -= 2; // step back
if ( dateptr < date ) return FALSE;
if (dateptr[0] != 'y' && dateptr[1] == ',') { // RFC 822 / RFC 1123 format
// FORMAT: Wkd, DD Mnth YYYY HH:MM:SS GMT
#if COIN_DEBUG && 0 // debug
SoDebugError::postInfo("SbTime::parseDate", "date format: RFC 822");
#endif // debug
dateptr += 2;
while (*dateptr == ' ' || *dateptr == '\t') dateptr++;
time.tm_mday = atoi(dateptr);
#if COIN_DEBUG && 0 // debug
SoDebugError::postInfo("SbTime::parseDate", "Day of month: %d",
time.tm_mday);
#endif // debug
while (*dateptr != ' ' && *dateptr != '\t' && *dateptr != '\0') dateptr++;
if (*dateptr == '\0') return FALSE;
while (*dateptr == ' ' || *dateptr == '\t') dateptr++;
int i;
for (i=0; i < 12; i++) {
if (! coin_strncasecmp(dateptr, months[i], 3)) {
time.tm_mon = i;
break;
}
}
if (i==12) {
#if COIN_DEBUG
SoDebugError::post("SbTime::parsedate", "Can't grok month name '%s'.",
SbString(dateptr).getSubString(0, 2).getString());
#endif // COIN_DEBUG
return FALSE;
}
#if COIN_DEBUG && 0 // debug
SoDebugError::postInfo("SbTime::parseDate", "Month: %d", time.tm_mon);
#endif // debug
while (*dateptr != ' ' && *dateptr != '\t' && *dateptr != '\0') dateptr++;
if (*dateptr == '\0') return FALSE;
while (*dateptr == ' ' || *dateptr == '\t') dateptr++;
time.tm_year = atoi(dateptr) - 1900;
while (*dateptr != ' ' && *dateptr != '\t' && *dateptr != '\0') dateptr++;
if (*dateptr == '\0') return FALSE;
while (*dateptr == ' ' || *dateptr == '\t') dateptr++;
time.tm_hour = atoi(dateptr);
while (*dateptr != ':' && *dateptr != '\0') dateptr++;
if (*dateptr == '\0') return FALSE;
dateptr++;
time.tm_min = atoi(dateptr);
while (*dateptr != ':' && *dateptr != '\0') dateptr++;
if (*dateptr == '\0') return FALSE;
dateptr++;
time.tm_sec = atoi(dateptr);
time.tm_wday = 0;
time.tm_yday = 0;
time.tm_isdst = 0;
} else if (dateptr[1] == ',') { // RFC 850 / RFC 1036 format
// FORMAT: Weekday, DD-Mnth-YY HH:MM:SS GMT
#if COIN_DEBUG && 0 // debug
SoDebugError::postInfo("SbTime::parseDate", "date format: RFC 850");
#endif // debug
dateptr += 2;
while (*dateptr == ' ' || *dateptr == '\t') dateptr++;
time.tm_mday = atoi(dateptr);
while (*dateptr != '-') dateptr++;
dateptr++;
int i;
for (i=0; i < 12; i++) {
if (! coin_strncasecmp(dateptr, months[i], 3)) {
time.tm_mon = i;
break;
}
}
if (i==12) {
#if COIN_DEBUG
SoDebugError::post("SbTime::parsedate", "Can't grok month name '%s'.",
SbString(dateptr).getSubString(0, 2).getString());
#endif // COIN_DEBUG
return FALSE;
}
while (*dateptr != '-' && *dateptr != '\0') dateptr++;
if (*dateptr == '\0') return FALSE;
dateptr++;
// put number of years since 1900 into tm_year
time.tm_year = atoi(dateptr);
if ( time.tm_year < 70 ) time.tm_year += 100;
while (*dateptr != ' ' && *dateptr != '\t' && *dateptr != '\0') dateptr++;
if (*dateptr == '\0') return FALSE;
while (*dateptr == ' ' || *dateptr == '\t') dateptr++;
time.tm_hour = atoi(dateptr);
while (*dateptr != ':' && *dateptr != '\0') dateptr++;
if (*dateptr == '\0') return FALSE;
dateptr++;
time.tm_min = atoi(dateptr);
while (*dateptr != ':' && *dateptr != '\0') dateptr++;
if (*dateptr == '\0') return FALSE;
dateptr++;
time.tm_sec = atoi(dateptr);
time.tm_wday = 0;
time.tm_yday = 0;
time.tm_isdst = 0;
} else { // assumed to be ANSI C's asctime() format
// format: Wkdy Mnth D HH:MM:SS YYYY
#if COIN_DEBUG && 0 // debug
SoDebugError::postInfo("SbTime::parseDate", "date format: asctime()");
#endif // debug
while (*dateptr != ' ' && *dateptr != '\t' && *dateptr != '\0') dateptr++;
if (*dateptr == '\0') return FALSE;
while (*dateptr == ' ' || *dateptr == '\t') dateptr++;
int i;
for (i=0; i < 12; i++) {
if (! coin_strncasecmp(dateptr, months[i], 3)) {
time.tm_mon = i;
break;
}
}
if (i==12) {
#if COIN_DEBUG
SoDebugError::post("SbTime::parsedate", "Can't grok month name '%s'.",
SbString(dateptr).getSubString(0, 2).getString());
#endif // COIN_DEBUG
return FALSE;
}
while (*dateptr != ' ' && *dateptr != '\t' && *dateptr != '\0') dateptr++;
if (*dateptr == '\0') return FALSE;
while (*dateptr == ' ' || *dateptr == '\t') dateptr++;
time.tm_mday = atoi(dateptr);
while (*dateptr != ' ' && *dateptr != '\t' && *dateptr != '\0') dateptr++;
if (*dateptr == '\0') return FALSE;
while (*dateptr == ' ' || *dateptr == '\t') dateptr++;
time.tm_hour = atoi(dateptr);
while (*dateptr != ':' && *dateptr != '\0') dateptr++;
if (*dateptr == '\0') return FALSE;
dateptr++;
time.tm_min = atoi(dateptr);
while (*dateptr != ':' && *dateptr != '\0') dateptr++;
if (*dateptr == '\0') return FALSE;
dateptr++;
time.tm_sec = atoi(dateptr);
while (*dateptr != ' ' && *dateptr != '\t' && *dateptr != '\0') dateptr++;
if (*dateptr == '\0') return FALSE;
while (*dateptr == ' ' || *dateptr == '\t') dateptr++;
time.tm_year = atoi(dateptr) - 1900;
time.tm_wday = 0;
time.tm_yday = 0;
time.tm_isdst = 0;
}
this->dtime = static_cast<double>(mktime(&time));
return TRUE;
}
/*!
\relates SbTime
Add the two SbTimes and return the result.
*/
SbTime
operator +(const SbTime & t0, const SbTime & t1)
{
SbTime t = t0;
t += t1;
return t;
}
/*!
\relates SbTime
Subtract \a t1 from \a t0 and return the result.
*/
SbTime
operator -(const SbTime & t0, const SbTime & t1)
{
SbTime t = t0;
t -= t1;
return t;
}
/*!
Add \a tm to time value and return reference to self.
*/
SbTime&
SbTime::operator +=(const SbTime & tm)
{
this->dtime += tm.dtime;
return *this;
}
/*!
Subtract \a tm from time value and return reference to self.
*/
SbTime&
SbTime::operator -=(const SbTime & tm)
{
this->dtime -= tm.dtime;
return *this;
}
/*!
Return the negated time.
*/
SbTime
SbTime::operator-(void) const
{
return SbTime(-this->getValue());
}
/*!
\relates SbTime
Multiply time value \a tm with \a s and return result.
*/
SbTime
operator *(const double s, const SbTime & tm)
{
SbTime t = tm;
t *= s;
return t;
}
/*!
\relates SbTime
Multiply time value \a tm with \a s and return result.
*/
SbTime
operator *(const SbTime & tm, const double s)
{
return s * tm;
}
/*!
\relates SbTime
Divide time value \a tm with \a s and return result.
*/
SbTime
operator /(const SbTime & tm, const double s)
{
SbTime t = tm;
t /= s;
return t;
}
/*!
\relates SbTime
Multiply time value with \a s and return reference to self.
*/
SbTime&
SbTime::operator *=(const double s)
{
this->dtime *= s;
return *this;
}
/*!
\relates SbTime
Divide time value with \a s and return reference to self.
*/
SbTime&
SbTime::operator /=(const double s)
{
#if COIN_DEBUG
if (s==0.0) {
SoDebugError::postWarning("SbTime::operator/=",
"Argument is zero => Division by zero.");
this->dtime /= s + SMALLEST_DOUBLE_TIMEUNIT;
return *this;
}
#endif // COIN_DEBUG
this->dtime /= s;
return *this;
}
/*!
\relates SbTime
Find the factor between this SbTime and the one given in \a tm, and
return the result.
*/
double
SbTime::operator /(const SbTime & tm) const
{
#if COIN_DEBUG
if (tm.getValue()==0.0) {
SoDebugError::postWarning("SbTime::operator/",
"Argument tm is zero => Division by zero.");
return 1.0/SMALLEST_DOUBLE_TIMEUNIT;
}
#endif // COIN_DEBUG
return this->getValue()/tm.getValue();
}
/*!
Returns the remainder time when dividing on \a tm.
*/
SbTime
SbTime::operator %(const SbTime & tm) const
{
#if COIN_DEBUG
if (tm.getValue()==0.0) {
SoDebugError::postWarning("SbTime::operator%",
"Argument tm is zero => Division by zero.");
return SbTime(1.0/SMALLEST_DOUBLE_TIMEUNIT);
}
#endif // COIN_DEBUG
return SbTime(fmod(this->getValue(), tm.getValue()));
}
/*!
Check if the time value is equal to that of \a tm.
*/
int
SbTime::operator ==(const SbTime & tm) const
{
if (fabs(this->dtime-tm.dtime) < (SMALLEST_DOUBLE_TIMEUNIT/2.0)) return TRUE;
return FALSE;
}
/*!
Check if the time value is not equal to that of \a tm.
*/
int
SbTime::operator !=(const SbTime & tm) const
{
return !(*this == tm);
}
/*!
Compares with \a tm and return TRUE if less.
*/
SbBool
SbTime::operator <(const SbTime & tm) const
{
double diff = tm.dtime - this->dtime;
if ((diff>0.0) && (fabs(diff) > (SMALLEST_DOUBLE_TIMEUNIT/2.0))) return TRUE;
return FALSE;
}
/*!
Compares with \a tm and return TRUE if larger than.
*/
SbBool
SbTime::operator >(const SbTime & tm) const
{
double diff = tm.dtime - this->dtime;
if ((diff<0.0) && (fabs(diff) > (SMALLEST_DOUBLE_TIMEUNIT/2.0))) return TRUE;
return FALSE;
}
/*!
Compares with \a tm and return TRUE if less or equal.
*/
SbBool
SbTime::operator <=(const SbTime & tm) const
{
if (*this < tm) return TRUE;
return (*this == tm);
}
/*!
Compares with \a tm and return TRUE if larger or equal.
*/
SbBool
SbTime::operator >=(const SbTime & tm) const
{
if (*this > tm) return TRUE;
return (*this == tm);
}
/*!
\COININTERNAL
Concatenate a string representation of \a val to \a str, ignoring
any decimals.
*/
void
SbTime::addToString(SbString & str, const double v) const
{
double val = v;
// Handle sign.
if (val < 0.0) {
str += '-';
val = -val;
}
// Code below depends on val != 0.0.
if (val == 0.0) {
str += '0';
return;
}
while (val > static_cast<double>(INT_MAX)) {
int steps = 0;
double vcopy = val;
// "Clamp" value to within bounds of an integer.
while (val > static_cast<double>(INT_MAX)) {
val /= 10.0;
steps++;
}
// Add to string.
val = floor(val);
str.addIntString(static_cast<int>(val));
int scopy = steps;
// Calculate remainder.
while (steps) {
val *= 10.0;
steps--;
}
val = vcopy - val;
// Add any trailing zeros.
if (val == 0.0) {
while (scopy) {
str += '0';
scopy--;
}
}
}
if (val != 0.0) str.addIntString(static_cast<int>(val));
}
/*!
Dump the state of this object to the \a file stream. Only works in
debug version of library, method does nothing in an optimized compile.
*/
void
SbTime::print(FILE * fp) const
{
#if COIN_DEBUG
struct timeval tm;
this->getValue(&tm);
SbString str = this->formatDate();
(void)fprintf(fp, "%s", str.getString());
(void)fprintf(fp, ", secs: %ld, msecs: %ld\n", static_cast<long int>(tm.tv_sec),
static_cast<long int>(tm.tv_usec));
#endif // COIN_DEBUG
}
|
/**
Copyright (c) 2014-2015, Sandia Corporation
All rights reserved.
This file is part of fast-matmul and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause.
*/
#include <chrono>
#include <iostream>
#include <mkl.h>
void Dgemm(double *A, double *B, double *C, int N) {
int M = N; int K = N;
double alpha = 1.0; double beta = 0.0;
int lda = N; int ldb = N; int ldc = N;
DGEMM("N", "N", &M, &N, &K, &alpha, A, &lda, B, &ldb, &beta, C, &ldc);
}
int main() {
int N = 8000;
double *A = new double[N * N];
double *B = new double[N * N];
double *C = new double[N * N];
auto start = std::chrono::high_resolution_clock::now();
Dgemm(A, B, C, N);
auto end = std::chrono::high_resolution_clock::now();
auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << diff.count() << " ms" << std::endl;
}
|
// Copyright (c) 2013-2018 LG Electronics, 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.
//
// SPDX-License-Identifier: Apache-2.0
/*
* TestResBundle.cpp
*
* @author Oleksandr Gorbunov
*/
#include "webosi18n/cxx/ResBundle.h"
#include "TestResBundle.h"
#include <stdlib.h>
#include <time.h>
#include <iostream>
/*
* Simple C++ Test Suite for ResBundle
*/
size_t resBundleTestFailures = 0;
bool assertNull(ResBundle* resBundle, string methodName) {
if (!resBundle) {
cout << "\n%TEST_FAILED% testname = " << methodName << " TestResBundle ResBundle is NULL" << endl;
resBundleTestFailures++;
return true;
}
return false;
}
void getLocaleSimpleTest(ResBundle* resBundle, string currentLocale, string method_name) {
if (currentLocale.compare(resBundle->getLocale()) != 0) {
cout << "\n%TEST_FAILED% testname = " << method_name << " TestResBundle message=error" << endl;
cout << " Expetcted: " << currentLocale << ", actual: " << resBundle->getLocale() << endl;
resBundleTestFailures++;
}
}
void containsSourseSimpleTest(ResBundle* resBundle, string source, bool existed, string method_name) {
bool result = resBundle->containsSource(source);
if (result != existed) {
cout << "\n%TEST_FAILED% testname = " << method_name << " TestResBundle message=error" << endl;
cout << " Source \"" << source << "\" is not found"<< endl;
resBundleTestFailures++;
}
}
void getLocStringSingleTest(ResBundle* resBundle, string source, string expected, string method_name) {
string result = resBundle->getLocString(source);
if (result.compare(expected) != 0) {
cout << "\n%TEST_FAILED% testname = " << method_name << " TestResBundle message=error" << endl;
cout << " Expetcted: " << expected << "; actual: " << result << endl;
resBundleTestFailures++;
}
}
void getLocStringWithKeySingleTest(ResBundle* resBundle, string key, string source, string expected, string method_name) {
string result = resBundle->getLocString(key, source);
if (result.compare(expected) != 0) {
cout << "\n%TEST_FAILED% testname = " << method_name << " TestResBundle message=error" << endl;
cout << " Expetcted: " << expected << "; actual: " << result << endl;
resBundleTestFailures++;
}
}
void testResBundleFilePathConstructor() {
std::string locale = "uk-UA";
const std::string file_path = "res/strings.json";
ResBundle* resBundle = new ResBundle(locale, file_path);
if (assertNull(resBundle, "testResBundleFilePathConstructor")) return;
delete resBundle;
}
void testResBundleFileAndPathConstructor() {
std::string locale = "uk-UA";
const std::string file = "strings.json";
const std::string resources_path = "res";
ResBundle* resBundle = new ResBundle(locale, file, resources_path);
if (assertNull(resBundle, "testResBundleFileAndPathConstructor")) return;
delete resBundle;
}
void testEmptyLocale() {
std::string locale("");
const std::string file_path = "res/strings.json";
ResBundle* resBundle = new ResBundle(locale, file_path);
if (assertNull(resBundle, "testEmptyLocale")) return;
getLocaleSimpleTest(resBundle, "en-US", "testEmptyLocale");
delete resBundle;
}
void testContainsSourceTrue() {
std::string locale = "fr-FR";
std::string file_path = "res/cppstrings.json";
ResBundle* resBundle = new ResBundle(locale, file_path);
if (assertNull(resBundle, "testContainsSourceTrue")) return;
containsSourseSimpleTest(resBundle, "Refresh label", true, "testContainsSourceTrue");
delete resBundle;
}
void testContainsSourceFalse() {
std::string locale = "fr-FR";
std::string file_path = "res/cppstrings.json";
ResBundle* resBundle = new ResBundle(locale, file_path);
if (assertNull(resBundle, "testContainsSourceFalse")) return;
containsSourseSimpleTest(resBundle, "French Add title", false, "testContainsSourceFalse");
delete resBundle;
}
void testGetLocString1() {
std::string locale = "es-MX";
const std::string file_path = "res/stringsMX.json";
ResBundle* resBundle = new ResBundle(locale, file_path);
if (assertNull(resBundle, "testGetLocString1")) return;
getLocStringSingleTest(resBundle, "Opt out failed. Try later",
"Falló la opción de no participar. Intenta más tarde", "testGetLocString1");
delete resBundle;
}
void testGetPseudoString1()
{
std::string locale = "zxx-XX";
ResBundle* resBundle = new ResBundle(locale, "");
if (assertNull(resBundle, "testGetPseudoString1")) return;
getLocStringSingleTest(resBundle, "HID device is connected.", "pnCĦÏÐ ðëvíçë íš çõññëçţëð.3210",
"testGetPseudoString1");
delete resBundle;
}
void testGetPseudoString2()
{
std::string locale = "zxx-Cyrl-XX";
ResBundle* resBundle = new ResBundle(locale, "", "");
if (assertNull(resBundle, "testGetPseudoString2")) return;
getLocStringSingleTest(resBundle, "HID device is connected.", "pnCХИД дэвичэ ис чоннэчтэд.3210",
"testGetPseudoString2");
delete resBundle;
}
void testGetPseudoString3()
{
std::string locale = "zxx-Hebr-XX";
ResBundle* resBundle = new ResBundle(locale, "", "");
if (assertNull(resBundle, "testGetPseudoString3")) return;
getLocStringSingleTest(resBundle, "HID device is connected.", "pnCהִדּ דֶבִקֶ ִס קֹננֶקטֶד.3210",
"testGetPseudoString3");
delete resBundle;
}
void testGetPseudoString4()
{
std::string locale = "zxx-Hans-XX";
ResBundle* resBundle = new ResBundle(locale, "", "");
if (assertNull(resBundle, "testGetPseudoString4")) return;
getLocStringSingleTest(resBundle, "HID device is connected.", "pnCĦИדּ ðэב意çэ 意š ק夥ñнֶ可ţэד.3210",
"testGetPseudoString4");
delete resBundle;
}
void testGetLocString2() {
std::string locale = "es-MX";
const std::string file_path = "res/stringsMX.json";
ResBundle* resBundle = new ResBundle(locale, file_path);
if (assertNull(resBundle, "testGetLocString2")) return;
getLocStringSingleTest(resBundle, "Done", "Listo", "testGetLocString2");
delete resBundle;
}
void testGetLocString3() {
std::string locale = "es-MX";
const std::string file_path = "res/stringsMX.json";
ResBundle* resBundle = new ResBundle(locale, file_path);
if (assertNull(resBundle, "testGetLocString3")) return;
getLocStringSingleTest(resBundle, "A verification email was sent to {email}.",
"Se ha enviado un mensaje de verificación a {email}.", "testGetLocString3");
delete resBundle;
}
void testGetLocStringResBundleFileAndPathConstructor() {
std::string locale = "uk-UA";
const std::string file = "strings.json";
const std::string resources_path = "res";
ResBundle* resBundle = new ResBundle(locale, file, resources_path);
if (assertNull(resBundle, "testGetLocStringResBundleFileAndPathConstructor")) return;
getLocStringSingleTest(resBundle, "Error", "Помилка", "testGetLocStringResBundleFileAndPathConstructor");
getLocStringSingleTest(resBundle, "enter password...", "Please, enter your password", "testGetLocStringResBundleFileAndPathConstructor");
getLocStringSingleTest(resBundle, "Edit Address", "Редагувати адресу", "testGetLocStringResBundleFileAndPathConstructor");
delete resBundle;
}
void testGetLocStringWithExistedKey1() {
std::string locale = "es-MX";
const std::string file_path = "res/stringsMX.json";
ResBundle* resBundle = new ResBundle(locale, file_path);
if (assertNull(resBundle, "testGetLocStringWithExistedKey1")) return;
getLocStringWithKeySingleTest(resBundle, "Opt out failed. Try later", "Try later",
"Falló la opción de no participar. Intenta más tarde", "testGetLocStringWithExistedKey1");
delete resBundle;
}
void testGetLocStringWithExistedKey2() {
std::string locale = "es-MX";
const std::string file_path = "res/stringsMX.json";
ResBundle* resBundle = new ResBundle(locale, file_path);
if (assertNull(resBundle, "testGetLocStringWithExistedKey2")) return;
getLocStringWithKeySingleTest(resBundle, "Done", "Task is done!", "Listo", "testGetLocStringWithExistedKey2");
delete resBundle;
}
void testGetLocStringWithNonExistedKey1() {
std::string locale = "fr-FR";
const std::string file_path = "res/cppstrings.json";
ResBundle* resBundle = new ResBundle(locale, file_path);
if (assertNull(resBundle, "testGetLocStringWithNonExistedKey1")) return;
getLocStringWithKeySingleTest(resBundle, "addtitle", "Add title", "Add title", "testGetLocStringWithNonExistedKey1");
delete resBundle;
}
void testGetLocStringWithNonExistedKey2() {
std::string locale = "fr-FR";
const std::string file_path = "res/cppstrings.json";
ResBundle* resBundle = new ResBundle(locale, file_path);
if (assertNull(resBundle, "testGetLocStringWithNonExistedKey2")) return;
getLocStringWithKeySingleTest(resBundle, "switchtomode", "Switch to mode", "Switch to mode", "testGetLocStringWithNonExistedKey2");
delete resBundle;
}
void testGetLocaleWithResourcesGerman() {
std::string locale = "de-DE";
std::string file_path = "res/strings.json";
ResBundle* resBundle = new ResBundle(locale, file_path);
if (assertNull(resBundle, "testGetLocaleWithResourcesGerman")) return;
getLocaleSimpleTest(resBundle, locale, "testGetLocaleWithResourcesGerman");
delete resBundle;
}
void testGetLocaleWithResourcesMongolian() {
std::string locale = "mn-Cyrl-MN";
std::string file_path = "res/strings.json";
ResBundle* resBundle = new ResBundle(locale, file_path);
if (assertNull(resBundle, "testGetLocaleWithResourcesGerman")) return;
getLocaleSimpleTest(resBundle, locale, "testGetLocaleWithResourcesGerman");
delete resBundle;
}
void testGetLocStringMultipleTimes() {
std::string locale = "fr-FR";
const std::string file_path = "res/cppstrings.json";
ResBundle* resBundle = new ResBundle(locale, file_path);
if (assertNull(resBundle, "testGetLocStringMultipleTimes")) return;
getLocStringSingleTest(resBundle, "Switch to mode", "French Switch to mode", "testGetLocStringMultipleTimes");
getLocStringSingleTest(resBundle, "Save title", "French Save title", "testGetLocStringMultipleTimes");
getLocStringSingleTest(resBundle, "Refresh label", "French Refresh label", "testGetLocStringMultipleTimes");
getLocStringSingleTest(resBundle, "Refresh label item", "Refresh label item", "testGetLocStringMultipleTimes");
getLocStringSingleTest(resBundle, "Add title", "French Add title", "testGetLocStringMultipleTimes");
delete resBundle;
}
void testGetLocStringMultipleTimesCrissCross() {
std::string locale = "de-DE";
std::string file_path = "res/strings.json";
ResBundle* resBundle = new ResBundle(locale, file_path);
if (assertNull(resBundle, "testGetLocStringMultipleTimesCrissCross")) return;
getLocaleSimpleTest(resBundle, locale, "testGetLocStringMultipleTimesCrissCross");
getLocStringSingleTest(resBundle, "Settings", "Einstellungen", "testGetLocStringMultipleTimesCrissCross");
getLocStringSingleTest(resBundle, "Back Up Now", "Jetzt sichern", "testGetLocStringMultipleTimesCrissCross");
getLocStringSingleTest(resBundle, "Settings", "Einstellungen", "testGetLocStringMultipleTimesCrissCross");
getLocStringSingleTest(resBundle, "Back Up Now", "Jetzt sichern", "testGetLocStringMultipleTimesCrissCross");
getLocStringSingleTest(resBundle, "Settings", "Einstellungen", "testGetLocStringMultipleTimesCrissCross");
getLocStringSingleTest(resBundle, "Settings", "Einstellungen", "testGetLocStringMultipleTimesCrissCross");
getLocStringSingleTest(resBundle, "Back Up Now", "Jetzt sichern", "testGetLocStringMultipleTimesCrissCross");
delete resBundle;
}
void testGetLocStringMultipleSameCallsInTime() {
std::string locale = "de-DE";
std::string file_path = "res/strings.json";
ResBundle* resBundle = new ResBundle(locale, file_path);
if (assertNull(resBundle, "testGetLocStringMultipleSameCallsInTime")) return;
getLocStringSingleTest(resBundle, "Select a question", "Frage auswählen", "testResBundleCGetLocStringMultipleSameCallsInTime");
getLocStringSingleTest(resBundle, "Error", "Fehler", "testResBundleCGetLocStringMultipleSameCallsInTime");
getLocStringSingleTest(resBundle, "Select a question", "Frage auswählen", "testResBundleCGetLocStringMultipleSameCallsInTime");
getLocStringSingleTest(resBundle, "Help", "Hilfe", "testResBundleCGetLocStringMultipleSameCallsInTime");
getLocStringSingleTest(resBundle, "Select a question", "Frage auswählen", "testResBundleCGetLocStringMultipleSameCallsInTime");
getLocStringSingleTest(resBundle, "Sign in", "Anmelden", "testResBundleCGetLocStringMultipleSameCallsInTime");
getLocStringSingleTest(resBundle, "Select a question", "Frage auswählen", "testResBundleCGetLocStringMultipleSameCallsInTime");
getLocStringSingleTest(resBundle, "Turn Off and Erase Backup", "Deakt./gesich. Daten löschen", "testResBundleCGetLocStringMultipleSameCallsInTime");
getLocStringSingleTest(resBundle, "Select a question", "Frage auswählen", "testResBundleCGetLocStringMultipleSameCallsInTime");
delete resBundle;
}
void testGetLocStringMultipleCrissCrossWithKeys()
{
std::string locale = "de-DE";
std::string file_path = "res/strings.json";
ResBundle* resBundle = new ResBundle(locale, file_path);
if (assertNull(resBundle, "testGetLocStringMultipleCrissCrossWithKeys")) return;
getLocStringWithKeySingleTest(resBundle, "preparingitem", "Preparing", "Preparing",
"testGetLocStringMultipleCrissCrossWithKeys");
getLocStringWithKeySingleTest(resBundle, "enter password...", "Enter password", "Kennwort eingeben…",
"testGetLocStringMultipleCrissCrossWithKeys");
getLocStringWithKeySingleTest(resBundle, "HPaccountSaved", "HP webOS Account saved", "HP webOS Account saved",
"testGetLocStringMultipleCrissCrossWithKeys");
getLocStringWithKeySingleTest(resBundle, "confirm password...", "confirm password", "Kennwort bestätigen…",
"testGetLocStringMultipleCrissCrossWithKeys");
getLocStringWithKeySingleTest(resBundle, "emailsending", "Sending password reset email", "Sending password reset email",
"testGetLocStringMultipleCrissCrossWithKeys");
delete resBundle;
}
void testGetLocStringMultipleSameCallsInTimeWithKeys()
{
std::string locale = "de-DE";
std::string file_path = "res/strings.json";
ResBundle* resBundle = new ResBundle(locale, file_path);
if (assertNull(resBundle, "testGetLocStringMultipleCrissCrossWithKeys")) return;
getLocStringWithKeySingleTest(resBundle, "enter password...", "Enter password", "Kennwort eingeben…",
"testGetLocStringMultipleSameCallsInTimeWithKeys");
getLocStringWithKeySingleTest(resBundle, "error.", "Error", "Error", "testGetLocStringMultipleSameCallsInTimeWithKeys");
getLocStringWithKeySingleTest(resBundle, "Select a question", "question", "Frage auswählen",
"testGetLocStringMultipleSameCallsInTimeWithKeys");
getLocStringWithKeySingleTest(resBundle, "enter password...", "Enter password", "Kennwort eingeben…",
"testGetLocStringMultipleSameCallsInTimeWithKeys");
getLocStringWithKeySingleTest(resBundle, "keepbackup", "Keep Backup On", "Keep Backup On",
"testGetLocStringMultipleSameCallsInTimeWithKeys");
getLocStringWithKeySingleTest(resBundle, "Sign in", "Sign in", "Anmelden",
"testGetLocStringMultipleSameCallsInTimeWithKeys");
getLocStringWithKeySingleTest(resBundle, "Keep Backup On", "whatever", "Sicherung aktiviert lassen",
"testGetLocStringMultipleSameCallsInTimeWithKeys");
getLocStringWithKeySingleTest(resBundle, "enter password...", "Enter password", "Kennwort eingeben…",
"testGetLocStringMultipleSameCallsInTimeWithKeys");
delete resBundle;
}
void testGetMultipleResourceBundles()
{
std::string englishLocale = "en-CN";
std::string chineseLocale = "zh-Hans-CN";
const std::string file = "strings.json";
const std::string resources_path = "res/";
ResBundle* resBundleEnglish = new ResBundle(englishLocale, file, resources_path);
ResBundle* resBundleChinese = new ResBundle(chineseLocale, file, resources_path);
if (assertNull(resBundleEnglish, "testGetMultipleResourceBundles")) return;
if (assertNull(resBundleChinese, "testGetMultipleResourceBundles")) return;
getLocStringSingleTest(resBundleEnglish, "Don't Update", "Do not update", "testGetMultipleResourceBundles");
getLocStringSingleTest(resBundleEnglish, "Change Password", "Password must be changed",
"testGetMultipleResourceBundles");
getLocStringSingleTest(resBundleChinese, "Done", "Chinese Done.", "testGetMultipleResourceBundles");
getLocStringSingleTest(resBundleChinese, "Change Password", "Chinese changing password",
"testGetMultipleResourceBundles");
delete resBundleEnglish;
resBundleEnglish = resBundleChinese;
getLocStringSingleTest(resBundleEnglish, "Don't Update", "Chinese Do not update", "testGetMultipleResourceBundles");
getLocStringSingleTest(resBundleEnglish, "Change Password", "Chinese changing password",
"testGetMultipleResourceBundles");
delete resBundleChinese;
}
void testGetLocStringMultipleDifferentCalls()
{
std::string locale = "de-DE";
std::string file_path = "res/strings.json";
ResBundle* resBundle = new ResBundle(locale, file_path);
if (assertNull(resBundle, "testGetLocStringMultipleDifferentCalls")) return;
getLocStringSingleTest(resBundle, "Select a question", "Frage auswählen", "testGetLocStringMultipleDifferentCalls");
getLocStringWithKeySingleTest(resBundle, "Enter password", "Enter password", "Enter password",
"testGetLocStringMultipleDifferentCalls");
getLocStringWithKeySingleTest(resBundle, "enter password...", "Enter password", "Kennwort eingeben…",
"testGetLocStringMultipleDifferentCalls");
getLocStringSingleTest(resBundle, "enter password...", "Kennwort eingeben…",
"testGetLocStringMultipleDifferentCalls");
getLocStringSingleTest(resBundle, "Backup server unavailable", "Sicherungsserver nicht verfügbar",
"testGetLocStringMultipleDifferentCalls");
getLocStringWithKeySingleTest(resBundle, "Backup server unavailable", "Help", "Sicherungsserver nicht verfügbar",
"testGetLocStringMultipleDifferentCalls");
getLocStringSingleTest(resBundle, "Don't Update", "Nicht aktualisieren", "testGetLocStringMultipleDifferentCalls");
getLocStringWithKeySingleTest(resBundle, "don't", "Don't Update", "Don't Update", "testGetLocStringMultipleDifferentCalls");
getLocStringSingleTest(resBundle, "enter password...", "Kennwort eingeben…",
"testGetLocStringMultipleDifferentCalls");
getLocStringWithKeySingleTest(resBundle, "We will send your confirmation email as soon as you have an internet connection.",
"..............", "Sie erhalten eine Bestätigungs-E-Mail, sobald eine Internetverbindung hergestellt ist.",
"testGetLocStringMultipleDifferentCalls");
getLocStringWithKeySingleTest(resBundle, "enter password...", "Enter password", "Kennwort eingeben…",
"testGetLocStringMultipleDifferentCalls");
delete resBundle;
}
void runTestResBundle(int* testsNumber, int* failuresNumber) {
cout << "Running TestResBundle file" << endl;
cout << "-------------------------------------------------------------" << endl;
clock_t begin, end, tmp;
double timeElapsed = .0000;
short tests_count = 0;
tmp = clock();
begin = tmp;
testResBundleFilePathConstructor();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testResBundleFilePathConstructor took " << timeElapsed << " seconds" << endl;
tests_count++;
tmp = clock();
testResBundleFileAndPathConstructor();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testResBundleFileAndPathConstructor took " << timeElapsed << " seconds" << endl;
tests_count++;
tmp = clock();
testEmptyLocale();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testEmptyLocale took " << timeElapsed << " seconds" << endl;
tests_count++;
tmp = clock();
testContainsSourceTrue();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testContainsSourceTrue took " << timeElapsed << " seconds" << endl;
tests_count++;
tmp = clock();
testContainsSourceFalse();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testContainsSourceFalse took " << timeElapsed << " seconds" << endl;
tests_count++;
tmp = clock();
testGetLocString1();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testGetLocString1 took " << timeElapsed << " seconds" << endl;
tests_count++;
tmp = clock();
testGetPseudoString1();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testGetPseudoString1 took " << timeElapsed << " seconds" << endl;
tests_count++;
tmp = clock();
testGetPseudoString2();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testGetPseudoString2 took " << timeElapsed << " seconds" << endl;
tests_count++;
tmp = clock();
testGetPseudoString3();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testGetPseudoString3 took " << timeElapsed << " seconds" << endl;
tests_count++;
tmp = clock();
testGetPseudoString4();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testGetPseudoString4 took " << timeElapsed << " seconds" << endl;
tests_count++;
tmp = clock();
testGetLocString2();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testGetLocString2 took " << timeElapsed << " seconds" << endl;
tests_count++;
tmp = clock();
testGetLocString3();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testGetLocString3 took " << timeElapsed << " seconds" << endl;
tests_count++;
tmp = clock();
testGetLocStringResBundleFileAndPathConstructor();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testGetLocStringResBundleFileAndPathConstructor took " << timeElapsed << " seconds" << endl;
tests_count++;
tmp = clock();
testGetLocStringWithExistedKey1();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testGetLocStringWithExistedKey1 took " << timeElapsed << " seconds" << endl;
tests_count++;
tmp = clock();
testGetLocStringWithExistedKey2();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testGetLocStringWithExistedKey2 took " << timeElapsed << " seconds" << endl;
tests_count++;
tmp = clock();
testGetLocStringWithNonExistedKey1();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testGetLocStringWithNonExistedKey1 took " << timeElapsed << " seconds" << endl;
tests_count++;
tmp = clock();
testGetLocStringWithNonExistedKey2();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testGetLocStringWithNonExistedKey2 took " << timeElapsed << " seconds" << endl;
tests_count++;
tmp = clock();
testGetLocaleWithResourcesGerman();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testGetLocaleWithResourcesGerman took " << timeElapsed << " seconds" << endl;
tests_count++;
tmp = clock();
testGetLocaleWithResourcesMongolian();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testGetLocaleWithResourcesMongolian took " << timeElapsed << " seconds" << endl;
tests_count++;
tmp = clock();
testGetLocStringMultipleTimes();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testGetLocStringMultipleTimes took " << timeElapsed << " seconds" << endl;
tests_count++;
tmp = clock();
testGetLocStringMultipleTimesCrissCross();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testGetLocStringMultipleTimesCrissCross took " << timeElapsed << " seconds" << endl;
tests_count++;
tmp = clock();
testGetLocStringMultipleSameCallsInTime();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testGetLocStringMultipleSameCallsInTime took " << timeElapsed << " seconds" << endl;
tests_count++;
tmp = clock();
testGetLocStringMultipleCrissCrossWithKeys();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testGetLocStringMultipleCrissCrossWithKeys took " << timeElapsed << " seconds" << endl;
tests_count++;
tmp = clock();
testGetLocStringMultipleSameCallsInTimeWithKeys();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testGetLocStringMultipleSameCallsInTimeWithKeys took " << timeElapsed << " seconds" << endl;
tests_count++;
tmp = clock();
testGetMultipleResourceBundles();
timeElapsed = ((double)(clock() - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testGetMultipleResourceBundles took " << timeElapsed << " seconds" << endl;
tests_count++;
tmp = clock();
testGetLocStringMultipleDifferentCalls();
end = clock();
timeElapsed = ((double)(end - tmp))/CLOCKS_PER_SEC;
cout << "Testcase: testGetLocStringMultipleDifferentCalls took " << timeElapsed << " seconds" << endl;
tests_count++;
*testsNumber += tests_count;
*failuresNumber += resBundleTestFailures;
cout << "Tests run: "<< tests_count << " , Failures: " << resBundleTestFailures << ", Time elapsed: " << ((double)(end- begin)/CLOCKS_PER_SEC) << " sec" << endl;
cout << "---------------------- Standard Output ----------------------" << endl;
}
|
#include "ZTimer.h"
#include "CodalCompat.h"
#include "CodalConfig.h"
#include "codal_target_hal.h"
#include "CodalDmesg.h"
// TODO get rid of division on SAMD21 - it's slow
namespace codal
{
// Global millisecond tick count
static volatile uint64_t ticks_ms = 0;
static volatile uint64_t nextTrigger = 0;
ZTimer *ZTimer::instance;
extern "C" void SysTick_Handler(void) {
int shouldTrigger = 0;
// SysTick interrupt handler called when the SysTick timer reaches zero
// (every millisecond).
target_disable_irq();
ticks_ms += 1;
// Read the control register to reset the COUNTFLAG.
(void) SysTick->CTRL;
if (nextTrigger && ticks_ms >= nextTrigger) {
nextTrigger = 0;
shouldTrigger = 1;
}
target_enable_irq();
if (shouldTrigger)
ZTimer::instance->trigger();
}
static void tick_init() {
if (ticks_ms)
return;
ticks_ms = 1;
uint32_t ticks_per_ms = CODAL_CPU_MHZ * 1000;
SysTick_Config(ticks_per_ms-1);
NVIC_EnableIRQ(SysTick_IRQn);
// Set all peripheral interrupt priorities to the lowest priority by default.
for (uint16_t i = 0; i < PERIPH_COUNT_IRQn; i++) {
NVIC_SetPriority((IRQn_Type)i, (1UL << __NVIC_PRIO_BITS) - 1UL);
}
// Bump up the systick interrupt so nothing else interferes with timekeeping.
NVIC_SetPriority(SysTick_IRQn, 0);
#ifdef SAMD21
NVIC_SetPriority(USB_IRQn, 1);
#endif
#ifdef SAMD51
NVIC_SetPriority(USB_0_IRQn, 1);
NVIC_SetPriority(USB_1_IRQn, 1);
NVIC_SetPriority(USB_2_IRQn, 1);
NVIC_SetPriority(USB_3_IRQn, 1);
#endif
}
extern "C" void target_wait_us(uint32_t us) {
tick_init();
uint32_t ticks_per_us = CODAL_CPU_MHZ;
uint32_t us_until_next_tick = SysTick->VAL / ticks_per_us;
uint32_t start_tick;
while (us >= us_until_next_tick) {
start_tick = SysTick->VAL; // wait for SysTick->VAL to RESET
while (SysTick->VAL < start_tick) {}
us -= us_until_next_tick;
us_until_next_tick = 1000;
}
while (SysTick->VAL > ((us_until_next_tick - us) * ticks_per_us)) {}
}
ZTimer::ZTimer() : codal::Timer()
{
instance = this;
}
void ZTimer::init()
{
tick_init();
}
void ZTimer::triggerIn(CODAL_TIMESTAMP t)
{
target_disable_irq();
nextTrigger = ticks_ms + t / 1000;
target_enable_irq();
}
void ZTimer::syncRequest()
{
target_disable_irq();
uint32_t ticks_per_us = CODAL_CPU_MHZ;
uint32_t tick_status = SysTick->CTRL;
uint32_t current_us = SysTick->VAL;
uint32_t tick_status2 = SysTick->CTRL;
uint64_t current_ms = ticks_ms;
// The second clause ensures our value actually rolled over. Its possible it hit zero between
// the VAL read and CTRL read.
if ((tick_status & SysTick_CTRL_COUNTFLAG_Msk) != 0 ||
((tick_status2 & SysTick_CTRL_COUNTFLAG_Msk) != 0 && current_us > ticks_per_us)) {
current_ms++;
}
currentTime = current_ms;
currentTimeUs = current_ms * 1000 + (1000 - (current_us / ticks_per_us));
target_enable_irq();
}
} // namespace codal
|
// This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE
#include "scene_manager.h"
#include "scene_events.h"
#include <cppconn/connection.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/sqlstring.h>
#include "swganh/logger.h"
#include "swganh_core/object/object.h"
#include "swganh_core/simulation/scene_interface.h"
using namespace sql;
using namespace std;
using namespace swganh::object;
using namespace swganh::simulation;
void SceneManager::LoadSceneDescriptionsFromDatabase(const std::shared_ptr<sql::Connection>& connection)
{
try
{
auto statement = connection->createStatement();
unique_ptr<ResultSet> result(statement->executeQuery(
"CALL sp_GetSceneDescriptions()"));
while(result->next())
{
SceneDescription description;
description.id = result->getUInt("id");
description.name = result->getString("name");
description.label = result->getString("label");
description.description = result->getString("description");
description.terrain = result->getString("terrain");
scene_descriptions_.insert(make_pair(description.label, description));
}
}
catch(SQLException &e)
{
LOG(error) << "SQLException at " << __FILE__ << " (" << __LINE__ << ": " << __FUNCTION__ << ")";
LOG(error) << "MySQL Error: (" << e.getErrorCode() << ": " << e.getSQLState() << ") " << e.what();
}
}
std::shared_ptr<swganh::simulation::SceneInterface> SceneManager::GetScene(const std::string& scene_label) const
{
auto find_iter = scenes_.find(scene_label);
if (find_iter == scenes_.end())
{
return nullptr;
}
return find_iter->second;
}
std::shared_ptr<swganh::simulation::SceneInterface> SceneManager::GetScene(uint32_t scene_id) const
{
auto find_iter = find_if(begin(scenes_), end(scenes_), [scene_id] (ScenePair scene_pair) {
return scene_pair.second->GetSceneId() == scene_id;
});
if (find_iter == scenes_.end())
{
return nullptr;
}
return find_iter->second;
}
void SceneManager::ViewScenes(std::function<void(const std::string&, std::shared_ptr<Scene>)> func)
{
std::for_each(scenes_.begin(), scenes_.end(), [&] (std::pair<std::string, std::shared_ptr<Scene>> pair)
{
func(pair.first, pair.second);
});
}
void SceneManager::StartScene(const std::string& scene_label, swganh::app::SwganhKernel* kernel)
{
auto description_iter = scene_descriptions_.find(scene_label);
if (description_iter == scene_descriptions_.end())
{
throw std::runtime_error("Requested an invalid scene: " + scene_label);
}
auto scene_iter = scenes_.find(scene_label);
if (scene_iter != scenes_.end())
{
throw std::runtime_error("Scene has already been loaded: " + scene_label);
}
LOG(info) << "Starting scene: " << scene_label;
auto scene = make_shared<Scene>(description_iter->second, kernel);
scenes_.insert(make_pair(scene_label, scene));
kernel->GetEventDispatcher()->Dispatch(std::make_shared<NewSceneEvent>("SceneManager:NewScene",
scene->GetSceneId(), scene->GetLabel(), scene->GetTerrainMap()));
}
void SceneManager::StopScene(const std::string& scene_label, swganh::app::SwganhKernel* kernel)
{
auto itr = scenes_.find(scene_label);
if(itr != scenes_.end()) {
kernel->GetEventDispatcher()->Dispatch(std::make_shared<DestroySceneEvent>("SceneManager:DestroyScene",
itr->second->GetSceneId()));
scenes_.erase(scene_label);
}
}
|
/*
* 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 <ignite/jni/java.h>
#include "ignite/impl/ignite_impl.h"
#include "ignite/ignite.h"
using namespace ignite::common::concurrent;
using namespace ignite::impl;
namespace ignite
{
Ignite::Ignite() : impl(SharedPointer<IgniteImpl>())
{
// No-op.
}
Ignite::Ignite(IgniteImpl* impl) : impl(SharedPointer<IgniteImpl>(impl))
{
// No-op.
}
const char* Ignite::GetName() const
{
return impl.Get()->GetName();
}
const IgniteConfiguration& Ignite::GetConfiguration() const
{
return impl.Get()->GetConfiguration();
}
bool Ignite::IsActive()
{
return impl.Get()->IsActive();
}
void Ignite::SetActive(bool active)
{
impl.Get()->SetActive(active);
}
transactions::Transactions Ignite::GetTransactions()
{
using ignite::common::concurrent::SharedPointer;
using ignite::impl::transactions::TransactionsImpl;
SharedPointer<TransactionsImpl> txImpl = impl.Get()->GetTransactions();
return transactions::Transactions(txImpl);
}
cluster::IgniteCluster Ignite::GetCluster()
{
return cluster::IgniteCluster(impl.Get()->GetCluster());
}
compute::Compute Ignite::GetCompute()
{
return compute::Compute(impl.Get()->GetCompute());
}
compute::Compute Ignite::GetCompute(cluster::ClusterGroup grp)
{
return compute::Compute(impl.Get()->GetCompute(grp));
}
IgniteBinding Ignite::GetBinding()
{
return impl.Get()->GetBinding();
}
}
|
/*
* Unicode Bidi-Language Implementation
* Nana C++ Library(http://www.nanapro.org)
* Copyright(C) 2003-2019 Jinhao(cnjinhao@hotmail.com)
*
* 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)
*
* @file: nana/unicode_bidi.cpp
* @contributors:
* glavangeorge(pr#440)
*/
#include <nana/unicode_bidi.hpp>
#include <nana/c++defines.hpp>
namespace nana
{
namespace bidi_charmap
{
enum t{ L, LRE, LRO, R, AL, RLE, RLO,
PDF, EN, ES, ET, AN, CS, NSM, BN,
B, S, WS, ON};
static unsigned char charmap_0x0000_0x00C0[192] = {
BN, BN, BN, BN, BN, BN, BN, BN, BN, S, B, S, WS, B, BN, BN,
BN, BN, BN, BN, BN, BN, BN, BN, BN, BN, BN, BN, B, B, B, S,
WS, ON, ON, ET, ET, ET, ON, ON, ON, ON, ON, ES, CS, ES, CS, CS,
EN, EN, EN, EN, EN, EN, EN, EN, EN, EN, CS, ON, ON, ON, ON, ON,
ON, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L,
L, L, L, L, L, L, L, L, L, L, L, ON, ON, ON, ON, ON,
ON, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L,
L, L, L, L, L, L, L, L, L, L, L, ON, ON, ON, ON, BN,
BN, BN, BN, BN, BN, B, BN, BN, BN, BN, BN, BN, BN, BN, BN, BN,
BN, BN, BN, BN, BN, BN, BN, BN, BN, BN, BN, BN, BN, BN, BN, BN,
CS, ON, ET, ET, ET, ET, ON, ON, ON, ON, L, ON, ON, BN, ON, ON,
ET, ET, EN, EN, ON, L, ON, ON, ON, EN, L, ON, ON, ON, ON, ON
};
t bidi_char_type(wchar_t ch)
{
if(ch <= 0x0FC6)
{
if(ch < 0x00C0) return static_cast<bidi_charmap::t>(charmap_0x0000_0x00C0[ch]);
if(ch == 0x00D7 || ch == 0x00F7) return ON;
if(ch <= 0x02B8) return L; //N = 449
if(ch <= 0x02BA) return ON; //N = 2
if(ch <= 0x02C1) return L; //N = 7
if(ch <= 0x02CF) return ON; //N = 14
if(ch <= 0x02D1) return L; //N = 2
if(ch <= 0x02DF) return ON; //N = 14
if(ch <= 0x02E4) return L; //N = 5
if(0x02EE == ch) return L;
if(ch <= 0x02FF) return ON; //N = 17
if(ch <= 0x036F) return NSM; //N = 112
if(ch <= 0x0373) return L; //N = 4
if(ch <= 0x0375) return ON; //N = 2
if(ch <= 0x037D) return L; //N = 8
if(ch <= 0x0385) return ON; //N = 8
if(0x0387 == ch || 0x03F6 == ch) return ON;
if(ch <= 0x0482) return L; //N = 140
if(ch <= 0x0489) return NSM; //N = 7
if(ch <= 0x0589) return L; //N = 256
if(0x058A == ch) return ON;
if(0x058F == ch) return ET;
if(0x05BE == ch || 0x05C0 == ch || 0x05C3 == ch || 0x05C6 == ch) return R;
if(ch <= 0x05C7) return NSM;
if(ch <= 0x05F4) return R; //N = 37
if(ch <= 0x0604) return AN; //N = 5
if(ch <= 0x0607) return ON; //N = 2
if(0x0608 == ch) return AL;
if(ch <= 0x060A) return ET; //N = 2
if(0x060B == ch) return AL;
if(0x060C == ch) return CS;
if(0x060D == ch) return AL;
if(ch <= 0x060F) return ON; //N = 2
if(ch <= 0x061A) return NSM; //N = 11
if(ch <= 0x064A) return AL; //N = 48
if(ch <= 0x065F) return NSM; //N = 21
if (0x066A == ch) return ET;
if(ch <= 0x066C) return AN; //N = 2
if (0x0670 == ch) return NSM;
if(ch <= 0x06D5) return AL; //N = 101
if(0x06DD == ch) return AN;
if(0x06DE == ch) return ON;
if(ch <= 0x06E4) return NSM; //N = 6
if(ch <= 0x06E6) return AL; //N = 2
if(0x06E9 == ch) return ON;
if(ch <= 0x06ED) return NSM; //N = 4
if(ch <= 0x06EF) return AL; //N = 2
if(ch <= 0x06F9) return EN; //N = 10
if(0x0711 == ch) return NSM;
if(ch <= 0x072F) return AL; //N = 30
if(ch <= 0x074A) return NSM; //N = 27
if(ch <= 0x07A5) return AL; //N = 89
if(ch <= 0x07B0) return NSM; //N = 11
if(0x07B1 == ch) return AL;
if(ch <= 0x07EA) return R; //N = 43
if(ch <= 0x07F3) return NSM; //N = 9
if(ch <= 0x07F5) return R; //N = 2
if(ch <= 0x07F9) return ON; //N = 4
if(ch <= 0x0815) return R; //N = 28
if(0x081A == ch || 0x0824 == ch || 0x0828 == ch) return R;
if(ch <= 0x082D) return NSM; //N = 5
if(ch <= 0x0858) return R; //N = 41
if(ch <= 0x085B) return NSM; //N = 3
if(0x085E == ch) return R;
if(ch <= 0x08AC) return AL; //N = 13
if(ch <= 0x0902) return NSM; //N = 31
if(0x093A == ch || 0x093C == ch) return NSM;
if(ch <= 0x0940) return L; //N = 4
if(ch <= 0x0948) return NSM; //N = 8
if(0x094D == ch) return NSM;
if(ch <= 0x0950) return L; //N = 3
if(ch <= 0x0957) return NSM; //N = 7
if(ch <= 0x0961) return L; //N = 10
if(ch <= 0x0963) return NSM; //N = 2
if(0x0981 == ch || 0x09BC == ch) return NSM;
if(ch <= 0x09C0) return L; //N = 4
if(ch <= 0x09C4) return NSM; //N = 4
if(0x09CD == ch) return NSM;
if(ch <= 0x09E1) return L; //N = 20
if(ch <= 0x09E3) return NSM; //N = 2
if(ch <= 0x09F1) return L; //N = 12
if(ch <= 0x09F3) return ET; //N = 2
if(ch <= 0x09FA) return L; //N = 7
if(0x09FB == ch) return ET;
if(ch <= 0x0A02) return NSM; //N = 2
if(0x0A3C == ch) return NSM;
if(ch <= 0x0A40) return L; //N = 3
if(ch <= 0x0A51) return NSM; //N = 17
if(ch <= 0x0A6F) return L; //N = 23
if(ch <= 0x0A71) return NSM; //N = 2
if(ch <= 0x0A74) return L; //N = 3
if(ch <= 0x0A82) return NSM; //N = 14
if(0x0ABC == ch) return NSM;
if(ch <= 0x0AC0) return L; //N = 4
if(ch <= 0x0AC8) return NSM; //N = 8
if(0x0ACD == ch) return NSM;
if(ch <= 0x0AE1) return L; //N = 18
if(ch <= 0x0AE3) return NSM; //N = 2
if(0x0AF1 == ch) return ET;
if(0x0B01 == ch || 0x0B3C == ch || 0x0B3F == ch) return NSM;
if(ch <= 0x0B40) return L;
if(ch <= 0x0B44) return NSM; //N = 4
if(ch <= 0x0B4C) return L; //N = 6
if(ch <= 0x0B56) return NSM; //N = 10
if(ch <= 0x0B61) return L; //N = 11
if(ch <= 0x0B63) return NSM; //N = 2
if(0x0B82 == ch || 0x0BC0 == ch || 0x0BCD == ch) return NSM;
if(ch <= 0x0BF2) return L; //N = 35
if(0x0BF9 == ch) return ET;
if(ch <= 0x0BFA) return ON;
if(ch <= 0x0C3D) return L; //N = 61
if(ch <= 0x0C40) return NSM; //N = 3
if(ch <= 0x0C44) return L; //N = 4
if(ch <= 0x0C56) return NSM; //N = 17
if(ch <= 0x0C61) return L; //N = 10
if(ch <= 0x0C63) return NSM; //N = 2
if(ch <= 0x0C6F) return L; //N = 10
if(ch <= 0x0C7E) return ON; //N = 7
if(0x0CBC == ch) return NSM;
if(ch <= 0x0CCB) return L; //N = 15
if(ch <= 0x0CCD) return NSM; //N = 2
if(ch <= 0x0CE1) return L; //N = 13
if(ch <= 0x0CE3) return NSM; //N = 2
if(ch <= 0x0D40) return L; //N = 91
if(ch <= 0x0D44) return NSM; //N = 4
if(0x0D4D == ch) return NSM;
if(ch <= 0x0D61) return L; //N = 20
if(ch <= 0x0D63) return NSM; //N = 2
if(0x0DCA == ch) return NSM;
if(ch <= 0x0DD1) return L; //N = 3
if(ch <= 0x0DD6) return NSM; //N = 5
if(0x0E31 == ch) return NSM;
if(ch <= 0x0E33) return L; //N = 2
if(ch <= 0x0E3A) return NSM; //N = 7
if(0x0E3F == ch) return ET;
if(ch <= 0x0E46) return L; //N = 7
if(ch <= 0x0E4E) return NSM; //N = 8
if(0x0EB1 == ch) return NSM;
if(ch <= 0x0EB3) return L; //N = 2
if(ch <= 0x0EBC) return NSM; //N = 9
if(ch <= 0x0EC6) return L; //N = 10
if(ch <= 0x0ECD) return NSM; //N = 6
if(ch <= 0x0F17) return L; //N = 72
if(ch <= 0x0F19) return NSM; //N = 2
if(ch <= 0x0F34) return L; //N = 27
if(ch <= 0x0F39) return (ch & 1 ? NSM : L);
if(ch <= 0x0F3D) return ON; //N = 4
if(ch <= 0x0F6C) return L; //N = 47
if(0x0F7F == ch || 0x0F85 == ch) return L;
if(ch <= 0x0F87) return NSM; //N = 2
if(ch <= 0x0F8C) return L; //N = 5
if(ch <= 0x0FBC) return NSM; //N = 48
if(ch <= 0x0FC5) return L; //N = 8
if(0x0FC6 == ch) return NSM;
}
if(ch <= 0x1FFE)
{
if(ch <= 0x102C) return L; //N = 102
if(0x1031 == ch || 0x1038 == ch) return L;
if(ch <= 0x103A) return NSM; //N = 2
if(ch <= 0x103C) return L; //N = 2
if(ch <= 0x103E) return NSM; //N = 2
if(ch <= 0x1057) return L; //N = 25
if(ch <= 0x1059) return NSM; //N = 2
if(ch <= 0x105D) return L; //N = 4
if(ch <= 0x1060) return NSM; //N = 3
if(ch <= 0x1070) return L; //N = 16
if(ch <= 0x1074) return NSM; //N = 4
if(0x1082 == ch) return NSM;
if(ch <= 0x1084) return L; //N = 2
if(ch <= 0x1086) return NSM; //N = 2
if(0x108D == ch || 0x109D == ch) return NSM;
if(ch <= 0x135A) return L; //N = 701
if(ch <= 0x135F) return NSM; //N = 3
if(ch <= 0x138F) return L; //N = 48
if(ch <= 0x1399) return ON; //N = 10
if(0x1400 == ch) return ON;
if(0x1680 == ch) return WS;
if(ch <= 0x169A) return L; //N = 26
if(ch <= 0x169C) return ON; //N = 2
if(ch <= 0x1711) return L; //N = 114
if(ch <= 0x1714) return NSM; //N = 3
if(ch <= 0x1731) return L; //N = 18
if(ch <= 0x1734) return NSM; //N = 3
if(ch <= 0x1751) return L; //N = 29
if(ch <= 0x1753) return NSM; //N = 2
if(ch <= 0x1770) return L; //N = 17
if(ch <= 0x1773) return NSM; //N = 2
if(ch <= 0x17B3) return L; //N = 52
if(0x17B6 == ch) return L;
if(ch <= 0x17BD) return NSM; //N = 7
if(0x17C6 == ch) return NSM;
if(ch <= 0x17C8) return L; //N = 2
if(ch <= 0x17D3) return NSM; //N = 11
if(0x17DB == ch) return ET;
if(0x17DD == ch) return NSM;
if(ch <= 0x17E9) return L; //N = 10
if(ch <= 0x180A) return ON; //N = 27
if(ch <= 0x180D) return NSM; //N = 3
if(0x180E == ch) return WS;
if(0x18A9 == ch) return NSM;
if(ch <= 0x191C) return L; //N = 115
if(ch <= 0x1922) return NSM; //N = 3
if(ch <= 0x1926) return L; //N = 4
if(ch <= 0x1928) return NSM; //N = 2
if(0x1932 == ch) return NSM;
if(ch <= 0x1938) return L; //N = 6
if(ch <= 0x193B) return NSM; //N = 3
if(ch <= 0x1945) return ON; //N = 6
if(ch <= 0x19DA) return L; //N = 149
if(ch <= 0x19FF) return ON; //N = 34
if(ch <= 0x1A16) return L; //N = 23
if(ch <= 0x1A18) return NSM; //N = 2
if(ch <= 0x1A55) return L; //N = 61
if(0x1A57 == ch) return L;
if(ch <= 0x1A60) return NSM; //N = 9
if(0x1A62 == ch) return NSM;
if(ch <= 0x1A64) return L; //N = 2
if(ch <= 0x1A6C) return NSM; //N = 8
if(ch <= 0x1A72) return L; //N = 6
if(ch <= 0x1A7F) return NSM; //N = 13
if(ch <= 0x1AAD) return L; //N = 46
if(ch <= 0x1B03) return NSM; //N = 4
if(ch <= 0x1B33) return L; //N = 48
if(0x1B35 == ch || 0x1B3B == ch) return L;
if(ch <= 0x1B3C) return NSM;
if(0x1B42 == ch) return NSM;
if(ch <= 0x1B6A) return L; //N = 40
if(ch <= 0x1B73) return NSM; //N = 9
if(ch <= 0x1B7C) return L; //N = 9
if(ch <= 0x1B81) return NSM; //N = 2
if(ch <= 0x1BA1) return L; //N = 32
if(ch <= 0x1BA5) return NSM; //N = 4
if(ch <= 0x1BA7) return L; //N = 2
if(ch <= 0x1BA9) return NSM; //N = 2
if(0x1BAB == ch || 0x1BE6 == ch) return NSM;
if(ch <= 0x1BE7) return L;
if(ch <= 0x1BE9) return NSM; //N = 2
if(ch <= 0x1BEC) return L; //N = 3
if(0x1BEE == ch) return L;
if(ch <= 0x1BF1) return NSM; //N = 3
if(ch <= 0x1C2B) return L; //N = 58
if(ch <= 0x1C33) return NSM; //N = 8
if(ch <= 0x1C35) return L; //N = 2
if(ch <= 0x1C37) return NSM; //N = 2
if(ch <= 0x1CC7) return L; //N = 141
if(0x1CD3 == ch || 0x1CE1 == ch) return L;
if(ch <= 0x1CE8) return NSM; //N = 7
if(0x1CED == ch || 0x1CF4 == ch) return NSM;
if(ch <= 0x1DBF) return L; //N = 203
if(ch <= 0x1DFF) return NSM; //N = 64
if(ch <= 0x1FBC) return L; //N = 445
if(0x1FBE == ch) return L;
if(ch <= 0x1FC1) return ON; //N = 3
if(ch <= 0x1FCC) return L; //N = 11
if(ch <= 0x1FCF) return ON; //N = 3
if(ch <= 0x1FDB) return L; //N = 12
if(ch <= 0x1FDF) return ON; //N = 3
if(ch <= 0x1FEC) return L; //N = 13
if(ch <= 0x1FEF) return ON; //N = 3
if(ch <= 0x1FFC) return L; //N = 11
if(ch <= 0x1FFE) return ON; //N = 2
}
if(ch <= 0x200A) return WS; //N = 11
if(ch <= 0x200D) return BN; //N = 3
if(0x200E == ch) return L;
if(0x200F == ch) return R;
if(ch <= 0x2027) return ON; //N = 24
if(0x2028 == ch) return WS;
if(0x2029 == ch) return B;
if(0x202A == ch) return LRE;
if(0x202B == ch) return RLE;
if(0x202C == ch) return PDF;
if(0x202D == ch) return LRO;
if(0x202E == ch) return RLO;
if(0x202F == ch) return CS;
if(ch <= 0x2034) return ET; //N = 5
if(ch <= 0x2043) return ON; //N = 15
if(0x2044 == ch) return CS;
if(ch <= 0x205E) return ON; //N = 26
if(0x205F == ch) return WS;
if(ch <= 0x206F) return BN; //N = 16
if(0x2070 == ch) return EN;
if(0x2071 == ch) return L;
if(ch <= 0x2079) return EN; //N = 6
if(ch <= 0x207B) return ES; //N = 2
if(ch <= 0x207E) return ON; //N = 3
if(0x207F == ch) return L;
if(ch <= 0x2089) return EN; //N = 10
if(ch <= 0x208B) return ES; //N = 2
if(ch <= 0x208E) return ON; //N = 3
if(ch <= 0x209C) return L; //N = 13
if(ch <= 0x20B9) return ET; //N = 26
if(ch <= 0x20F0) return NSM; //N = 33
if(0x2102 == ch) return L;
if(0x2107 == ch) return L;
if(ch <= 0x2109) return ON; //N = 2
if(ch <= 0x2113) return L; //N = 10
if(0x2115 == ch) return L;
if(ch <= 0x2118) return ON; //N = 3
if(ch <= 0x211D) return L; //N = 5
if(ch <= 0x2123) return ON; //N = 6
if(ch <= 0x2129) return (ch & 1 ? ON : L);
if(0x212E == ch) return ET;
if(ch <= 0x2139) return L; //N = 11
if(ch <= 0x213B) return ON; //N = 2
if(ch <= 0x213F) return L; //N = 4
if(ch <= 0x2144) return ON; //N = 5
if(ch <= 0x2149) return L; //N = 5
if(ch <= 0x214D) return ON; //N = 4
if(ch <= 0x214F) return L; //N = 2
if(ch <= 0x215F) return ON; //N = 16
if(ch <= 0x2188) return L; //N = 41
if(ch <= 0x2211) return ON; //N = 137
if(0x2212 == ch) return ES;
if(0x2213 == ch) return ET;
if(ch <= 0x2335) return ON; //N = 290
if(ch <= 0x237A) return L; //N = 69
if(0x2395 == ch) return L;
if(ch <= 0x2487) return ON; //N = 242
if(ch <= 0x249B) return EN; //N = 20
if(ch <= 0x24E9) return L; //N = 78
if(0x26AC == ch) return L;
if(ch <= 0x27FF) return ON; //N = 339
if(ch <= 0x28FF) return L; //N = 256
if(ch <= 0x2B59) return ON; //N = 602
if(ch <= 0x2CE4) return L; //N = 229
if(ch <= 0x2CEA) return ON; //N = 6
if(ch <= 0x2CEE) return L; //N = 4
if(ch <= 0x2CF1) return NSM; //N = 3
if(ch <= 0x2CF3) return L; //N = 2
if(ch <= 0x2CFF) return ON; //N = 7
if(0x2D7F == ch) return NSM;
if(ch <= 0x2DDE) return L; //N = 95
if(ch <= 0x2DFF) return NSM; //N = 32
if(0x3000 == ch) return WS;
if(ch <= 0x3004) return ON; //N = 4
if(ch <= 0x3007) return L; //N = 3
if(ch <= 0x3020) return ON; //N = 25
if(ch <= 0x3029) return L; //N = 9
if(ch <= 0x302D) return NSM; //N = 4
if(0x3030 == ch) return ON;
if(ch <= 0x3035) return L; //N = 5
if(ch <= 0x3037) return ON; //N = 2
if(ch <= 0x303C) return L; //N = 5
if(ch <= 0x303F) return ON; //N = 3
if(ch <= 0x3096) return L; //N = 86
if(ch <= 0x309A) return NSM; //N = 2
if(ch <= 0x309C) return ON; //N = 2
if(0x30A0 == ch) return ON;
if(0x30FB == ch) return ON;
if(ch <= 0x31BA) return L; //N = 191
if(ch <= 0x31E3) return ON; //N = 36
if(ch <= 0x321C) return L; //N = 45
if(ch <= 0x321E) return ON; //N = 2
if(ch <= 0x324F) return L; //N = 48
if(ch <= 0x325F) return ON; //N = 16
if(ch <= 0x327B) return L; //N = 28
if(ch <= 0x327E) return ON; //N = 3
if(ch <= 0x32B0) return L; //N = 50
if(ch <= 0x32BF) return ON; //N = 15
if(ch <= 0x32CB) return L; //N = 12
if(ch <= 0x32CF) return ON; //N = 4
if(ch <= 0x3376) return L; //N = 167
if(ch <= 0x337A) return ON; //N = 4
if(ch <= 0x33DD) return L; //N = 99
if(ch <= 0x33DF) return ON; //N = 2
if(0x33FF == ch) return ON;
if(ch <= 0x4DB5) return L; //N = 6582
if(ch <= 0x4DFF) return ON; //N = 64
if(ch <= 0xA48C) return L; //N = 22157
if(ch <= 0xA4C6) return ON; //N = 55
if(ch <= 0xA60C) return L; //N = 317
if(ch <= 0xA60F) return ON; //N = 3
if(ch <= 0xA66E) return L; //N = 95
if(0xA673 == ch) return ON;
if(ch <= 0xA67D) return NSM; //N = 10
if(ch <= 0xA67F) return ON; //N = 2
if(0xA69F == ch) return NSM;
if(ch <= 0xA6EF) return L; //N = 80
if(ch <= 0xA6F1) return NSM; //N = 2
if(ch <= 0xA6F7) return L; //N = 6
if(ch <= 0xA721) return ON; //N = 34
if(0xA788 == ch) return ON;
if(0xA802 == ch) return NSM;
if(0xA806 == ch) return NSM;
if(0xA80B == ch) return NSM;
if(ch <= 0xA824) return L; //N = 25
if(ch <= 0xA826) return NSM; //N = 2
if(0xA827 == ch) return L;
if(ch <= 0xA82B) return ON; //N = 4
if(ch <= 0xA837) return L; //N = 8
if(ch <= 0xA839) return ET; //N = 2
if(ch <= 0xA873) return L; //N = 52
if(ch <= 0xA877) return ON; //N = 4
if(0xA8C4 == ch) return NSM;
if(ch <= 0xA8D9) return L; //N = 12
if(ch <= 0xA8F1) return NSM; //N = 18
if(ch <= 0xA925) return L; //N = 52
if(ch <= 0xA92D) return NSM; //N = 8
if(ch <= 0xA946) return L; //N = 25
if(ch <= 0xA951) return NSM; //N = 11
if(ch <= 0xA97C) return L; //N = 43
if(ch <= 0xA982) return NSM; //N = 3
if(0xA9B3 == ch) return NSM;
if(ch <= 0xA9B5) return L; //N = 2
if(ch <= 0xA9B9) return NSM; //N = 4
if(0xA9BC == ch) return NSM;
if(ch <= 0xAA28) return L; //N = 108
if(ch <= 0xAA2E) return NSM; //N = 6
if(ch <= 0xAA30) return L; //N = 2
if(ch <= 0xAA32) return NSM; //N = 2
if(ch <= 0xAA34) return L; //N = 2
if(ch <= 0xAA36) return NSM; //N = 2
if(0xAA43 == ch) return NSM;
if(0xAA4C == ch) return NSM;
if(0xAAB0 == ch) return NSM;
if(ch <= 0xAAB1) return L;
if(ch <= 0xAAB4) return NSM; //N = 3
if(ch <= 0xAAB6) return L; //N = 2
if(ch <= 0xAAB8) return NSM; //N = 2
if(ch <= 0xAABD) return L; //N = 5
if(ch <= 0xAABF) return NSM; //N = 2
if(0xAAC1 == ch) return NSM;
if(ch <= 0xAAEB) return L; //N = 42
if(ch <= 0xAAED) return NSM; //N = 2
if(0xAAF6 == ch) return NSM;
if(0xABE5 == ch) return NSM;
if(0xABE8 == ch) return NSM;
if(0xABED == ch) return NSM;
if(ch <= 0xFB17) return L; //N = 20264
if(0xFB1E == ch) return NSM;
if(0xFB29 == ch) return ES;
if(ch <= 0xFB4F) return R; //N = 38
if(ch <= 0xFD3D) return AL; //N = 494
if(ch <= 0xFD3F) return ON; //N = 2
if(ch <= 0xFDFC) return AL; //N = 173
if(0xFDFD == ch) return ON;
if(ch <= 0xFE0F) return NSM; //N = 16
if(ch <= 0xFE19) return ON; //N = 10
if(ch <= 0xFE26) return NSM; //N = 7
if(ch <= 0xFE4F) return ON; //N = 32
if(ch <= 0xFE52) return (ch & 1 ? ON : CS);
if(0xFE55 == ch) return CS;
if(0xFE5F == ch) return ET;
if(ch <= 0xFE61) return ON; //N = 2
if(ch <= 0xFE63) return ES; //N = 2
if(ch <= 0xFE68) return ON; //N = 5
if(ch <= 0xFE6A) return ET; //N = 2
if(0xFE6B == ch) return ON;
if(ch <= 0xFEFC) return AL; //N = 141
if(0xFEFF == ch) return BN;
if(ch <= 0xFF02) return ON; //N = 2
if(ch <= 0xFF05) return ET; //N = 3
if(ch <= 0xFF0A) return ON; //N = 5
if(ch <= 0xFF0D) return (ch & 1 ? ES : CS);
if(ch <= 0xFF0F) return CS; //N = 2
if(ch <= 0xFF19) return EN; //N = 10
if(0xFF1A == ch) return CS;
if(ch <= 0xFF20) return ON; //N = 6
if(ch <= 0xFF3A) return L; //N = 26
if(ch <= 0xFF40) return ON; //N = 6
if(ch <= 0xFF5A) return L; //N = 26
if(ch <= 0xFF65) return ON; //N = 11
if(ch <= 0xFFDC) return L; //N = 119
if(ch <= 0xFFE1) return ET; //N = 2
if(ch <= 0xFFE4) return ON; //N = 3
if(ch <= 0xFFE6) return ET; //N = 2
if(ch <= 0xFFFD) return ON; //N = 22
return ON;
}
}
//class unicode_bidi
std::vector<unicode_bidi::entity> unicode_bidi::reorder(const char_type* str, std::size_t len)
{
levels_.clear();
const char_type * const end = str + len;
std::vector<remember> stack;
remember cur = { 0, directional_override_status::neutral };
cur.level = _m_paragraph_level(str, end);
//First character type
bidi_char begin_char_type = {};
const char_type * begin_character = nullptr;
for (const char_type * c = str; c < end; ++c)
{
if (PDF == *c)
{
if (cur.level)
{
if (begin_character)
{
_m_push_entity(begin_character, c, cur.level, begin_char_type);
begin_character = nullptr;
}
cur = stack.back();
stack.pop_back();
}
continue;
}
else if (LRE <= *c && *c <= RLO)
{
stack.emplace_back(cur);
if (begin_character)
{
_m_push_entity(begin_character, c, cur.level, begin_char_type);
begin_character = nullptr;
}
switch (*c)
{
case LRE:
cur.directional_override = directional_override_status::neutral;
cur.level += 2 - (cur.level & 1);
break;
case RLE:
cur.directional_override = directional_override_status::neutral;
cur.level += (cur.level & 1) + 1;
break;
case LRO:
cur.directional_override = directional_override_status::left_to_right;
cur.level += 2 - (cur.level & 1);
break;
case RLO:
cur.directional_override = directional_override_status::right_to_left;
cur.level = (cur.level & 1) + 1;
break;
}
continue;
}
bidi_char type = _m_char_dir(*c);
if (nullptr == begin_character)
{
begin_character = c;
begin_char_type = type;
}
else if (begin_char_type != type)
{
_m_push_entity(begin_character, c, cur.level, begin_char_type);
begin_char_type = type;
begin_character = c;
}
}
if (begin_character)
_m_push_entity(begin_character, end, cur.level, begin_char_type);
_m_resolve_weak_types();
_m_resolve_neutral_types();
_m_resolve_implicit_levels();
std::vector<unicode_bidi::entity> reordered;
_m_reordering_resolved_levels(reordered);
return reordered;
}
unsigned unicode_bidi::_m_paragraph_level(const char_type * begin, const char_type * end)
{
for(const char_type* i = begin; i != end; ++i)
{
switch(_m_char_dir(*i))
{
case bidi_char::AL:
case bidi_char::R:
return 1;
case bidi_char::L:
return 0;
default:
break;
}
}
return 0;
}
void unicode_bidi::_m_push_entity(const char_type * begin, const char_type *end, unsigned level, bidi_char bidi_char_type)
{
#ifdef _nana_std_has_emplace_return_type
auto & e = levels_.emplace_back();
#else
levels_.emplace_back();
auto & e = levels_.back();
#endif
e.begin = begin;
e.end = end;
e.level = level;
e.bidi_char_type = bidi_char_type;
}
std::vector<unicode_bidi::entity>::iterator unicode_bidi::_m_search_first_character()
{
return levels_.begin();
}
auto unicode_bidi::_m_eor(std::vector<entity>::iterator i) ->bidi_char
{
const auto end = levels_.end();
unsigned level = i->level;
for (; i != end; ++i)
{
if (i->level != level)
return i->bidi_char_type;
}
i = _m_search_first_character();
if(i != end)
return (i->level & 1 ? bidi_char::R : bidi_char::L);
return bidi_char::L;
}
void unicode_bidi::_m_resolve_weak_types()
{
const auto end = levels_.end();
auto begin_character = _m_search_first_character();
if(begin_character == end)
return;
unsigned level_of_run = begin_character->level;
const auto last = end - 1;
//W1. Examine each nonspacing mark, and change the type of the NSM to the type of the previous
//character.
//W2. Search backward from each instance of a European number until the first strong type(R, L, AL, or sor) is found
//If an AL is found, change the type of the European Number to Arabic number.
//W3. Change all ALs to R.
//The three phases could be combined as one process. Because these phases are standalone.
//Generally, the directional char type of sor is taken on current level.
bidi_char prev = (level_of_run & 1 ? bidi_char::R : bidi_char::L); //sor is either L or R
bool change_european_number = false;
for(auto i = begin_character; i != end; ++i)
{
if(level_of_run != i->level)
{
level_of_run = i->level;
prev = (level_of_run & 1 ? bidi_char::R : bidi_char::L); //sor is either L or R
}
switch(i->bidi_char_type)
{
case bidi_char::NSM:
i->bidi_char_type = prev;
break;
case bidi_char::EN:
if(change_european_number)
i->bidi_char_type = bidi_char::AN;
break;
case bidi_char::AL:
change_european_number = true;
i->bidi_char_type = bidi_char::R;
break;
case bidi_char::L:
case bidi_char::R:
if(change_european_number)
change_european_number = false;
break;
default: break;
}
prev = i->bidi_char_type;
}
//W4. A single European separator between two European numbers changes to a European number.
//A single common separator between two numbers of the same type changes to that type.
//
//W5. A sequence of European terminators adjacent to European numbers changes to all European numbers.
//W6. Otherwise, separators and terminators change to Other Neutral.
auto etpos = end; //Indicates the head of the sequence of European Terminators
bool head = true;
for(auto i = begin_character; i != end; ++i)
{
switch(i->bidi_char_type)
{
case bidi_char::ES:
i->bidi_char_type = bidi_char::ON; //W6
if((false == head) && (i != last))
{
if((bidi_char::EN == (i - 1)->bidi_char_type) && (bidi_char::EN == (i + 1)->bidi_char_type))
i->bidi_char_type = bidi_char::EN;
}
else
head = false;
break;
case bidi_char::CS:
i->bidi_char_type = bidi_char::ON; //W6
if((false == head) && (i != last))
{
auto right_one = (i + 1)->bidi_char_type;
if(((i-1)->bidi_char_type == right_one) && (bidi_char::AN == right_one || bidi_char::EN == right_one))
i->bidi_char_type = right_one;
}
else
head = false;
break;
case bidi_char::ET:
if((false == head) && (bidi_char::EN == (i-1)->bidi_char_type))
{
i->bidi_char_type = bidi_char::EN;
}
else
{
if(etpos == end)
etpos = i;
}
break;
case bidi_char::EN:
if(end != etpos)
{
for(; etpos != i; ++etpos)
etpos->bidi_char_type = bidi_char::EN;
etpos = end;
}
break;
default:
break;
}
//W6.
if((end != etpos) && (bidi_char::ET != i->bidi_char_type))
{
for(; etpos != i; ++etpos)
etpos->bidi_char_type = bidi_char::ON;
etpos = end;
}
}
//The final check etpos out
for(; etpos != end; ++etpos)
etpos->bidi_char_type = bidi_char::ON;
//W7. Search backward from each instance of a European number until the first strong type (R, L, or sor) is found.
//If an L is found, then change the type of the European number to L.
level_of_run = begin_character->level;
bidi_char sor = (level_of_run & 1 ? bidi_char::R : bidi_char::L);
change_european_number = (sor == bidi_char::L);
for(auto i = begin_character; i != end; ++i)
{
if(level_of_run != i->level)
{
level_of_run = i->level;
sor = (level_of_run & 1 ? bidi_char::R : bidi_char::L);
change_european_number = (sor == bidi_char::L);
}
switch(i->bidi_char_type)
{
case bidi_char::EN:
if(change_european_number)
i->bidi_char_type = bidi_char::L;
break;
case bidi_char::L:
change_european_number = true;
break;
case bidi_char::R:
change_european_number = false;
break;
default:
break;
}
}
}
void unicode_bidi::_m_resolve_neutral_types()
{
const auto end = levels_.end();
auto begin_character = _m_search_first_character();
if(begin_character == end)
return;
unsigned level_of_run = begin_character->level;
bool head_of_run = true;
auto begin_neutral = end;
//N1. A sequence of neutrals takes the direction of the surrounding strong text if the text on both sides has the same direction.
//European and Arabic numbers act as if they were R in terms of their influence on neutrals.
//Start-of-level-run (sor) and end-of-level-run (eor) are used at level run boundaries.
bidi_char left = {};
for(auto i = begin_character; i != end; ++i)
{
if(level_of_run != i->level)
{
level_of_run = i->level;
head_of_run = true;
}
if(_m_bidi_category(i->bidi_char_type) == bidi_category::neutral)
{
if(begin_neutral == end)
{
begin_neutral = i;
left = (head_of_run ? (level_of_run & 1 ? bidi_char::R : bidi_char::L) : (i-1)->bidi_char_type); //Head ? sor : prev_char
if(bidi_char::EN == left || bidi_char::AN == left)
left = bidi_char::R;
}
}
else if(begin_neutral != end) //This element is not a neutral
{
bidi_char right;
//Check if i is the end of the level run.
if(i->level != begin_neutral->level)
right = _m_eor(begin_neutral);
else
right = i->bidi_char_type;
if(bidi_char::EN == right || bidi_char::AN == right)
right = bidi_char::R;
bidi_char target = (left == right ? left : (begin_neutral->level & 1 ? bidi_char::R : bidi_char::L));
for(auto n = begin_neutral; n != i; ++n)
n->bidi_char_type = target;
begin_neutral = end;
}
head_of_run = false;
}
if(begin_neutral != end)
{
bidi_char eor = begin_character->level & 1 ? bidi_char::R : bidi_char::L;
bidi_char target = (left == eor ? left : (begin_neutral->level & 1 ? bidi_char::R : bidi_char::L));
for(auto i = begin_neutral; i != end; ++i)
i->bidi_char_type = target;
}
}
void unicode_bidi::_m_resolve_implicit_levels()
{
//I1. For all characters with an even (left-to-right) embedding direction, those of type R go up one level and those of type AN or EN go up two levels.
//I2. For all characters with an odd (right-to-left) embedding direction, those of type L, EN or AN go up one level.
for(auto & i : levels_)
{
switch(i.bidi_char_type)
{
case bidi_char::L:
i.level += (i.level & 1);
break;
case bidi_char::R:
if(0 == (i.level & 1))
++(i.level);
break;
case bidi_char::EN:
case bidi_char::AN:
i.level += 2 - (i.level & 1);
break;
default:
break;
}
}
}
void unicode_bidi::_m_reordering_resolved_levels(std::vector<entity> & reordered)
{
reordered = levels_;
//First find the highest_level for resolution, because the resolution is from highest level.
unsigned highest_level = 0;
for(auto & i : levels_)
{
if(i.level > highest_level)
highest_level = i.level;
}
for(unsigned level = highest_level; level >= 1; --level)
{
for(auto i = levels_.begin(); i != levels_.end(); ++i)
{
if(i->level >= level)
{
auto beg = i, end = i + 1;
while(end != levels_.end() && (end->level >= level))
++end;
//Reverse this run.
std::size_t p = beg - levels_.begin();
std::size_t plast = (end - levels_.begin() - 1);
for(; p < plast; ++p, --plast)
std::swap(reordered[p], reordered[plast]);
i = end - 1;
}
}
}
}
unicode_bidi::bidi_category unicode_bidi::_m_bidi_category(bidi_char bidi_char_type)
{
return static_cast<unicode_bidi::bidi_category>(static_cast<int>(bidi_char_type) & 0xF000);
}
unicode_bidi::bidi_char unicode_bidi::_m_char_dir(char_type ch)
{
auto type = bidi_charmap::bidi_char_type(ch);
if (type < bidi_charmap::PDF)
return static_cast<bidi_char>(type);
if (type < bidi_charmap::B)
return static_cast<bidi_char>(static_cast<int>(type - bidi_charmap::PDF) + 0x1000);
return static_cast<bidi_char>(static_cast<int>(type - bidi_charmap::B) + 0x2000);
}
//end class unicode_bidi
std::vector<unicode_bidi::entity> unicode_reorder(const wchar_t* text, std::size_t length)
{
return unicode_bidi{}.reorder(text, length);
}
enum class unicode_character_type
{
format,
katakana,
aletter,
midletter,
midnumlet,
midnum,
numeric,
other
};
//http://www.unicode.org/reports/tr29/WordBreakTest.html
unicode_character_type unicode_char_type(unsigned long ch)
{
if ((0x0600 <= ch && ch <= 0x0603) || (0x06DD == ch || 0x070F == ch || 0x17B4 == ch || 0x17B5 == ch) || (0x200C <= ch && ch <= 0x200F) ||
(0x202A <= ch && ch <= 0x202E) || (0x2060 <= ch && ch <= 0x2063) || (0x206A <= ch && ch <= 0x206F) || (0xFEFF == ch) || (0xFFF9 <= ch && ch <= 0xFFFB) ||
(0x1D173 <= ch && ch <= 0x1D17A) || (0xE0001 == ch) || (0xE0020 <= ch && ch <= 0xE007F))
return unicode_character_type::format;
if ((0x30A1 <= ch && ch <= 0x30FA) || (0x30FC <= ch && ch <= 0x30FF) || (0x31F0 <= ch && ch <= 0x31FF) || (0xFF66 <= ch && ch <= 0xFF9F))
return unicode_character_type::katakana;
if (('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z') || (0x00AA == ch || 0x00B5 == ch || 0x00BA == ch) || (0x00C0 <= ch && ch <= 0x00D6) ||
(0x00D8 <= ch && ch <= 0x00F6) || (0x00F8 <= ch && ch <= 0x0236) || (0x0250 <= ch && ch <= 0x02C1))
return unicode_character_type::aletter;
if ('\'' == ch || 0x00AD == ch || 0x00B7 == ch || 0x05F4 == ch || 0x2019 == ch || 0x2027 == ch)
return unicode_character_type::midletter;
if ('.' == ch || '\\' == ch || ':' == ch)
return unicode_character_type::midnumlet;
if (0x2024 <= ch && ch <= 0x2026)
return unicode_character_type::midnum;
if (('0' <= ch && ch <= '9') || (0x0660 <= ch && ch <= 0x0669) || (0x06F0 <= ch && ch <= 0x06F9))
return unicode_character_type::numeric;
return unicode_character_type::other;
}
bool unicode_wordbreak(wchar_t left, wchar_t right)
{
auto l_type = unicode_char_type(left);
auto r_type = unicode_char_type(right);
switch (l_type)
{
case unicode_character_type::format:
case unicode_character_type::midletter:
case unicode_character_type::midnumlet:
case unicode_character_type::midnum:
case unicode_character_type::other:
return (r_type != unicode_character_type::format);
case unicode_character_type::katakana:
return !(unicode_character_type::format == r_type) || (unicode_character_type::katakana == r_type);
case unicode_character_type::aletter:
case unicode_character_type::numeric:
return !(unicode_character_type::format == r_type) || (unicode_character_type::aletter == r_type) || (unicode_character_type::numeric == r_type);
}
return true;
}
}//end namespace nana
|
// license:BSD-3-Clause
// copyright-holders:Frank Palazzolo
/*******************************************************************************
Mouser - Video Hardware:
Character map with scrollable rows, 1024 possible characters.
- index = byte from videoram + 2 bits from colorram)
- (if row is scrolled, videoram is offset, colorram is not)
- 16 4-color combinations for each char, from colorram
15 Sprites controlled by 4-byte records
- 16 4-color combinations
- 2 banks of 64 sprite characters each
*******************************************************************************/
#include "emu.h"
#include "includes/mouser.h"
PALETTE_INIT_MEMBER(mouser_state, mouser)
{
const uint8_t *color_prom = memregion("proms")->base();
int i;
for (i = 0; i < palette.entries(); i++)
{
int bit0, bit1, bit2, r, g, b;
/* red component */
bit0 = BIT(*color_prom, 0);
bit1 = BIT(*color_prom, 1);
bit2 = BIT(*color_prom, 2);
r = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2;
/* green component */
bit0 = BIT(*color_prom, 3);
bit1 = BIT(*color_prom, 4);
bit2 = BIT(*color_prom, 5);
g = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2;
/* blue component */
bit0 = BIT(*color_prom, 6);
bit1 = BIT(*color_prom, 7);
b = 0x4f * bit0 + 0xa8 * bit1;
palette.set_pen_color(i,rgb_t(r,g,b));
color_prom++;
}
}
WRITE_LINE_MEMBER(mouser_state::flip_screen_x_w)
{
flip_screen_x_set(!state);
}
WRITE_LINE_MEMBER(mouser_state::flip_screen_y_w)
{
flip_screen_y_set(!state);
}
uint32_t mouser_state::screen_update_mouser(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
{
uint8_t *spriteram = m_spriteram;
int offs;
int sx, sy;
int flipx, flipy;
/* for every character in the Video RAM */
for (offs = 0x3ff; offs >= 0; offs--)
{
int scrolled_y_position;
int color_offs;
sx = offs % 32;
sy = offs / 32;
if (flip_screen_x())
{
sx = 31 - sx;
}
if (flip_screen_y())
{
sy = 31 - sy;
}
/* This bit of spriteram appears to be for row scrolling */
/* Note: this is dependant on flipping in y */
scrolled_y_position = (256 + 8*sy - spriteram[offs%32])%256;
/* I think we still need to fetch the colorram bits to from the ram underneath, which is not scrolled */
/* Ideally we would merge these on a pixel-by-pixel basis, but it's ok to do this char-by-char, */
/* Since it's only for the MOUSER logo and it looks fine */
/* Note: this is _not_ dependant on flipping */
color_offs = offs % 32 + ((256 + 8 * (offs / 32) - spriteram[offs % 32] )% 256) / 8 * 32;
m_gfxdecode->gfx(0)->opaque(bitmap,cliprect,
m_videoram[offs] | (m_colorram[color_offs] >> 5) * 256 | ((m_colorram[color_offs] >> 4) & 1) * 512,
m_colorram[color_offs]%16,
flip_screen_x(),flip_screen_y(),
8*sx,scrolled_y_position);
}
/* There seem to be two sets of sprites, each decoded identically */
/* This is the first set of 7 sprites */
for(offs = 0x0084; offs < 0x00A0; offs += 4)
{
sx = spriteram[offs + 3];
sy = 0xef - spriteram[offs + 2];
flipx = BIT(spriteram[offs], 6);
flipy = BIT(spriteram[offs], 7);
if (flip_screen_x())
{
flipx = !flipx;
sx = 240 - sx;
}
if (flip_screen_y())
{
flipy = !flipy;
sy = 238 - sy;
}
if (BIT(spriteram[offs + 1], 4))
m_gfxdecode->gfx(1+((spriteram[offs+1]&0x20)>>5))->transpen(bitmap,cliprect,
spriteram[offs]&0x3f,
spriteram[offs+1]%16,
flipx,flipy,
sx,sy,0);
}
/* This is the second set of 8 sprites */
for(offs = 0x00C4; offs < 0x00e4; offs += 4)
{
sx = spriteram[offs + 3];
sy = 0xef - spriteram[offs + 2];
flipx = BIT(spriteram[offs], 6);
flipy = BIT(spriteram[offs], 7);
if (flip_screen_x())
{
flipx = !flipx;
sx = 240 - sx;
}
if (flip_screen_y())
{
flipy = !flipy;
sy = 238 - sy;
}
if (BIT(spriteram[offs + 1], 4))
m_gfxdecode->gfx(1+((spriteram[offs+1]&0x20)>>5))->transpen(bitmap,cliprect,
spriteram[offs]&0x3f,
spriteram[offs+1]%16,
flipx,flipy,
sx,sy,0);
}
return 0;
}
|
#ifndef BOOST_MPL_LIST_AUX_EMPTY_HPP_INCLUDED
#define BOOST_MPL_LIST_AUX_EMPTY_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2004
//
// 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)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id: empty.hpp 49267 2008-10-11 06:19:02Z agurtovoy $
// $Date: 2008-10-11 02:19:02 -0400 (Sat, 11 Oct 2008) $
// $Revision: 49267 $
#include <boost/mpl/empty_fwd.hpp>
#include <boost/mpl/not.hpp>
#include <boost/mpl/list/aux_/tag.hpp>
namespace boost { namespace mpl {
template<>
struct empty_impl< aux::list_tag >
{
template< typename List > struct apply
: not_<typename List::size>
{
};
};
}}
#endif // BOOST_MPL_LIST_AUX_EMPTY_HPP_INCLUDED
|
#include "caffe2/perfkernels/embedding_lookup.h"
#include "caffe2/core/types.h"
#include "caffe2/perfkernels/common.h"
#include <c10/util/irange.h>
namespace caffe2 {
/**
* Base implementation does runtime dispatch for each segment of reduction
* @return false if there is an out-of-bound error
*/
template <
typename IndexType,
typename InType,
typename OutType,
bool IS_WEIGHT_POSITIONAL = false>
static bool EmbeddingLookupGenericSlow(
const int64_t block_size,
const int64_t output_size,
const int64_t index_size,
const int64_t data_size,
const InType* input,
const IndexType* indices,
const int* lengths,
const float* weights, // optional, can be null for sum reducer
const float* scale_bias, // optional scale & bias params for uint8 input
bool normalize_by_lengths,
OutType* out) {
int64_t current = 0;
for (const auto m : c10::irange(output_size)) {
memset(out, 0, sizeof(OutType) * block_size);
if (current + lengths[m] > index_size) {
return false;
}
for (int i = 0; i < lengths[m]; ++i) {
int64_t idx = indices[current];
if (idx < 0 || idx >= data_size) {
return false;
}
#ifdef __GNUC__
if (current + 1 < index_size) {
__builtin_prefetch(input + block_size * indices[current + 1], 0, 1);
}
#endif // __GNUC__
float w = 1.f, b = 0.f;
if (weights) {
w = weights[IS_WEIGHT_POSITIONAL ? i : current];
}
if (scale_bias) {
b = w * scale_bias[2 * indices[current] + 1];
w = w * scale_bias[2 * indices[current]];
}
for (const auto j : c10::irange(block_size)) {
out[j] += w * input[block_size * indices[current] + j] + b;
}
++current;
}
if (normalize_by_lengths && lengths[m]) {
float scale = 1.f / lengths[m];
for (const auto j : c10::irange(block_size)) {
out[j] *= scale;
}
}
out += block_size;
}
return current == index_size;
}
// Proxy back to generic implementation
#define EMBEDDING_SPECIALIZATION( \
IndexType, InTypeName, InType, OutType, IS_WEIGHT_POSITIONAL) \
bool \
EmbeddingLookup_##IndexType##_##InTypeName##_##OutType##_##IS_WEIGHT_POSITIONAL##__base( \
const int64_t block_size, \
const int64_t output_size, \
const int64_t index_size, \
const int64_t data_size, \
const InType* input, \
const IndexType* indices, \
const int* lengths, \
const float* weights, \
const float* scale_bias, \
bool normalize_by_lengths, \
OutType* out) { \
return EmbeddingLookupGenericSlow< \
IndexType, \
InType, \
OutType, \
IS_WEIGHT_POSITIONAL>( \
block_size, \
output_size, \
index_size, \
data_size, \
input, \
indices, \
lengths, \
weights, \
scale_bias, \
normalize_by_lengths, \
out); \
} \
decltype( \
EmbeddingLookup_##IndexType##_##InTypeName##_##OutType##_##IS_WEIGHT_POSITIONAL##__base) \
EmbeddingLookup_##IndexType##_##InTypeName##_##OutType##_##IS_WEIGHT_POSITIONAL##__avx2_fma; \
bool \
EmbeddingLookup_##IndexType##_##InTypeName##_##OutType##_##IS_WEIGHT_POSITIONAL( \
const int64_t block_size, \
const int64_t output_size, \
const int64_t index_size, \
const int64_t data_size, \
const InType* input, \
const IndexType* indices, \
const int* lengths, \
const float* weights, \
const float* scale_bias, \
bool normalize_by_lengths, \
OutType* out) { \
if (std::is_same<InType, uint8_t>::value) { \
CAFFE_ENFORCE(scale_bias != nullptr, "scale_bias must not be nullptr"); \
} else { \
CAFFE_ENFORCE(scale_bias == nullptr, "scale_bias must be nullptr"); \
} \
AVX2_FMA_DO( \
EmbeddingLookup_##IndexType##_##InTypeName##_##OutType##_##IS_WEIGHT_POSITIONAL, \
block_size, \
output_size, \
index_size, \
data_size, \
input, \
indices, \
lengths, \
weights, \
scale_bias, \
normalize_by_lengths, \
out); \
BASE_DO( \
EmbeddingLookup_##IndexType##_##InTypeName##_##OutType##_##IS_WEIGHT_POSITIONAL, \
block_size, \
output_size, \
index_size, \
data_size, \
input, \
indices, \
lengths, \
weights, \
scale_bias, \
normalize_by_lengths, \
out); \
} \
template <> \
void EmbeddingLookup<IndexType, InType, OutType, IS_WEIGHT_POSITIONAL>( \
const int64_t block_size, \
const int64_t output_size, \
const int64_t index_size, \
const int64_t data_size, \
const InType* input, \
const IndexType* indices, \
const int* lengths, \
const float* weights, \
const float* scale_bias, \
bool normalize_by_lengths, \
OutType* out) { \
bool success = \
EmbeddingLookup_##IndexType##_##InTypeName##_##OutType##_##IS_WEIGHT_POSITIONAL( \
block_size, \
output_size, \
index_size, \
data_size, \
input, \
indices, \
lengths, \
weights, \
scale_bias, \
normalize_by_lengths, \
out); \
if (success) { \
return; \
} \
int64_t current = 0; \
for (int m = 0; m < output_size; ++m) { \
for (int i = 0; i < lengths[m]; ++i) { \
CAFFE_ENFORCE_LT(current, index_size); \
IndexType idx = indices[current]; \
CAFFE_ENFORCE( \
0 <= idx && idx < data_size, \
"Index ", \
current, \
" is out of bounds: ", \
idx, \
", range 0 to ", \
data_size); \
++current; \
} \
} \
CAFFE_ENFORCE_EQ( \
current, \
index_size, \
"Your input seems to be incorrect: the sum of lengths values should be " \
"the size of the indices tensor, but it appears not."); \
}
EMBEDDING_SPECIALIZATION(int32_t, float, float, float, false);
EMBEDDING_SPECIALIZATION(int64_t, float, float, float, false);
EMBEDDING_SPECIALIZATION(int32_t, half, at::Half, float, false);
EMBEDDING_SPECIALIZATION(int64_t, half, at::Half, float, false);
EMBEDDING_SPECIALIZATION(int32_t, uint8_t, uint8_t, float, false);
EMBEDDING_SPECIALIZATION(int64_t, uint8_t, uint8_t, float, false);
EMBEDDING_SPECIALIZATION(int32_t, float, float, float, true);
EMBEDDING_SPECIALIZATION(int64_t, float, float, float, true);
EMBEDDING_SPECIALIZATION(int32_t, half, at::Half, float, true);
EMBEDDING_SPECIALIZATION(int64_t, half, at::Half, float, true);
EMBEDDING_SPECIALIZATION(int32_t, uint8_t, uint8_t, float, true);
EMBEDDING_SPECIALIZATION(int64_t, uint8_t, uint8_t, float, true);
#undef EMBEDDING_SPECIALIZATION
} // namespace caffe2
|
/**********************************************************************
* File: fpchop.cpp (Formerly fp_chop.c)
* Description: Code to chop fixed pitch text into character cells.
* Author: Ray Smith
* Created: Thu Sep 16 11:14:15 BST 1993
*
* (C) Copyright 1993, Hewlett-Packard 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 "mfcpch.h"
#ifdef __UNIX__
#include <assert.h>
#endif
#include "stderr.h"
#include "blobbox.h"
#include "statistc.h"
#include "drawtord.h"
#include "tovars.h"
#include "topitch.h"
#include "fpchop.h"
#include "notdll.h"
// Include automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
#define EXTERN
EXTERN INT_VAR (textord_fp_chop_error, 2,
"Max allowed bending of chop cells");
EXTERN double_VAR (textord_fp_chop_snap, 0.5,
"Max distance of chop pt from vertex");
ELISTIZE(C_OUTLINE_FRAG)
//#undef ASSERT_HOST
//#define ASSERT_HOST(x) if (!(x)) AfxMessageBox(#x);
/**********************************************************************
* fixed_pitch_words
*
* Make a ROW from a fixed pitch TO_ROW.
**********************************************************************/
ROW *fixed_pitch_words( //find lines
TO_ROW *row, //row to do
FCOORD rotation //for drawing
) {
BOOL8 bol; //start of line
uinT8 blanks; //in front of word
uinT8 new_blanks; //blanks in empty cell
inT16 chop_coord; //chop boundary
inT16 prev_chop_coord; //start of cell
inT16 rep_left; //left edge of rep word
ROW *real_row; //output row
C_OUTLINE_LIST left_coutlines;
C_OUTLINE_LIST right_coutlines;
C_BLOB_LIST cblobs;
C_BLOB_IT cblob_it = &cblobs;
WERD_LIST words;
WERD_IT word_it = &words; //new words
//repeated blobs
WERD_IT rep_it = &row->rep_words;
WERD *word; //new word
inT32 xstarts[2]; //row ends
double coeffs[3]; //quadratic
inT32 prev_x; //end of prev blob
//iterator
BLOBNBOX_IT box_it = row->blob_list ();
//boundaries
ICOORDELT_IT cell_it = &row->char_cells;
#ifndef GRAPHICS_DISABLED
if (textord_show_page_cuts && to_win != NULL) {
plot_row_cells (to_win, ScrollView::RED, row, 0, &row->char_cells);
}
#endif
prev_x = -MAX_INT16;
bol = TRUE;
blanks = 0;
if (rep_it.empty ())
rep_left = MAX_INT16;
else
rep_left = rep_it.data ()->bounding_box ().left ();
if (box_it.empty ())
return NULL; //empty row
xstarts[0] = box_it.data ()->bounding_box ().left ();
if (rep_left < xstarts[0]) {
xstarts[0] = rep_left;
}
if (cell_it.empty () || row->char_cells.singleton ()) {
tprintf ("Row without enough char cells!\n");
tprintf ("Leftmost blob is at (%d,%d)\n",
box_it.data ()->bounding_box ().left (),
box_it.data ()->bounding_box ().bottom ());
return NULL;
}
ASSERT_HOST (!cell_it.empty () && !row->char_cells.singleton ());
prev_chop_coord = cell_it.data ()->x ();
word = NULL;
while (rep_left < cell_it.data ()->x ()) {
word = add_repeated_word (&rep_it, rep_left, prev_chop_coord,
blanks, row->fixed_pitch, &word_it);
}
cell_it.mark_cycle_pt ();
if (prev_chop_coord >= cell_it.data ()->x ())
cell_it.forward ();
for (; !cell_it.cycled_list (); cell_it.forward ()) {
chop_coord = cell_it.data ()->x ();
while (!box_it.empty ()
&& box_it.data ()->bounding_box ().left () <= chop_coord) {
if (box_it.data ()->bounding_box ().right () > prev_x)
prev_x = box_it.data ()->bounding_box ().right ();
split_to_blob (box_it.extract (), chop_coord,
textord_fp_chop_error + 0.5f,
&left_coutlines,
&right_coutlines);
box_it.forward ();
while (!box_it.empty() && box_it.data()->cblob() == NULL) {
delete box_it.extract();
box_it.forward();
}
}
if (!right_coutlines.empty() && left_coutlines.empty())
split_to_blob (NULL, chop_coord,
textord_fp_chop_error + 0.5f,
&left_coutlines,
&right_coutlines);
if (!left_coutlines.empty ())
cblob_it.add_after_then_move (new C_BLOB (&left_coutlines));
else {
if (rep_left < chop_coord) {
if (rep_left > prev_chop_coord)
new_blanks = (uinT8) floor ((rep_left - prev_chop_coord)
/ row->fixed_pitch + 0.5);
else
new_blanks = 0;
}
else {
if (chop_coord > prev_chop_coord)
new_blanks = (uinT8) floor ((chop_coord - prev_chop_coord)
/ row->fixed_pitch + 0.5);
else
new_blanks = 0;
}
if (!cblob_it.empty()) {
if (blanks < 1 && word != NULL && !word->flag (W_REP_CHAR))
blanks = 1;
word = new WERD (&cblobs, blanks, NULL);
cblob_it.set_to_list (&cblobs);
word->set_flag (W_DONT_CHOP, TRUE);
word_it.add_after_then_move (word);
if (bol) {
word->set_flag (W_BOL, TRUE);
bol = FALSE;
}
blanks = new_blanks;
}
else
blanks += new_blanks;
while (rep_left < chop_coord) {
word = add_repeated_word (&rep_it, rep_left, prev_chop_coord,
blanks, row->fixed_pitch, &word_it);
}
}
if (prev_chop_coord < chop_coord)
prev_chop_coord = chop_coord;
}
if (!cblob_it.empty()) {
word = new WERD(&cblobs, blanks, NULL);
word->set_flag (W_DONT_CHOP, TRUE);
word_it.add_after_then_move (word);
if (bol)
word->set_flag (W_BOL, TRUE);
}
ASSERT_HOST (word != NULL);
while (!rep_it.empty ()) {
add_repeated_word (&rep_it, rep_left, prev_chop_coord,
blanks, row->fixed_pitch, &word_it);
}
//at end of line
word_it.data ()->set_flag (W_EOL, TRUE);
if (prev_chop_coord > prev_x)
prev_x = prev_chop_coord;
xstarts[1] = prev_x + 1;
coeffs[0] = 0;
coeffs[1] = row->line_m ();
coeffs[2] = row->line_c ();
real_row = new ROW (row, (inT16) row->kern_size, (inT16) row->space_size);
word_it.set_to_list (real_row->word_list ());
//put words in row
word_it.add_list_after (&words);
real_row->recalc_bounding_box ();
return real_row;
}
/**********************************************************************
* add_repeated_word
*
* Add repeated word into the row at the given point.
**********************************************************************/
WERD *add_repeated_word( //move repeated word
WERD_IT *rep_it, //repeated words
inT16 &rep_left, //left edge of word
inT16 &prev_chop_coord, //previous word end
uinT8 &blanks, //no of blanks
float pitch, //char cell size
WERD_IT *word_it //list of words
) {
WERD *word; //word to move
inT16 new_blanks; //extra blanks
if (rep_left > prev_chop_coord) {
new_blanks = (uinT8) floor ((rep_left - prev_chop_coord) / pitch + 0.5);
blanks += new_blanks;
}
word = rep_it->extract ();
prev_chop_coord = word->bounding_box ().right ();
word_it->add_after_then_move (word);
word->set_blanks (blanks);
rep_it->forward ();
if (rep_it->empty ())
rep_left = MAX_INT16;
else
rep_left = rep_it->data ()->bounding_box ().left ();
blanks = 0;
return word;
}
/**********************************************************************
* split_to_blob
*
* Split a BLOBNBOX across a vertical chop line and put the pieces
* into a left outline list and a right outline list.
**********************************************************************/
void split_to_blob( //split the blob
BLOBNBOX *blob, //blob to split
inT16 chop_coord, //place to chop
float pitch_error, //allowed deviation
C_OUTLINE_LIST *left_coutlines, //for cblobs
C_OUTLINE_LIST *right_coutlines) {
C_BLOB *real_cblob; //cblob to chop
if (blob != NULL) {
real_cblob = blob->cblob();
} else {
real_cblob = NULL;
}
if (!right_coutlines->empty() || real_cblob != NULL)
fixed_chop_cblob(real_cblob,
chop_coord,
pitch_error,
left_coutlines,
right_coutlines);
if (blob != NULL)
delete blob; //free it
}
/**********************************************************************
* fixed_chop_cblob
*
* Chop the given cblob (if any) and the existing right outlines to
* produce a list of outlines left of the chop point and more to the right.
**********************************************************************/
void fixed_chop_cblob( //split the blob
C_BLOB *blob, //blob to split
inT16 chop_coord, //place to chop
float pitch_error, //allowed deviation
C_OUTLINE_LIST *left_outlines, //left half of chop
C_OUTLINE_LIST *right_outlines //right half of chop
) {
C_OUTLINE *old_right; //already there
C_OUTLINE_LIST new_outlines; //new right ones
//ouput iterator
C_OUTLINE_IT left_it = left_outlines;
//in/out iterator
C_OUTLINE_IT right_it = right_outlines;
C_OUTLINE_IT new_it = &new_outlines;
C_OUTLINE_IT blob_it; //outlines in blob
if (!right_it.empty ()) {
while (!right_it.empty ()) {
old_right = right_it.extract ();
right_it.forward ();
fixed_split_coutline(old_right,
chop_coord,
pitch_error,
&left_it,
&new_it);
}
right_it.add_list_before (&new_outlines);
}
if (blob != NULL) {
blob_it.set_to_list (blob->out_list ());
for (blob_it.mark_cycle_pt (); !blob_it.cycled_list ();
blob_it.forward ())
fixed_split_coutline (blob_it.extract (), chop_coord, pitch_error,
&left_it, &right_it);
delete blob;
}
}
/**********************************************************************
* fixed_split_outline
*
* Chop the given outline (if necessary) placing the fragments which
* fall either side of the chop line into the appropriate list.
**********************************************************************/
void fixed_split_coutline( //chop the outline
C_OUTLINE *srcline, //source outline
inT16 chop_coord, //place to chop
float pitch_error, //allowed deviation
C_OUTLINE_IT *left_it, //left half of chop
C_OUTLINE_IT *right_it //right half of chop
) {
C_OUTLINE *child; //child outline
TBOX srcbox; //box of outline
C_OUTLINE_LIST left_ch; //left children
C_OUTLINE_LIST right_ch; //right children
C_OUTLINE_FRAG_LIST left_frags;//chopped fragments
C_OUTLINE_FRAG_LIST right_frags;;
C_OUTLINE_IT left_ch_it = &left_ch;
//for whole children
C_OUTLINE_IT right_ch_it = &right_ch;
//for holes
C_OUTLINE_IT child_it = srcline->child ();
srcbox = srcline->bounding_box ();
//left of line
if (srcbox.left () + srcbox.right () <= chop_coord * 2
//and not far over
&& srcbox.right () < chop_coord + pitch_error)
//stick whole in left
left_it->add_after_then_move (srcline);
else if (srcbox.left () + srcbox.right () > chop_coord * 2
&& srcbox.left () > chop_coord - pitch_error)
//stick whole in right
right_it->add_before_stay_put (srcline);
else {
//needs real chopping
if (fixed_chop_coutline (srcline, chop_coord, pitch_error,
&left_frags, &right_frags)) {
for (child_it.mark_cycle_pt (); !child_it.cycled_list ();
child_it.forward ()) {
child = child_it.extract ();
srcbox = child->bounding_box ();
if (srcbox.right () < chop_coord)
left_ch_it.add_after_then_move (child);
else if (srcbox.left () > chop_coord)
right_ch_it.add_after_then_move (child);
else {
if (fixed_chop_coutline (child, chop_coord, pitch_error,
&left_frags, &right_frags))
delete child;
else {
if (srcbox.left () + srcbox.right () <= chop_coord * 2)
left_ch_it.add_after_then_move (child);
else
right_ch_it.add_after_then_move (child);
}
}
}
close_chopped_cfragments(&left_frags, &left_ch, pitch_error, left_it);
close_chopped_cfragments(&right_frags, &right_ch, pitch_error, right_it);
ASSERT_HOST (left_ch.empty () && right_ch.empty ());
//no children left
delete srcline; //smashed up
}
else {
if (srcbox.left () + srcbox.right () <= chop_coord * 2)
//stick whole in left
left_it->add_after_then_move (srcline);
else
right_it->add_before_stay_put (srcline);
}
}
}
/**********************************************************************
* fixed_chop_coutline
*
* Chop the given coutline (if necessary) placing the fragments which
* fall either side of the chop line into the appropriate list.
* If the coutline lies too heavily to one side to chop, FALSE is returned.
**********************************************************************/
BOOL8 fixed_chop_coutline( //chop the outline
C_OUTLINE *srcline, //source outline
inT16 chop_coord, //place to chop
float pitch_error, //allowed deviation
C_OUTLINE_FRAG_LIST *left_frags, //left half of chop
C_OUTLINE_FRAG_LIST *right_frags //right half of chop
) {
BOOL8 first_frag; //fragment
BOOL8 anticlock; //direction of loop
inT16 left_edge; //of outline
inT16 startindex; //in first fragment
inT32 length; //of outline
inT16 stepindex; //into outline
inT16 head_index; //start of fragment
ICOORD head_pos; //start of fragment
inT16 tail_index; //end of fragment
ICOORD tail_pos; //end of fragment
ICOORD pos; //current point
inT16 first_index = 0; //first tail
ICOORD first_pos; //first tail
length = srcline->pathlength ();
pos = srcline->start_pos ();
anticlock = srcline->turn_direction () > 0;
left_edge = pos.x ();
tail_index = 0;
tail_pos = pos;
for (stepindex = 0; stepindex < length; stepindex++) {
if (pos.x () < left_edge) {
left_edge = pos.x ();
tail_index = stepindex;
tail_pos = pos;
}
pos += srcline->step (stepindex);
}
if (left_edge >= chop_coord - pitch_error)
return FALSE; //not worth it
startindex = tail_index;
first_frag = TRUE;
head_index = tail_index;
head_pos = tail_pos;
do {
do {
tail_pos += srcline->step (tail_index);
tail_index++;
if (tail_index == length)
tail_index = 0;
}
while (tail_pos.x () != chop_coord && tail_index != startindex);
if (tail_index == startindex) {
if (first_frag)
return FALSE; //doesn't cross line
else
break;
}
//#ifdef __UNIX__
ASSERT_HOST (head_index != tail_index);
//#endif
if (!first_frag) {
save_chop_cfragment(head_index,
head_pos,
tail_index,
tail_pos,
srcline,
left_frags);
}
else {
first_index = tail_index;
first_pos = tail_pos;
first_frag = FALSE;
}
while (srcline->step (tail_index).x () == 0) {
tail_pos += srcline->step (tail_index);
tail_index++;
if (tail_index == length)
tail_index = 0;
}
head_index = tail_index;
head_pos = tail_pos;
while (srcline->step (tail_index).x () > 0) {
do {
tail_pos += srcline->step (tail_index);
tail_index++;
if (tail_index == length)
tail_index = 0;
}
while (tail_pos.x () != chop_coord);
//#ifdef __UNIX__
ASSERT_HOST (head_index != tail_index);
//#endif
save_chop_cfragment(head_index,
head_pos,
tail_index,
tail_pos,
srcline,
right_frags);
while (srcline->step (tail_index).x () == 0) {
tail_pos += srcline->step (tail_index);
tail_index++;
if (tail_index == length)
tail_index = 0;
}
head_index = tail_index;
head_pos = tail_pos;
}
}
while (tail_index != startindex);
save_chop_cfragment(head_index,
head_pos,
first_index,
first_pos,
srcline,
left_frags);
return TRUE; //did some chopping
}
/**********************************************************************
* next_anti_left_seg
*
* Search the outline for a suitable point at which it crosses the
* chop_coord from left to right.
**********************************************************************/
inT16 next_anti_left_seg( //chop the outline
C_OUTLINE *srcline, //source outline
inT16 tail_index, //of tailpos
inT16 startindex, //end of search
inT32 length, //of outline
inT16 chop_coord, //place to chop
float pitch_error, //allowed deviation
ICOORD *tail_pos //current position
) {
BOOL8 test_valid; //test pt valid
inT16 chop_starty; //test chop pt
inT16 test_index; //possible chop pt
ICOORD test_pos; //possible chop pt
ICOORD prev_step; //in x to tail pos
test_valid = FALSE;
chop_starty = -MAX_INT16;
test_index = tail_index; //stop warnings
do {
*tail_pos += srcline->step (tail_index);
prev_step = srcline->step (tail_index);
tail_index++;
if (tail_index >= length)
tail_index = 0;
if (test_valid && tail_pos->x () == chop_coord && prev_step.x () < 0) {
if (tail_pos->y () >= chop_starty) {
chop_starty = -MAX_INT16;
test_valid = FALSE;
}
else {
*tail_pos = test_pos;
tail_index = test_index;
break; //must chop there
}
}
if (tail_pos->x () == chop_coord
&& srcline->step (tail_index).x () > 0
&& tail_pos->y () > chop_starty) {
chop_starty = tail_pos->y ();
test_index = tail_index;
test_pos = *tail_pos;
test_valid = TRUE;
}
else if (tail_pos->x () == chop_coord
&& srcline->step (tail_index).y () < 0
&& prev_step.x () > 0 && tail_pos->y () > chop_starty)
break; //must chop here
}
while (tail_index != startindex
&& tail_pos->x () < chop_coord + pitch_error);
return tail_index;
}
/**********************************************************************
* next_anti_right_seg
*
* Search the outline for a suitable point at which it crosses the
* chop_coord from right to left.
**********************************************************************/
inT16 next_anti_right_seg( //chop the outline
C_OUTLINE *srcline, //source outline
inT16 tail_index, //of tailpos
inT16 startindex, //end of search
inT32 length, //of outline
inT16 chop_coord, //place to chop
float pitch_error, //allowed deviation
ICOORD *tail_pos //current position
) {
BOOL8 test_valid; //test pt valid
inT16 chop_starty; //test chop pt
inT16 test_index; //possible chop pt
ICOORD test_pos; //possible chop pt
ICOORD prev_step; //in x to tail pos
test_valid = FALSE;
chop_starty = MAX_INT16;
test_index = tail_index; //stop warnings
do {
//move forward
*tail_pos += srcline->step (tail_index);
prev_step = srcline->step (tail_index);
tail_index++;
if (tail_index >= length)
tail_index = 0;
if (test_valid && tail_pos->x () == chop_coord && prev_step.x () > 0) {
if (tail_pos->y () <= chop_starty) {
chop_starty = MAX_INT16;
test_valid = FALSE;
}
else {
*tail_pos = test_pos;
tail_index = test_index;
break; //must chop there
}
}
if (tail_pos->x () == chop_coord
&& srcline->step (tail_index).x () < 0
&& tail_pos->y () < chop_starty) {
chop_starty = tail_pos->y ();
test_index = tail_index;
test_pos = *tail_pos;
test_valid = TRUE; //save possible chop pt
}
else if (tail_pos->x () == chop_coord
&& srcline->step (tail_index).y () > 0
&& prev_step.x () < 0 && tail_pos->y () < chop_starty)
break; //must chop here
}
while (tail_index != startindex
&& tail_pos->x () > chop_coord - pitch_error);
return tail_index;
}
/**********************************************************************
* next_clock_left_seg
*
* Search the outline for a suitable point at which it crosses the
* chop_coord from left to right.
**********************************************************************/
inT16 next_clock_left_seg( //chop the outline
C_OUTLINE *srcline, //source outline
inT16 tail_index, //of tailpos
inT16 startindex, //end of search
inT32 length, //of outline
inT16 chop_coord, //place to chop
float pitch_error, //allowed deviation
ICOORD *tail_pos //current position
) {
BOOL8 test_valid; //test pt valid
inT16 chop_starty; //test chop pt
inT16 test_index; //possible chop pt
ICOORD test_pos; //possible chop pt
ICOORD prev_step; //in x to tail pos
test_valid = FALSE;
chop_starty = MAX_INT16;
test_index = tail_index; //stop warnings
do {
*tail_pos += srcline->step (tail_index);
prev_step = srcline->step (tail_index);
tail_index++;
if (tail_index >= length)
tail_index = 0;
if (test_valid && tail_pos->x () == chop_coord && prev_step.x () < 0) {
if (tail_pos->y () <= chop_starty) {
chop_starty = MAX_INT16;
test_valid = FALSE;
}
else {
*tail_pos = test_pos;
tail_index = test_index;
break; //must chop there
}
}
if (tail_pos->x () == chop_coord
&& srcline->step (tail_index).x () > 0
&& tail_pos->y () < chop_starty) {
chop_starty = tail_pos->y ();
test_index = tail_index;
test_pos = *tail_pos;
test_valid = TRUE;
}
else if (tail_pos->x () == chop_coord
&& srcline->step (tail_index).y () > 0
&& prev_step.x () > 0 && tail_pos->y () < chop_starty)
break; //must chop here
}
while (tail_index != startindex
&& tail_pos->x () < chop_coord + pitch_error);
return tail_index;
}
/**********************************************************************
* next_clock_right_seg
*
* Search the outline for a suitable point at which it crosses the
* chop_coord from right to left.
**********************************************************************/
inT16 next_clock_right_seg( //chop the outline
C_OUTLINE *srcline, //source outline
inT16 tail_index, //of tailpos
inT16 startindex, //end of search
inT32 length, //of outline
inT16 chop_coord, //place to chop
float pitch_error, //allowed deviation
ICOORD *tail_pos //current position
) {
BOOL8 test_valid; //test pt valid
inT16 chop_starty; //test chop pt
inT16 test_index; //possible chop pt
ICOORD test_pos; //possible chop pt
ICOORD prev_step; //in x to tail pos
test_valid = FALSE;
chop_starty = MAX_INT16;
test_index = tail_index; //stop warnings
do {
//move forward
*tail_pos += srcline->step (tail_index);
prev_step = srcline->step (tail_index);
tail_index++;
if (tail_index >= length)
tail_index = 0;
if (test_valid && tail_pos->x () == chop_coord && prev_step.x () > 0) {
if (tail_pos->y () >= chop_starty) {
chop_starty = MAX_INT16;
test_valid = FALSE;
}
else {
*tail_pos = test_pos;
tail_index = test_index;
break; //must chop there
}
}
if (tail_pos->x () == chop_coord
&& srcline->step (tail_index).x () < 0
&& tail_pos->y () > chop_starty) {
chop_starty = tail_pos->y ();
test_index = tail_index;
test_pos = *tail_pos;
test_valid = TRUE; //save possible chop pt
}
else if (tail_pos->x () == chop_coord
&& srcline->step (tail_index).y () < 0
&& prev_step.x () < 0 && tail_pos->y () > chop_starty)
break; //must chop here
}
while (tail_index != startindex
&& tail_pos->x () > chop_coord - pitch_error);
return tail_index;
}
/**********************************************************************
* save_chop_cfragment
*
* Store the given fragment in the given fragment list.
**********************************************************************/
void save_chop_cfragment( //chop the outline
inT16 head_index, //head of fragment
ICOORD head_pos, //head of fragment
inT16 tail_index, //tail of fragment
ICOORD tail_pos, //tail of fragment
C_OUTLINE *srcline, //source of edgesteps
C_OUTLINE_FRAG_LIST *frags //fragment list
) {
inT16 jump; //gap across end
inT16 stepcount; //total steps
C_OUTLINE_FRAG *head; //head of fragment
C_OUTLINE_FRAG *tail; //tail of fragment
inT16 tail_y; //ycoord of tail
ASSERT_HOST (tail_pos.x () == head_pos.x ());
ASSERT_HOST (tail_index != head_index);
stepcount = tail_index - head_index;
if (stepcount < 0)
stepcount += srcline->pathlength ();
jump = tail_pos.y () - head_pos.y ();
if (jump < 0)
jump = -jump;
if (jump == stepcount)
return; //its a nop
tail_y = tail_pos.y ();
head = new C_OUTLINE_FRAG (head_pos, tail_pos, srcline,
head_index, tail_index);
tail = new C_OUTLINE_FRAG (head, tail_y);
head->other_end = tail;
add_frag_to_list(head, frags);
add_frag_to_list(tail, frags);
}
/**********************************************************************
* C_OUTLINE_FRAG::C_OUTLINE_FRAG
*
* Constructors for C_OUTLINE_FRAG.
**********************************************************************/
C_OUTLINE_FRAG::C_OUTLINE_FRAG( //record fragment
ICOORD start_pt, //start coord
ICOORD end_pt, //end coord
C_OUTLINE *outline, //source of steps
inT16 start_index,
inT16 end_index) {
start = start_pt;
end = end_pt;
ycoord = start_pt.y ();
stepcount = end_index - start_index;
if (stepcount < 0)
stepcount += outline->pathlength ();
ASSERT_HOST (stepcount > 0);
steps = new DIR128[stepcount];
if (end_index > start_index) {
for (int i = start_index; i < end_index; ++i)
steps[i - start_index] = outline->step_dir(i);
}
else {
int len = outline->pathlength();
int i = start_index;
for (; i < len; ++i)
steps[i - start_index] = outline->step_dir(i);
if (end_index > 0)
for (; i < end_index + len; ++i)
steps[i - start_index] = outline->step_dir(i - len);
}
other_end = NULL;
delete close();
}
C_OUTLINE_FRAG::C_OUTLINE_FRAG( //record fragment
C_OUTLINE_FRAG *head, //other end
inT16 tail_y) {
ycoord = tail_y;
other_end = head;
start = head->start;
end = head->end;
steps = NULL;
stepcount = 0;
}
/**********************************************************************
* add_frag_to_list
*
* Insert the fragment in the list at the appropriate place to keep
* them in ascending ycoord order.
**********************************************************************/
void add_frag_to_list( //ordered add
C_OUTLINE_FRAG *frag, //fragment to add
C_OUTLINE_FRAG_LIST *frags //fragment list
) {
//output list
C_OUTLINE_FRAG_IT frag_it = frags;
if (!frags->empty ()) {
for (frag_it.mark_cycle_pt (); !frag_it.cycled_list ();
frag_it.forward ()) {
if (frag_it.data ()->ycoord > frag->ycoord
|| (frag_it.data ()->ycoord == frag->ycoord
&& frag->other_end->ycoord < frag->ycoord)) {
frag_it.add_before_then_move (frag);
return;
}
}
}
frag_it.add_to_end (frag);
}
/**********************************************************************
* close_chopped_cfragments
*
* Clear the given list of fragments joining them up into outlines.
* Each outline made soaks up any of the child outlines which it encloses.
**********************************************************************/
void close_chopped_cfragments( //chop the outline
C_OUTLINE_FRAG_LIST *frags, //list to clear
C_OUTLINE_LIST *children, //potential children
float pitch_error, //allowed shrinkage
C_OUTLINE_IT *dest_it //output list
) {
//iterator
C_OUTLINE_FRAG_IT frag_it = frags;
C_OUTLINE_FRAG *bottom_frag; //bottom of cut
C_OUTLINE_FRAG *top_frag; //top of cut
C_OUTLINE *outline; //new outline
C_OUTLINE *child; //current child
C_OUTLINE_IT child_it = children;
C_OUTLINE_IT olchild_it; //children of outline
while (!frag_it.empty ()) {
frag_it.move_to_first ();
//get bottom one
bottom_frag = frag_it.extract ();
frag_it.forward ();
top_frag = frag_it.data (); //look at next
if ((bottom_frag->steps == 0 && top_frag->steps == 0)
|| (bottom_frag->steps != 0 && top_frag->steps != 0)) {
if (frag_it.data_relative (1)->ycoord == top_frag->ycoord)
frag_it.forward ();
}
top_frag = frag_it.extract ();
if (top_frag->other_end != bottom_frag) {
outline = join_chopped_fragments (bottom_frag, top_frag);
ASSERT_HOST (outline == NULL);
}
else {
outline = join_chopped_fragments (bottom_frag, top_frag);
ASSERT_HOST (outline != NULL);
olchild_it.set_to_list (outline->child ());
for (child_it.mark_cycle_pt (); !child_it.cycled_list ();
child_it.forward ()) {
child = child_it.data ();
if (*child < *outline)
olchild_it.add_to_end (child_it.extract ());
}
if (outline->bounding_box ().width () > pitch_error)
dest_it->add_after_then_move (outline);
else
delete outline; //make it disappear
}
}
while (!child_it.empty ()) {
dest_it->add_after_then_move (child_it.extract ());
child_it.forward ();
}
}
/**********************************************************************
* join_chopped_fragments
*
* Join the two lists of POLYPTs such that neither OUTLINE_FRAG
* operand keeps responsibility for the fragment.
**********************************************************************/
C_OUTLINE *join_chopped_fragments( //join pieces
C_OUTLINE_FRAG *bottom, //bottom of cut
C_OUTLINE_FRAG *top //top of cut
) {
C_OUTLINE *outline; //closed loop
if (bottom->other_end == top) {
if (bottom->steps == 0)
outline = top->close (); //turn to outline
else
outline = bottom->close ();
delete top;
delete bottom;
return outline;
}
if (bottom->steps == 0) {
ASSERT_HOST (top->steps != 0);
join_segments (bottom->other_end, top);
}
else {
ASSERT_HOST (top->steps == 0);
join_segments (top->other_end, bottom);
}
top->other_end->other_end = bottom->other_end;
bottom->other_end->other_end = top->other_end;
delete bottom;
delete top;
return NULL;
}
/**********************************************************************
* join_segments
*
* Join the two edgestep fragments such that the second comes after
* the first and the gap beween them is closed.
**********************************************************************/
void join_segments( //join pieces
C_OUTLINE_FRAG *bottom, //bottom of cut
C_OUTLINE_FRAG *top //top of cut
) {
DIR128 *steps; //new steps
inT32 stepcount; //no of steps
inT16 fake_count; //fake steps
DIR128 fake_step; //step entry
ASSERT_HOST (bottom->end.x () == top->start.x ());
fake_count = top->start.y () - bottom->end.y ();
if (fake_count < 0) {
fake_count = -fake_count;
fake_step = 32;
}
else
fake_step = 96;
stepcount = bottom->stepcount + fake_count + top->stepcount;
steps = new DIR128[stepcount];
memmove (steps, bottom->steps, bottom->stepcount);
memset (steps + bottom->stepcount, fake_step.get_dir(), fake_count);
memmove (steps + bottom->stepcount + fake_count, top->steps,
top->stepcount);
delete [] bottom->steps;
bottom->steps = steps;
bottom->stepcount = stepcount;
bottom->end = top->end;
bottom->other_end->end = top->end;
}
/**********************************************************************
* C_OUTLINE_FRAG::close
*
* Join the ends of this fragment and turn it into an outline.
**********************************************************************/
C_OUTLINE *C_OUTLINE_FRAG::close() { //join pieces
DIR128 *new_steps; //new steps
inT32 new_stepcount; //no of steps
inT16 fake_count; //fake steps
DIR128 fake_step; //step entry
ASSERT_HOST (start.x () == end.x ());
fake_count = start.y () - end.y ();
if (fake_count < 0) {
fake_count = -fake_count;
fake_step = 32;
}
else
fake_step = 96;
new_stepcount = stepcount + fake_count;
new_steps = new DIR128[new_stepcount];
memmove(new_steps, steps, stepcount);
memset (new_steps + stepcount, fake_step.get_dir(), fake_count);
C_OUTLINE* result = new C_OUTLINE (start, new_steps, new_stepcount);
delete [] new_steps;
return result;
}
/**********************************************************************
* C_OUTLINE_FRAG::operator=
*
* Copy this fragment.
**********************************************************************/
//join pieces
C_OUTLINE_FRAG & C_OUTLINE_FRAG::operator= (
const C_OUTLINE_FRAG & src //fragment to copy
) {
if (steps != NULL)
delete [] steps;
stepcount = src.stepcount;
steps = new DIR128[stepcount];
memmove (steps, src.steps, stepcount);
start = src.start;
end = src.end;
ycoord = src.ycoord;
return *this;
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/window_snapshot/window_snapshot.h"
#include "base/logging.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/aura/window.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/dip_util.h"
#include "ui/compositor/layer.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/rect.h"
namespace chrome {
namespace internal {
bool GrabWindowSnapshot(gfx::NativeWindow window,
std::vector<unsigned char>* png_representation,
const gfx::Rect& snapshot_bounds) {
ui::Compositor* compositor = window->layer()->GetCompositor();
gfx::Rect read_pixels_bounds = snapshot_bounds;
// When not in compact mode we must take into account the window's position on
// the desktop.
read_pixels_bounds.Offset(window->bounds().OffsetFromOrigin());
gfx::Rect read_pixels_bounds_in_pixel =
ui::ConvertRectToPixel(window->layer(), read_pixels_bounds);
DCHECK_GE(compositor->size().width(), read_pixels_bounds_in_pixel.right());
DCHECK_GE(compositor->size().height(), read_pixels_bounds_in_pixel.bottom());
DCHECK_LE(0, read_pixels_bounds.x());
DCHECK_LE(0, read_pixels_bounds.y());
SkBitmap bitmap;
if (!compositor->ReadPixels(&bitmap, read_pixels_bounds_in_pixel))
return false;
unsigned char* pixels = reinterpret_cast<unsigned char*>(bitmap.getPixels());
gfx::PNGCodec::Encode(pixels, gfx::PNGCodec::FORMAT_BGRA,
read_pixels_bounds_in_pixel.size(),
bitmap.rowBytes(), true,
std::vector<gfx::PNGCodec::Comment>(),
png_representation);
return true;
}
} // namespace internal
} // namespace chrome
|
#include <thread>
#include <plog/Log.h>
#include <plog/Appenders/ColorConsoleAppender.h>
#include "types_flatrpc.hpp"
using namespace std;
using namespace examples::simple;
zmqpp::context ctx;
TypesClient client(ctx);
int main(int argc, char *argv[]) {
static plog::ColorConsoleAppender<plog::TxtFormatter> consoleAppender;
plog::init(plog::verbose, &consoleAppender);
client.connect("unix:///tmp/typesserver");
thread clientThread([] {
client.run(); // Run the client event loop
});
PLOG_INFO << "Bool request";
PLOG_INFO << "Reply: " << (int) client.Bool(true).get()->bool_field;
PLOG_INFO << "Byte request";
PLOG_INFO << "Reply: " << (int) client.Byte(-1).get()->byte_field;
PLOG_INFO << "Ubyte request";
PLOG_INFO << "Reply: " << (int) client.Ubyte(-1).get()->ubyte_field;
PLOG_INFO << "Short request";
PLOG_INFO << "Reply: " << client.Short(-1).get()->short_field;
PLOG_INFO << "Ushort request";
PLOG_INFO << "Reply: " << client.Ushort(-1).get()->ushort_field;
PLOG_INFO << "Int request";
PLOG_INFO << "Reply: " << client.Int(-1).get()->int_field;
PLOG_INFO << "Uint request";
PLOG_INFO << "Reply: " << client.Uint(-1).get()->uint_field;
PLOG_INFO << "Long request";
PLOG_INFO << "Reply: " << client.Long(-1).get()->long_field;
PLOG_INFO << "Ulong request";
PLOG_INFO << "Reply: " << client.Ulong(-1).get()->ulong_field;
PLOG_INFO << "Float request";
PLOG_INFO << "Reply: " << client.Float(-1).get()->float_field;
PLOG_INFO << "Double request";
PLOG_INFO << "Reply: " << client.Double(-1).get()->double_field;
PLOG_INFO << "String request";
PLOG_INFO << "Reply: " << client.String("Hello World").get()->string_field;
client.Quit().get();
client.stop();
clientThread.join();
return 0;
}
|
//============================================================================
// Problem : 1078A - Barcelonian Distance
// Category : Geometry
//============================================================================
#include <bits/stdc++.h>
using namespace std;
struct point { double x,y; };
bool operator < (const point &a, const point &b) { return a.x != b.x? a.x < b.x : a.y < b.y; }
long long a,b,c; // a*x + b*y + c = 0
point p,q;
set<point> v;
void intersections() {
double aux_x,aux_y;
if(b != 0) {
aux_y = (-a*p.x - c)/b;
if(min(p.y,q.y) <= aux_y && aux_y <= max(p.y,q.y)) {
v.insert({p.x, aux_y});
}
aux_y = (-a*q.x - c)/b;
if(min(p.y,q.y) <= aux_y && aux_y <= max(p.y,q.y)) {
v.insert({q.x, aux_y});
}
}
if(a != 0) {
aux_x = (-b*p.y - c)/a;
if(min(p.x,q.x) <= aux_x && aux_x <= max(p.x,q.x)) {
v.insert({aux_x, p.y});
}
aux_x = (-b*q.y - c)/a;
if(min(p.x,q.x) <= aux_x && aux_x <= max(p.x,q.x)) {
v.insert({aux_x, q.y});
}
}
}
double euclid(point a, point b) { return sqrt((a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y)); }
double manhattan(point a, point b) { return fabs(a.x-b.x) + fabs(a.y-b.y); }
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
double ans;
while(cin >> a >> b >> c >> p.x >> p.y >> q.x >> q.y) {
v.clear();
intersections();
ans = manhattan(p,q);
if(v.size() == 2) {
point l1 = *v.begin(), l2 = *(--v.end());
ans = min(ans, min(manhattan(p,l1) + euclid(l1,l2) + manhattan(l2,q),
manhattan(p,l2) + euclid(l2,l1) + manhattan(l1,q)));
}
cout << fixed << setprecision(10) << ans << '\n';
}
return 0;
}
|
//===-- ThreadPlanStepOut.cpp -----------------------------------*- C++ -*-===//
//
// 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
//
//===----------------------------------------------------------------------===//
#include "lldb/Target/ThreadPlanStepOut.h"
#include "lldb/Breakpoint/Breakpoint.h"
#include "lldb/Core/Value.h"
#include "lldb/Core/ValueObjectConstResult.h"
#include "lldb/Symbol/Block.h"
#include "lldb/Symbol/CompileUnit.h"
#include "lldb/Symbol/Function.h"
#include "lldb/Symbol/Symbol.h"
#include "lldb/Symbol/Type.h"
#include "lldb/Symbol/VariableList.h"
#include "lldb/Target/ABI.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/RegisterContext.h"
#include "lldb/Target/StopInfo.h"
#include "lldb/Target/SwiftLanguageRuntime.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/ThreadPlanStepOverRange.h"
#include "lldb/Target/ThreadPlanStepThrough.h"
#include "lldb/Utility/Log.h"
#include <memory>
using namespace lldb;
using namespace lldb_private;
uint32_t ThreadPlanStepOut::s_default_flag_values = 0;
//----------------------------------------------------------------------
// ThreadPlanStepOut: Step out of the current frame
//----------------------------------------------------------------------
ThreadPlanStepOut::ThreadPlanStepOut(
Thread &thread, SymbolContext *context, bool first_insn, bool stop_others,
Vote stop_vote, Vote run_vote, uint32_t frame_idx,
LazyBool step_out_avoids_code_without_debug_info,
bool continue_to_next_branch, bool gather_return_value)
: ThreadPlan(ThreadPlan::eKindStepOut, "Step out", thread, stop_vote,
run_vote),
ThreadPlanShouldStopHere(this), m_step_from_insn(LLDB_INVALID_ADDRESS),
m_return_bp_id(LLDB_INVALID_BREAK_ID),
m_return_addr(LLDB_INVALID_ADDRESS),
m_swift_error_return(),
m_swift_error_check_after_return(false),
m_stop_others(stop_others), m_immediate_step_from_function(nullptr),
m_is_swift_error_value(false),
m_calculate_return_value(gather_return_value) {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
SetFlagsToDefault();
SetupAvoidNoDebug(step_out_avoids_code_without_debug_info);
m_step_from_insn = m_thread.GetRegisterContext()->GetPC(0);
uint32_t return_frame_index = frame_idx + 1;
StackFrameSP return_frame_sp(
m_thread.GetStackFrameAtIndex(return_frame_index));
StackFrameSP immediate_return_from_sp(
m_thread.GetStackFrameAtIndex(frame_idx));
if (!return_frame_sp || !immediate_return_from_sp)
return; // we can't do anything here. ValidatePlan() will return false.
// While stepping out, behave as-if artificial frames are not present.
while (return_frame_sp->IsArtificial()) {
m_stepped_past_frames.push_back(return_frame_sp);
++return_frame_index;
return_frame_sp = m_thread.GetStackFrameAtIndex(return_frame_index);
// We never expect to see an artificial frame without a regular ancestor.
// If this happens, log the issue and defensively refuse to step out.
if (!return_frame_sp) {
LLDB_LOG(log, "Can't step out of frame with artificial ancestors");
return;
}
}
m_step_out_to_id = return_frame_sp->GetStackID();
m_immediate_step_from_id = immediate_return_from_sp->GetStackID();
// If the frame directly below the one we are returning to is inlined, we
// have to be a little more careful. It is non-trivial to determine the real
// "return code address" for an inlined frame, so we have to work our way to
// that frame and then step out.
if (immediate_return_from_sp->IsInlined()) {
if (frame_idx > 0) {
// First queue a plan that gets us to this inlined frame, and when we get
// there we'll queue a second plan that walks us out of this frame.
m_step_out_to_inline_plan_sp = std::make_shared<ThreadPlanStepOut>(
m_thread, nullptr, false, stop_others, eVoteNoOpinion, eVoteNoOpinion,
frame_idx - 1, eLazyBoolNo, continue_to_next_branch);
static_cast<ThreadPlanStepOut *>(m_step_out_to_inline_plan_sp.get())
->SetShouldStopHereCallbacks(nullptr, nullptr);
m_step_out_to_inline_plan_sp->SetPrivate(true);
} else {
// If we're already at the inlined frame we're stepping through, then
// just do that now.
QueueInlinedStepPlan(false);
}
} else {
// Find the return address and set a breakpoint there:
// FIXME - can we do this more securely if we know first_insn?
Address return_address(return_frame_sp->GetFrameCodeAddress());
if (continue_to_next_branch) {
SymbolContext return_address_sc;
AddressRange range;
Address return_address_decr_pc = return_address;
if (return_address_decr_pc.GetOffset() > 0)
return_address_decr_pc.Slide(-1);
return_address_decr_pc.CalculateSymbolContext(
&return_address_sc, lldb::eSymbolContextLineEntry);
if (return_address_sc.line_entry.IsValid()) {
range =
return_address_sc.line_entry.GetSameLineContiguousAddressRange();
if (range.GetByteSize() > 0) {
return_address =
m_thread.GetProcess()->AdvanceAddressToNextBranchInstruction(
return_address, range);
}
}
}
m_return_addr =
return_address.GetLoadAddress(&m_thread.GetProcess()->GetTarget());
if (m_return_addr == LLDB_INVALID_ADDRESS)
return;
Breakpoint *return_bp = m_thread.CalculateTarget()
->CreateBreakpoint(m_return_addr, true, false)
.get();
if (return_bp != nullptr) {
if (return_bp->IsHardware() && !return_bp->HasResolvedLocations())
m_could_not_resolve_hw_bp = true;
return_bp->SetThreadID(m_thread.GetID());
m_return_bp_id = return_bp->GetID();
return_bp->SetBreakpointKind("step-out");
}
if (immediate_return_from_sp) {
const SymbolContext &sc =
immediate_return_from_sp->GetSymbolContext(eSymbolContextFunction);
if (sc.function) {
m_immediate_step_from_function = sc.function;
}
}
}
// If we are about to step out of a swift frame, we need to store away the
// location that swift will use for
// any error return:
// FIXME: I'm only doing this if you are stepping out ONE frame at present.
// I'll have to change the stepping
// code so that it first runs to the frame we are stepping out FROM, then
// capture the error return pointer, then
// step out. That's more than I have time to do right now.
if (frame_idx == 0) {
StackFrameSP frame_sp = m_thread.GetStackFrameAtIndex(0);
if (frame_sp->GuessLanguage() == eLanguageTypeSwift) {
SwiftLanguageRuntime *swift_runtime =
SwiftLanguageRuntime::Get(*m_thread.GetProcess());
if (swift_runtime) {
m_swift_error_return =
swift_runtime->GetErrorReturnLocationBeforeReturn(
frame_sp, m_swift_error_check_after_return);
}
}
}
}
void ThreadPlanStepOut::SetupAvoidNoDebug(
LazyBool step_out_avoids_code_without_debug_info) {
bool avoid_nodebug = true;
switch (step_out_avoids_code_without_debug_info) {
case eLazyBoolYes:
avoid_nodebug = true;
break;
case eLazyBoolNo:
avoid_nodebug = false;
break;
case eLazyBoolCalculate:
avoid_nodebug = m_thread.GetStepOutAvoidsNoDebug();
break;
}
if (avoid_nodebug)
GetFlags().Set(ThreadPlanShouldStopHere::eStepOutAvoidNoDebug);
else
GetFlags().Clear(ThreadPlanShouldStopHere::eStepOutAvoidNoDebug);
}
void ThreadPlanStepOut::DidPush() {
if (m_step_out_to_inline_plan_sp)
m_thread.QueueThreadPlan(m_step_out_to_inline_plan_sp, false);
else if (m_step_through_inline_plan_sp)
m_thread.QueueThreadPlan(m_step_through_inline_plan_sp, false);
}
ThreadPlanStepOut::~ThreadPlanStepOut() {
if (m_return_bp_id != LLDB_INVALID_BREAK_ID)
m_thread.CalculateTarget()->RemoveBreakpointByID(m_return_bp_id);
}
void ThreadPlanStepOut::GetDescription(Stream *s,
lldb::DescriptionLevel level) {
if (level == lldb::eDescriptionLevelBrief)
s->Printf("step out");
else {
if (m_step_out_to_inline_plan_sp)
s->Printf("Stepping out to inlined frame so we can walk through it.");
else if (m_step_through_inline_plan_sp)
s->Printf("Stepping out by stepping through inlined function.");
else {
s->Printf("Stepping out from ");
Address tmp_address;
if (tmp_address.SetLoadAddress(m_step_from_insn, &GetTarget())) {
tmp_address.Dump(s, &GetThread(), Address::DumpStyleResolvedDescription,
Address::DumpStyleLoadAddress);
} else {
s->Printf("address 0x%" PRIx64 "", (uint64_t)m_step_from_insn);
}
// FIXME: find some useful way to present the m_return_id, since there may
// be multiple copies of the
// same function on the stack.
s->Printf(" returning to frame at ");
if (tmp_address.SetLoadAddress(m_return_addr, &GetTarget())) {
tmp_address.Dump(s, &GetThread(), Address::DumpStyleResolvedDescription,
Address::DumpStyleLoadAddress);
} else {
s->Printf("address 0x%" PRIx64 "", (uint64_t)m_return_addr);
}
if (level == eDescriptionLevelVerbose)
s->Printf(" using breakpoint site %d", m_return_bp_id);
}
}
s->Printf("\n");
for (StackFrameSP frame_sp : m_stepped_past_frames) {
s->Printf("Stepped out past: ");
frame_sp->DumpUsingSettingsFormat(s);
}
}
bool ThreadPlanStepOut::ValidatePlan(Stream *error) {
if (m_step_out_to_inline_plan_sp)
return m_step_out_to_inline_plan_sp->ValidatePlan(error);
if (m_step_through_inline_plan_sp)
return m_step_through_inline_plan_sp->ValidatePlan(error);
if (m_could_not_resolve_hw_bp) {
if (error)
error->PutCString(
"Could not create hardware breakpoint for thread plan.");
return false;
}
if (m_return_bp_id == LLDB_INVALID_BREAK_ID) {
if (error)
error->PutCString("Could not create return address breakpoint.");
return false;
}
return true;
}
bool ThreadPlanStepOut::DoPlanExplainsStop(Event *event_ptr) {
// If the step out plan is done, then we just need to step through the
// inlined frame.
if (m_step_out_to_inline_plan_sp) {
return m_step_out_to_inline_plan_sp->MischiefManaged();
} else if (m_step_through_inline_plan_sp) {
if (m_step_through_inline_plan_sp->MischiefManaged()) {
CalculateReturnValue();
SetPlanComplete();
return true;
} else
return false;
} else if (m_step_out_further_plan_sp) {
return m_step_out_further_plan_sp->MischiefManaged();
}
// We don't explain signals or breakpoints (breakpoints that handle stepping
// in or out will be handled by a child plan.
StopInfoSP stop_info_sp = GetPrivateStopInfo();
if (stop_info_sp) {
StopReason reason = stop_info_sp->GetStopReason();
if (reason == eStopReasonBreakpoint) {
// If this is OUR breakpoint, we're fine, otherwise we don't know why
// this happened...
BreakpointSiteSP site_sp(
m_thread.GetProcess()->GetBreakpointSiteList().FindByID(
stop_info_sp->GetValue()));
if (site_sp && site_sp->IsBreakpointAtThisSite(m_return_bp_id)) {
bool done;
StackID frame_zero_id = m_thread.GetStackFrameAtIndex(0)->GetStackID();
if (m_step_out_to_id == frame_zero_id)
done = true;
else if (m_step_out_to_id < frame_zero_id) {
// Either we stepped past the breakpoint, or the stack ID calculation
// was incorrect and we should probably stop.
done = true;
} else {
done = (m_immediate_step_from_id < frame_zero_id);
}
if (done) {
CalculateReturnValue();
if (InvokeShouldStopHereCallback(eFrameCompareOlder, m_status)) {
SetPlanComplete();
}
}
// If there was only one owner, then we're done. But if we also hit
// some user breakpoint on our way out, we should mark ourselves as
// done, but also not claim to explain the stop, since it is more
// important to report the user breakpoint than the step out
// completion.
if (site_sp->GetNumberOfOwners() == 1)
return true;
}
return false;
} else if (IsUsuallyUnexplainedStopReason(reason))
return false;
else
return true;
}
return true;
}
bool ThreadPlanStepOut::ShouldStop(Event *event_ptr) {
if (IsPlanComplete())
return true;
bool done = false;
if (m_step_out_to_inline_plan_sp) {
if (m_step_out_to_inline_plan_sp->MischiefManaged()) {
// Now step through the inlined stack we are in:
if (QueueInlinedStepPlan(true)) {
// If we can't queue a plan to do this, then just call ourselves done.
m_step_out_to_inline_plan_sp.reset();
SetPlanComplete(false);
return true;
} else
done = true;
} else
return m_step_out_to_inline_plan_sp->ShouldStop(event_ptr);
} else if (m_step_through_inline_plan_sp) {
if (m_step_through_inline_plan_sp->MischiefManaged())
done = true;
else
return m_step_through_inline_plan_sp->ShouldStop(event_ptr);
} else if (m_step_out_further_plan_sp) {
if (m_step_out_further_plan_sp->MischiefManaged())
m_step_out_further_plan_sp.reset();
else
return m_step_out_further_plan_sp->ShouldStop(event_ptr);
}
if (!done) {
StackID frame_zero_id = m_thread.GetStackFrameAtIndex(0)->GetStackID();
done = !(frame_zero_id < m_step_out_to_id);
}
// The normal step out computations think we are done, so all we need to do
// is consult the ShouldStopHere, and we are done.
if (done) {
CalculateReturnValue();
if (InvokeShouldStopHereCallback(eFrameCompareOlder, m_status)) {
SetPlanComplete();
} else {
m_step_out_further_plan_sp =
QueueStepOutFromHerePlan(m_flags, eFrameCompareOlder, m_status);
if (m_step_out_further_plan_sp->GetKind() == eKindStepOut)
{
// If we are planning to step out further, then the frame we are going
// to step out to is about to go away, so we need to reset the frame
// we are stepping out to to the one our step out plan is aiming for.
ThreadPlanStepOut *as_step_out
= static_cast<ThreadPlanStepOut *>(m_step_out_further_plan_sp.get());
m_step_out_to_id = as_step_out->m_step_out_to_id;
}
done = false;
}
}
return done;
}
bool ThreadPlanStepOut::StopOthers() { return m_stop_others; }
StateType ThreadPlanStepOut::GetPlanRunState() { return eStateRunning; }
bool ThreadPlanStepOut::DoWillResume(StateType resume_state,
bool current_plan) {
if (m_step_out_to_inline_plan_sp || m_step_through_inline_plan_sp)
return true;
if (m_return_bp_id == LLDB_INVALID_BREAK_ID)
return false;
if (current_plan) {
Breakpoint *return_bp =
m_thread.CalculateTarget()->GetBreakpointByID(m_return_bp_id).get();
if (return_bp != nullptr)
return_bp->SetEnabled(true);
}
return true;
}
bool ThreadPlanStepOut::WillStop() {
if (m_return_bp_id != LLDB_INVALID_BREAK_ID) {
Breakpoint *return_bp =
m_thread.CalculateTarget()->GetBreakpointByID(m_return_bp_id).get();
if (return_bp != nullptr)
return_bp->SetEnabled(false);
}
return true;
}
bool ThreadPlanStepOut::MischiefManaged() {
if (IsPlanComplete()) {
// Did I reach my breakpoint? If so I'm done.
//
// I also check the stack depth, since if we've blown past the breakpoint
// for some
// reason and we're now stopping for some other reason altogether, then
// we're done with this step out operation.
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
if (log)
log->Printf("Completed step out plan.");
if (m_return_bp_id != LLDB_INVALID_BREAK_ID) {
m_thread.CalculateTarget()->RemoveBreakpointByID(m_return_bp_id);
m_return_bp_id = LLDB_INVALID_BREAK_ID;
}
ThreadPlan::MischiefManaged();
return true;
} else {
return false;
}
}
bool ThreadPlanStepOut::QueueInlinedStepPlan(bool queue_now) {
// Now figure out the range of this inlined block, and set up a "step through
// range" plan for that. If we've been provided with a context, then use the
// block in that context.
StackFrameSP immediate_return_from_sp(m_thread.GetStackFrameAtIndex(0));
if (!immediate_return_from_sp)
return false;
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
if (log) {
StreamString s;
immediate_return_from_sp->Dump(&s, true, false);
log->Printf("Queuing inlined frame to step past: %s.", s.GetData());
}
Block *from_block = immediate_return_from_sp->GetFrameBlock();
if (from_block) {
Block *inlined_block = from_block->GetContainingInlinedBlock();
if (inlined_block) {
size_t num_ranges = inlined_block->GetNumRanges();
AddressRange inline_range;
if (inlined_block->GetRangeAtIndex(0, inline_range)) {
SymbolContext inlined_sc;
inlined_block->CalculateSymbolContext(&inlined_sc);
inlined_sc.target_sp = GetTarget().shared_from_this();
RunMode run_mode =
m_stop_others ? lldb::eOnlyThisThread : lldb::eAllThreads;
const LazyBool avoid_no_debug = eLazyBoolNo;
m_step_through_inline_plan_sp =
std::make_shared<ThreadPlanStepOverRange>(
m_thread, inline_range, inlined_sc, run_mode, avoid_no_debug);
ThreadPlanStepOverRange *step_through_inline_plan_ptr =
static_cast<ThreadPlanStepOverRange *>(
m_step_through_inline_plan_sp.get());
m_step_through_inline_plan_sp->SetPrivate(true);
step_through_inline_plan_ptr->SetOkayToDiscard(true);
StreamString errors;
if (!step_through_inline_plan_ptr->ValidatePlan(&errors)) {
// FIXME: Log this failure.
delete step_through_inline_plan_ptr;
return false;
}
for (size_t i = 1; i < num_ranges; i++) {
if (inlined_block->GetRangeAtIndex(i, inline_range))
step_through_inline_plan_ptr->AddRange(inline_range);
}
if (queue_now)
m_thread.QueueThreadPlan(m_step_through_inline_plan_sp, false);
return true;
}
}
}
return false;
}
void ThreadPlanStepOut::CalculateReturnValue() {
if (!m_calculate_return_value)
return;
if (m_return_valobj_sp)
return;
// First check if we have an error return address, and if that pointer
// contains a valid error return, grab it:
SwiftLanguageRuntime *swift_runtime =
SwiftLanguageRuntime::Get(*m_thread.GetProcess());
if (swift_runtime) {
// In some ABI's the error is in a memory location in the caller's frame
// and we need to fetch that location from the frame before we leave the
// throwing frame. In others, the actual error address is in a register,
// so we need to fetch the value of the address AFTER leaving the frame.
if (m_swift_error_check_after_return)
{
StackFrameSP frame_sp = m_thread.GetStackFrameAtIndex(0);
if (!frame_sp)
return;
m_swift_error_return =
swift_runtime->GetErrorReturnLocationAfterReturn(frame_sp);
}
if (m_swift_error_return) {
ConstString name("swift_thrown_error");
m_return_valobj_sp = swift_runtime->CalculateErrorValueObjectFromValue(
m_swift_error_return.getValue(), name, true);
// Even if we couldn't figure out what the error return was, we
// were told there was an error, so don't show the user a false return value
// instead.
m_is_swift_error_value = true;
return;
}
}
// We don't have a swift error, so let's compute the actual return:
if (m_immediate_step_from_function != nullptr) {
CompilerType return_compiler_type =
m_immediate_step_from_function->GetCompilerType()
.GetFunctionReturnType();
if (return_compiler_type) {
lldb::ABISP abi_sp = m_thread.GetProcess()->GetABI();
if (abi_sp)
m_return_valobj_sp =
abi_sp->GetReturnValueObject(m_thread, return_compiler_type);
}
}
}
bool ThreadPlanStepOut::IsPlanStale() {
// If we are still lower on the stack than the frame we are returning to,
// then there's something for us to do. Otherwise, we're stale.
StackID frame_zero_id = m_thread.GetStackFrameAtIndex(0)->GetStackID();
return !(frame_zero_id < m_step_out_to_id);
}
|
// Copyright (c) 2018 Jyocoin Project, Derived from 2014-2018, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder 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 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.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
/*!
* \file simplewallet.cpp
*
* \brief Source file that defines simple_wallet class.
*/
#include <thread>
#include <iostream>
#include <sstream>
#include <fstream>
#include <ctype.h>
#include <boost/lexical_cast.hpp>
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
#include <boost/regex.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include "include_base_utils.h"
#include "common/i18n.h"
#include "common/command_line.h"
#include "common/util.h"
#include "common/dns_utils.h"
#include "common/base58.h"
#include "common/scoped_message_writer.h"
#include "cryptonote_protocol/cryptonote_protocol_handler.h"
#include "simplewallet.h"
#include "cryptonote_basic/cryptonote_format_utils.h"
#include "storages/http_abstract_invoke.h"
#include "rpc/core_rpc_server_commands_defs.h"
#include "crypto/crypto.h" // for crypto::secret_key definition
#include "mnemonics/electrum-words.h"
#include "rapidjson/document.h"
#include "common/json_util.h"
#include "ringct/rctSigs.h"
#include "multisig/multisig.h"
#include "wallet/wallet_args.h"
#include "version.h"
#include <stdexcept>
#ifdef WIN32
#include <boost/locale.hpp>
#include <boost/filesystem.hpp>
#endif
#ifdef HAVE_READLINE
#include "readline_buffer.h"
#endif
using namespace std;
using namespace epee;
using namespace cryptonote;
using boost::lexical_cast;
namespace po = boost::program_options;
typedef cryptonote::simple_wallet sw;
#undef jyocoin_DEFAULT_LOG_CATEGORY
#define jyocoin_DEFAULT_LOG_CATEGORY "wallet.simplewallet"
#define EXTENDED_LOGS_FILE "wallet_details.log"
#define DEFAULT_MIX 10
#define MIN_RING_SIZE 11 // Used to inform user about min ring size -- does not track actual protocol
#define LOCK_IDLE_SCOPE() \
bool auto_refresh_enabled = m_auto_refresh_enabled.load(std::memory_order_relaxed); \
m_auto_refresh_enabled.store(false, std::memory_order_relaxed); \
/* stop any background refresh, and take over */ \
m_wallet->stop(); \
boost::unique_lock<boost::mutex> lock(m_idle_mutex); \
m_idle_cond.notify_all(); \
epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){ \
m_auto_refresh_enabled.store(auto_refresh_enabled, std::memory_order_relaxed); \
})
#define SCOPED_WALLET_UNLOCK() \
LOCK_IDLE_SCOPE(); \
boost::optional<tools::password_container> pwd_container = boost::none; \
if (m_wallet->ask_password() && !(pwd_container = get_and_verify_password())) { return true; } \
tools::wallet_keys_unlocker unlocker(*m_wallet, pwd_container);
enum TransferType {
Transfer,
TransferLocked,
};
namespace
{
const std::array<const char* const, 5> allowed_priority_strings = {{"default", "unimportant", "normal", "elevated", "priority"}};
const auto arg_wallet_file = wallet_args::arg_wallet_file();
const command_line::arg_descriptor<std::string> arg_generate_new_wallet = {"generate-new-wallet", sw::tr("Generate new wallet and save it to <arg>"), ""};
const command_line::arg_descriptor<std::string> arg_generate_from_device = {"generate-from-device", sw::tr("Generate new wallet from device and save it to <arg>"), ""};
const command_line::arg_descriptor<std::string> arg_generate_from_view_key = {"generate-from-view-key", sw::tr("Generate incoming-only wallet from view key"), ""};
const command_line::arg_descriptor<std::string> arg_generate_from_spend_key = {"generate-from-spend-key", sw::tr("Generate deterministic wallet from spend key"), ""};
const command_line::arg_descriptor<std::string> arg_generate_from_keys = {"generate-from-keys", sw::tr("Generate wallet from private keys"), ""};
const command_line::arg_descriptor<std::string> arg_generate_from_multisig_keys = {"generate-from-multisig-keys", sw::tr("Generate a master wallet from multisig wallet keys"), ""};
const auto arg_generate_from_json = wallet_args::arg_generate_from_json();
const command_line::arg_descriptor<std::string> arg_mnemonic_language = {"mnemonic-language", sw::tr("Language for mnemonic"), ""};
const command_line::arg_descriptor<std::string> arg_electrum_seed = {"electrum-seed", sw::tr("Specify Electrum seed for wallet recovery/creation"), ""};
const command_line::arg_descriptor<bool> arg_restore_deterministic_wallet = {"restore-deterministic-wallet", sw::tr("Recover wallet using Electrum-style mnemonic seed"), false};
const command_line::arg_descriptor<bool> arg_restore_multisig_wallet = {"restore-multisig-wallet", sw::tr("Recover multisig wallet using Electrum-style mnemonic seed"), false};
const command_line::arg_descriptor<bool> arg_non_deterministic = {"non-deterministic", sw::tr("Generate non-deterministic view and spend keys"), false};
const command_line::arg_descriptor<bool> arg_allow_mismatched_daemon_version = {"allow-mismatched-daemon-version", sw::tr("Allow communicating with a daemon that uses a different RPC version"), false};
const command_line::arg_descriptor<uint64_t> arg_restore_height = {"restore-height", sw::tr("Restore from specific blockchain height"), 0};
const command_line::arg_descriptor<bool> arg_do_not_relay = {"do-not-relay", sw::tr("The newly created transaction will not be relayed to the jyocoin network"), false};
const command_line::arg_descriptor<bool> arg_create_address_file = {"create-address-file", sw::tr("Create an address file for new wallets"), false};
const command_line::arg_descriptor<std::string> arg_subaddress_lookahead = {"subaddress-lookahead", tools::wallet2::tr("Set subaddress lookahead sizes to <major>:<minor>"), ""};
const command_line::arg_descriptor<bool> arg_use_english_language_names = {"use-english-language-names", sw::tr("Display English language names"), false};
const command_line::arg_descriptor< std::vector<std::string> > arg_command = {"command", ""};
std::string input_line(const std::string& prompt)
{
#ifdef HAVE_READLINE
rdln::suspend_readline pause_readline;
#endif
std::cout << prompt;
std::string buf;
#ifdef _WIN32
buf = tools::input_line_win();
#else
std::getline(std::cin, buf);
#endif
return epee::string_tools::trim(buf);
}
epee::wipeable_string input_secure_line(const std::string& prompt)
{
#ifdef HAVE_READLINE
rdln::suspend_readline pause_readline;
#endif
auto pwd_container = tools::password_container::prompt(false, prompt.c_str(), false);
if (!pwd_container)
{
MERROR("Failed to read secure line");
return "";
}
epee::wipeable_string buf = pwd_container->password();
buf.trim();
return buf;
}
boost::optional<tools::password_container> password_prompter(const char *prompt, bool verify)
{
#ifdef HAVE_READLINE
rdln::suspend_readline pause_readline;
#endif
auto pwd_container = tools::password_container::prompt(verify, prompt);
if (!pwd_container)
{
tools::fail_msg_writer() << sw::tr("failed to read wallet password");
}
return pwd_container;
}
boost::optional<tools::password_container> default_password_prompter(bool verify)
{
return password_prompter(verify ? sw::tr("Enter a new password for the wallet") : sw::tr("Wallet password"), verify);
}
inline std::string interpret_rpc_response(bool ok, const std::string& status)
{
std::string err;
if (ok)
{
if (status == CORE_RPC_STATUS_BUSY)
{
err = sw::tr("daemon is busy. Please try again later.");
}
else if (status != CORE_RPC_STATUS_OK)
{
err = status;
}
}
else
{
err = sw::tr("possibly lost connection to daemon");
}
return err;
}
tools::scoped_message_writer success_msg_writer(bool color = false)
{
return tools::scoped_message_writer(color ? console_color_green : console_color_default, false, std::string(), el::Level::Info);
}
tools::scoped_message_writer message_writer(epee::console_colors color = epee::console_color_default, bool bright = false)
{
return tools::scoped_message_writer(color, bright);
}
tools::scoped_message_writer fail_msg_writer()
{
return tools::scoped_message_writer(console_color_red, true, sw::tr("Error: "), el::Level::Error);
}
bool parse_bool(const std::string& s, bool& result)
{
if (s == "1" || command_line::is_yes(s))
{
result = true;
return true;
}
if (s == "0" || command_line::is_no(s))
{
result = false;
return true;
}
boost::algorithm::is_iequal ignore_case{};
if (boost::algorithm::equals("true", s, ignore_case) || boost::algorithm::equals(simple_wallet::tr("true"), s, ignore_case))
{
result = true;
return true;
}
if (boost::algorithm::equals("false", s, ignore_case) || boost::algorithm::equals(simple_wallet::tr("false"), s, ignore_case))
{
result = false;
return true;
}
return false;
}
template <typename F>
bool parse_bool_and_use(const std::string& s, F func)
{
bool r;
if (parse_bool(s, r))
{
func(r);
return true;
}
else
{
fail_msg_writer() << sw::tr("invalid argument: must be either 0/1, true/false, y/n, yes/no");
return false;
}
}
const struct
{
const char *name;
tools::wallet2::RefreshType refresh_type;
} refresh_type_names[] =
{
{ "full", tools::wallet2::RefreshFull },
{ "optimize-coinbase", tools::wallet2::RefreshOptimizeCoinbase },
{ "optimized-coinbase", tools::wallet2::RefreshOptimizeCoinbase },
{ "no-coinbase", tools::wallet2::RefreshNoCoinbase },
{ "default", tools::wallet2::RefreshDefault },
};
bool parse_refresh_type(const std::string &s, tools::wallet2::RefreshType &refresh_type)
{
for (size_t n = 0; n < sizeof(refresh_type_names) / sizeof(refresh_type_names[0]); ++n)
{
if (s == refresh_type_names[n].name)
{
refresh_type = refresh_type_names[n].refresh_type;
return true;
}
}
fail_msg_writer() << cryptonote::simple_wallet::tr("failed to parse refresh type");
return false;
}
std::string get_refresh_type_name(tools::wallet2::RefreshType type)
{
for (size_t n = 0; n < sizeof(refresh_type_names) / sizeof(refresh_type_names[0]); ++n)
{
if (type == refresh_type_names[n].refresh_type)
return refresh_type_names[n].name;
}
return "invalid";
}
std::string get_version_string(uint32_t version)
{
return boost::lexical_cast<std::string>(version >> 16) + "." + boost::lexical_cast<std::string>(version & 0xffff);
}
std::string oa_prompter(const std::string &url, const std::vector<std::string> &addresses, bool dnssec_valid)
{
if (addresses.empty())
return {};
// prompt user for confirmation.
// inform user of DNSSEC validation status as well.
std::string dnssec_str;
if (dnssec_valid)
{
dnssec_str = sw::tr("DNSSEC validation passed");
}
else
{
dnssec_str = sw::tr("WARNING: DNSSEC validation was unsuccessful, this address may not be correct!");
}
std::stringstream prompt;
prompt << sw::tr("For URL: ") << url
<< ", " << dnssec_str << std::endl
<< sw::tr(" jyocoin Address = ") << addresses[0]
<< std::endl
<< sw::tr("Is this OK? (Y/n) ")
;
// prompt the user for confirmation given the dns query and dnssec status
std::string confirm_dns_ok = input_line(prompt.str());
if (std::cin.eof())
{
return {};
}
if (!command_line::is_yes(confirm_dns_ok))
{
std::cout << sw::tr("you have cancelled the transfer request") << std::endl;
return {};
}
return addresses[0];
}
bool parse_subaddress_indices(const std::string& arg, std::set<uint32_t>& subaddr_indices)
{
subaddr_indices.clear();
if (arg.substr(0, 6) != "index=")
return false;
std::string subaddr_indices_str_unsplit = arg.substr(6, arg.size() - 6);
std::vector<std::string> subaddr_indices_str;
boost::split(subaddr_indices_str, subaddr_indices_str_unsplit, boost::is_any_of(","));
for (const auto& subaddr_index_str : subaddr_indices_str)
{
uint32_t subaddr_index;
if(!epee::string_tools::get_xtype_from_string(subaddr_index, subaddr_index_str))
{
fail_msg_writer() << sw::tr("failed to parse index: ") << subaddr_index_str;
subaddr_indices.clear();
return false;
}
subaddr_indices.insert(subaddr_index);
}
return true;
}
boost::optional<std::pair<uint32_t, uint32_t>> parse_subaddress_lookahead(const std::string& str)
{
auto r = tools::parse_subaddress_lookahead(str);
if (!r)
fail_msg_writer() << sw::tr("invalid format for subaddress lookahead; must be <major>:<minor>");
return r;
}
void handle_transfer_exception(const std::exception_ptr &e, bool trusted_daemon)
{
bool warn_of_possible_attack = !trusted_daemon;
try
{
std::rethrow_exception(e);
}
catch (const tools::error::daemon_busy&)
{
fail_msg_writer() << sw::tr("daemon is busy. Please try again later.");
}
catch (const tools::error::no_connection_to_daemon&)
{
fail_msg_writer() << sw::tr("no connection to daemon. Please make sure daemon is running.");
}
catch (const tools::error::wallet_rpc_error& e)
{
LOG_ERROR("RPC error: " << e.to_string());
fail_msg_writer() << sw::tr("RPC error: ") << e.what();
}
catch (const tools::error::get_outs_error &e)
{
fail_msg_writer() << sw::tr("failed to get random outputs to mix: ") << e.what();
}
catch (const tools::error::not_enough_unlocked_money& e)
{
LOG_PRINT_L0(boost::format("not enough money to transfer, available only %s, sent amount %s") %
print_money(e.available()) %
print_money(e.tx_amount()));
fail_msg_writer() << sw::tr("Not enough money in unlocked balance");
warn_of_possible_attack = false;
}
catch (const tools::error::not_enough_money& e)
{
LOG_PRINT_L0(boost::format("not enough money to transfer, available only %s, sent amount %s") %
print_money(e.available()) %
print_money(e.tx_amount()));
fail_msg_writer() << sw::tr("Not enough money in unlocked balance");
warn_of_possible_attack = false;
}
catch (const tools::error::tx_not_possible& e)
{
LOG_PRINT_L0(boost::format("not enough money to transfer, available only %s, transaction amount %s = %s + %s (fee)") %
print_money(e.available()) %
print_money(e.tx_amount() + e.fee()) %
print_money(e.tx_amount()) %
print_money(e.fee()));
fail_msg_writer() << sw::tr("Failed to find a way to create transactions. This is usually due to dust which is so small it cannot pay for itself in fees, or trying to send more money than the unlocked balance, or not leaving enough for fees");
warn_of_possible_attack = false;
}
catch (const tools::error::not_enough_outs_to_mix& e)
{
auto writer = fail_msg_writer();
writer << sw::tr("not enough outputs for specified ring size") << " = " << (e.mixin_count() + 1) << ":";
for (std::pair<uint64_t, uint64_t> outs_for_amount : e.scanty_outs())
{
writer << "\n" << sw::tr("output amount") << " = " << print_money(outs_for_amount.first) << ", " << sw::tr("found outputs to use") << " = " << outs_for_amount.second;
}
writer << sw::tr("Please use sweep_unmixable.");
}
catch (const tools::error::tx_not_constructed&)
{
fail_msg_writer() << sw::tr("transaction was not constructed");
warn_of_possible_attack = false;
}
catch (const tools::error::tx_rejected& e)
{
fail_msg_writer() << (boost::format(sw::tr("transaction %s was rejected by daemon with status: ")) % get_transaction_hash(e.tx())) << e.status();
std::string reason = e.reason();
if (!reason.empty())
fail_msg_writer() << sw::tr("Reason: ") << reason;
}
catch (const tools::error::tx_sum_overflow& e)
{
fail_msg_writer() << e.what();
warn_of_possible_attack = false;
}
catch (const tools::error::zero_destination&)
{
fail_msg_writer() << sw::tr("one of destinations is zero");
warn_of_possible_attack = false;
}
catch (const tools::error::tx_too_big& e)
{
fail_msg_writer() << sw::tr("failed to find a suitable way to split transactions");
warn_of_possible_attack = false;
}
catch (const tools::error::transfer_error& e)
{
LOG_ERROR("unknown transfer error: " << e.to_string());
fail_msg_writer() << sw::tr("unknown transfer error: ") << e.what();
}
catch (const tools::error::multisig_export_needed& e)
{
LOG_ERROR("Multisig error: " << e.to_string());
fail_msg_writer() << sw::tr("Multisig error: ") << e.what();
warn_of_possible_attack = false;
}
catch (const tools::error::wallet_internal_error& e)
{
LOG_ERROR("internal error: " << e.to_string());
fail_msg_writer() << sw::tr("internal error: ") << e.what();
}
catch (const std::exception& e)
{
LOG_ERROR("unexpected error: " << e.what());
fail_msg_writer() << sw::tr("unexpected error: ") << e.what();
}
if (warn_of_possible_attack)
fail_msg_writer() << sw::tr("There was an error, which could mean the node may be trying to get you to retry creating a transaction, and zero in on which outputs you own. Or it could be a bona fide error. It may be prudent to disconnect from this node, and not try to send a transaction immediately. Alternatively, connect to another node so the original node cannot correlate information.");
}
bool check_file_overwrite(const std::string &filename)
{
boost::system::error_code errcode;
if (boost::filesystem::exists(filename, errcode))
{
if (boost::ends_with(filename, ".keys"))
{
fail_msg_writer() << boost::format(sw::tr("File %s likely stores wallet private keys! Use a different file name.")) % filename;
return false;
}
return command_line::is_yes(input_line((boost::format(sw::tr("File %s already exists. Are you sure to overwrite it? (Y/Yes/N/No): ")) % filename).str()));
}
return true;
}
void print_secret_key(const crypto::secret_key &k)
{
static constexpr const char hex[] = u8"0123456789abcdef";
const uint8_t *ptr = (const uint8_t*)k.data;
for (size_t i = 0, sz = sizeof(k); i < sz; ++i)
{
putchar(hex[*ptr >> 4]);
putchar(hex[*ptr & 15]);
++ptr;
}
}
}
bool parse_priority(const std::string& arg, uint32_t& priority)
{
auto priority_pos = std::find(
allowed_priority_strings.begin(),
allowed_priority_strings.end(),
arg);
if(priority_pos != allowed_priority_strings.end()) {
priority = std::distance(allowed_priority_strings.begin(), priority_pos);
return true;
}
return false;
}
std::string join_priority_strings(const char *delimiter)
{
std::string s;
for (size_t n = 0; n < allowed_priority_strings.size(); ++n)
{
if (!s.empty())
s += delimiter;
s += allowed_priority_strings[n];
}
return s;
}
std::string simple_wallet::get_commands_str()
{
std::stringstream ss;
ss << tr("Commands: ") << ENDL;
std::string usage = m_cmd_binder.get_usage();
boost::replace_all(usage, "\n", "\n ");
usage.insert(0, " ");
ss << usage << ENDL;
return ss.str();
}
std::string simple_wallet::get_command_usage(const std::vector<std::string> &args)
{
std::pair<std::string, std::string> documentation = m_cmd_binder.get_documentation(args);
std::stringstream ss;
if(documentation.first.empty())
{
ss << tr("Unknown command: ") << args.front();
}
else
{
std::string usage = documentation.second.empty() ? args.front() : documentation.first;
std::string description = documentation.second.empty() ? documentation.first : documentation.second;
usage.insert(0, " ");
ss << tr("Command usage: ") << ENDL << usage << ENDL << ENDL;
boost::replace_all(description, "\n", "\n ");
description.insert(0, " ");
ss << tr("Command description: ") << ENDL << description << ENDL;
}
return ss.str();
}
bool simple_wallet::viewkey(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
// don't log
PAUSE_READLINE();
if (m_wallet->key_on_device()) {
std::cout << "secret: On device. Not available" << std::endl;
} else {
SCOPED_WALLET_UNLOCK();
printf("secret: ");
print_secret_key(m_wallet->get_account().get_keys().m_view_secret_key);
putchar('\n');
}
std::cout << "public: " << string_tools::pod_to_hex(m_wallet->get_account().get_keys().m_account_address.m_view_public_key) << std::endl;
return true;
}
bool simple_wallet::spendkey(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
if (m_wallet->watch_only())
{
fail_msg_writer() << tr("wallet is watch-only and has no spend key");
return true;
}
// don't log
PAUSE_READLINE();
if (m_wallet->key_on_device()) {
std::cout << "secret: On device. Not available" << std::endl;
} else {
SCOPED_WALLET_UNLOCK();
printf("secret: ");
print_secret_key(m_wallet->get_account().get_keys().m_spend_secret_key);
putchar('\n');
}
std::cout << "public: " << string_tools::pod_to_hex(m_wallet->get_account().get_keys().m_account_address.m_spend_public_key) << std::endl;
return true;
}
bool simple_wallet::print_seed(bool encrypted)
{
bool success = false;
epee::wipeable_string seed;
bool ready, multisig;
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if (m_wallet->watch_only())
{
fail_msg_writer() << tr("wallet is watch-only and has no seed");
return true;
}
multisig = m_wallet->multisig(&ready);
if (multisig)
{
if (!ready)
{
fail_msg_writer() << tr("wallet is multisig but not yet finalized");
return true;
}
}
SCOPED_WALLET_UNLOCK();
if (!multisig && !m_wallet->is_deterministic())
{
fail_msg_writer() << tr("wallet is non-deterministic and has no seed");
return true;
}
epee::wipeable_string seed_pass;
if (encrypted)
{
auto pwd_container = password_prompter(tr("Enter optional seed offset passphrase, empty to see raw seed"), true);
if (std::cin.eof() || !pwd_container)
return true;
seed_pass = pwd_container->password();
}
if (multisig)
success = m_wallet->get_multisig_seed(seed, seed_pass);
else if (m_wallet->is_deterministic())
success = m_wallet->get_seed(seed, seed_pass);
if (success)
{
print_seed(seed);
}
else
{
fail_msg_writer() << tr("Failed to retrieve seed");
}
return true;
}
bool simple_wallet::seed(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
return print_seed(false);
}
bool simple_wallet::encrypted_seed(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
return print_seed(true);
}
bool simple_wallet::seed_set_language(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if (m_wallet->multisig())
{
fail_msg_writer() << tr("wallet is multisig and has no seed");
return true;
}
if (m_wallet->watch_only())
{
fail_msg_writer() << tr("wallet is watch-only and has no seed");
return true;
}
epee::wipeable_string password;
{
SCOPED_WALLET_UNLOCK();
if (!m_wallet->is_deterministic())
{
fail_msg_writer() << tr("wallet is non-deterministic and has no seed");
return true;
}
// we need the password, even if ask-password is unset
if (!pwd_container)
{
pwd_container = get_and_verify_password();
if (pwd_container == boost::none)
{
fail_msg_writer() << tr("Incorrect password");
return true;
}
}
password = pwd_container->password();
}
std::string mnemonic_language = get_mnemonic_language();
if (mnemonic_language.empty())
return true;
m_wallet->set_seed_language(std::move(mnemonic_language));
m_wallet->rewrite(m_wallet_file, password);
return true;
}
bool simple_wallet::change_password(const std::vector<std::string> &args)
{
const auto orig_pwd_container = get_and_verify_password();
if(orig_pwd_container == boost::none)
{
fail_msg_writer() << tr("Your original password was incorrect.");
return true;
}
// prompts for a new password, pass true to verify the password
const auto pwd_container = default_password_prompter(true);
if(!pwd_container)
return true;
try
{
m_wallet->change_password(m_wallet_file, orig_pwd_container->password(), pwd_container->password());
}
catch (const tools::error::wallet_logic_error& e)
{
fail_msg_writer() << tr("Error with wallet rewrite: ") << e.what();
return true;
}
return true;
}
bool simple_wallet::payment_id(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
crypto::hash payment_id;
if (args.size() > 0)
{
fail_msg_writer() << tr("usage: payment_id");
return true;
}
payment_id = crypto::rand<crypto::hash>();
success_msg_writer() << tr("Random payment ID: ") << payment_id;
return true;
}
bool simple_wallet::print_fee_info(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
if (!try_connect_to_daemon())
return true;
const bool per_byte = m_wallet->use_fork_rules(HF_VERSION_PER_BYTE_FEE);
const uint64_t base_fee = m_wallet->get_base_fee();
const char *base = per_byte ? "byte" : "kB";
const uint64_t typical_size = per_byte ? 2500 : 13;
const uint64_t size_granularity = per_byte ? 1 : 1024;
message_writer() << (boost::format(tr("Current fee is %s %s per %s")) % print_money(base_fee) % cryptonote::get_unit(cryptonote::get_default_decimal_point()) % base).str();
std::vector<uint64_t> fees;
for (uint32_t priority = 1; priority <= 4; ++priority)
{
uint64_t mult = m_wallet->get_fee_multiplier(priority);
fees.push_back(base_fee * typical_size * mult);
}
std::vector<std::pair<uint64_t, uint64_t>> blocks;
try
{
uint64_t base_size = typical_size * size_granularity;
blocks = m_wallet->estimate_backlog(base_size, base_size + size_granularity - 1, fees);
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Error: failed to estimate backlog array size: ") << e.what();
return true;
}
if (blocks.size() != 4)
{
fail_msg_writer() << tr("Error: bad estimated backlog array size");
return true;
}
for (uint32_t priority = 1; priority <= 4; ++priority)
{
uint64_t nblocks_low = blocks[priority - 1].first;
uint64_t nblocks_high = blocks[priority - 1].second;
if (nblocks_low > 0)
{
std::string msg;
if (priority == m_wallet->get_default_priority() || (m_wallet->get_default_priority() == 0 && priority == 2))
msg = tr(" (current)");
uint64_t minutes_low = nblocks_low * DIFFICULTY_TARGET_V2 / 60, minutes_high = nblocks_high * DIFFICULTY_TARGET_V2 / 60;
if (nblocks_high == nblocks_low)
message_writer() << (boost::format(tr("%u block (%u minutes) backlog at priority %u%s")) % nblocks_low % minutes_low % priority % msg).str();
else
message_writer() << (boost::format(tr("%u to %u block (%u to %u minutes) backlog at priority %u")) % nblocks_low % nblocks_high % minutes_low % minutes_high % priority).str();
}
else
message_writer() << tr("No backlog at priority ") << priority;
}
return true;
}
bool simple_wallet::prepare_multisig(const std::vector<std::string> &args)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if (m_wallet->multisig())
{
fail_msg_writer() << tr("This wallet is already multisig");
return true;
}
if (m_wallet->watch_only())
{
fail_msg_writer() << tr("wallet is watch-only and cannot be made multisig");
return true;
}
if(m_wallet->get_num_transfer_details())
{
fail_msg_writer() << tr("This wallet has been used before, please use a new wallet to create a multisig wallet");
return true;
}
SCOPED_WALLET_UNLOCK();
std::string multisig_info = m_wallet->get_multisig_info();
success_msg_writer() << multisig_info;
success_msg_writer() << tr("Send this multisig info to all other participants, then use make_multisig <threshold> <info1> [<info2>...] with others' multisig info");
success_msg_writer() << tr("This includes the PRIVATE view key, so needs to be disclosed only to that multisig wallet's participants ");
return true;
}
bool simple_wallet::make_multisig(const std::vector<std::string> &args)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if (m_wallet->multisig())
{
fail_msg_writer() << tr("This wallet is already multisig");
return true;
}
if (m_wallet->watch_only())
{
fail_msg_writer() << tr("wallet is watch-only and cannot be made multisig");
return true;
}
if(m_wallet->get_num_transfer_details())
{
fail_msg_writer() << tr("This wallet has been used before, please use a new wallet to create a multisig wallet");
return true;
}
if (args.size() < 2)
{
fail_msg_writer() << tr("usage: make_multisig <threshold> <multisiginfo1> [<multisiginfo2>...]");
return true;
}
// parse threshold
uint32_t threshold;
if (!string_tools::get_xtype_from_string(threshold, args[0]))
{
fail_msg_writer() << tr("Invalid threshold");
return true;
}
const auto orig_pwd_container = get_and_verify_password();
if(orig_pwd_container == boost::none)
{
fail_msg_writer() << tr("Your original password was incorrect.");
return true;
}
LOCK_IDLE_SCOPE();
try
{
auto local_args = args;
local_args.erase(local_args.begin());
std::string multisig_extra_info = m_wallet->make_multisig(orig_pwd_container->password(), local_args, threshold);
if (!multisig_extra_info.empty())
{
success_msg_writer() << tr("Another step is needed");
success_msg_writer() << multisig_extra_info;
success_msg_writer() << tr("Send this multisig info to all other participants, then use exchange_multisig_keys <info1> [<info2>...] with others' multisig info");
return true;
}
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Error creating multisig: ") << e.what();
return true;
}
uint32_t total;
if (!m_wallet->multisig(NULL, &threshold, &total))
{
fail_msg_writer() << tr("Error creating multisig: new wallet is not multisig");
return true;
}
success_msg_writer() << std::to_string(threshold) << "/" << total << tr(" multisig address: ")
<< m_wallet->get_account().get_public_address_str(m_wallet->nettype());
return true;
}
bool simple_wallet::finalize_multisig(const std::vector<std::string> &args)
{
bool ready;
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
const auto pwd_container = get_and_verify_password();
if(pwd_container == boost::none)
{
fail_msg_writer() << tr("Your original password was incorrect.");
return true;
}
if (!m_wallet->multisig(&ready))
{
fail_msg_writer() << tr("This wallet is not multisig");
return true;
}
if (ready)
{
fail_msg_writer() << tr("This wallet is already finalized");
return true;
}
LOCK_IDLE_SCOPE();
if (args.size() < 2)
{
fail_msg_writer() << tr("usage: finalize_multisig <multisiginfo1> [<multisiginfo2>...]");
return true;
}
try
{
if (!m_wallet->finalize_multisig(pwd_container->password(), args))
{
fail_msg_writer() << tr("Failed to finalize multisig");
return true;
}
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to finalize multisig: ") << e.what();
return true;
}
return true;
}
bool simple_wallet::exchange_multisig_keys(const std::vector<std::string> &args) {
bool ready;
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if (!m_wallet->multisig(&ready))
{
fail_msg_writer() << tr("This wallet is not multisig");
return true;
}
if (ready)
{
fail_msg_writer() << tr("This wallet is already finalized");
return true;
}
const auto orig_pwd_container = get_and_verify_password();
if(orig_pwd_container == boost::none)
{
fail_msg_writer() << tr("Your original password was incorrect.");
return true;
}
if (args.size() < 2)
{
fail_msg_writer() << tr("usage: exchange_multisig_keys <multisiginfo1> [<multisiginfo2>...]");
return true;
}
try
{
std::string multisig_extra_info = m_wallet->exchange_multisig_keys(orig_pwd_container->password(), args);
if (!multisig_extra_info.empty())
{
message_writer() << tr("Another step is needed");
message_writer() << multisig_extra_info;
message_writer() << tr("Send this multisig info to all other participants, then use exchange_multisig_keys <info1> [<info2>...] with others' multisig info");
return true;
} else {
uint32_t threshold, total;
m_wallet->multisig(NULL, &threshold, &total);
success_msg_writer() << tr("Multisig wallet has been successfully created. Current wallet type: ") << threshold << "/" << total;
}
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to perform multisig keys exchange: ") << e.what();
return true;
}
return true;
}
bool simple_wallet::export_multisig(const std::vector<std::string> &args)
{
bool ready;
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if (!m_wallet->multisig(&ready))
{
fail_msg_writer() << tr("This wallet is not multisig");
return true;
}
if (!ready)
{
fail_msg_writer() << tr("This multisig wallet is not yet finalized");
return true;
}
if (args.size() != 1)
{
fail_msg_writer() << tr("usage: export_multisig_info <filename>");
return true;
}
const std::string filename = args[0];
if (m_wallet->confirm_export_overwrite() && !check_file_overwrite(filename))
return true;
SCOPED_WALLET_UNLOCK();
try
{
cryptonote::blobdata ciphertext = m_wallet->export_multisig();
bool r = epee::file_io_utils::save_string_to_file(filename, ciphertext);
if (!r)
{
fail_msg_writer() << tr("failed to save file ") << filename;
return true;
}
}
catch (const std::exception &e)
{
LOG_ERROR("Error exporting multisig info: " << e.what());
fail_msg_writer() << tr("Error exporting multisig info: ") << e.what();
return true;
}
success_msg_writer() << tr("Multisig info exported to ") << filename;
return true;
}
bool simple_wallet::import_multisig(const std::vector<std::string> &args)
{
bool ready;
uint32_t threshold, total;
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if (!m_wallet->multisig(&ready, &threshold, &total))
{
fail_msg_writer() << tr("This wallet is not multisig");
return true;
}
if (!ready)
{
fail_msg_writer() << tr("This multisig wallet is not yet finalized");
return true;
}
if (args.size() < threshold - 1)
{
fail_msg_writer() << tr("usage: import_multisig_info <filename1> [<filename2>...] - one for each other participant");
return true;
}
std::vector<cryptonote::blobdata> info;
for (size_t n = 0; n < args.size(); ++n)
{
const std::string filename = args[n];
std::string data;
bool r = epee::file_io_utils::load_file_to_string(filename, data);
if (!r)
{
fail_msg_writer() << tr("failed to read file ") << filename;
return true;
}
info.push_back(std::move(data));
}
SCOPED_WALLET_UNLOCK();
// all read and parsed, actually import
try
{
m_in_manual_refresh.store(true, std::memory_order_relaxed);
epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){m_in_manual_refresh.store(false, std::memory_order_relaxed);});
size_t n_outputs = m_wallet->import_multisig(info);
// Clear line "Height xxx of xxx"
std::cout << "\r \r";
success_msg_writer() << tr("Multisig info imported");
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to import multisig info: ") << e.what();
return true;
}
if (m_wallet->is_trusted_daemon())
{
try
{
m_wallet->rescan_spent();
}
catch (const std::exception &e)
{
message_writer() << tr("Failed to update spent status after importing multisig info: ") << e.what();
}
}
else
{
message_writer() << tr("Untrusted daemon, spent status may be incorrect. Use a trusted daemon and run \"rescan_spent\"");
}
return true;
}
bool simple_wallet::accept_loaded_tx(const tools::wallet2::multisig_tx_set &txs)
{
std::string extra_message;
return accept_loaded_tx([&txs](){return txs.m_ptx.size();}, [&txs](size_t n)->const tools::wallet2::tx_construction_data&{return txs.m_ptx[n].construction_data;}, extra_message);
}
bool simple_wallet::sign_multisig(const std::vector<std::string> &args)
{
bool ready;
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if(!m_wallet->multisig(&ready))
{
fail_msg_writer() << tr("This is not a multisig wallet");
return true;
}
if (!ready)
{
fail_msg_writer() << tr("This multisig wallet is not yet finalized");
return true;
}
if (args.size() != 1)
{
fail_msg_writer() << tr("usage: sign_multisig <filename>");
return true;
}
SCOPED_WALLET_UNLOCK();
std::string filename = args[0];
std::vector<crypto::hash> txids;
uint32_t signers = 0;
try
{
bool r = m_wallet->sign_multisig_tx_from_file(filename, txids, [&](const tools::wallet2::multisig_tx_set &tx){ signers = tx.m_signers.size(); return accept_loaded_tx(tx); });
if (!r)
{
fail_msg_writer() << tr("Failed to sign multisig transaction");
return true;
}
}
catch (const tools::error::multisig_export_needed& e)
{
fail_msg_writer() << tr("Multisig error: ") << e.what();
return true;
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to sign multisig transaction: ") << e.what();
return true;
}
if (txids.empty())
{
uint32_t threshold;
m_wallet->multisig(NULL, &threshold);
uint32_t signers_needed = threshold - signers - 1;
success_msg_writer(true) << tr("Transaction successfully signed to file ") << filename << ", "
<< signers_needed << " more signer(s) needed";
return true;
}
else
{
std::string txids_as_text;
for (const auto &txid: txids)
{
if (!txids_as_text.empty())
txids_as_text += (", ");
txids_as_text += epee::string_tools::pod_to_hex(txid);
}
success_msg_writer(true) << tr("Transaction successfully signed to file ") << filename << ", txid " << txids_as_text;
success_msg_writer(true) << tr("It may be relayed to the network with submit_multisig");
}
return true;
}
bool simple_wallet::submit_multisig(const std::vector<std::string> &args)
{
bool ready;
uint32_t threshold;
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if (!m_wallet->multisig(&ready, &threshold))
{
fail_msg_writer() << tr("This is not a multisig wallet");
return true;
}
if (!ready)
{
fail_msg_writer() << tr("This multisig wallet is not yet finalized");
return true;
}
if (args.size() != 1)
{
fail_msg_writer() << tr("usage: submit_multisig <filename>");
return true;
}
if (!try_connect_to_daemon())
return true;
SCOPED_WALLET_UNLOCK();
std::string filename = args[0];
try
{
tools::wallet2::multisig_tx_set txs;
bool r = m_wallet->load_multisig_tx_from_file(filename, txs, [&](const tools::wallet2::multisig_tx_set &tx){ return accept_loaded_tx(tx); });
if (!r)
{
fail_msg_writer() << tr("Failed to load multisig transaction from file");
return true;
}
if (txs.m_signers.size() < threshold)
{
fail_msg_writer() << (boost::format(tr("Multisig transaction signed by only %u signers, needs %u more signatures"))
% txs.m_signers.size() % (threshold - txs.m_signers.size())).str();
return true;
}
// actually commit the transactions
for (auto &ptx: txs.m_ptx)
{
m_wallet->commit_tx(ptx);
success_msg_writer(true) << tr("Transaction successfully submitted, transaction ") << get_transaction_hash(ptx.tx) << ENDL
<< tr("You can check its status by using the `show_transfers` command.");
}
}
catch (const std::exception &e)
{
handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
}
catch (...)
{
LOG_ERROR("unknown error");
fail_msg_writer() << tr("unknown error");
}
return true;
}
bool simple_wallet::export_raw_multisig(const std::vector<std::string> &args)
{
bool ready;
uint32_t threshold;
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if (!m_wallet->multisig(&ready, &threshold))
{
fail_msg_writer() << tr("This is not a multisig wallet");
return true;
}
if (!ready)
{
fail_msg_writer() << tr("This multisig wallet is not yet finalized");
return true;
}
if (args.size() != 1)
{
fail_msg_writer() << tr("usage: export_raw_multisig <filename>");
return true;
}
std::string filename = args[0];
if (m_wallet->confirm_export_overwrite() && !check_file_overwrite(filename))
return true;
SCOPED_WALLET_UNLOCK();
try
{
tools::wallet2::multisig_tx_set txs;
bool r = m_wallet->load_multisig_tx_from_file(filename, txs, [&](const tools::wallet2::multisig_tx_set &tx){ return accept_loaded_tx(tx); });
if (!r)
{
fail_msg_writer() << tr("Failed to load multisig transaction from file");
return true;
}
if (txs.m_signers.size() < threshold)
{
fail_msg_writer() << (boost::format(tr("Multisig transaction signed by only %u signers, needs %u more signatures"))
% txs.m_signers.size() % (threshold - txs.m_signers.size())).str();
return true;
}
// save the transactions
std::string filenames;
for (auto &ptx: txs.m_ptx)
{
const crypto::hash txid = cryptonote::get_transaction_hash(ptx.tx);
const std::string filename = std::string("raw_multisig_jyocoin_tx_") + epee::string_tools::pod_to_hex(txid);
if (!filenames.empty())
filenames += ", ";
filenames += filename;
if (!epee::file_io_utils::save_string_to_file(filename, cryptonote::tx_to_blob(ptx.tx)))
{
fail_msg_writer() << tr("Failed to export multisig transaction to file ") << filename;
return true;
}
}
success_msg_writer() << tr("Saved exported multisig transaction file(s): ") << filenames;
}
catch (const std::exception& e)
{
LOG_ERROR("unexpected error: " << e.what());
fail_msg_writer() << tr("unexpected error: ") << e.what();
}
catch (...)
{
LOG_ERROR("Unknown error");
fail_msg_writer() << tr("unknown error");
}
return true;
}
bool simple_wallet::print_ring(const std::vector<std::string> &args)
{
crypto::key_image key_image;
crypto::hash txid;
if (args.size() != 1)
{
fail_msg_writer() << tr("usage: print_ring <key_image|txid>");
return true;
}
if (!epee::string_tools::hex_to_pod(args[0], key_image))
{
fail_msg_writer() << tr("Invalid key image");
return true;
}
// this one will always work, they're all 32 byte hex
if (!epee::string_tools::hex_to_pod(args[0], txid))
{
fail_msg_writer() << tr("Invalid txid");
return true;
}
std::vector<uint64_t> ring;
std::vector<std::pair<crypto::key_image, std::vector<uint64_t>>> rings;
try
{
if (m_wallet->get_ring(key_image, ring))
rings.push_back({key_image, ring});
else if (!m_wallet->get_rings(txid, rings))
{
fail_msg_writer() << tr("Key image either not spent, or spent with mixin 0");
return true;
}
for (const auto &ring: rings)
{
std::stringstream str;
for (const auto &x: ring.second)
str << x<< " ";
// do NOT translate this "absolute" below, the lin can be used as input to set_ring
success_msg_writer() << epee::string_tools::pod_to_hex(ring.first) << " absolute " << str.str();
}
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to get key image ring: ") << e.what();
}
return true;
}
bool simple_wallet::set_ring(const std::vector<std::string> &args)
{
crypto::key_image key_image;
// try filename first
if (args.size() == 1)
{
if (!epee::file_io_utils::is_file_exist(args[0]))
{
fail_msg_writer() << tr("File doesn't exist");
return true;
}
char str[4096];
std::unique_ptr<FILE, tools::close_file> f(fopen(args[0].c_str(), "r"));
if (f)
{
while (!feof(f.get()))
{
if (!fgets(str, sizeof(str), f.get()))
break;
const size_t len = strlen(str);
if (len > 0 && str[len - 1] == '\n')
str[len - 1] = 0;
if (!str[0])
continue;
char key_image_str[65], type_str[9];
int read_after_key_image = 0, read = 0;
int fields = sscanf(str, "%64[abcdefABCDEF0123456789] %n%8s %n", key_image_str, &read_after_key_image, type_str, &read);
if (fields != 2)
{
fail_msg_writer() << tr("Invalid ring specification: ") << str;
continue;
}
key_image_str[64] = 0;
type_str[8] = 0;
crypto::key_image key_image;
if (read_after_key_image == 0 || !epee::string_tools::hex_to_pod(key_image_str, key_image))
{
fail_msg_writer() << tr("Invalid key image: ") << str;
continue;
}
if (read == read_after_key_image+8 || (strcmp(type_str, "absolute") && strcmp(type_str, "relative")))
{
fail_msg_writer() << tr("Invalid ring type, expected relative or abosolute: ") << str;
continue;
}
bool relative = !strcmp(type_str, "relative");
if (read < 0 || (size_t)read > strlen(str))
{
fail_msg_writer() << tr("Error reading line: ") << str;
continue;
}
bool valid = true;
std::vector<uint64_t> ring;
const char *ptr = str + read;
while (*ptr)
{
unsigned long offset;
int elements = sscanf(ptr, "%lu %n", &offset, &read);
if (elements == 0 || read <= 0 || (size_t)read > strlen(str))
{
fail_msg_writer() << tr("Error reading line: ") << str;
valid = false;
break;
}
ring.push_back(offset);
ptr += read;
}
if (!valid)
continue;
if (ring.empty())
{
fail_msg_writer() << tr("Invalid ring: ") << str;
continue;
}
if (relative)
{
for (size_t n = 1; n < ring.size(); ++n)
{
if (ring[n] <= 0)
{
fail_msg_writer() << tr("Invalid relative ring: ") << str;
valid = false;
break;
}
}
}
else
{
for (size_t n = 1; n < ring.size(); ++n)
{
if (ring[n] <= ring[n-1])
{
fail_msg_writer() << tr("Invalid absolute ring: ") << str;
valid = false;
break;
}
}
}
if (!valid)
continue;
if (!m_wallet->set_ring(key_image, ring, relative))
fail_msg_writer() << tr("Failed to set ring for key image: ") << key_image << ". " << tr("Continuing.");
}
f.reset();
}
return true;
}
if (args.size() < 3)
{
fail_msg_writer() << tr("usage: set_ring <filename> | ( <key_image> absolute|relative <index> [<index>...] )");
return true;
}
if (!epee::string_tools::hex_to_pod(args[0], key_image))
{
fail_msg_writer() << tr("Invalid key image");
return true;
}
bool relative;
if (args[1] == "absolute")
{
relative = false;
}
else if (args[1] == "relative")
{
relative = true;
}
else
{
fail_msg_writer() << tr("Missing absolute or relative keyword");
return true;
}
std::vector<uint64_t> ring;
for (size_t n = 2; n < args.size(); ++n)
{
ring.resize(ring.size() + 1);
if (!string_tools::get_xtype_from_string(ring.back(), args[n]))
{
fail_msg_writer() << tr("invalid index: must be a strictly positive unsigned integer");
return true;
}
if (relative)
{
if (ring.size() > 1 && !ring.back())
{
fail_msg_writer() << tr("invalid index: must be a strictly positive unsigned integer");
return true;
}
uint64_t sum = 0;
for (uint64_t out: ring)
{
if (out > std::numeric_limits<uint64_t>::max() - sum)
{
fail_msg_writer() << tr("invalid index: indices wrap");
return true;
}
sum += out;
}
}
else
{
if (ring.size() > 1 && ring[ring.size() - 2] >= ring[ring.size() - 1])
{
fail_msg_writer() << tr("invalid index: indices should be in strictly ascending order");
return true;
}
}
}
if (!m_wallet->set_ring(key_image, ring, relative))
{
fail_msg_writer() << tr("failed to set ring");
return true;
}
return true;
}
bool simple_wallet::blackball(const std::vector<std::string> &args)
{
uint64_t amount = std::numeric_limits<uint64_t>::max(), offset, num_offsets;
if (args.size() == 0)
{
fail_msg_writer() << tr("usage: mark_output_spent <amount>/<offset> | <filename> [add]");
return true;
}
try
{
if (sscanf(args[0].c_str(), "%" PRIu64 "/%" PRIu64, &amount, &offset) == 2)
{
m_wallet->blackball_output(std::make_pair(amount, offset));
}
else if (epee::file_io_utils::is_file_exist(args[0]))
{
std::vector<std::pair<uint64_t, uint64_t>> outputs;
char str[256];
std::unique_ptr<FILE, tools::close_file> f(fopen(args[0].c_str(), "r"));
if (f)
{
while (!feof(f.get()))
{
if (!fgets(str, sizeof(str), f.get()))
break;
const size_t len = strlen(str);
if (len > 0 && str[len - 1] == '\n')
str[len - 1] = 0;
if (!str[0])
continue;
if (sscanf(str, "@%" PRIu64, &amount) == 1)
{
continue;
}
if (amount == std::numeric_limits<uint64_t>::max())
{
fail_msg_writer() << tr("First line is not an amount");
return true;
}
if (sscanf(str, "%" PRIu64 "*%" PRIu64, &offset, &num_offsets) == 2 && num_offsets <= std::numeric_limits<uint64_t>::max() - offset)
{
while (num_offsets--)
outputs.push_back(std::make_pair(amount, offset++));
}
else if (sscanf(str, "%" PRIu64, &offset) == 1)
{
outputs.push_back(std::make_pair(amount, offset));
}
else
{
fail_msg_writer() << tr("Invalid output: ") << str;
return true;
}
}
f.reset();
bool add = false;
if (args.size() > 1)
{
if (args[1] != "add")
{
fail_msg_writer() << tr("Bad argument: ") + args[1] + ": " + tr("should be \"add\"");
return true;
}
add = true;
}
m_wallet->set_blackballed_outputs(outputs, add);
}
else
{
fail_msg_writer() << tr("Failed to open file");
return true;
}
}
else
{
fail_msg_writer() << tr("Invalid output key, and file doesn't exist");
return true;
}
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to mark output spent: ") << e.what();
}
return true;
}
bool simple_wallet::unblackball(const std::vector<std::string> &args)
{
std::pair<uint64_t, uint64_t> output;
if (args.size() != 1)
{
fail_msg_writer() << tr("usage: mark_output_unspent <amount>/<offset>");
return true;
}
if (sscanf(args[0].c_str(), "%" PRIu64 "/%" PRIu64, &output.first, &output.second) != 2)
{
fail_msg_writer() << tr("Invalid output");
return true;
}
try
{
m_wallet->unblackball_output(output);
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to mark output unspent: ") << e.what();
}
return true;
}
bool simple_wallet::blackballed(const std::vector<std::string> &args)
{
std::pair<uint64_t, uint64_t> output;
if (args.size() != 1)
{
fail_msg_writer() << tr("usage: is_output_spent <amount>/<offset>");
return true;
}
if (sscanf(args[0].c_str(), "%" PRIu64 "/%" PRIu64, &output.first, &output.second) != 2)
{
fail_msg_writer() << tr("Invalid output");
return true;
}
try
{
if (m_wallet->is_output_blackballed(output))
message_writer() << tr("Spent: ") << output.first << "/" << output.second;
else
message_writer() << tr("Not spent: ") << output.first << "/" << output.second;
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to check whether output is spent: ") << e.what();
}
return true;
}
bool simple_wallet::save_known_rings(const std::vector<std::string> &args)
{
try
{
LOCK_IDLE_SCOPE();
m_wallet->find_and_save_rings();
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to save known rings: ") << e.what();
}
return true;
}
bool simple_wallet::version(const std::vector<std::string> &args)
{
message_writer() << "jyocoin '" << jyocoin_RELEASE_NAME << "' (v" << jyocoin_VERSION_FULL << ")";
return true;
}
bool simple_wallet::cold_sign_tx(const std::vector<tools::wallet2::pending_tx>& ptx_vector, tools::wallet2::signed_tx_set &exported_txs, std::vector<cryptonote::address_parse_info> &dsts_info, std::function<bool(const tools::wallet2::signed_tx_set &)> accept_func)
{
std::vector<std::string> tx_aux;
message_writer(console_color_white, false) << tr("Please confirm the transaction on the device");
m_wallet->cold_sign_tx(ptx_vector, exported_txs, dsts_info, tx_aux);
if (accept_func && !accept_func(exported_txs))
{
MERROR("Transactions rejected by callback");
return false;
}
// aux info
m_wallet->cold_tx_aux_import(exported_txs.ptx, tx_aux);
// import key images
return m_wallet->import_key_images(exported_txs.key_images);
}
bool simple_wallet::set_always_confirm_transfers(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
parse_bool_and_use(args[1], [&](bool r) {
m_wallet->always_confirm_transfers(r);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
});
}
return true;
}
bool simple_wallet::set_print_ring_members(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
parse_bool_and_use(args[1], [&](bool r) {
m_wallet->print_ring_members(r);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
});
}
return true;
}
bool simple_wallet::set_store_tx_info(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
if (m_wallet->watch_only())
{
fail_msg_writer() << tr("wallet is watch-only and cannot transfer");
return true;
}
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
parse_bool_and_use(args[1], [&](bool r) {
m_wallet->store_tx_info(r);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
});
}
return true;
}
bool simple_wallet::set_default_ring_size(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
if (m_wallet->watch_only())
{
fail_msg_writer() << tr("wallet is watch-only and cannot transfer");
return true;
}
try
{
if (strchr(args[1].c_str(), '-'))
{
fail_msg_writer() << tr("ring size must be an integer >= ") << MIN_RING_SIZE;
return true;
}
uint32_t ring_size = boost::lexical_cast<uint32_t>(args[1]);
if (ring_size < MIN_RING_SIZE && ring_size != 0)
{
fail_msg_writer() << tr("ring size must be an integer >= ") << MIN_RING_SIZE;
return true;
}
if (ring_size != 0 && ring_size != DEFAULT_MIX+1)
message_writer() << tr("WARNING: this is a non default ring size, which may harm your privacy. Default is recommended.");
else if (ring_size == DEFAULT_MIX)
message_writer() << tr("WARNING: from v8, ring size will be fixed and this setting will be ignored.");
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
m_wallet->default_mixin(ring_size > 0 ? ring_size - 1 : 0);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
return true;
}
catch(const boost::bad_lexical_cast &)
{
fail_msg_writer() << tr("ring size must be an integer >= ") << MIN_RING_SIZE;
return true;
}
catch(...)
{
fail_msg_writer() << tr("could not change default ring size");
return true;
}
}
bool simple_wallet::set_default_priority(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
uint32_t priority = 0;
try
{
if (strchr(args[1].c_str(), '-'))
{
fail_msg_writer() << tr("priority must be either 0, 1, 2, 3, or 4, or one of: ") << join_priority_strings(", ");
return true;
}
if (args[1] == "0")
{
priority = 0;
}
else
{
bool found = false;
for (size_t n = 0; n < allowed_priority_strings.size(); ++n)
{
if (allowed_priority_strings[n] == args[1])
{
found = true;
priority = n;
}
}
if (!found)
{
priority = boost::lexical_cast<int>(args[1]);
if (priority < 1 || priority > 4)
{
fail_msg_writer() << tr("priority must be either 0, 1, 2, 3, or 4, or one of: ") << join_priority_strings(", ");
return true;
}
}
}
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
m_wallet->set_default_priority(priority);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
return true;
}
catch(const boost::bad_lexical_cast &)
{
fail_msg_writer() << tr("priority must be either 0, 1, 2, 3, or 4, or one of: ") << join_priority_strings(", ");
return true;
}
catch(...)
{
fail_msg_writer() << tr("could not change default priority");
return true;
}
}
bool simple_wallet::set_auto_refresh(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
parse_bool_and_use(args[1], [&](bool auto_refresh) {
m_auto_refresh_enabled.store(false, std::memory_order_relaxed);
m_wallet->auto_refresh(auto_refresh);
m_idle_mutex.lock();
m_auto_refresh_enabled.store(auto_refresh, std::memory_order_relaxed);
m_idle_cond.notify_one();
m_idle_mutex.unlock();
m_wallet->rewrite(m_wallet_file, pwd_container->password());
});
}
return true;
}
bool simple_wallet::set_refresh_type(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
tools::wallet2::RefreshType refresh_type;
if (!parse_refresh_type(args[1], refresh_type))
{
return true;
}
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
m_wallet->set_refresh_type(refresh_type);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
return true;
}
bool simple_wallet::set_confirm_missing_payment_id(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
parse_bool_and_use(args[1], [&](bool r) {
m_wallet->confirm_missing_payment_id(r);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
});
}
return true;
}
bool simple_wallet::set_ask_password(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
tools::wallet2::AskPasswordType ask = tools::wallet2::AskPasswordToDecrypt;
if (args[1] == "never" || args[1] == "0")
ask = tools::wallet2::AskPasswordNever;
else if (args[1] == "action" || args[1] == "1")
ask = tools::wallet2::AskPasswordOnAction;
else if (args[1] == "encrypt" || args[1] == "decrypt" || args[1] == "2")
ask = tools::wallet2::AskPasswordToDecrypt;
else
{
fail_msg_writer() << tr("invalid argument: must be either 0/never, 1/action, or 2/encrypt/decrypt");
return true;
}
const tools::wallet2::AskPasswordType cur_ask = m_wallet->ask_password();
if (!m_wallet->watch_only())
{
if (cur_ask == tools::wallet2::AskPasswordToDecrypt && ask != tools::wallet2::AskPasswordToDecrypt)
m_wallet->decrypt_keys(pwd_container->password());
else if (cur_ask != tools::wallet2::AskPasswordToDecrypt && ask == tools::wallet2::AskPasswordToDecrypt)
m_wallet->encrypt_keys(pwd_container->password());
}
m_wallet->ask_password(ask);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
return true;
}
bool simple_wallet::set_unit(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const std::string &unit = args[1];
unsigned int decimal_point = CRYPTONOTE_DISPLAY_DECIMAL_POINT;
if (unit == "jyocoin")
decimal_point = CRYPTONOTE_DISPLAY_DECIMAL_POINT;
else if (unit == "millinero")
decimal_point = CRYPTONOTE_DISPLAY_DECIMAL_POINT - 3;
else if (unit == "micronero")
decimal_point = CRYPTONOTE_DISPLAY_DECIMAL_POINT - 6;
else if (unit == "nanonero")
decimal_point = CRYPTONOTE_DISPLAY_DECIMAL_POINT - 9;
else if (unit == "piconero")
decimal_point = 0;
else
{
fail_msg_writer() << tr("invalid unit");
return true;
}
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
cryptonote::set_default_decimal_point(decimal_point);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
return true;
}
bool simple_wallet::set_min_output_count(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
uint32_t count;
if (!string_tools::get_xtype_from_string(count, args[1]))
{
fail_msg_writer() << tr("invalid count: must be an unsigned integer");
return true;
}
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
m_wallet->set_min_output_count(count);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
return true;
}
bool simple_wallet::set_min_output_value(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
uint64_t value;
if (!cryptonote::parse_amount(value, args[1]))
{
fail_msg_writer() << tr("invalid value");
return true;
}
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
m_wallet->set_min_output_value(value);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
return true;
}
bool simple_wallet::set_merge_destinations(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
parse_bool_and_use(args[1], [&](bool r) {
m_wallet->merge_destinations(r);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
});
}
return true;
}
bool simple_wallet::set_confirm_backlog(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
parse_bool_and_use(args[1], [&](bool r) {
m_wallet->confirm_backlog(r);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
});
}
return true;
}
bool simple_wallet::set_confirm_backlog_threshold(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
uint32_t threshold;
if (!string_tools::get_xtype_from_string(threshold, args[1]))
{
fail_msg_writer() << tr("invalid count: must be an unsigned integer");
return true;
}
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
m_wallet->set_confirm_backlog_threshold(threshold);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
return true;
}
bool simple_wallet::set_confirm_export_overwrite(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
parse_bool_and_use(args[1], [&](bool r) {
m_wallet->confirm_export_overwrite(r);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
});
}
return true;
}
bool simple_wallet::set_refresh_from_block_height(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
uint64_t height;
if (!epee::string_tools::get_xtype_from_string(height, args[1]))
{
fail_msg_writer() << tr("Invalid height");
return true;
}
m_wallet->set_refresh_from_block_height(height);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
return true;
}
bool simple_wallet::set_auto_low_priority(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
parse_bool_and_use(args[1], [&](bool r) {
m_wallet->auto_low_priority(r);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
});
}
return true;
}
bool simple_wallet::set_segregate_pre_fork_outputs(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
parse_bool_and_use(args[1], [&](bool r) {
m_wallet->segregate_pre_fork_outputs(r);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
});
}
return true;
}
bool simple_wallet::set_key_reuse_mitigation2(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
parse_bool_and_use(args[1], [&](bool r) {
m_wallet->key_reuse_mitigation2(r);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
});
}
return true;
}
bool simple_wallet::set_subaddress_lookahead(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
auto lookahead = parse_subaddress_lookahead(args[1]);
if (lookahead)
{
m_wallet->set_subaddress_lookahead(lookahead->first, lookahead->second);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
}
return true;
}
bool simple_wallet::set_segregation_height(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
uint64_t height;
if (!epee::string_tools::get_xtype_from_string(height, args[1]))
{
fail_msg_writer() << tr("Invalid height");
return true;
}
m_wallet->segregation_height(height);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
}
return true;
}
bool simple_wallet::set_ignore_fractional_outputs(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
parse_bool_and_use(args[1], [&](bool r) {
m_wallet->ignore_fractional_outputs(r);
m_wallet->rewrite(m_wallet_file, pwd_container->password());
});
}
return true;
}
bool simple_wallet::set_device_name(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
const auto pwd_container = get_and_verify_password();
if (pwd_container)
{
if (args.size() == 0){
fail_msg_writer() << tr("Device name not specified");
return true;
}
m_wallet->device_name(args[0]);
bool r = false;
try {
r = m_wallet->reconnect_device();
if (!r){
fail_msg_writer() << tr("Device reconnect failed");
}
} catch(const std::exception & e){
MWARNING("Device reconnect failed: " << e.what());
fail_msg_writer() << tr("Device reconnect failed: ") << e.what();
}
}
return true;
}
bool simple_wallet::help(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
if(args.empty())
{
success_msg_writer() << get_commands_str();
}
else
{
success_msg_writer() << get_command_usage(args);
}
return true;
}
simple_wallet::simple_wallet()
: m_allow_mismatched_daemon_version(false)
, m_refresh_progress_reporter(*this)
, m_idle_run(true)
, m_auto_refresh_enabled(false)
, m_auto_refresh_refreshing(false)
, m_in_manual_refresh(false)
, m_current_subaddress_account(0)
{
m_cmd_binder.set_handler("start_mining",
boost::bind(&simple_wallet::start_mining, this, _1),
tr("start_mining [<number_of_threads>] [bg_mining] [ignore_battery]"),
tr("Start mining in the daemon (bg_mining and ignore_battery are optional booleans)."));
m_cmd_binder.set_handler("stop_mining",
boost::bind(&simple_wallet::stop_mining, this, _1),
tr("Stop mining in the daemon."));
m_cmd_binder.set_handler("set_daemon",
boost::bind(&simple_wallet::set_daemon, this, _1),
tr("set_daemon <host>[:<port>] [trusted|untrusted]"),
tr("Set another daemon to connect to."));
m_cmd_binder.set_handler("save_bc",
boost::bind(&simple_wallet::save_bc, this, _1),
tr("Save the current blockchain data."));
m_cmd_binder.set_handler("refresh",
boost::bind(&simple_wallet::refresh, this, _1),
tr("Synchronize the transactions and balance."));
m_cmd_binder.set_handler("balance",
boost::bind(&simple_wallet::show_balance, this, _1),
tr("balance [detail]"),
tr("Show the wallet's balance of the currently selected account."));
m_cmd_binder.set_handler("incoming_transfers",
boost::bind(&simple_wallet::show_incoming_transfers, this, _1),
tr("incoming_transfers [available|unavailable] [verbose] [index=<N1>[,<N2>[,...]]]"),
tr("Show the incoming transfers, all or filtered by availability and address index."));
m_cmd_binder.set_handler("payments",
boost::bind(&simple_wallet::show_payments, this, _1),
tr("payments <PID_1> [<PID_2> ... <PID_N>]"),
tr("Show the payments for the given payment IDs."));
m_cmd_binder.set_handler("bc_height",
boost::bind(&simple_wallet::show_blockchain_height, this, _1),
tr("Show the blockchain height."));
m_cmd_binder.set_handler("transfer", boost::bind(&simple_wallet::transfer, this, _1),
tr("transfer [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] (<URI> | <address> <amount>) [<payment_id>]"),
tr("Transfer <amount> to <address>. If the parameter \"index=<N1>[,<N2>,...]\" is specified, the wallet uses outputs received by addresses of those indices. If omitted, the wallet randomly chooses address indices to be used. In any case, it tries its best not to combine outputs across multiple addresses. <priority> is the priority of the transaction. The higher the priority, the higher the transaction fee. Valid values in priority order (from lowest to highest) are: unimportant, normal, elevated, priority. If omitted, the default value (see the command \"set priority\") is used. <ring_size> is the number of inputs to include for untraceability. Multiple payments can be made at once by adding URI_2 or <address_2> <amount_2> etcetera (before the payment ID, if it's included)"));
m_cmd_binder.set_handler("locked_transfer",
boost::bind(&simple_wallet::locked_transfer, this, _1),
tr("locked_transfer [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] (<URI> | <addr> <amount>) <lockblocks> [<payment_id>]"),
tr("Transfer <amount> to <address> and lock it for <lockblocks> (max. 1000000). If the parameter \"index=<N1>[,<N2>,...]\" is specified, the wallet uses outputs received by addresses of those indices. If omitted, the wallet randomly chooses address indices to be used. In any case, it tries its best not to combine outputs across multiple addresses. <priority> is the priority of the transaction. The higher the priority, the higher the transaction fee. Valid values in priority order (from lowest to highest) are: unimportant, normal, elevated, priority. If omitted, the default value (see the command \"set priority\") is used. <ring_size> is the number of inputs to include for untraceability. Multiple payments can be made at once by adding URI_2 or <address_2> <amount_2> etcetera (before the payment ID, if it's included)"));
m_cmd_binder.set_handler("locked_sweep_all",
boost::bind(&simple_wallet::locked_sweep_all, this, _1),
tr("locked_sweep_all [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] <address> <lockblocks> [<payment_id>]"),
tr("Send all unlocked balance to an address and lock it for <lockblocks> (max. 1000000). If the parameter \"index<N1>[,<N2>,...]\" is specified, the wallet sweeps outputs received by those address indices. If omitted, the wallet randomly chooses an address index to be used. <priority> is the priority of the sweep. The higher the priority, the higher the transaction fee. Valid values in priority order (from lowest to highest) are: unimportant, normal, elevated, priority. If omitted, the default value (see the command \"set priority\") is used. <ring_size> is the number of inputs to include for untraceability."));
m_cmd_binder.set_handler("sweep_unmixable",
boost::bind(&simple_wallet::sweep_unmixable, this, _1),
tr("Send all unmixable outputs to yourself with ring_size 1"));
m_cmd_binder.set_handler("sweep_all", boost::bind(&simple_wallet::sweep_all, this, _1),
tr("sweep_all [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] [outputs=<N>] <address> [<payment_id>]"),
tr("Send all unlocked balance to an address. If the parameter \"index<N1>[,<N2>,...]\" is specified, the wallet sweeps outputs received by those address indices. If omitted, the wallet randomly chooses an address index to be used. If the parameter \"outputs=<N>\" is specified and N > 0, wallet splits the transaction into N even outputs."));
m_cmd_binder.set_handler("sweep_below",
boost::bind(&simple_wallet::sweep_below, this, _1),
tr("sweep_below <amount_threshold> [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] <address> [<payment_id>]"),
tr("Send all unlocked outputs below the threshold to an address."));
m_cmd_binder.set_handler("sweep_single",
boost::bind(&simple_wallet::sweep_single, this, _1),
tr("sweep_single [<priority>] [<ring_size>] [outputs=<N>] <key_image> <address> [<payment_id>]"),
tr("Send a single output of the given key image to an address without change."));
m_cmd_binder.set_handler("donate",
boost::bind(&simple_wallet::donate, this, _1),
tr("donate [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] <amount> [<payment_id>]"),
tr("Donate <amount> to the development team (donate.getjyocoin.org)."));
m_cmd_binder.set_handler("sign_transfer",
boost::bind(&simple_wallet::sign_transfer, this, _1),
tr("sign_transfer [export_raw]"),
tr("Sign a transaction from a file. If the parameter \"export_raw\" is specified, transaction raw hex data suitable for the daemon RPC /sendrawtransaction is exported."));
m_cmd_binder.set_handler("submit_transfer",
boost::bind(&simple_wallet::submit_transfer, this, _1),
tr("Submit a signed transaction from a file."));
m_cmd_binder.set_handler("set_log",
boost::bind(&simple_wallet::set_log, this, _1),
tr("set_log <level>|{+,-,}<categories>"),
tr("Change the current log detail (level must be <0-4>)."));
m_cmd_binder.set_handler("account",
boost::bind(&simple_wallet::account, this, _1),
tr("account\n"
" account new <label text with white spaces allowed>\n"
" account switch <index> \n"
" account label <index> <label text with white spaces allowed>\n"
" account tag <tag_name> <account_index_1> [<account_index_2> ...]\n"
" account untag <account_index_1> [<account_index_2> ...]\n"
" account tag_description <tag_name> <description>"),
tr("If no arguments are specified, the wallet shows all the existing accounts along with their balances.\n"
"If the \"new\" argument is specified, the wallet creates a new account with its label initialized by the provided label text (which can be empty).\n"
"If the \"switch\" argument is specified, the wallet switches to the account specified by <index>.\n"
"If the \"label\" argument is specified, the wallet sets the label of the account specified by <index> to the provided label text.\n"
"If the \"tag\" argument is specified, a tag <tag_name> is assigned to the specified accounts <account_index_1>, <account_index_2>, ....\n"
"If the \"untag\" argument is specified, the tags assigned to the specified accounts <account_index_1>, <account_index_2> ..., are removed.\n"
"If the \"tag_description\" argument is specified, the tag <tag_name> is assigned an arbitrary text <description>."));
m_cmd_binder.set_handler("address",
boost::bind(&simple_wallet::print_address, this, _1),
tr("address [ new <label text with white spaces allowed> | all | <index_min> [<index_max>] | label <index> <label text with white spaces allowed>]"),
tr("If no arguments are specified or <index> is specified, the wallet shows the default or specified address. If \"all\" is specified, the wallet shows all the existing addresses in the currently selected account. If \"new \" is specified, the wallet creates a new address with the provided label text (which can be empty). If \"label\" is specified, the wallet sets the label of the address specified by <index> to the provided label text."));
m_cmd_binder.set_handler("integrated_address",
boost::bind(&simple_wallet::print_integrated_address, this, _1),
tr("integrated_address [<payment_id> | <address>]"),
tr("Encode a payment ID into an integrated address for the current wallet public address (no argument uses a random payment ID), or decode an integrated address to standard address and payment ID"));
m_cmd_binder.set_handler("address_book",
boost::bind(&simple_wallet::address_book, this, _1),
tr("address_book [(add ((<address> [pid <id>])|<integrated address>) [<description possibly with whitespaces>])|(delete <index>)]"),
tr("Print all entries in the address book, optionally adding/deleting an entry to/from it."));
m_cmd_binder.set_handler("save",
boost::bind(&simple_wallet::save, this, _1),
tr("Save the wallet data."));
m_cmd_binder.set_handler("save_watch_only",
boost::bind(&simple_wallet::save_watch_only, this, _1),
tr("Save a watch-only keys file."));
m_cmd_binder.set_handler("viewkey",
boost::bind(&simple_wallet::viewkey, this, _1),
tr("Display the private view key."));
m_cmd_binder.set_handler("spendkey",
boost::bind(&simple_wallet::spendkey, this, _1),
tr("Display the private spend key."));
m_cmd_binder.set_handler("seed",
boost::bind(&simple_wallet::seed, this, _1),
tr("Display the Electrum-style mnemonic seed"));
m_cmd_binder.set_handler("set",
boost::bind(&simple_wallet::set_variable, this, _1),
tr("set <option> [<value>]"),
tr("Available options:\n "
"seed language\n "
" Set the wallet's seed language.\n "
"always-confirm-transfers <1|0>\n "
" Whether to confirm unsplit txes.\n "
"print-ring-members <1|0>\n "
" Whether to print detailed information about ring members during confirmation.\n "
"store-tx-info <1|0>\n "
" Whether to store outgoing tx info (destination address, payment ID, tx secret key) for future reference.\n "
"default-ring-size <n>\n "
" Set the default ring size (obsolete).\n "
"auto-refresh <1|0>\n "
" Whether to automatically synchronize new blocks from the daemon.\n "
"refresh-type <full|optimize-coinbase|no-coinbase|default>\n "
" Set the wallet's refresh behaviour.\n "
"priority [0|1|2|3|4]\n "
" Set the fee to default/unimportant/normal/elevated/priority.\n "
"confirm-missing-payment-id <1|0>\n "
"ask-password <0|1|2 (or never|action|decrypt)>\n "
"unit <jyocoin|millinero|micronero|nanonero|piconero>\n "
" Set the default jyocoin (sub-)unit.\n "
"min-outputs-count [n]\n "
" Try to keep at least that many outputs of value at least min-outputs-value.\n "
"min-outputs-value [n]\n "
" Try to keep at least min-outputs-count outputs of at least that value.\n "
"merge-destinations <1|0>\n "
" Whether to merge multiple payments to the same destination address.\n "
"confirm-backlog <1|0>\n "
" Whether to warn if there is transaction backlog.\n "
"confirm-backlog-threshold [n]\n "
" Set a threshold for confirm-backlog to only warn if the transaction backlog is greater than n blocks.\n "
"refresh-from-block-height [n]\n "
" Set the height before which to ignore blocks.\n "
"auto-low-priority <1|0>\n "
" Whether to automatically use the low priority fee level when it's safe to do so.\n "
"segregate-pre-fork-outputs <1|0>\n "
" Set this if you intend to spend outputs on both jyocoin AND a key reusing fork.\n "
"key-reuse-mitigation2 <1|0>\n "
" Set this if you are not sure whether you will spend on a key reusing jyocoin fork later.\n"
"subaddress-lookahead <major>:<minor>\n "
" Set the lookahead sizes for the subaddress hash table.\n "
" Set this if you are not sure whether you will spend on a key reusing jyocoin fork later.\n "
"segregation-height <n>\n "
" Set to the height of a key reusing fork you want to use, 0 to use default."));
m_cmd_binder.set_handler("encrypted_seed",
boost::bind(&simple_wallet::encrypted_seed, this, _1),
tr("Display the encrypted Electrum-style mnemonic seed."));
m_cmd_binder.set_handler("rescan_spent",
boost::bind(&simple_wallet::rescan_spent, this, _1),
tr("Rescan the blockchain for spent outputs."));
m_cmd_binder.set_handler("get_tx_key",
boost::bind(&simple_wallet::get_tx_key, this, _1),
tr("get_tx_key <txid>"),
tr("Get the transaction key (r) for a given <txid>."));
m_cmd_binder.set_handler("set_tx_key",
boost::bind(&simple_wallet::set_tx_key, this, _1),
tr("set_tx_key <txid> <tx_key>"),
tr("Set the transaction key (r) for a given <txid> in case the tx was made by some other device or 3rd party wallet."));
m_cmd_binder.set_handler("check_tx_key",
boost::bind(&simple_wallet::check_tx_key, this, _1),
tr("check_tx_key <txid> <txkey> <address>"),
tr("Check the amount going to <address> in <txid>."));
m_cmd_binder.set_handler("get_tx_proof",
boost::bind(&simple_wallet::get_tx_proof, this, _1),
tr("get_tx_proof <txid> <address> [<message>]"),
tr("Generate a signature proving funds sent to <address> in <txid>, optionally with a challenge string <message>, using either the transaction secret key (when <address> is not your wallet's address) or the view secret key (otherwise), which does not disclose the secret key."));
m_cmd_binder.set_handler("check_tx_proof",
boost::bind(&simple_wallet::check_tx_proof, this, _1),
tr("check_tx_proof <txid> <address> <signature_file> [<message>]"),
tr("Check the proof for funds going to <address> in <txid> with the challenge string <message> if any."));
m_cmd_binder.set_handler("get_spend_proof",
boost::bind(&simple_wallet::get_spend_proof, this, _1),
tr("get_spend_proof <txid> [<message>]"),
tr("Generate a signature proving that you generated <txid> using the spend secret key, optionally with a challenge string <message>."));
m_cmd_binder.set_handler("check_spend_proof",
boost::bind(&simple_wallet::check_spend_proof, this, _1),
tr("check_spend_proof <txid> <signature_file> [<message>]"),
tr("Check a signature proving that the signer generated <txid>, optionally with a challenge string <message>."));
m_cmd_binder.set_handler("get_reserve_proof",
boost::bind(&simple_wallet::get_reserve_proof, this, _1),
tr("get_reserve_proof (all|<amount>) [<message>]"),
tr("Generate a signature proving that you own at least this much, optionally with a challenge string <message>.\n"
"If 'all' is specified, you prove the entire sum of all of your existing accounts' balances.\n"
"Otherwise, you prove the reserve of the smallest possible amount above <amount> available in your current account."));
m_cmd_binder.set_handler("check_reserve_proof",
boost::bind(&simple_wallet::check_reserve_proof, this, _1),
tr("check_reserve_proof <address> <signature_file> [<message>]"),
tr("Check a signature proving that the owner of <address> holds at least this much, optionally with a challenge string <message>."));
m_cmd_binder.set_handler("show_transfers",
boost::bind(&simple_wallet::show_transfers, this, _1),
tr("show_transfers [in|out|pending|failed|pool|coinbase] [index=<N1>[,<N2>,...]] [<min_height> [<max_height>]]"),
// Seemingly broken formatting to compensate for the backslash before the quotes.
tr("Show the incoming/outgoing transfers within an optional height range.\n\n"
"Output format:\n"
"In or Coinbase: Block Number, \"block\"|\"in\", Time, Amount, Transaction Hash, Payment ID, Subaddress Index, \"-\", Note\n"
"Out: Block Number, \"out\", Time, Amount*, Transaction Hash, Payment ID, Fee, Destinations, Input addresses**, \"-\", Note\n"
"Pool: \"pool\", \"in\", Time, Amount, Transaction Hash, Payment Id, Subaddress Index, \"-\", Note, Double Spend Note\n"
"Pending or Failed: \"failed\"|\"pending\", \"out\", Time, Amount*, Transaction Hash, Payment ID, Fee, Input addresses**, \"-\", Note\n\n"
"* Excluding change and fee.\n"
"** Set of address indices used as inputs in this transfer."));
m_cmd_binder.set_handler("export_transfers",
boost::bind(&simple_wallet::export_transfers, this, _1),
tr("export_transfers [in|out|all|pending|failed|coinbase] [index=<N1>[,<N2>,...]] [<min_height> [<max_height>]] [output=<filepath>]"),
tr("Export to CSV the incoming/outgoing transfers within an optional height range."));
m_cmd_binder.set_handler("unspent_outputs",
boost::bind(&simple_wallet::unspent_outputs, this, _1),
tr("unspent_outputs [index=<N1>[,<N2>,...]] [<min_amount> [<max_amount>]]"),
tr("Show the unspent outputs of a specified address within an optional amount range."));
m_cmd_binder.set_handler("rescan_bc",
boost::bind(&simple_wallet::rescan_blockchain, this, _1),
tr("rescan_bc [hard]"),
tr("Rescan the blockchain from scratch, losing any information which can not be recovered from the blockchain itself."));
m_cmd_binder.set_handler("set_tx_note",
boost::bind(&simple_wallet::set_tx_note, this, _1),
tr("set_tx_note <txid> [free text note]"),
tr("Set an arbitrary string note for a <txid>."));
m_cmd_binder.set_handler("get_tx_note",
boost::bind(&simple_wallet::get_tx_note, this, _1),
tr("get_tx_note <txid>"),
tr("Get a string note for a txid."));
m_cmd_binder.set_handler("set_description",
boost::bind(&simple_wallet::set_description, this, _1),
tr("set_description [free text note]"),
tr("Set an arbitrary description for the wallet."));
m_cmd_binder.set_handler("get_description",
boost::bind(&simple_wallet::get_description, this, _1),
tr("Get the description of the wallet."));
m_cmd_binder.set_handler("status",
boost::bind(&simple_wallet::status, this, _1),
tr("Show the wallet's status."));
m_cmd_binder.set_handler("wallet_info",
boost::bind(&simple_wallet::wallet_info, this, _1),
tr("Show the wallet's information."));
m_cmd_binder.set_handler("sign",
boost::bind(&simple_wallet::sign, this, _1),
tr("sign <file>"),
tr("Sign the contents of a file."));
m_cmd_binder.set_handler("verify",
boost::bind(&simple_wallet::verify, this, _1),
tr("verify <filename> <address> <signature>"),
tr("Verify a signature on the contents of a file."));
m_cmd_binder.set_handler("export_key_images",
boost::bind(&simple_wallet::export_key_images, this, _1),
tr("export_key_images <file>"),
tr("Export a signed set of key images to a <file>."));
m_cmd_binder.set_handler("import_key_images",
boost::bind(&simple_wallet::import_key_images, this, _1),
tr("import_key_images <file>"),
tr("Import a signed key images list and verify their spent status."));
m_cmd_binder.set_handler("hw_key_images_sync",
boost::bind(&simple_wallet::hw_key_images_sync, this, _1),
tr("hw_key_images_sync"),
tr("Synchronizes key images with the hw wallet."));
m_cmd_binder.set_handler("hw_reconnect",
boost::bind(&simple_wallet::hw_reconnect, this, _1),
tr("hw_reconnect"),
tr("Attempts to reconnect HW wallet."));
m_cmd_binder.set_handler("export_outputs",
boost::bind(&simple_wallet::export_outputs, this, _1),
tr("export_outputs <file>"),
tr("Export a set of outputs owned by this wallet."));
m_cmd_binder.set_handler("import_outputs",
boost::bind(&simple_wallet::import_outputs, this, _1),
tr("import_outputs <file>"),
tr("Import a set of outputs owned by this wallet."));
m_cmd_binder.set_handler("show_transfer",
boost::bind(&simple_wallet::show_transfer, this, _1),
tr("show_transfer <txid>"),
tr("Show information about a transfer to/from this address."));
m_cmd_binder.set_handler("password",
boost::bind(&simple_wallet::change_password, this, _1),
tr("Change the wallet's password."));
m_cmd_binder.set_handler("payment_id",
boost::bind(&simple_wallet::payment_id, this, _1),
tr("Generate a new random full size payment id. These will be unencrypted on the blockchain, see integrated_address for encrypted short payment ids."));
m_cmd_binder.set_handler("fee",
boost::bind(&simple_wallet::print_fee_info, this, _1),
tr("Print the information about the current fee and transaction backlog."));
m_cmd_binder.set_handler("prepare_multisig", boost::bind(&simple_wallet::prepare_multisig, this, _1),
tr("Export data needed to create a multisig wallet"));
m_cmd_binder.set_handler("make_multisig", boost::bind(&simple_wallet::make_multisig, this, _1),
tr("make_multisig <threshold> <string1> [<string>...]"),
tr("Turn this wallet into a multisig wallet"));
m_cmd_binder.set_handler("finalize_multisig",
boost::bind(&simple_wallet::finalize_multisig, this, _1),
tr("finalize_multisig <string> [<string>...]"),
tr("Turn this wallet into a multisig wallet, extra step for N-1/N wallets"));
m_cmd_binder.set_handler("exchange_multisig_keys",
boost::bind(&simple_wallet::exchange_multisig_keys, this, _1),
tr("exchange_multisig_keys <string> [<string>...]"),
tr("Performs extra multisig keys exchange rounds. Needed for arbitrary M/N multisig wallets"));
m_cmd_binder.set_handler("export_multisig_info",
boost::bind(&simple_wallet::export_multisig, this, _1),
tr("export_multisig_info <filename>"),
tr("Export multisig info for other participants"));
m_cmd_binder.set_handler("import_multisig_info",
boost::bind(&simple_wallet::import_multisig, this, _1),
tr("import_multisig_info <filename> [<filename>...]"),
tr("Import multisig info from other participants"));
m_cmd_binder.set_handler("sign_multisig",
boost::bind(&simple_wallet::sign_multisig, this, _1),
tr("sign_multisig <filename>"),
tr("Sign a multisig transaction from a file"));
m_cmd_binder.set_handler("submit_multisig",
boost::bind(&simple_wallet::submit_multisig, this, _1),
tr("submit_multisig <filename>"),
tr("Submit a signed multisig transaction from a file"));
m_cmd_binder.set_handler("export_raw_multisig_tx",
boost::bind(&simple_wallet::export_raw_multisig, this, _1),
tr("export_raw_multisig_tx <filename>"),
tr("Export a signed multisig transaction to a file"));
m_cmd_binder.set_handler("print_ring",
boost::bind(&simple_wallet::print_ring, this, _1),
tr("print_ring <key_image> | <txid>"),
tr("Print the ring(s) used to spend a given key image or transaction (if the ring size is > 1)"));
m_cmd_binder.set_handler("set_ring",
boost::bind(&simple_wallet::set_ring, this, _1),
tr("set_ring <filename> | ( <key_image> absolute|relative <index> [<index>...] )"),
tr("Set the ring used for a given key image, so it can be reused in a fork"));
m_cmd_binder.set_handler("save_known_rings",
boost::bind(&simple_wallet::save_known_rings, this, _1),
tr("save_known_rings"),
tr("Save known rings to the shared rings database"));
m_cmd_binder.set_handler("mark_output_spent",
boost::bind(&simple_wallet::blackball, this, _1),
tr("mark_output_spent <amount>/<offset> | <filename> [add]"),
tr("Mark output(s) as spent so they never get selected as fake outputs in a ring"));
m_cmd_binder.set_handler("mark_output_unspent",
boost::bind(&simple_wallet::unblackball, this, _1),
tr("mark_output_unspent <amount>/<offset>"),
tr("Marks an output as unspent so it may get selected as a fake output in a ring"));
m_cmd_binder.set_handler("is_output_spent",
boost::bind(&simple_wallet::blackballed, this, _1),
tr("is_output_spent <amount>/<offset>"),
tr("Checks whether an output is marked as spent"));
m_cmd_binder.set_handler("version",
boost::bind(&simple_wallet::version, this, _1),
tr("version"),
tr("Returns version information"));
m_cmd_binder.set_handler("help",
boost::bind(&simple_wallet::help, this, _1),
tr("help [<command>]"),
tr("Show the help section or the documentation about a <command>."));
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::set_variable(const std::vector<std::string> &args)
{
if (args.empty())
{
std::string seed_language = m_wallet->get_seed_language();
if (m_use_english_language_names)
seed_language = crypto::ElectrumWords::get_english_name_for(seed_language);
std::string priority_string = "invalid";
uint32_t priority = m_wallet->get_default_priority();
if (priority < allowed_priority_strings.size())
priority_string = allowed_priority_strings[priority];
std::string ask_password_string = "invalid";
switch (m_wallet->ask_password())
{
case tools::wallet2::AskPasswordNever: ask_password_string = "never"; break;
case tools::wallet2::AskPasswordOnAction: ask_password_string = "action"; break;
case tools::wallet2::AskPasswordToDecrypt: ask_password_string = "decrypt"; break;
}
success_msg_writer() << "seed = " << seed_language;
success_msg_writer() << "always-confirm-transfers = " << m_wallet->always_confirm_transfers();
success_msg_writer() << "print-ring-members = " << m_wallet->print_ring_members();
success_msg_writer() << "store-tx-info = " << m_wallet->store_tx_info();
success_msg_writer() << "default-ring-size = " << (m_wallet->default_mixin() ? m_wallet->default_mixin() + 1 : 0);
success_msg_writer() << "auto-refresh = " << m_wallet->auto_refresh();
success_msg_writer() << "refresh-type = " << get_refresh_type_name(m_wallet->get_refresh_type());
success_msg_writer() << "priority = " << priority<< " (" << priority_string << ")";
success_msg_writer() << "confirm-missing-payment-id = " << m_wallet->confirm_missing_payment_id();
success_msg_writer() << "ask-password = " << m_wallet->ask_password() << " (" << ask_password_string << ")";
success_msg_writer() << "unit = " << cryptonote::get_unit(cryptonote::get_default_decimal_point());
success_msg_writer() << "min-outputs-count = " << m_wallet->get_min_output_count();
success_msg_writer() << "min-outputs-value = " << cryptonote::print_money(m_wallet->get_min_output_value());
success_msg_writer() << "merge-destinations = " << m_wallet->merge_destinations();
success_msg_writer() << "confirm-backlog = " << m_wallet->confirm_backlog();
success_msg_writer() << "confirm-backlog-threshold = " << m_wallet->get_confirm_backlog_threshold();
success_msg_writer() << "confirm-export-overwrite = " << m_wallet->confirm_export_overwrite();
success_msg_writer() << "refresh-from-block-height = " << m_wallet->get_refresh_from_block_height();
success_msg_writer() << "auto-low-priority = " << m_wallet->auto_low_priority();
success_msg_writer() << "segregate-pre-fork-outputs = " << m_wallet->segregate_pre_fork_outputs();
success_msg_writer() << "key-reuse-mitigation2 = " << m_wallet->key_reuse_mitigation2();
const std::pair<size_t, size_t> lookahead = m_wallet->get_subaddress_lookahead();
success_msg_writer() << "subaddress-lookahead = " << lookahead.first << ":" << lookahead.second;
success_msg_writer() << "segregation-height = " << m_wallet->segregation_height();
success_msg_writer() << "ignore-fractional-outputs = " << m_wallet->ignore_fractional_outputs();
success_msg_writer() << "device_name = " << m_wallet->device_name();
return true;
}
else
{
#define CHECK_SIMPLE_VARIABLE(name, f, help) do \
if (args[0] == name) { \
if (args.size() <= 1) \
{ \
fail_msg_writer() << "set " << #name << ": " << tr("needs an argument") << " (" << help << ")"; \
return true; \
} \
else \
{ \
f(args); \
return true; \
} \
} while(0)
if (args[0] == "seed")
{
if (args.size() == 1)
{
fail_msg_writer() << tr("set seed: needs an argument. available options: language");
return true;
}
else if (args[1] == "language")
{
seed_set_language(args);
return true;
}
}
CHECK_SIMPLE_VARIABLE("always-confirm-transfers", set_always_confirm_transfers, tr("0 or 1"));
CHECK_SIMPLE_VARIABLE("print-ring-members", set_print_ring_members, tr("0 or 1"));
CHECK_SIMPLE_VARIABLE("store-tx-info", set_store_tx_info, tr("0 or 1"));
CHECK_SIMPLE_VARIABLE("default-ring-size", set_default_ring_size, tr("integer >= ") << MIN_RING_SIZE);
CHECK_SIMPLE_VARIABLE("auto-refresh", set_auto_refresh, tr("0 or 1"));
CHECK_SIMPLE_VARIABLE("refresh-type", set_refresh_type, tr("full (slowest, no assumptions); optimize-coinbase (fast, assumes the whole coinbase is paid to a single address); no-coinbase (fastest, assumes we receive no coinbase transaction), default (same as optimize-coinbase)"));
CHECK_SIMPLE_VARIABLE("priority", set_default_priority, tr("0, 1, 2, 3, or 4, or one of ") << join_priority_strings(", "));
CHECK_SIMPLE_VARIABLE("confirm-missing-payment-id", set_confirm_missing_payment_id, tr("0 or 1"));
CHECK_SIMPLE_VARIABLE("ask-password", set_ask_password, tr("0|1|2 (or never|action|decrypt)"));
CHECK_SIMPLE_VARIABLE("unit", set_unit, tr("jyocoin, millinero, micronero, nanonero, piconero"));
CHECK_SIMPLE_VARIABLE("min-outputs-count", set_min_output_count, tr("unsigned integer"));
CHECK_SIMPLE_VARIABLE("min-outputs-value", set_min_output_value, tr("amount"));
CHECK_SIMPLE_VARIABLE("merge-destinations", set_merge_destinations, tr("0 or 1"));
CHECK_SIMPLE_VARIABLE("confirm-backlog", set_confirm_backlog, tr("0 or 1"));
CHECK_SIMPLE_VARIABLE("confirm-backlog-threshold", set_confirm_backlog_threshold, tr("unsigned integer"));
CHECK_SIMPLE_VARIABLE("confirm-export-overwrite", set_confirm_export_overwrite, tr("0 or 1"));
CHECK_SIMPLE_VARIABLE("refresh-from-block-height", set_refresh_from_block_height, tr("block height"));
CHECK_SIMPLE_VARIABLE("auto-low-priority", set_auto_low_priority, tr("0 or 1"));
CHECK_SIMPLE_VARIABLE("segregate-pre-fork-outputs", set_segregate_pre_fork_outputs, tr("0 or 1"));
CHECK_SIMPLE_VARIABLE("key-reuse-mitigation2", set_key_reuse_mitigation2, tr("0 or 1"));
CHECK_SIMPLE_VARIABLE("subaddress-lookahead", set_subaddress_lookahead, tr("<major>:<minor>"));
CHECK_SIMPLE_VARIABLE("segregation-height", set_segregation_height, tr("unsigned integer"));
CHECK_SIMPLE_VARIABLE("ignore-fractional-outputs", set_ignore_fractional_outputs, tr("0 or 1"));
CHECK_SIMPLE_VARIABLE("device-name", set_device_name, tr("<device_name[:device_spec]>"));
}
fail_msg_writer() << tr("set: unrecognized argument(s)");
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::set_log(const std::vector<std::string> &args)
{
if(args.size() > 1)
{
fail_msg_writer() << tr("usage: set_log <log_level_number_0-4> | <categories>");
return true;
}
if(!args.empty())
{
uint16_t level = 0;
if(epee::string_tools::get_xtype_from_string(level, args[0]))
{
if(4 < level)
{
fail_msg_writer() << tr("wrong number range, use: set_log <log_level_number_0-4> | <categories>");
return true;
}
mlog_set_log_level(level);
}
else
{
mlog_set_log(args[0].c_str());
}
}
success_msg_writer() << "New log categories: " << mlog_get_categories();
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::ask_wallet_create_if_needed()
{
LOG_PRINT_L3("simple_wallet::ask_wallet_create_if_needed() started");
std::string wallet_path;
std::string confirm_creation;
bool wallet_name_valid = false;
bool keys_file_exists;
bool wallet_file_exists;
do{
LOG_PRINT_L3("User asked to specify wallet file name.");
wallet_path = input_line(
tr(m_restoring ? "Specify a new wallet file name for your restored wallet (e.g., MyWallet).\n"
"Wallet file name (or Ctrl-C to quit): " :
"Specify wallet file name (e.g., MyWallet). If the wallet doesn't exist, it will be created.\n"
"Wallet file name (or Ctrl-C to quit): ")
);
if(std::cin.eof())
{
LOG_ERROR("Unexpected std::cin.eof() - Exited simple_wallet::ask_wallet_create_if_needed()");
return false;
}
if(!tools::wallet2::wallet_valid_path_format(wallet_path))
{
fail_msg_writer() << tr("Wallet name not valid. Please try again or use Ctrl-C to quit.");
wallet_name_valid = false;
}
else
{
tools::wallet2::wallet_exists(wallet_path, keys_file_exists, wallet_file_exists);
LOG_PRINT_L3("wallet_path: " << wallet_path << "");
LOG_PRINT_L3("keys_file_exists: " << std::boolalpha << keys_file_exists << std::noboolalpha
<< " wallet_file_exists: " << std::boolalpha << wallet_file_exists << std::noboolalpha);
if((keys_file_exists || wallet_file_exists) && (!m_generate_new.empty() || m_restoring))
{
fail_msg_writer() << tr("Attempting to generate or restore wallet, but specified file(s) exist. Exiting to not risk overwriting.");
return false;
}
if(wallet_file_exists && keys_file_exists) //Yes wallet, yes keys
{
success_msg_writer() << tr("Wallet and key files found, loading...");
m_wallet_file = wallet_path;
return true;
}
else if(!wallet_file_exists && keys_file_exists) //No wallet, yes keys
{
success_msg_writer() << tr("Key file found but not wallet file. Regenerating...");
m_wallet_file = wallet_path;
return true;
}
else if(wallet_file_exists && !keys_file_exists) //Yes wallet, no keys
{
fail_msg_writer() << tr("Key file not found. Failed to open wallet: ") << "\"" << wallet_path << "\". Exiting.";
return false;
}
else if(!wallet_file_exists && !keys_file_exists) //No wallet, no keys
{
bool ok = true;
if (!m_restoring)
{
message_writer() << tr("No wallet found with that name. Confirm creation of new wallet named: ") << wallet_path;
confirm_creation = input_line(tr("(Y/Yes/N/No): "));
if(std::cin.eof())
{
LOG_ERROR("Unexpected std::cin.eof() - Exited simple_wallet::ask_wallet_create_if_needed()");
return false;
}
ok = command_line::is_yes(confirm_creation);
}
if (ok)
{
success_msg_writer() << tr("Generating new wallet...");
m_generate_new = wallet_path;
return true;
}
}
}
} while(!wallet_name_valid);
LOG_ERROR("Failed out of do-while loop in ask_wallet_create_if_needed()");
return false;
}
/*!
* \brief Prints the seed with a nice message
* \param seed seed to print
*/
void simple_wallet::print_seed(const epee::wipeable_string &seed)
{
success_msg_writer(true) << "\n" << boost::format(tr("NOTE: the following %s can be used to recover access to your wallet. "
"Write them down and store them somewhere safe and secure. Please do not store them in "
"your email or on file storage services outside of your immediate control.\n")) % (m_wallet->multisig() ? tr("string") : tr("25 words"));
// don't log
int space_index = 0;
size_t len = seed.size();
for (const char *ptr = seed.data(); len--; ++ptr)
{
if (*ptr == ' ')
{
if (space_index == 15 || space_index == 7)
putchar('\n');
else
putchar(*ptr);
++space_index;
}
else
putchar(*ptr);
}
putchar('\n');
fflush(stdout);
}
//----------------------------------------------------------------------------------------------------
static bool might_be_partial_seed(const epee::wipeable_string &words)
{
std::vector<epee::wipeable_string> seed;
words.split(seed);
return seed.size() < 24;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::init(const boost::program_options::variables_map& vm)
{
epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){
m_electrum_seed.wipe();
});
const bool testnet = tools::wallet2::has_testnet_option(vm);
const bool stagenet = tools::wallet2::has_stagenet_option(vm);
if (testnet && stagenet)
{
fail_msg_writer() << tr("Can't specify more than one of --testnet and --stagenet");
return false;
}
const network_type nettype = testnet ? TESTNET : stagenet ? STAGENET : MAINNET;
epee::wipeable_string multisig_keys;
if (!handle_command_line(vm))
return false;
if((!m_generate_new.empty()) + (!m_wallet_file.empty()) + (!m_generate_from_device.empty()) + (!m_generate_from_view_key.empty()) + (!m_generate_from_spend_key.empty()) + (!m_generate_from_keys.empty()) + (!m_generate_from_multisig_keys.empty()) + (!m_generate_from_json.empty()) > 1)
{
fail_msg_writer() << tr("can't specify more than one of --generate-new-wallet=\"wallet_name\", --wallet-file=\"wallet_name\", --generate-from-view-key=\"wallet_name\", --generate-from-spend-key=\"wallet_name\", --generate-from-keys=\"wallet_name\", --generate-from-multisig-keys=\"wallet_name\", --generate-from-json=\"jsonfilename\" and --generate-from-device=\"wallet_name\"");
return false;
}
else if (m_generate_new.empty() && m_wallet_file.empty() && m_generate_from_device.empty() && m_generate_from_view_key.empty() && m_generate_from_spend_key.empty() && m_generate_from_keys.empty() && m_generate_from_multisig_keys.empty() && m_generate_from_json.empty())
{
if(!ask_wallet_create_if_needed()) return false;
}
if (!m_generate_new.empty() || m_restoring)
{
if (!m_subaddress_lookahead.empty() && !parse_subaddress_lookahead(m_subaddress_lookahead))
return false;
std::string old_language;
// check for recover flag. if present, require electrum word list (only recovery option for now).
if (m_restore_deterministic_wallet || m_restore_multisig_wallet)
{
if (m_non_deterministic)
{
fail_msg_writer() << tr("can't specify both --restore-deterministic-wallet or --restore-multisig-wallet and --non-deterministic");
return false;
}
if (!m_wallet_file.empty())
{
if (m_restore_multisig_wallet)
fail_msg_writer() << tr("--restore-multisig-wallet uses --generate-new-wallet, not --wallet-file");
else
fail_msg_writer() << tr("--restore-deterministic-wallet uses --generate-new-wallet, not --wallet-file");
return false;
}
if (m_electrum_seed.empty())
{
if (m_restore_multisig_wallet)
{
const char *prompt = "Specify multisig seed";
m_electrum_seed = input_secure_line(prompt);
if (std::cin.eof())
return false;
if (m_electrum_seed.empty())
{
fail_msg_writer() << tr("specify a recovery parameter with the --electrum-seed=\"multisig seed here\"");
return false;
}
}
else
{
m_electrum_seed = "";
do
{
const char *prompt = m_electrum_seed.empty() ? "Specify Electrum seed" : "Electrum seed continued";
epee::wipeable_string electrum_seed = input_secure_line(prompt);
if (std::cin.eof())
return false;
if (electrum_seed.empty())
{
fail_msg_writer() << tr("specify a recovery parameter with the --electrum-seed=\"words list here\"");
return false;
}
m_electrum_seed += electrum_seed;
m_electrum_seed += ' ';
} while (might_be_partial_seed(m_electrum_seed));
}
}
if (m_restore_multisig_wallet)
{
const boost::optional<epee::wipeable_string> parsed = m_electrum_seed.parse_hexstr();
if (!parsed)
{
fail_msg_writer() << tr("Multisig seed failed verification");
return false;
}
multisig_keys = *parsed;
}
else
{
if (!crypto::ElectrumWords::words_to_bytes(m_electrum_seed, m_recovery_key, old_language))
{
fail_msg_writer() << tr("Electrum-style word list failed verification");
return false;
}
}
auto pwd_container = password_prompter(tr("Enter seed offset passphrase, empty if none"), false);
if (std::cin.eof() || !pwd_container)
return false;
epee::wipeable_string seed_pass = pwd_container->password();
if (!seed_pass.empty())
{
if (m_restore_multisig_wallet)
{
crypto::secret_key key;
crypto::cn_slow_hash(seed_pass.data(), seed_pass.size(), (crypto::hash&)key);
sc_reduce32((unsigned char*)key.data);
multisig_keys = m_wallet->decrypt<epee::wipeable_string>(std::string(multisig_keys.data(), multisig_keys.size()), key, true);
}
else
m_recovery_key = cryptonote::decrypt_key(m_recovery_key, seed_pass);
}
}
epee::wipeable_string password;
if (!m_generate_from_view_key.empty())
{
m_wallet_file = m_generate_from_view_key;
// parse address
std::string address_string = input_line("Standard address: ");
if (std::cin.eof())
return false;
if (address_string.empty()) {
fail_msg_writer() << tr("No data supplied, cancelled");
return false;
}
cryptonote::address_parse_info info;
if(!get_account_address_from_str(info, nettype, address_string))
{
fail_msg_writer() << tr("failed to parse address");
return false;
}
if (info.is_subaddress)
{
fail_msg_writer() << tr("This address is a subaddress which cannot be used here.");
return false;
}
// parse view secret key
epee::wipeable_string viewkey_string = input_secure_line("Secret view key: ");
if (std::cin.eof())
return false;
if (viewkey_string.empty()) {
fail_msg_writer() << tr("No data supplied, cancelled");
return false;
}
crypto::secret_key viewkey;
if (!viewkey_string.hex_to_pod(unwrap(unwrap(viewkey))))
{
fail_msg_writer() << tr("failed to parse view key secret key");
return false;
}
m_wallet_file=m_generate_from_view_key;
// check the view key matches the given address
crypto::public_key pkey;
if (!crypto::secret_key_to_public_key(viewkey, pkey)) {
fail_msg_writer() << tr("failed to verify view key secret key");
return false;
}
if (info.address.m_view_public_key != pkey) {
fail_msg_writer() << tr("view key does not match standard address");
return false;
}
auto r = new_wallet(vm, info.address, boost::none, viewkey);
CHECK_AND_ASSERT_MES(r, false, tr("account creation failed"));
password = *r;
}
else if (!m_generate_from_spend_key.empty())
{
m_wallet_file = m_generate_from_spend_key;
// parse spend secret key
epee::wipeable_string spendkey_string = input_secure_line("Secret spend key: ");
if (std::cin.eof())
return false;
if (spendkey_string.empty()) {
fail_msg_writer() << tr("No data supplied, cancelled");
return false;
}
if (!spendkey_string.hex_to_pod(unwrap(unwrap(m_recovery_key))))
{
fail_msg_writer() << tr("failed to parse spend key secret key");
return false;
}
auto r = new_wallet(vm, m_recovery_key, true, false, "");
CHECK_AND_ASSERT_MES(r, false, tr("account creation failed"));
password = *r;
}
else if (!m_generate_from_keys.empty())
{
m_wallet_file = m_generate_from_keys;
// parse address
std::string address_string = input_line("Standard address: ");
if (std::cin.eof())
return false;
if (address_string.empty()) {
fail_msg_writer() << tr("No data supplied, cancelled");
return false;
}
cryptonote::address_parse_info info;
if(!get_account_address_from_str(info, nettype, address_string))
{
fail_msg_writer() << tr("failed to parse address");
return false;
}
if (info.is_subaddress)
{
fail_msg_writer() << tr("This address is a subaddress which cannot be used here.");
return false;
}
// parse spend secret key
epee::wipeable_string spendkey_string = input_secure_line("Secret spend key: ");
if (std::cin.eof())
return false;
if (spendkey_string.empty()) {
fail_msg_writer() << tr("No data supplied, cancelled");
return false;
}
crypto::secret_key spendkey;
if (!spendkey_string.hex_to_pod(unwrap(unwrap(spendkey))))
{
fail_msg_writer() << tr("failed to parse spend key secret key");
return false;
}
// parse view secret key
epee::wipeable_string viewkey_string = input_secure_line("Secret view key: ");
if (std::cin.eof())
return false;
if (viewkey_string.empty()) {
fail_msg_writer() << tr("No data supplied, cancelled");
return false;
}
crypto::secret_key viewkey;
if(!viewkey_string.hex_to_pod(unwrap(unwrap(viewkey))))
{
fail_msg_writer() << tr("failed to parse view key secret key");
return false;
}
m_wallet_file=m_generate_from_keys;
// check the spend and view keys match the given address
crypto::public_key pkey;
if (!crypto::secret_key_to_public_key(spendkey, pkey)) {
fail_msg_writer() << tr("failed to verify spend key secret key");
return false;
}
if (info.address.m_spend_public_key != pkey) {
fail_msg_writer() << tr("spend key does not match standard address");
return false;
}
if (!crypto::secret_key_to_public_key(viewkey, pkey)) {
fail_msg_writer() << tr("failed to verify view key secret key");
return false;
}
if (info.address.m_view_public_key != pkey) {
fail_msg_writer() << tr("view key does not match standard address");
return false;
}
auto r = new_wallet(vm, info.address, spendkey, viewkey);
CHECK_AND_ASSERT_MES(r, false, tr("account creation failed"));
password = *r;
}
// Asks user for all the data required to merge secret keys from multisig wallets into one master wallet, which then gets full control of the multisig wallet. The resulting wallet will be the same as any other regular wallet.
else if (!m_generate_from_multisig_keys.empty())
{
m_wallet_file = m_generate_from_multisig_keys;
unsigned int multisig_m;
unsigned int multisig_n;
// parse multisig type
std::string multisig_type_string = input_line("Multisig type (input as M/N with M <= N and M > 1): ");
if (std::cin.eof())
return false;
if (multisig_type_string.empty())
{
fail_msg_writer() << tr("No data supplied, cancelled");
return false;
}
if (sscanf(multisig_type_string.c_str(), "%u/%u", &multisig_m, &multisig_n) != 2)
{
fail_msg_writer() << tr("Error: expected M/N, but got: ") << multisig_type_string;
return false;
}
if (multisig_m <= 1 || multisig_m > multisig_n)
{
fail_msg_writer() << tr("Error: expected N > 1 and N <= M, but got: ") << multisig_type_string;
return false;
}
if (multisig_m != multisig_n)
{
fail_msg_writer() << tr("Error: M/N is currently unsupported. ");
return false;
}
message_writer() << boost::format(tr("Generating master wallet from %u of %u multisig wallet keys")) % multisig_m % multisig_n;
// parse multisig address
std::string address_string = input_line("Multisig wallet address: ");
if (std::cin.eof())
return false;
if (address_string.empty()) {
fail_msg_writer() << tr("No data supplied, cancelled");
return false;
}
cryptonote::address_parse_info info;
if(!get_account_address_from_str(info, nettype, address_string))
{
fail_msg_writer() << tr("failed to parse address");
return false;
}
// parse secret view key
epee::wipeable_string viewkey_string = input_secure_line("Secret view key: ");
if (std::cin.eof())
return false;
if (viewkey_string.empty())
{
fail_msg_writer() << tr("No data supplied, cancelled");
return false;
}
crypto::secret_key viewkey;
if(!viewkey_string.hex_to_pod(unwrap(unwrap(viewkey))))
{
fail_msg_writer() << tr("failed to parse secret view key");
return false;
}
// check that the view key matches the given address
crypto::public_key pkey;
if (!crypto::secret_key_to_public_key(viewkey, pkey))
{
fail_msg_writer() << tr("failed to verify secret view key");
return false;
}
if (info.address.m_view_public_key != pkey)
{
fail_msg_writer() << tr("view key does not match standard address");
return false;
}
// parse multisig spend keys
crypto::secret_key spendkey;
// parsing N/N
if(multisig_m == multisig_n)
{
std::vector<crypto::secret_key> multisig_secret_spendkeys(multisig_n);
epee::wipeable_string spendkey_string;
cryptonote::blobdata spendkey_data;
// get N secret spend keys from user
for(unsigned int i=0; i<multisig_n; ++i)
{
spendkey_string = input_secure_line(tr((boost::format(tr("Secret spend key (%u of %u):")) % (i+1) % multisig_m).str().c_str()));
if (std::cin.eof())
return false;
if (spendkey_string.empty())
{
fail_msg_writer() << tr("No data supplied, cancelled");
return false;
}
if(!spendkey_string.hex_to_pod(unwrap(unwrap(multisig_secret_spendkeys[i]))))
{
fail_msg_writer() << tr("failed to parse spend key secret key");
return false;
}
}
// sum the spend keys together to get the master spend key
spendkey = multisig_secret_spendkeys[0];
for(unsigned int i=1; i<multisig_n; ++i)
sc_add(reinterpret_cast<unsigned char*>(&spendkey), reinterpret_cast<unsigned char*>(&spendkey), reinterpret_cast<unsigned char*>(&multisig_secret_spendkeys[i]));
}
// parsing M/N
else
{
fail_msg_writer() << tr("Error: M/N is currently unsupported");
return false;
}
// check that the spend key matches the given address
if (!crypto::secret_key_to_public_key(spendkey, pkey))
{
fail_msg_writer() << tr("failed to verify spend key secret key");
return false;
}
if (info.address.m_spend_public_key != pkey)
{
fail_msg_writer() << tr("spend key does not match standard address");
return false;
}
// create wallet
auto r = new_wallet(vm, info.address, spendkey, viewkey);
CHECK_AND_ASSERT_MES(r, false, tr("account creation failed"));
password = *r;
}
else if (!m_generate_from_json.empty())
{
try
{
auto rc = tools::wallet2::make_from_json(vm, false, m_generate_from_json, password_prompter);
m_wallet = std::move(rc.first);
password = rc.second.password();
m_wallet_file = m_wallet->path();
}
catch (const std::exception &e)
{
fail_msg_writer() << e.what();
return false;
}
if (!m_wallet)
return false;
}
else if (!m_generate_from_device.empty())
{
m_wallet_file = m_generate_from_device;
// create wallet
auto r = new_wallet(vm);
CHECK_AND_ASSERT_MES(r, false, tr("account creation failed"));
password = *r;
// if no block_height is specified, assume its a new account and start it "now"
if(m_wallet->get_refresh_from_block_height() == 0) {
{
tools::scoped_message_writer wrt = tools::msg_writer();
wrt << tr("No restore height is specified.");
wrt << tr("Assumed you are creating a new account, restore will be done from current estimated blockchain height.");
wrt << tr("Use --restore-height if you want to restore an already setup account from a specific height");
}
std::string confirm = input_line(tr("Is this okay? (Y/Yes/N/No): "));
if (std::cin.eof() || !command_line::is_yes(confirm))
CHECK_AND_ASSERT_MES(false, false, tr("account creation aborted"));
m_wallet->set_refresh_from_block_height(m_wallet->estimate_blockchain_height()-1);
m_wallet->explicit_refresh_from_block_height(true);
m_restore_height = m_wallet->get_refresh_from_block_height();
}
}
else
{
if (m_generate_new.empty()) {
fail_msg_writer() << tr("specify a wallet path with --generate-new-wallet (not --wallet-file)");
return false;
}
m_wallet_file = m_generate_new;
boost::optional<epee::wipeable_string> r;
if (m_restore_multisig_wallet)
r = new_wallet(vm, multisig_keys, old_language);
else
r = new_wallet(vm, m_recovery_key, m_restore_deterministic_wallet, m_non_deterministic, old_language);
CHECK_AND_ASSERT_MES(r, false, tr("account creation failed"));
password = *r;
}
if (m_restoring && m_generate_from_json.empty() && m_generate_from_device.empty())
{
m_wallet->explicit_refresh_from_block_height(!command_line::is_arg_defaulted(vm, arg_restore_height));
}
if (!m_wallet->explicit_refresh_from_block_height() && m_restoring)
{
uint32_t version;
bool connected = try_connect_to_daemon(false, &version);
while (true)
{
std::string heightstr;
if (!connected || version < MAKE_CORE_RPC_VERSION(1, 6))
heightstr = input_line("Restore from specific blockchain height (optional, default 0): ");
else
heightstr = input_line("Restore from specific blockchain height (optional, default 0),\nor alternatively from specific date (YYYY-MM-DD): ");
if (std::cin.eof())
return false;
if (heightstr.empty())
{
m_restore_height = 0;
break;
}
try
{
m_restore_height = boost::lexical_cast<uint64_t>(heightstr);
break;
}
catch (const boost::bad_lexical_cast &)
{
if (!connected || version < MAKE_CORE_RPC_VERSION(1, 6))
{
fail_msg_writer() << tr("bad m_restore_height parameter: ") << heightstr;
continue;
}
if (heightstr.size() != 10 || heightstr[4] != '-' || heightstr[7] != '-')
{
fail_msg_writer() << tr("date format must be YYYY-MM-DD");
continue;
}
uint16_t year;
uint8_t month; // 1, 2, ..., 12
uint8_t day; // 1, 2, ..., 31
try
{
year = boost::lexical_cast<uint16_t>(heightstr.substr(0,4));
// lexical_cast<uint8_t> won't work because uint8_t is treated as character type
month = boost::lexical_cast<uint16_t>(heightstr.substr(5,2));
day = boost::lexical_cast<uint16_t>(heightstr.substr(8,2));
m_restore_height = m_wallet->get_blockchain_height_by_date(year, month, day);
success_msg_writer() << tr("Restore height is: ") << m_restore_height;
std::string confirm = input_line(tr("Is this okay? (Y/Yes/N/No): "));
if (std::cin.eof())
return false;
if(command_line::is_yes(confirm))
break;
}
catch (const boost::bad_lexical_cast &)
{
fail_msg_writer() << tr("bad m_restore_height parameter: ") << heightstr;
}
catch (const std::runtime_error& e)
{
fail_msg_writer() << e.what();
}
}
}
}
if (m_restoring)
{
uint64_t estimate_height = m_wallet->estimate_blockchain_height();
if (m_restore_height >= estimate_height)
{
success_msg_writer() << tr("Restore height ") << m_restore_height << (" is not yet reached. The current estimated height is ") << estimate_height;
std::string confirm = input_line(tr("Still apply restore height? (Y/Yes/N/No): "));
if (std::cin.eof() || command_line::is_no(confirm))
m_restore_height = 0;
}
m_wallet->set_refresh_from_block_height(m_restore_height);
}
m_wallet->rewrite(m_wallet_file, password);
}
else
{
assert(!m_wallet_file.empty());
if (!m_subaddress_lookahead.empty())
{
fail_msg_writer() << tr("can't specify --subaddress-lookahead and --wallet-file at the same time");
return false;
}
bool r = open_wallet(vm);
CHECK_AND_ASSERT_MES(r, false, tr("failed to open account"));
}
if (!m_wallet)
{
fail_msg_writer() << tr("wallet is null");
return false;
}
if (!m_wallet->is_trusted_daemon())
message_writer() << (boost::format(tr("Warning: using an untrusted daemon at %s, privacy will be lessened")) % m_wallet->get_daemon_address()).str();
if (m_wallet->get_ring_database().empty())
fail_msg_writer() << tr("Failed to initialize ring database: privacy enhancing features will be inactive");
m_wallet->callback(this);
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::deinit()
{
if (!m_wallet.get())
return true;
return close_wallet();
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::handle_command_line(const boost::program_options::variables_map& vm)
{
m_wallet_file = command_line::get_arg(vm, arg_wallet_file);
m_generate_new = command_line::get_arg(vm, arg_generate_new_wallet);
m_generate_from_device = command_line::get_arg(vm, arg_generate_from_device);
m_generate_from_view_key = command_line::get_arg(vm, arg_generate_from_view_key);
m_generate_from_spend_key = command_line::get_arg(vm, arg_generate_from_spend_key);
m_generate_from_keys = command_line::get_arg(vm, arg_generate_from_keys);
m_generate_from_multisig_keys = command_line::get_arg(vm, arg_generate_from_multisig_keys);
m_generate_from_json = command_line::get_arg(vm, arg_generate_from_json);
m_mnemonic_language = command_line::get_arg(vm, arg_mnemonic_language);
m_electrum_seed = command_line::get_arg(vm, arg_electrum_seed);
m_restore_deterministic_wallet = command_line::get_arg(vm, arg_restore_deterministic_wallet);
m_restore_multisig_wallet = command_line::get_arg(vm, arg_restore_multisig_wallet);
m_non_deterministic = command_line::get_arg(vm, arg_non_deterministic);
m_allow_mismatched_daemon_version = command_line::get_arg(vm, arg_allow_mismatched_daemon_version);
m_restore_height = command_line::get_arg(vm, arg_restore_height);
m_do_not_relay = command_line::get_arg(vm, arg_do_not_relay);
m_subaddress_lookahead = command_line::get_arg(vm, arg_subaddress_lookahead);
m_use_english_language_names = command_line::get_arg(vm, arg_use_english_language_names);
m_restoring = !m_generate_from_view_key.empty() ||
!m_generate_from_spend_key.empty() ||
!m_generate_from_keys.empty() ||
!m_generate_from_multisig_keys.empty() ||
!m_generate_from_json.empty() ||
!m_generate_from_device.empty() ||
m_restore_deterministic_wallet ||
m_restore_multisig_wallet;
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::try_connect_to_daemon(bool silent, uint32_t* version)
{
uint32_t version_ = 0;
if (!version)
version = &version_;
if (!m_wallet->check_connection(version))
{
if (!silent)
fail_msg_writer() << tr("wallet failed to connect to daemon: ") << m_wallet->get_daemon_address() << ". " <<
tr("Daemon either is not started or wrong port was passed. "
"Please make sure daemon is running or change the daemon address using the 'set_daemon' command.");
return false;
}
if (!m_allow_mismatched_daemon_version && ((*version >> 16) != CORE_RPC_VERSION_MAJOR))
{
if (!silent)
fail_msg_writer() << boost::format(tr("Daemon uses a different RPC major version (%u) than the wallet (%u): %s. Either update one of them, or use --allow-mismatched-daemon-version.")) % (*version>>16) % CORE_RPC_VERSION_MAJOR % m_wallet->get_daemon_address();
return false;
}
return true;
}
/*!
* \brief Gets the word seed language from the user.
*
* User is asked to choose from a list of supported languages.
*
* \return The chosen language.
*/
std::string simple_wallet::get_mnemonic_language()
{
std::vector<std::string> language_list_self, language_list_english;
const std::vector<std::string> &language_list = m_use_english_language_names ? language_list_english : language_list_self;
std::string language_choice;
int language_number = -1;
crypto::ElectrumWords::get_language_list(language_list_self, false);
crypto::ElectrumWords::get_language_list(language_list_english, true);
std::cout << tr("List of available languages for your wallet's seed:") << std::endl;
std::cout << tr("If your display freezes, exit blind with ^C, then run again with --use-english-language-names") << std::endl;
int ii;
std::vector<std::string>::const_iterator it;
for (it = language_list.begin(), ii = 0; it != language_list.end(); it++, ii++)
{
std::cout << ii << " : " << *it << std::endl;
}
while (language_number < 0)
{
language_choice = input_line(tr("Enter the number corresponding to the language of your choice: "));
if (std::cin.eof())
return std::string();
try
{
language_number = std::stoi(language_choice);
if (!((language_number >= 0) && (static_cast<unsigned int>(language_number) < language_list.size())))
{
language_number = -1;
fail_msg_writer() << tr("invalid language choice entered. Please try again.\n");
}
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("invalid language choice entered. Please try again.\n");
}
}
return language_list_self[language_number];
}
//----------------------------------------------------------------------------------------------------
boost::optional<tools::password_container> simple_wallet::get_and_verify_password() const
{
auto pwd_container = default_password_prompter(m_wallet_file.empty());
if (!pwd_container)
return boost::none;
if (!m_wallet->verify_password(pwd_container->password()))
{
fail_msg_writer() << tr("invalid password");
return boost::none;
}
return pwd_container;
}
//----------------------------------------------------------------------------------------------------
boost::optional<epee::wipeable_string> simple_wallet::new_wallet(const boost::program_options::variables_map& vm,
const crypto::secret_key& recovery_key, bool recover, bool two_random, const std::string &old_language)
{
auto rc = tools::wallet2::make_new(vm, false, password_prompter);
m_wallet = std::move(rc.first);
if (!m_wallet)
{
return {};
}
epee::wipeable_string password = rc.second.password();
if (!m_subaddress_lookahead.empty())
{
auto lookahead = parse_subaddress_lookahead(m_subaddress_lookahead);
assert(lookahead);
m_wallet->set_subaddress_lookahead(lookahead->first, lookahead->second);
}
bool was_deprecated_wallet = m_restore_deterministic_wallet && ((old_language == crypto::ElectrumWords::old_language_name) ||
crypto::ElectrumWords::get_is_old_style_seed(m_electrum_seed));
std::string mnemonic_language = old_language;
std::vector<std::string> language_list;
crypto::ElectrumWords::get_language_list(language_list);
if (mnemonic_language.empty() && std::find(language_list.begin(), language_list.end(), m_mnemonic_language) != language_list.end())
{
mnemonic_language = m_mnemonic_language;
}
// Ask for seed language if:
// it's a deterministic wallet AND
// a seed language is not already specified AND
// (it is not a wallet restore OR if it was a deprecated wallet
// that was earlier used before this restore)
if ((!two_random) && (mnemonic_language.empty() || mnemonic_language == crypto::ElectrumWords::old_language_name) && (!m_restore_deterministic_wallet || was_deprecated_wallet))
{
if (was_deprecated_wallet)
{
// The user had used an older version of the wallet with old style mnemonics.
message_writer(console_color_green, false) << "\n" << tr("You had been using "
"a deprecated version of the wallet. Please use the new seed that we provide.\n");
}
mnemonic_language = get_mnemonic_language();
if (mnemonic_language.empty())
return {};
}
m_wallet->set_seed_language(mnemonic_language);
bool create_address_file = command_line::get_arg(vm, arg_create_address_file);
crypto::secret_key recovery_val;
try
{
recovery_val = m_wallet->generate(m_wallet_file, std::move(rc.second).password(), recovery_key, recover, two_random, create_address_file);
message_writer(console_color_white, true) << tr("Generated new wallet: ")
<< m_wallet->get_account().get_public_address_str(m_wallet->nettype());
PAUSE_READLINE();
std::cout << tr("View key: ");
print_secret_key(m_wallet->get_account().get_keys().m_view_secret_key);
putchar('\n');
}
catch (const std::exception& e)
{
fail_msg_writer() << tr("failed to generate new wallet: ") << e.what();
return {};
}
// convert rng value to electrum-style word list
epee::wipeable_string electrum_words;
crypto::ElectrumWords::bytes_to_words(recovery_val, electrum_words, mnemonic_language);
success_msg_writer() <<
"**********************************************************************\n" <<
tr("Your wallet has been generated!\n"
"To start synchronizing with the daemon, use the \"refresh\" command.\n"
"Use the \"help\" command to see the list of available commands.\n"
"Use \"help <command>\" to see a command's documentation.\n"
"Always use the \"exit\" command when closing jyocoin-wallet-cli to save \n"
"your current session's state. Otherwise, you might need to synchronize \n"
"your wallet again (your wallet keys are NOT at risk in any case).\n")
;
if (!two_random)
{
print_seed(electrum_words);
}
success_msg_writer() << "**********************************************************************";
return std::move(password);
}
//----------------------------------------------------------------------------------------------------
boost::optional<epee::wipeable_string> simple_wallet::new_wallet(const boost::program_options::variables_map& vm,
const cryptonote::account_public_address& address, const boost::optional<crypto::secret_key>& spendkey,
const crypto::secret_key& viewkey)
{
auto rc = tools::wallet2::make_new(vm, false, password_prompter);
m_wallet = std::move(rc.first);
if (!m_wallet)
{
return {};
}
epee::wipeable_string password = rc.second.password();
if (!m_subaddress_lookahead.empty())
{
auto lookahead = parse_subaddress_lookahead(m_subaddress_lookahead);
assert(lookahead);
m_wallet->set_subaddress_lookahead(lookahead->first, lookahead->second);
}
if (m_restore_height)
m_wallet->set_refresh_from_block_height(m_restore_height);
bool create_address_file = command_line::get_arg(vm, arg_create_address_file);
try
{
if (spendkey)
{
m_wallet->generate(m_wallet_file, std::move(rc.second).password(), address, *spendkey, viewkey, create_address_file);
}
else
{
m_wallet->generate(m_wallet_file, std::move(rc.second).password(), address, viewkey, create_address_file);
}
message_writer(console_color_white, true) << tr("Generated new wallet: ")
<< m_wallet->get_account().get_public_address_str(m_wallet->nettype());
}
catch (const std::exception& e)
{
fail_msg_writer() << tr("failed to generate new wallet: ") << e.what();
return {};
}
return std::move(password);
}
//----------------------------------------------------------------------------------------------------
boost::optional<epee::wipeable_string> simple_wallet::new_wallet(const boost::program_options::variables_map& vm)
{
auto rc = tools::wallet2::make_new(vm, false, password_prompter);
m_wallet = std::move(rc.first);
if (!m_wallet)
{
return {};
}
epee::wipeable_string password = rc.second.password();
if (!m_subaddress_lookahead.empty())
{
auto lookahead = parse_subaddress_lookahead(m_subaddress_lookahead);
assert(lookahead);
m_wallet->set_subaddress_lookahead(lookahead->first, lookahead->second);
}
if (m_restore_height)
m_wallet->set_refresh_from_block_height(m_restore_height);
auto device_desc = tools::wallet2::device_name_option(vm);
try
{
bool create_address_file = command_line::get_arg(vm, arg_create_address_file);
m_wallet->restore(m_wallet_file, std::move(rc.second).password(), device_desc.empty() ? "Ledger" : device_desc, create_address_file);
message_writer(console_color_white, true) << tr("Generated new wallet on hw device: ")
<< m_wallet->get_account().get_public_address_str(m_wallet->nettype());
}
catch (const std::exception& e)
{
fail_msg_writer() << tr("failed to generate new wallet: ") << e.what();
return {};
}
return std::move(password);
}
//----------------------------------------------------------------------------------------------------
boost::optional<epee::wipeable_string> simple_wallet::new_wallet(const boost::program_options::variables_map& vm,
const epee::wipeable_string &multisig_keys, const std::string &old_language)
{
auto rc = tools::wallet2::make_new(vm, false, password_prompter);
m_wallet = std::move(rc.first);
if (!m_wallet)
{
return {};
}
epee::wipeable_string password = rc.second.password();
if (!m_subaddress_lookahead.empty())
{
auto lookahead = parse_subaddress_lookahead(m_subaddress_lookahead);
assert(lookahead);
m_wallet->set_subaddress_lookahead(lookahead->first, lookahead->second);
}
std::string mnemonic_language = old_language;
std::vector<std::string> language_list;
crypto::ElectrumWords::get_language_list(language_list);
if (mnemonic_language.empty() && std::find(language_list.begin(), language_list.end(), m_mnemonic_language) != language_list.end())
{
mnemonic_language = m_mnemonic_language;
}
m_wallet->set_seed_language(mnemonic_language);
bool create_address_file = command_line::get_arg(vm, arg_create_address_file);
try
{
m_wallet->generate(m_wallet_file, std::move(rc.second).password(), multisig_keys, create_address_file);
bool ready;
uint32_t threshold, total;
if (!m_wallet->multisig(&ready, &threshold, &total) || !ready)
{
fail_msg_writer() << tr("failed to generate new mutlisig wallet");
return {};
}
message_writer(console_color_white, true) << boost::format(tr("Generated new %u/%u multisig wallet: ")) % threshold % total
<< m_wallet->get_account().get_public_address_str(m_wallet->nettype());
}
catch (const std::exception& e)
{
fail_msg_writer() << tr("failed to generate new wallet: ") << e.what();
return {};
}
return std::move(password);
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::open_wallet(const boost::program_options::variables_map& vm)
{
if (!tools::wallet2::wallet_valid_path_format(m_wallet_file))
{
fail_msg_writer() << tr("wallet file path not valid: ") << m_wallet_file;
return false;
}
bool keys_file_exists;
bool wallet_file_exists;
tools::wallet2::wallet_exists(m_wallet_file, keys_file_exists, wallet_file_exists);
if(!keys_file_exists)
{
fail_msg_writer() << tr("Key file not found. Failed to open wallet");
return false;
}
epee::wipeable_string password;
try
{
auto rc = tools::wallet2::make_from_file(vm, false, m_wallet_file, password_prompter);
m_wallet = std::move(rc.first);
password = std::move(std::move(rc.second).password());
if (!m_wallet)
{
return false;
}
std::string prefix;
bool ready;
uint32_t threshold, total;
if (m_wallet->watch_only())
prefix = tr("Opened watch-only wallet");
else if (m_wallet->multisig(&ready, &threshold, &total))
prefix = (boost::format(tr("Opened %u/%u multisig wallet%s")) % threshold % total % (ready ? "" : " (not yet finalized)")).str();
else
prefix = tr("Opened wallet");
message_writer(console_color_white, true) <<
prefix << ": " << m_wallet->get_account().get_public_address_str(m_wallet->nettype());
if (m_wallet->get_account().get_device()) {
message_writer(console_color_white, true) << "Wallet is on device: " << m_wallet->get_account().get_device().get_name();
}
// If the wallet file is deprecated, we should ask for mnemonic language again and store
// everything in the new format.
// NOTE: this is_deprecated() refers to the wallet file format before becoming JSON. It does not refer to the "old english" seed words form of "deprecated" used elsewhere.
if (m_wallet->is_deprecated())
{
bool is_deterministic;
{
SCOPED_WALLET_UNLOCK();
is_deterministic = m_wallet->is_deterministic();
}
if (is_deterministic)
{
message_writer(console_color_green, false) << "\n" << tr("You had been using "
"a deprecated version of the wallet. Please proceed to upgrade your wallet.\n");
std::string mnemonic_language = get_mnemonic_language();
if (mnemonic_language.empty())
return false;
m_wallet->set_seed_language(mnemonic_language);
m_wallet->rewrite(m_wallet_file, password);
// Display the seed
epee::wipeable_string seed;
m_wallet->get_seed(seed);
print_seed(seed);
}
else
{
message_writer(console_color_green, false) << "\n" << tr("You had been using "
"a deprecated version of the wallet. Your wallet file format is being upgraded now.\n");
m_wallet->rewrite(m_wallet_file, password);
}
}
}
catch (const std::exception& e)
{
fail_msg_writer() << tr("failed to load wallet: ") << e.what();
if (m_wallet)
{
// only suggest removing cache if the password was actually correct
bool password_is_correct = false;
try
{
password_is_correct = m_wallet->verify_password(password);
}
catch (...) { } // guard against I/O errors
if (password_is_correct)
fail_msg_writer() << boost::format(tr("You may want to remove the file \"%s\" and try again")) % m_wallet_file;
}
return false;
}
success_msg_writer() <<
"**********************************************************************\n" <<
tr("Use the \"help\" command to see the list of available commands.\n") <<
tr("Use \"help <command>\" to see a command's documentation.\n") <<
"**********************************************************************";
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::close_wallet()
{
if (m_idle_run.load(std::memory_order_relaxed))
{
m_idle_run.store(false, std::memory_order_relaxed);
m_wallet->stop();
{
boost::unique_lock<boost::mutex> lock(m_idle_mutex);
m_idle_cond.notify_one();
}
m_idle_thread.join();
}
bool r = m_wallet->deinit();
if (!r)
{
fail_msg_writer() << tr("failed to deinitialize wallet");
return false;
}
try
{
m_wallet->store();
}
catch (const std::exception& e)
{
fail_msg_writer() << e.what();
return false;
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::save(const std::vector<std::string> &args)
{
try
{
LOCK_IDLE_SCOPE();
m_wallet->store();
success_msg_writer() << tr("Wallet data saved");
}
catch (const std::exception& e)
{
fail_msg_writer() << e.what();
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::save_watch_only(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
if (m_wallet->multisig())
{
fail_msg_writer() << tr("wallet is multisig and cannot save a watch-only version");
return true;
}
const auto pwd_container = password_prompter(tr("Password for new watch-only wallet"), true);
if (!pwd_container)
{
fail_msg_writer() << tr("failed to read wallet password");
return true;
}
try
{
std::string new_keys_filename;
m_wallet->write_watch_only_wallet(m_wallet_file, pwd_container->password(), new_keys_filename);
success_msg_writer() << tr("Watch only wallet saved as: ") << new_keys_filename;
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to save watch only wallet: ") << e.what();
return true;
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::start_mining(const std::vector<std::string>& args)
{
if (!m_wallet->is_trusted_daemon())
{
fail_msg_writer() << tr("this command requires a trusted daemon. Enable with --trusted-daemon");
return true;
}
if (!try_connect_to_daemon())
return true;
if (!m_wallet)
{
fail_msg_writer() << tr("wallet is null");
return true;
}
COMMAND_RPC_START_MINING::request req = AUTO_VAL_INIT(req);
req.miner_address = m_wallet->get_account().get_public_address_str(m_wallet->nettype());
bool ok = true;
size_t arg_size = args.size();
if(arg_size >= 3)
{
if (!parse_bool_and_use(args[2], [&](bool r) { req.ignore_battery = r; }))
return true;
}
if(arg_size >= 2)
{
if (!parse_bool_and_use(args[1], [&](bool r) { req.do_background_mining = r; }))
return true;
}
if(arg_size >= 1)
{
uint16_t num = 1;
ok = string_tools::get_xtype_from_string(num, args[0]);
ok = ok && 1 <= num;
req.threads_count = num;
}
else
{
req.threads_count = 1;
}
if (!ok)
{
fail_msg_writer() << tr("invalid arguments. Please use start_mining [<number_of_threads>] [do_bg_mining] [ignore_battery]");
return true;
}
COMMAND_RPC_START_MINING::response res;
bool r = m_wallet->invoke_http_json("/start_mining", req, res);
std::string err = interpret_rpc_response(r, res.status);
if (err.empty())
success_msg_writer() << tr("Mining started in daemon");
else
fail_msg_writer() << tr("mining has NOT been started: ") << err;
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::stop_mining(const std::vector<std::string>& args)
{
if (!try_connect_to_daemon())
return true;
if (!m_wallet)
{
fail_msg_writer() << tr("wallet is null");
return true;
}
COMMAND_RPC_STOP_MINING::request req;
COMMAND_RPC_STOP_MINING::response res;
bool r = m_wallet->invoke_http_json("/stop_mining", req, res);
std::string err = interpret_rpc_response(r, res.status);
if (err.empty())
success_msg_writer() << tr("Mining stopped in daemon");
else
fail_msg_writer() << tr("mining has NOT been stopped: ") << err;
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::set_daemon(const std::vector<std::string>& args)
{
std::string daemon_url;
if (args.size() < 1)
{
fail_msg_writer() << tr("missing daemon URL argument");
return true;
}
boost::regex rgx("^(.*://)?([A-Za-z0-9\\-\\.]+)(:[0-9]+)?");
boost::cmatch match;
// If user input matches URL regex
if (boost::regex_match(args[0].c_str(), match, rgx))
{
if (match.length() < 4)
{
fail_msg_writer() << tr("Unexpected array length - Exited simple_wallet::set_daemon()");
return true;
}
// If no port has been provided, use the default from config
if (!match[3].length())
{
int daemon_port = get_config(m_wallet->nettype()).RPC_DEFAULT_PORT;
daemon_url = match[1] + match[2] + std::string(":") + std::to_string(daemon_port);
} else {
daemon_url = args[0];
}
LOCK_IDLE_SCOPE();
m_wallet->init(daemon_url);
if (args.size() == 2)
{
if (args[1] == "trusted")
m_wallet->set_trusted_daemon(true);
else if (args[1] == "untrusted")
m_wallet->set_trusted_daemon(false);
else
{
fail_msg_writer() << tr("Expected trusted or untrusted, got ") << args[1] << ": assuming untrusted";
m_wallet->set_trusted_daemon(false);
}
}
else
{
m_wallet->set_trusted_daemon(false);
try
{
if (tools::is_local_address(m_wallet->get_daemon_address()))
{
MINFO(tr("Daemon is local, assuming trusted"));
m_wallet->set_trusted_daemon(true);
}
}
catch (const std::exception &e) { }
}
success_msg_writer() << boost::format("Daemon set to %s, %s") % daemon_url % (m_wallet->is_trusted_daemon() ? tr("trusted") : tr("untrusted"));
} else {
fail_msg_writer() << tr("This does not seem to be a valid daemon URL.");
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::save_bc(const std::vector<std::string>& args)
{
if (!try_connect_to_daemon())
return true;
if (!m_wallet)
{
fail_msg_writer() << tr("wallet is null");
return true;
}
COMMAND_RPC_SAVE_BC::request req;
COMMAND_RPC_SAVE_BC::response res;
bool r = m_wallet->invoke_http_json("/save_bc", req, res);
std::string err = interpret_rpc_response(r, res.status);
if (err.empty())
success_msg_writer() << tr("Blockchain saved");
else
fail_msg_writer() << tr("blockchain can't be saved: ") << err;
return true;
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::on_new_block(uint64_t height, const cryptonote::block& block)
{
if (!m_auto_refresh_refreshing)
m_refresh_progress_reporter.update(height, false);
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::on_money_received(uint64_t height, const crypto::hash &txid, const cryptonote::transaction& tx, uint64_t amount, const cryptonote::subaddress_index& subaddr_index)
{
message_writer(console_color_green, false) << "\r" <<
tr("Height ") << height << ", " <<
tr("txid ") << txid << ", " <<
print_money(amount) << ", " <<
tr("idx ") << subaddr_index;
const uint64_t warn_height = m_wallet->nettype() == TESTNET ? 1000000 : m_wallet->nettype() == STAGENET ? 50000 : 1650000;
if (height >= warn_height)
{
std::vector<tx_extra_field> tx_extra_fields;
parse_tx_extra(tx.extra, tx_extra_fields); // failure ok
tx_extra_nonce extra_nonce;
if (find_tx_extra_field_by_type(tx_extra_fields, extra_nonce))
{
crypto::hash8 payment_id8 = crypto::null_hash8;
crypto::hash payment_id = crypto::null_hash;
if (get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8))
message_writer() <<
tr("NOTE: this transaction uses an encrypted payment ID: consider using subaddresses instead");
else if (get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id))
message_writer(console_color_red, false) <<
tr("WARNING: this transaction uses an unencrypted payment ID: consider using subaddresses instead");
}
}
if (m_auto_refresh_refreshing)
m_cmd_binder.print_prompt();
else
m_refresh_progress_reporter.update(height, true);
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::on_unconfirmed_money_received(uint64_t height, const crypto::hash &txid, const cryptonote::transaction& tx, uint64_t amount, const cryptonote::subaddress_index& subaddr_index)
{
// Not implemented in CLI wallet
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::on_money_spent(uint64_t height, const crypto::hash &txid, const cryptonote::transaction& in_tx, uint64_t amount, const cryptonote::transaction& spend_tx, const cryptonote::subaddress_index& subaddr_index)
{
message_writer(console_color_magenta, false) << "\r" <<
tr("Height ") << height << ", " <<
tr("txid ") << txid << ", " <<
tr("spent ") << print_money(amount) << ", " <<
tr("idx ") << subaddr_index;
if (m_auto_refresh_refreshing)
m_cmd_binder.print_prompt();
else
m_refresh_progress_reporter.update(height, true);
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::on_skip_transaction(uint64_t height, const crypto::hash &txid, const cryptonote::transaction& tx)
{
}
//----------------------------------------------------------------------------------------------------
boost::optional<epee::wipeable_string> simple_wallet::on_get_password(const char *reason)
{
// can't ask for password from a background thread
if (!m_in_manual_refresh.load(std::memory_order_relaxed))
{
message_writer(console_color_red, false) << boost::format(tr("Password needed (%s) - use the refresh command")) % reason;
m_cmd_binder.print_prompt();
return boost::none;
}
#ifdef HAVE_READLINE
rdln::suspend_readline pause_readline;
#endif
std::string msg = tr("Enter password");
if (reason && *reason)
msg += std::string(" (") + reason + ")";
auto pwd_container = tools::password_container::prompt(false, msg.c_str());
if (!pwd_container)
{
MERROR("Failed to read password");
return boost::none;
}
return pwd_container->password();
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::refresh_main(uint64_t start_height, enum ResetType reset, bool is_init)
{
if (!try_connect_to_daemon(is_init))
return true;
LOCK_IDLE_SCOPE();
if (reset != ResetNone)
m_wallet->rescan_blockchain(reset == ResetHard, false);
#ifdef HAVE_READLINE
rdln::suspend_readline pause_readline;
#endif
message_writer() << tr("Starting refresh...");
uint64_t fetched_blocks = 0;
bool ok = false;
std::ostringstream ss;
try
{
m_in_manual_refresh.store(true, std::memory_order_relaxed);
epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){m_in_manual_refresh.store(false, std::memory_order_relaxed);});
m_wallet->refresh(m_wallet->is_trusted_daemon(), start_height, fetched_blocks);
ok = true;
// Clear line "Height xxx of xxx"
std::cout << "\r \r";
success_msg_writer(true) << tr("Refresh done, blocks received: ") << fetched_blocks;
if (is_init)
print_accounts();
show_balance_unlocked();
}
catch (const tools::error::daemon_busy&)
{
ss << tr("daemon is busy. Please try again later.");
}
catch (const tools::error::no_connection_to_daemon&)
{
ss << tr("no connection to daemon. Please make sure daemon is running.");
}
catch (const tools::error::wallet_rpc_error& e)
{
LOG_ERROR("RPC error: " << e.to_string());
ss << tr("RPC error: ") << e.what();
}
catch (const tools::error::refresh_error& e)
{
LOG_ERROR("refresh error: " << e.to_string());
ss << tr("refresh error: ") << e.what();
}
catch (const tools::error::wallet_internal_error& e)
{
LOG_ERROR("internal error: " << e.to_string());
ss << tr("internal error: ") << e.what();
}
catch (const std::exception& e)
{
LOG_ERROR("unexpected error: " << e.what());
ss << tr("unexpected error: ") << e.what();
}
catch (...)
{
LOG_ERROR("unknown error");
ss << tr("unknown error");
}
if (!ok)
{
fail_msg_writer() << tr("refresh failed: ") << ss.str() << ". " << tr("Blocks received: ") << fetched_blocks;
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::refresh(const std::vector<std::string>& args)
{
uint64_t start_height = 0;
if(!args.empty()){
try
{
start_height = boost::lexical_cast<uint64_t>( args[0] );
}
catch(const boost::bad_lexical_cast &)
{
start_height = 0;
}
}
return refresh_main(start_height, ResetNone);
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::show_balance_unlocked(bool detailed)
{
std::string extra;
if (m_wallet->has_multisig_partial_key_images())
extra = tr(" (Some owned outputs have partial key images - import_multisig_info needed)");
else if (m_wallet->has_unknown_key_images())
extra += tr(" (Some owned outputs have missing key images - import_key_images needed)");
success_msg_writer() << tr("Currently selected account: [") << m_current_subaddress_account << tr("] ") << m_wallet->get_subaddress_label({m_current_subaddress_account, 0});
const std::string tag = m_wallet->get_account_tags().second[m_current_subaddress_account];
success_msg_writer() << tr("Tag: ") << (tag.empty() ? std::string{tr("(No tag assigned)")} : tag);
success_msg_writer() << tr("Balance: ") << print_money(m_wallet->balance(m_current_subaddress_account)) << ", "
<< tr("unlocked balance: ") << print_money(m_wallet->unlocked_balance(m_current_subaddress_account)) << extra;
std::map<uint32_t, uint64_t> balance_per_subaddress = m_wallet->balance_per_subaddress(m_current_subaddress_account);
std::map<uint32_t, uint64_t> unlocked_balance_per_subaddress = m_wallet->unlocked_balance_per_subaddress(m_current_subaddress_account);
if (!detailed || balance_per_subaddress.empty())
return true;
success_msg_writer() << tr("Balance per address:");
success_msg_writer() << boost::format("%15s %21s %21s %7s %21s") % tr("Address") % tr("Balance") % tr("Unlocked balance") % tr("Outputs") % tr("Label");
std::vector<tools::wallet2::transfer_details> transfers;
m_wallet->get_transfers(transfers);
for (const auto& i : balance_per_subaddress)
{
cryptonote::subaddress_index subaddr_index = {m_current_subaddress_account, i.first};
std::string address_str = m_wallet->get_subaddress_as_str(subaddr_index).substr(0, 6);
uint64_t num_unspent_outputs = std::count_if(transfers.begin(), transfers.end(), [&subaddr_index](const tools::wallet2::transfer_details& td) { return !td.m_spent && td.m_subaddr_index == subaddr_index; });
success_msg_writer() << boost::format(tr("%8u %6s %21s %21s %7u %21s")) % i.first % address_str % print_money(i.second) % print_money(unlocked_balance_per_subaddress[i.first]) % num_unspent_outputs % m_wallet->get_subaddress_label(subaddr_index);
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::show_balance(const std::vector<std::string>& args/* = std::vector<std::string>()*/)
{
if (args.size() > 1 || (args.size() == 1 && args[0] != "detail"))
{
fail_msg_writer() << tr("usage: balance [detail]");
return true;
}
LOCK_IDLE_SCOPE();
show_balance_unlocked(args.size() == 1);
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::show_incoming_transfers(const std::vector<std::string>& args)
{
if (args.size() > 3)
{
fail_msg_writer() << tr("usage: incoming_transfers [available|unavailable] [verbose] [index=<N>]");
return true;
}
auto local_args = args;
LOCK_IDLE_SCOPE();
bool filter = false;
bool available = false;
bool verbose = false;
if (local_args.size() > 0)
{
if (local_args[0] == "available")
{
filter = true;
available = true;
local_args.erase(local_args.begin());
}
else if (local_args[0] == "unavailable")
{
filter = true;
available = false;
local_args.erase(local_args.begin());
}
}
if (local_args.size() > 0 && local_args[0] == "verbose")
{
verbose = true;
local_args.erase(local_args.begin());
}
PAUSE_READLINE();
std::set<uint32_t> subaddr_indices;
if (local_args.size() > 0 && local_args[0].substr(0, 6) == "index=")
{
if (!parse_subaddress_indices(local_args[0], subaddr_indices))
return true;
local_args.erase(local_args.begin());
}
if (local_args.size() > 0)
{
fail_msg_writer() << tr("usage: incoming_transfers [available|unavailable] [verbose] [index=<N>]");
return true;
}
tools::wallet2::transfer_container transfers;
m_wallet->get_transfers(transfers);
size_t transfers_found = 0;
for (const auto& td : transfers)
{
if (!filter || available != td.m_spent)
{
if (m_current_subaddress_account != td.m_subaddr_index.major || (!subaddr_indices.empty() && subaddr_indices.count(td.m_subaddr_index.minor) == 0))
continue;
if (!transfers_found)
{
std::string verbose_string;
if (verbose)
verbose_string = (boost::format("%68s%68s") % tr("pubkey") % tr("key image")).str();
message_writer() << boost::format("%21s%8s%12s%8s%16s%68s%16s%s") % tr("amount") % tr("spent") % tr("unlocked") % tr("ringct") % tr("global index") % tr("tx id") % tr("addr index") % verbose_string;
}
std::string verbose_string;
if (verbose)
verbose_string = (boost::format("%68s%68s") % td.get_public_key() % (td.m_key_image_known ? epee::string_tools::pod_to_hex(td.m_key_image) : td.m_key_image_partial ? (epee::string_tools::pod_to_hex(td.m_key_image) + "/p") : std::string(64, '?'))).str();
message_writer(td.m_spent ? console_color_magenta : console_color_green, false) <<
boost::format("%21s%8s%12s%8s%16u%68s%16u%s") %
print_money(td.amount()) %
(td.m_spent ? tr("T") : tr("F")) %
(m_wallet->is_transfer_unlocked(td) ? tr("unlocked") : tr("locked")) %
(td.is_rct() ? tr("RingCT") : tr("-")) %
td.m_global_output_index %
td.m_txid %
td.m_subaddr_index.minor %
verbose_string;
++transfers_found;
}
}
if (!transfers_found)
{
if (!filter)
{
success_msg_writer() << tr("No incoming transfers");
}
else if (available)
{
success_msg_writer() << tr("No incoming available transfers");
}
else
{
success_msg_writer() << tr("No incoming unavailable transfers");
}
}
else
{
success_msg_writer() << boost::format("Found %u/%u transfers") % transfers_found % transfers.size();
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::show_payments(const std::vector<std::string> &args)
{
if(args.empty())
{
fail_msg_writer() << tr("expected at least one payment ID");
return true;
}
LOCK_IDLE_SCOPE();
PAUSE_READLINE();
message_writer() << boost::format("%68s%68s%12s%21s%16s%16s") %
tr("payment") % tr("transaction") % tr("height") % tr("amount") % tr("unlock time") % tr("addr index");
bool payments_found = false;
for(std::string arg : args)
{
crypto::hash payment_id;
if(tools::wallet2::parse_payment_id(arg, payment_id))
{
std::list<tools::wallet2::payment_details> payments;
m_wallet->get_payments(payment_id, payments);
if(payments.empty())
{
success_msg_writer() << tr("No payments with id ") << payment_id;
continue;
}
for (const tools::wallet2::payment_details& pd : payments)
{
if(!payments_found)
{
payments_found = true;
}
success_msg_writer(true) <<
boost::format("%68s%68s%12s%21s%16s%16s") %
payment_id %
pd.m_tx_hash %
pd.m_block_height %
print_money(pd.m_amount) %
pd.m_unlock_time %
pd.m_subaddr_index.minor;
}
}
else
{
fail_msg_writer() << tr("payment ID has invalid format, expected 16 or 64 character hex string: ") << arg;
}
}
return true;
}
//----------------------------------------------------------------------------------------------------
uint64_t simple_wallet::get_daemon_blockchain_height(std::string& err)
{
if (!m_wallet)
{
throw std::runtime_error("simple_wallet null wallet");
}
return m_wallet->get_daemon_blockchain_height(err);
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::show_blockchain_height(const std::vector<std::string>& args)
{
if (!try_connect_to_daemon())
return true;
std::string err;
uint64_t bc_height = get_daemon_blockchain_height(err);
if (err.empty())
success_msg_writer() << bc_height;
else
fail_msg_writer() << tr("failed to get blockchain height: ") << err;
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::rescan_spent(const std::vector<std::string> &args)
{
if (!m_wallet->is_trusted_daemon())
{
fail_msg_writer() << tr("this command requires a trusted daemon. Enable with --trusted-daemon");
return true;
}
if (!try_connect_to_daemon())
return true;
try
{
LOCK_IDLE_SCOPE();
m_wallet->rescan_spent();
}
catch (const tools::error::daemon_busy&)
{
fail_msg_writer() << tr("daemon is busy. Please try again later.");
}
catch (const tools::error::no_connection_to_daemon&)
{
fail_msg_writer() << tr("no connection to daemon. Please make sure daemon is running.");
}
catch (const tools::error::is_key_image_spent_error&)
{
fail_msg_writer() << tr("failed to get spent status");
}
catch (const tools::error::wallet_rpc_error& e)
{
LOG_ERROR("RPC error: " << e.to_string());
fail_msg_writer() << tr("RPC error: ") << e.what();
}
catch (const std::exception& e)
{
LOG_ERROR("unexpected error: " << e.what());
fail_msg_writer() << tr("unexpected error: ") << e.what();
}
catch (...)
{
LOG_ERROR("unknown error");
fail_msg_writer() << tr("unknown error");
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::print_ring_members(const std::vector<tools::wallet2::pending_tx>& ptx_vector, std::ostream& ostr)
{
uint32_t version;
if (!try_connect_to_daemon(false, &version))
return false;
// available for RPC version 1.4 or higher
if (version < MAKE_CORE_RPC_VERSION(1, 4))
return true;
std::string err;
uint64_t blockchain_height = get_daemon_blockchain_height(err);
if (!err.empty())
{
fail_msg_writer() << tr("failed to get blockchain height: ") << err;
return false;
}
// for each transaction
for (size_t n = 0; n < ptx_vector.size(); ++n)
{
const cryptonote::transaction& tx = ptx_vector[n].tx;
const tools::wallet2::tx_construction_data& construction_data = ptx_vector[n].construction_data;
ostr << boost::format(tr("\nTransaction %llu/%llu: txid=%s")) % (n + 1) % ptx_vector.size() % cryptonote::get_transaction_hash(tx);
// for each input
std::vector<uint64_t> spent_key_height(tx.vin.size());
std::vector<crypto::hash> spent_key_txid (tx.vin.size());
for (size_t i = 0; i < tx.vin.size(); ++i)
{
if (tx.vin[i].type() != typeid(cryptonote::txin_to_key))
continue;
const cryptonote::txin_to_key& in_key = boost::get<cryptonote::txin_to_key>(tx.vin[i]);
const tools::wallet2::transfer_details &td = m_wallet->get_transfer_details(construction_data.selected_transfers[i]);
const cryptonote::tx_source_entry *sptr = NULL;
for (const auto &src: construction_data.sources)
if (src.outputs[src.real_output].second.dest == td.get_public_key())
sptr = &src;
if (!sptr)
{
fail_msg_writer() << tr("failed to find construction data for tx input");
return false;
}
const cryptonote::tx_source_entry& source = *sptr;
ostr << boost::format(tr("\nInput %llu/%llu: amount=%s")) % (i + 1) % tx.vin.size() % print_money(source.amount);
// convert relative offsets of ring member keys into absolute offsets (indices) associated with the amount
std::vector<uint64_t> absolute_offsets = cryptonote::relative_output_offsets_to_absolute(in_key.key_offsets);
// get block heights from which those ring member keys originated
COMMAND_RPC_GET_OUTPUTS_BIN::request req = AUTO_VAL_INIT(req);
req.outputs.resize(absolute_offsets.size());
for (size_t j = 0; j < absolute_offsets.size(); ++j)
{
req.outputs[j].amount = in_key.amount;
req.outputs[j].index = absolute_offsets[j];
}
COMMAND_RPC_GET_OUTPUTS_BIN::response res = AUTO_VAL_INIT(res);
bool r = m_wallet->invoke_http_bin("/get_outs.bin", req, res);
err = interpret_rpc_response(r, res.status);
if (!err.empty())
{
fail_msg_writer() << tr("failed to get output: ") << err;
return false;
}
// make sure that returned block heights are less than blockchain height
for (auto& res_out : res.outs)
{
if (res_out.height >= blockchain_height)
{
fail_msg_writer() << tr("output key's originating block height shouldn't be higher than the blockchain height");
return false;
}
}
ostr << tr("\nOriginating block heights: ");
for (size_t j = 0; j < absolute_offsets.size(); ++j)
ostr << tr(j == source.real_output ? " *" : " ") << res.outs[j].height;
spent_key_height[i] = res.outs[source.real_output].height;
spent_key_txid [i] = res.outs[source.real_output].txid;
// visualize the distribution, using the code by jyocoinexamples onion-jyocoin-viewer
const uint64_t resolution = 79;
std::string ring_str(resolution, '_');
for (size_t j = 0; j < absolute_offsets.size(); ++j)
{
uint64_t pos = (res.outs[j].height * resolution) / blockchain_height;
ring_str[pos] = 'o';
}
uint64_t pos = (res.outs[source.real_output].height * resolution) / blockchain_height;
ring_str[pos] = '*';
ostr << tr("\n|") << ring_str << tr("|\n");
}
// warn if rings contain keys originating from the same tx or temporally very close block heights
bool are_keys_from_same_tx = false;
bool are_keys_from_close_height = false;
for (size_t i = 0; i < tx.vin.size(); ++i) {
for (size_t j = i + 1; j < tx.vin.size(); ++j)
{
if (spent_key_txid[i] == spent_key_txid[j])
are_keys_from_same_tx = true;
if (std::abs((int64_t)(spent_key_height[i] - spent_key_height[j])) < (int64_t)5)
are_keys_from_close_height = true;
}
}
if (are_keys_from_same_tx || are_keys_from_close_height)
{
ostr
<< tr("\nWarning: Some input keys being spent are from ")
<< (are_keys_from_same_tx ? tr("the same transaction") : tr("blocks that are temporally very close"))
<< tr(", which can break the anonymity of ring signature. Make sure this is intentional!");
}
ostr << ENDL;
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::transfer_main(int transfer_type, const std::vector<std::string> &args_)
{
// "transfer [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] <address> <amount> [<payment_id>]"
if (!try_connect_to_daemon())
return true;
std::vector<std::string> local_args = args_;
std::set<uint32_t> subaddr_indices;
if (local_args.size() > 0 && local_args[0].substr(0, 6) == "index=")
{
if (!parse_subaddress_indices(local_args[0], subaddr_indices))
return true;
local_args.erase(local_args.begin());
}
uint32_t priority = 0;
if (local_args.size() > 0 && parse_priority(local_args[0], priority))
local_args.erase(local_args.begin());
priority = m_wallet->adjust_priority(priority);
size_t fake_outs_count = 0;
if(local_args.size() > 0) {
size_t ring_size;
if(!epee::string_tools::get_xtype_from_string(ring_size, local_args[0]))
{
fake_outs_count = m_wallet->default_mixin();
if (fake_outs_count == 0)
fake_outs_count = DEFAULT_MIX;
}
else if (ring_size == 0)
{
fail_msg_writer() << tr("Ring size must not be 0");
return true;
}
else
{
fake_outs_count = ring_size - 1;
local_args.erase(local_args.begin());
}
}
uint64_t adjusted_fake_outs_count = m_wallet->adjust_mixin(fake_outs_count);
if (adjusted_fake_outs_count > fake_outs_count)
{
fail_msg_writer() << (boost::format(tr("ring size %u is too small, minimum is %u")) % (fake_outs_count+1) % (adjusted_fake_outs_count+1)).str();
return true;
}
if (adjusted_fake_outs_count < fake_outs_count)
{
fail_msg_writer() << (boost::format(tr("ring size %u is too large, maximum is %u")) % (fake_outs_count+1) % (adjusted_fake_outs_count+1)).str();
return true;
}
const size_t min_args = (transfer_type == TransferLocked) ? 2 : 1;
if(local_args.size() < min_args)
{
fail_msg_writer() << tr("wrong number of arguments");
return true;
}
std::vector<uint8_t> extra;
bool payment_id_seen = false;
if (!local_args.empty())
{
std::string payment_id_str = local_args.back();
crypto::hash payment_id;
bool r = true;
if (tools::wallet2::parse_long_payment_id(payment_id_str, payment_id))
{
std::string extra_nonce;
set_payment_id_to_tx_extra_nonce(extra_nonce, payment_id);
r = add_extra_nonce_to_tx_extra(extra, extra_nonce);
local_args.pop_back();
payment_id_seen = true;
message_writer() << tr("Unencrypted payment IDs are bad for privacy: ask the recipient to use subaddresses instead");
}
else
{
crypto::hash8 payment_id8;
if (tools::wallet2::parse_short_payment_id(payment_id_str, payment_id8))
{
std::string extra_nonce;
set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, payment_id8);
r = add_extra_nonce_to_tx_extra(extra, extra_nonce);
local_args.pop_back();
payment_id_seen = true;
}
}
if(!r)
{
fail_msg_writer() << tr("payment id failed to encode");
return true;
}
}
uint64_t locked_blocks = 0;
if (transfer_type == TransferLocked)
{
try
{
locked_blocks = boost::lexical_cast<uint64_t>(local_args.back());
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("bad locked_blocks parameter:") << " " << local_args.back();
return true;
}
if (locked_blocks > 1000000)
{
fail_msg_writer() << tr("Locked blocks too high, max 1000000 (˜4 yrs)");
return true;
}
local_args.pop_back();
}
vector<cryptonote::address_parse_info> dsts_info;
vector<cryptonote::tx_destination_entry> dsts;
size_t num_subaddresses = 0;
for (size_t i = 0; i < local_args.size(); )
{
dsts_info.emplace_back();
cryptonote::address_parse_info & info = dsts_info.back();
cryptonote::tx_destination_entry de;
bool r = true;
// check for a URI
std::string address_uri, payment_id_uri, tx_description, recipient_name, error;
std::vector<std::string> unknown_parameters;
uint64_t amount = 0;
bool has_uri = m_wallet->parse_uri(local_args[i], address_uri, payment_id_uri, amount, tx_description, recipient_name, unknown_parameters, error);
if (has_uri)
{
r = cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), address_uri, oa_prompter);
if (payment_id_uri.size() == 16)
{
if (!tools::wallet2::parse_short_payment_id(payment_id_uri, info.payment_id))
{
fail_msg_writer() << tr("failed to parse short payment ID from URI");
return true;
}
info.has_payment_id = true;
}
de.amount = amount;
++i;
}
else if (i + 1 < local_args.size())
{
r = cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), local_args[i], oa_prompter);
bool ok = cryptonote::parse_amount(de.amount, local_args[i + 1]);
if(!ok || 0 == de.amount)
{
fail_msg_writer() << tr("amount is wrong: ") << local_args[i] << ' ' << local_args[i + 1] <<
", " << tr("expected number from 0 to ") << print_money(std::numeric_limits<uint64_t>::max());
return true;
}
i += 2;
}
else
{
if (boost::starts_with(local_args[i], "jyocoin:"))
fail_msg_writer() << tr("Invalid last argument: ") << local_args.back() << ": " << error;
else
fail_msg_writer() << tr("Invalid last argument: ") << local_args.back();
return true;
}
if (!r)
{
fail_msg_writer() << tr("failed to parse address");
return true;
}
de.addr = info.address;
de.is_subaddress = info.is_subaddress;
num_subaddresses += info.is_subaddress;
if (info.has_payment_id || !payment_id_uri.empty())
{
if (payment_id_seen)
{
fail_msg_writer() << tr("a single transaction cannot use more than one payment id");
return true;
}
crypto::hash payment_id;
std::string extra_nonce;
if (info.has_payment_id)
{
set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, info.payment_id);
}
else if (tools::wallet2::parse_payment_id(payment_id_uri, payment_id))
{
set_payment_id_to_tx_extra_nonce(extra_nonce, payment_id);
message_writer() << tr("Unencrypted payment IDs are bad for privacy: ask the recipient to use subaddresses instead");
}
else
{
fail_msg_writer() << tr("failed to parse payment id, though it was detected");
return true;
}
bool r = add_extra_nonce_to_tx_extra(extra, extra_nonce);
if(!r)
{
fail_msg_writer() << tr("failed to set up payment id, though it was decoded correctly");
return true;
}
payment_id_seen = true;
}
dsts.push_back(de);
}
// prompt is there is no payment id and confirmation is required
if (!payment_id_seen && m_wallet->confirm_missing_payment_id() && dsts.size() > num_subaddresses)
{
std::string accepted = input_line(tr("No payment id is included with this transaction. Is this okay? (Y/Yes/N/No): "));
if (std::cin.eof())
return true;
if (!command_line::is_yes(accepted))
{
fail_msg_writer() << tr("transaction cancelled.");
return true;
}
}
SCOPED_WALLET_UNLOCK();
try
{
// figure out what tx will be necessary
std::vector<tools::wallet2::pending_tx> ptx_vector;
uint64_t bc_height, unlock_block = 0;
std::string err;
switch (transfer_type)
{
case TransferLocked:
bc_height = get_daemon_blockchain_height(err);
if (!err.empty())
{
fail_msg_writer() << tr("failed to get blockchain height: ") << err;
return true;
}
unlock_block = bc_height + locked_blocks;
ptx_vector = m_wallet->create_transactions_2(dsts, fake_outs_count, unlock_block /* unlock_time */, priority, extra, m_current_subaddress_account, subaddr_indices);
break;
default:
LOG_ERROR("Unknown transfer method, using default");
/* FALLTHRU */
case Transfer:
ptx_vector = m_wallet->create_transactions_2(dsts, fake_outs_count, 0 /* unlock_time */, priority, extra, m_current_subaddress_account, subaddr_indices);
break;
}
if (ptx_vector.empty())
{
fail_msg_writer() << tr("No outputs found, or daemon is not ready");
return true;
}
// if we need to check for backlog, check the worst case tx
if (m_wallet->confirm_backlog())
{
std::stringstream prompt;
double worst_fee_per_byte = std::numeric_limits<double>::max();
for (size_t n = 0; n < ptx_vector.size(); ++n)
{
const uint64_t blob_size = cryptonote::tx_to_blob(ptx_vector[n].tx).size();
const double fee_per_byte = ptx_vector[n].fee / (double)blob_size;
if (fee_per_byte < worst_fee_per_byte)
{
worst_fee_per_byte = fee_per_byte;
}
}
try
{
std::vector<std::pair<uint64_t, uint64_t>> nblocks = m_wallet->estimate_backlog({std::make_pair(worst_fee_per_byte, worst_fee_per_byte)});
if (nblocks.size() != 1)
{
prompt << "Internal error checking for backlog. " << tr("Is this okay anyway? (Y/Yes/N/No): ");
}
else
{
if (nblocks[0].first > m_wallet->get_confirm_backlog_threshold())
prompt << (boost::format(tr("There is currently a %u block backlog at that fee level. Is this okay? (Y/Yes/N/No): ")) % nblocks[0].first).str();
}
}
catch (const std::exception &e)
{
prompt << tr("Failed to check for backlog: ") << e.what() << ENDL << tr("Is this okay anyway? (Y/Yes/N/No): ");
}
std::string prompt_str = prompt.str();
if (!prompt_str.empty())
{
std::string accepted = input_line(prompt_str);
if (std::cin.eof())
return true;
if (!command_line::is_yes(accepted))
{
fail_msg_writer() << tr("transaction cancelled.");
return true;
}
}
}
// if more than one tx necessary, prompt user to confirm
if (m_wallet->always_confirm_transfers() || ptx_vector.size() > 1)
{
uint64_t total_sent = 0;
uint64_t total_fee = 0;
uint64_t dust_not_in_fee = 0;
uint64_t dust_in_fee = 0;
for (size_t n = 0; n < ptx_vector.size(); ++n)
{
total_fee += ptx_vector[n].fee;
for (auto i: ptx_vector[n].selected_transfers)
total_sent += m_wallet->get_transfer_details(i).amount();
total_sent -= ptx_vector[n].change_dts.amount + ptx_vector[n].fee;
if (ptx_vector[n].dust_added_to_fee)
dust_in_fee += ptx_vector[n].dust;
else
dust_not_in_fee += ptx_vector[n].dust;
}
std::stringstream prompt;
for (size_t n = 0; n < ptx_vector.size(); ++n)
{
prompt << tr("\nTransaction ") << (n + 1) << "/" << ptx_vector.size() << ":\n";
subaddr_indices.clear();
for (uint32_t i : ptx_vector[n].construction_data.subaddr_indices)
subaddr_indices.insert(i);
for (uint32_t i : subaddr_indices)
prompt << boost::format(tr("Spending from address index %d\n")) % i;
if (subaddr_indices.size() > 1)
prompt << tr("WARNING: Outputs of multiple addresses are being used together, which might potentially compromise your privacy.\n");
}
prompt << boost::format(tr("Sending %s. ")) % print_money(total_sent);
if (ptx_vector.size() > 1)
{
prompt << boost::format(tr("Your transaction needs to be split into %llu transactions. "
"This will result in a transaction fee being applied to each transaction, for a total fee of %s")) %
((unsigned long long)ptx_vector.size()) % print_money(total_fee);
}
else
{
prompt << boost::format(tr("The transaction fee is %s")) %
print_money(total_fee);
}
if (dust_in_fee != 0) prompt << boost::format(tr(", of which %s is dust from change")) % print_money(dust_in_fee);
if (dust_not_in_fee != 0) prompt << tr(".") << ENDL << boost::format(tr("A total of %s from dust change will be sent to dust address"))
% print_money(dust_not_in_fee);
if (transfer_type == TransferLocked)
{
float days = locked_blocks / 720.0f;
prompt << boost::format(tr(".\nThis transaction will unlock on block %llu, in approximately %s days (assuming 2 minutes per block)")) % ((unsigned long long)unlock_block) % days;
}
if (m_wallet->print_ring_members())
{
if (!print_ring_members(ptx_vector, prompt))
return true;
}
bool default_ring_size = true;
for (const auto &ptx: ptx_vector)
{
for (const auto &vin: ptx.tx.vin)
{
if (vin.type() == typeid(txin_to_key))
{
const txin_to_key& in_to_key = boost::get<txin_to_key>(vin);
if (in_to_key.key_offsets.size() != DEFAULT_MIX + 1)
default_ring_size = false;
}
}
}
if (m_wallet->confirm_non_default_ring_size() && !default_ring_size)
{
prompt << tr("WARNING: this is a non default ring size, which may harm your privacy. Default is recommended.");
}
prompt << ENDL << tr("Is this okay? (Y/Yes/N/No): ");
std::string accepted = input_line(prompt.str());
if (std::cin.eof())
return true;
if (!command_line::is_yes(accepted))
{
fail_msg_writer() << tr("transaction cancelled.");
return true;
}
}
// actually commit the transactions
if (m_wallet->multisig())
{
bool r = m_wallet->save_multisig_tx(ptx_vector, "multisig_jyocoin_tx");
if (!r)
{
fail_msg_writer() << tr("Failed to write transaction(s) to file");
}
else
{
success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "multisig_jyocoin_tx";
}
}
else if (m_wallet->get_account().get_device().has_tx_cold_sign())
{
try
{
tools::wallet2::signed_tx_set signed_tx;
if (!cold_sign_tx(ptx_vector, signed_tx, dsts_info, [&](const tools::wallet2::signed_tx_set &tx){ return accept_loaded_tx(tx); })){
fail_msg_writer() << tr("Failed to cold sign transaction with HW wallet");
return true;
}
commit_or_save(signed_tx.ptx, m_do_not_relay);
}
catch (const std::exception& e)
{
handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
}
catch (...)
{
LOG_ERROR("Unknown error");
fail_msg_writer() << tr("unknown error");
}
}
else if (m_wallet->watch_only())
{
bool r = m_wallet->save_tx(ptx_vector, "unsigned_jyocoin_tx");
if (!r)
{
fail_msg_writer() << tr("Failed to write transaction(s) to file");
}
else
{
success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "unsigned_jyocoin_tx";
}
}
else
{
commit_or_save(ptx_vector, m_do_not_relay);
}
}
catch (const std::exception &e)
{
handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
}
catch (...)
{
LOG_ERROR("unknown error");
fail_msg_writer() << tr("unknown error");
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::transfer(const std::vector<std::string> &args_)
{
return transfer_main(Transfer, args_);
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::locked_transfer(const std::vector<std::string> &args_)
{
return transfer_main(TransferLocked, args_);
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::locked_sweep_all(const std::vector<std::string> &args_)
{
return sweep_main(0, true, args_);
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::sweep_unmixable(const std::vector<std::string> &args_)
{
if (!try_connect_to_daemon())
return true;
SCOPED_WALLET_UNLOCK();
try
{
// figure out what tx will be necessary
auto ptx_vector = m_wallet->create_unmixable_sweep_transactions();
if (ptx_vector.empty())
{
fail_msg_writer() << tr("No unmixable outputs found");
return true;
}
// give user total and fee, and prompt to confirm
uint64_t total_fee = 0, total_unmixable = 0;
for (size_t n = 0; n < ptx_vector.size(); ++n)
{
total_fee += ptx_vector[n].fee;
for (auto i: ptx_vector[n].selected_transfers)
total_unmixable += m_wallet->get_transfer_details(i).amount();
}
std::string prompt_str = tr("Sweeping ") + print_money(total_unmixable);
if (ptx_vector.size() > 1) {
prompt_str = (boost::format(tr("Sweeping %s in %llu transactions for a total fee of %s. Is this okay? (Y/Yes/N/No): ")) %
print_money(total_unmixable) %
((unsigned long long)ptx_vector.size()) %
print_money(total_fee)).str();
}
else {
prompt_str = (boost::format(tr("Sweeping %s for a total fee of %s. Is this okay? (Y/Yes/N/No): ")) %
print_money(total_unmixable) %
print_money(total_fee)).str();
}
std::string accepted = input_line(prompt_str);
if (std::cin.eof())
return true;
if (!command_line::is_yes(accepted))
{
fail_msg_writer() << tr("transaction cancelled.");
return true;
}
// actually commit the transactions
if (m_wallet->multisig())
{
bool r = m_wallet->save_multisig_tx(ptx_vector, "multisig_jyocoin_tx");
if (!r)
{
fail_msg_writer() << tr("Failed to write transaction(s) to file");
}
else
{
success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "multisig_jyocoin_tx";
}
}
else if (m_wallet->watch_only())
{
bool r = m_wallet->save_tx(ptx_vector, "unsigned_jyocoin_tx");
if (!r)
{
fail_msg_writer() << tr("Failed to write transaction(s) to file");
}
else
{
success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "unsigned_jyocoin_tx";
}
}
else
{
commit_or_save(ptx_vector, m_do_not_relay);
}
}
catch (const tools::error::not_enough_unlocked_money& e)
{
fail_msg_writer() << tr("Not enough money in unlocked balance");
std::string accepted = input_line((boost::format(tr("Discarding %s of unmixable outputs that cannot be spent, which can be undone by \"rescan_spent\". Is this okay? (Y/Yes/N/No): ")) % print_money(e.available())).str());
if (std::cin.eof())
return true;
if (command_line::is_yes(accepted))
{
try
{
m_wallet->discard_unmixable_outputs();
} catch (...) {}
}
}
catch (const std::exception &e)
{
handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
}
catch (...)
{
LOG_ERROR("unknown error");
fail_msg_writer() << tr("unknown error");
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::sweep_main(uint64_t below, bool locked, const std::vector<std::string> &args_)
{
auto print_usage = [below]()
{
fail_msg_writer() << boost::format(tr("usage: %s [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] [outputs=<N>] <address> [<payment_id>]")) % (below ? "sweep_below" : "sweep_all");
};
if (args_.size() == 0)
{
fail_msg_writer() << tr("No address given");
print_usage();
return true;
}
if (!try_connect_to_daemon())
return true;
std::vector<std::string> local_args = args_;
std::set<uint32_t> subaddr_indices;
if (local_args.size() > 0 && local_args[0].substr(0, 6) == "index=")
{
if (!parse_subaddress_indices(local_args[0], subaddr_indices))
{
print_usage();
return true;
}
local_args.erase(local_args.begin());
}
uint32_t priority = 0;
if (local_args.size() > 0 && parse_priority(local_args[0], priority))
local_args.erase(local_args.begin());
priority = m_wallet->adjust_priority(priority);
size_t fake_outs_count = 0;
if(local_args.size() > 0) {
size_t ring_size;
if(!epee::string_tools::get_xtype_from_string(ring_size, local_args[0]))
{
fake_outs_count = m_wallet->default_mixin();
if (fake_outs_count == 0)
fake_outs_count = DEFAULT_MIX;
}
else if (ring_size == 0)
{
fail_msg_writer() << tr("Ring size must not be 0");
return true;
}
else
{
fake_outs_count = ring_size - 1;
local_args.erase(local_args.begin());
}
}
uint64_t adjusted_fake_outs_count = m_wallet->adjust_mixin(fake_outs_count);
if (adjusted_fake_outs_count > fake_outs_count)
{
fail_msg_writer() << (boost::format(tr("ring size %u is too small, minimum is %u")) % (fake_outs_count+1) % (adjusted_fake_outs_count+1)).str();
return true;
}
if (adjusted_fake_outs_count < fake_outs_count)
{
fail_msg_writer() << (boost::format(tr("ring size %u is too large, maximum is %u")) % (fake_outs_count+1) % (adjusted_fake_outs_count+1)).str();
return true;
}
uint64_t unlock_block = 0;
if (locked) {
uint64_t locked_blocks = 0;
if (local_args.size() < 2) {
fail_msg_writer() << tr("missing lockedblocks parameter");
return true;
}
try
{
locked_blocks = boost::lexical_cast<uint64_t>(local_args[1]);
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("bad locked_blocks parameter");
return true;
}
if (locked_blocks > 1000000)
{
fail_msg_writer() << tr("Locked blocks too high, max 1000000 (˜4 yrs)");
return true;
}
std::string err;
uint64_t bc_height = get_daemon_blockchain_height(err);
if (!err.empty())
{
fail_msg_writer() << tr("failed to get blockchain height: ") << err;
return true;
}
unlock_block = bc_height + locked_blocks;
local_args.erase(local_args.begin() + 1);
}
size_t outputs = 1;
if (local_args.size() > 0 && local_args[0].substr(0, 8) == "outputs=")
{
if (!epee::string_tools::get_xtype_from_string(outputs, local_args[0].substr(8)))
{
fail_msg_writer() << tr("Failed to parse number of outputs");
return true;
}
else if (outputs < 1)
{
fail_msg_writer() << tr("Amount of outputs should be greater than 0");
return true;
}
else
{
local_args.erase(local_args.begin());
}
}
std::vector<uint8_t> extra;
bool payment_id_seen = false;
if (local_args.size() >= 2)
{
std::string payment_id_str = local_args.back();
crypto::hash payment_id;
bool r = tools::wallet2::parse_long_payment_id(payment_id_str, payment_id);
if(r)
{
std::string extra_nonce;
set_payment_id_to_tx_extra_nonce(extra_nonce, payment_id);
r = add_extra_nonce_to_tx_extra(extra, extra_nonce);
payment_id_seen = true;
}
else
{
crypto::hash8 payment_id8;
r = tools::wallet2::parse_short_payment_id(payment_id_str, payment_id8);
if(r)
{
std::string extra_nonce;
set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, payment_id8);
r = add_extra_nonce_to_tx_extra(extra, extra_nonce);
payment_id_seen = true;
}
}
if(!r && local_args.size() == 3)
{
fail_msg_writer() << tr("payment id has invalid format, expected 16 or 64 character hex string: ") << payment_id_str;
print_usage();
return true;
}
if (payment_id_seen)
local_args.pop_back();
}
cryptonote::address_parse_info info;
if (!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), local_args[0], oa_prompter))
{
fail_msg_writer() << tr("failed to parse address");
print_usage();
return true;
}
if (info.has_payment_id)
{
if (payment_id_seen)
{
fail_msg_writer() << tr("a single transaction cannot use more than one payment id: ") << local_args[0];
return true;
}
std::string extra_nonce;
set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, info.payment_id);
bool r = add_extra_nonce_to_tx_extra(extra, extra_nonce);
if(!r)
{
fail_msg_writer() << tr("failed to set up payment id, though it was decoded correctly");
return true;
}
payment_id_seen = true;
}
// prompt is there is no payment id and confirmation is required
if (!payment_id_seen && m_wallet->confirm_missing_payment_id() && !info.is_subaddress)
{
std::string accepted = input_line(tr("No payment id is included with this transaction. Is this okay? (Y/Yes/N/No): "));
if (std::cin.eof())
return true;
if (!command_line::is_yes(accepted))
{
fail_msg_writer() << tr("transaction cancelled.");
return true;
}
}
SCOPED_WALLET_UNLOCK();
try
{
// figure out what tx will be necessary
auto ptx_vector = m_wallet->create_transactions_all(below, info.address, info.is_subaddress, outputs, fake_outs_count, unlock_block /* unlock_time */, priority, extra, m_current_subaddress_account, subaddr_indices);
if (ptx_vector.empty())
{
fail_msg_writer() << tr("No outputs found, or daemon is not ready");
return true;
}
// give user total and fee, and prompt to confirm
uint64_t total_fee = 0, total_sent = 0;
for (size_t n = 0; n < ptx_vector.size(); ++n)
{
total_fee += ptx_vector[n].fee;
for (auto i: ptx_vector[n].selected_transfers)
total_sent += m_wallet->get_transfer_details(i).amount();
}
std::ostringstream prompt;
for (size_t n = 0; n < ptx_vector.size(); ++n)
{
prompt << tr("\nTransaction ") << (n + 1) << "/" << ptx_vector.size() << ":\n";
subaddr_indices.clear();
for (uint32_t i : ptx_vector[n].construction_data.subaddr_indices)
subaddr_indices.insert(i);
for (uint32_t i : subaddr_indices)
prompt << boost::format(tr("Spending from address index %d\n")) % i;
if (subaddr_indices.size() > 1)
prompt << tr("WARNING: Outputs of multiple addresses are being used together, which might potentially compromise your privacy.\n");
}
if (m_wallet->print_ring_members() && !print_ring_members(ptx_vector, prompt))
return true;
if (ptx_vector.size() > 1) {
prompt << boost::format(tr("Sweeping %s in %llu transactions for a total fee of %s. Is this okay? (Y/Yes/N/No): ")) %
print_money(total_sent) %
((unsigned long long)ptx_vector.size()) %
print_money(total_fee);
}
else {
prompt << boost::format(tr("Sweeping %s for a total fee of %s. Is this okay? (Y/Yes/N/No): ")) %
print_money(total_sent) %
print_money(total_fee);
}
std::string accepted = input_line(prompt.str());
if (std::cin.eof())
return true;
if (!command_line::is_yes(accepted))
{
fail_msg_writer() << tr("transaction cancelled.");
return true;
}
// actually commit the transactions
if (m_wallet->multisig())
{
bool r = m_wallet->save_multisig_tx(ptx_vector, "multisig_jyocoin_tx");
if (!r)
{
fail_msg_writer() << tr("Failed to write transaction(s) to file");
}
else
{
success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "multisig_jyocoin_tx";
}
}
else if (m_wallet->get_account().get_device().has_tx_cold_sign())
{
try
{
tools::wallet2::signed_tx_set signed_tx;
std::vector<cryptonote::address_parse_info> dsts_info;
dsts_info.push_back(info);
if (!cold_sign_tx(ptx_vector, signed_tx, dsts_info, [&](const tools::wallet2::signed_tx_set &tx){ return accept_loaded_tx(tx); })){
fail_msg_writer() << tr("Failed to cold sign transaction with HW wallet");
return true;
}
commit_or_save(signed_tx.ptx, m_do_not_relay);
}
catch (const std::exception& e)
{
handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
}
catch (...)
{
LOG_ERROR("Unknown error");
fail_msg_writer() << tr("unknown error");
}
}
else if (m_wallet->watch_only())
{
bool r = m_wallet->save_tx(ptx_vector, "unsigned_jyocoin_tx");
if (!r)
{
fail_msg_writer() << tr("Failed to write transaction(s) to file");
}
else
{
success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "unsigned_jyocoin_tx";
}
}
else
{
commit_or_save(ptx_vector, m_do_not_relay);
}
}
catch (const std::exception& e)
{
handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
}
catch (...)
{
LOG_ERROR("unknown error");
fail_msg_writer() << tr("unknown error");
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::sweep_single(const std::vector<std::string> &args_)
{
if (!try_connect_to_daemon())
return true;
std::vector<std::string> local_args = args_;
uint32_t priority = 0;
if (local_args.size() > 0 && parse_priority(local_args[0], priority))
local_args.erase(local_args.begin());
priority = m_wallet->adjust_priority(priority);
size_t fake_outs_count = 0;
if(local_args.size() > 0) {
size_t ring_size;
if(!epee::string_tools::get_xtype_from_string(ring_size, local_args[0]))
{
fake_outs_count = m_wallet->default_mixin();
if (fake_outs_count == 0)
fake_outs_count = DEFAULT_MIX;
}
else if (ring_size == 0)
{
fail_msg_writer() << tr("Ring size must not be 0");
return true;
}
else
{
fake_outs_count = ring_size - 1;
local_args.erase(local_args.begin());
}
}
uint64_t adjusted_fake_outs_count = m_wallet->adjust_mixin(fake_outs_count);
if (adjusted_fake_outs_count > fake_outs_count)
{
fail_msg_writer() << (boost::format(tr("ring size %u is too small, minimum is %u")) % (fake_outs_count+1) % (adjusted_fake_outs_count+1)).str();
return true;
}
if (adjusted_fake_outs_count < fake_outs_count)
{
fail_msg_writer() << (boost::format(tr("ring size %u is too large, maximum is %u")) % (fake_outs_count+1) % (adjusted_fake_outs_count+1)).str();
return true;
}
size_t outputs = 1;
if (local_args.size() > 0 && local_args[0].substr(0, 8) == "outputs=")
{
if (!epee::string_tools::get_xtype_from_string(outputs, local_args[0].substr(8)))
{
fail_msg_writer() << tr("Failed to parse number of outputs");
return true;
}
else if (outputs < 1)
{
fail_msg_writer() << tr("Amount of outputs should be greater than 0");
return true;
}
else
{
local_args.erase(local_args.begin());
}
}
std::vector<uint8_t> extra;
bool payment_id_seen = false;
if (local_args.size() == 3)
{
crypto::hash payment_id;
crypto::hash8 payment_id8;
std::string extra_nonce;
if (tools::wallet2::parse_long_payment_id(local_args.back(), payment_id))
{
set_payment_id_to_tx_extra_nonce(extra_nonce, payment_id);
}
else if(tools::wallet2::parse_short_payment_id(local_args.back(), payment_id8))
{
set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, payment_id8);
}
else
{
fail_msg_writer() << tr("failed to parse Payment ID");
return true;
}
if (!add_extra_nonce_to_tx_extra(extra, extra_nonce))
{
fail_msg_writer() << tr("failed to set up payment id, though it was decoded correctly");
return true;
}
local_args.pop_back();
payment_id_seen = true;
}
if (local_args.size() != 2)
{
fail_msg_writer() << tr("usage: sweep_single [<priority>] [<ring_size>] [outputs=<N>] <key_image> <address> [<payment_id>]");
return true;
}
crypto::key_image ki;
if (!epee::string_tools::hex_to_pod(local_args[0], ki))
{
fail_msg_writer() << tr("failed to parse key image");
return true;
}
cryptonote::address_parse_info info;
if (!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), local_args[1], oa_prompter))
{
fail_msg_writer() << tr("failed to parse address");
return true;
}
if (info.has_payment_id)
{
if (payment_id_seen)
{
fail_msg_writer() << tr("a single transaction cannot use more than one payment id: ") << local_args[0];
return true;
}
std::string extra_nonce;
set_encrypted_payment_id_to_tx_extra_nonce(extra_nonce, info.payment_id);
if (!add_extra_nonce_to_tx_extra(extra, extra_nonce))
{
fail_msg_writer() << tr("failed to set up payment id, though it was decoded correctly");
return true;
}
payment_id_seen = true;
}
// prompt if there is no payment id and confirmation is required
if (!payment_id_seen && m_wallet->confirm_missing_payment_id() && !info.is_subaddress)
{
std::string accepted = input_line(tr("No payment id is included with this transaction. Is this okay? (Y/Yes/N/No): "));
if (std::cin.eof())
return true;
if (!command_line::is_yes(accepted))
{
fail_msg_writer() << tr("transaction cancelled.");
// would like to return false, because no tx made, but everything else returns true
// and I don't know what returning false might adversely affect. *sigh*
return true;
}
}
SCOPED_WALLET_UNLOCK();
try
{
// figure out what tx will be necessary
auto ptx_vector = m_wallet->create_transactions_single(ki, info.address, info.is_subaddress, outputs, fake_outs_count, 0 /* unlock_time */, priority, extra);
if (ptx_vector.empty())
{
fail_msg_writer() << tr("No outputs found");
return true;
}
if (ptx_vector.size() > 1)
{
fail_msg_writer() << tr("Multiple transactions are created, which is not supposed to happen");
return true;
}
if (ptx_vector[0].selected_transfers.size() != 1)
{
fail_msg_writer() << tr("The transaction uses multiple or no inputs, which is not supposed to happen");
return true;
}
// give user total and fee, and prompt to confirm
uint64_t total_fee = ptx_vector[0].fee;
uint64_t total_sent = m_wallet->get_transfer_details(ptx_vector[0].selected_transfers.front()).amount();
std::ostringstream prompt;
if (!print_ring_members(ptx_vector, prompt))
return true;
prompt << boost::format(tr("Sweeping %s for a total fee of %s. Is this okay? (Y/Yes/N/No): ")) %
print_money(total_sent) %
print_money(total_fee);
std::string accepted = input_line(prompt.str());
if (std::cin.eof())
return true;
if (!command_line::is_yes(accepted))
{
fail_msg_writer() << tr("transaction cancelled.");
return true;
}
// actually commit the transactions
if (m_wallet->multisig())
{
bool r = m_wallet->save_multisig_tx(ptx_vector, "multisig_jyocoin_tx");
if (!r)
{
fail_msg_writer() << tr("Failed to write transaction(s) to file");
}
else
{
success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "multisig_jyocoin_tx";
}
}
else if (m_wallet->watch_only())
{
bool r = m_wallet->save_tx(ptx_vector, "unsigned_jyocoin_tx");
if (!r)
{
fail_msg_writer() << tr("Failed to write transaction(s) to file");
}
else
{
success_msg_writer(true) << tr("Unsigned transaction(s) successfully written to file: ") << "unsigned_jyocoin_tx";
}
}
else
{
m_wallet->commit_tx(ptx_vector[0]);
success_msg_writer(true) << tr("Money successfully sent, transaction: ") << get_transaction_hash(ptx_vector[0].tx);
}
}
catch (const std::exception& e)
{
handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
}
catch (...)
{
LOG_ERROR("unknown error");
fail_msg_writer() << tr("unknown error");
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::sweep_all(const std::vector<std::string> &args_)
{
return sweep_main(0, false, args_);
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::sweep_below(const std::vector<std::string> &args_)
{
uint64_t below = 0;
if (args_.size() < 1)
{
fail_msg_writer() << tr("missing threshold amount");
return true;
}
if (!cryptonote::parse_amount(below, args_[0]))
{
fail_msg_writer() << tr("invalid amount threshold");
return true;
}
return sweep_main(below, false, std::vector<std::string>(++args_.begin(), args_.end()));
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::donate(const std::vector<std::string> &args_)
{
if(m_wallet->nettype() != cryptonote::MAINNET)
{
fail_msg_writer() << tr("donations are not enabled on the testnet or on the stagenet");
return true;
}
std::vector<std::string> local_args = args_;
if(local_args.empty() || local_args.size() > 5)
{
fail_msg_writer() << tr("usage: donate [index=<N1>[,<N2>,...]] [<priority>] [<ring_size>] <amount> [<payment_id>]");
return true;
}
std::string amount_str;
std::string payment_id_str;
// get payment id and pop
crypto::hash payment_id;
crypto::hash8 payment_id8;
if (tools::wallet2::parse_long_payment_id (local_args.back(), payment_id ) ||
tools::wallet2::parse_short_payment_id(local_args.back(), payment_id8))
{
payment_id_str = local_args.back();
local_args.pop_back();
}
// get amount and pop
amount_str = local_args.back();
local_args.pop_back();
// push back address, amount, payment id
local_args.push_back(jyocoin_DONATION_ADDR);
local_args.push_back(amount_str);
if (!payment_id_str.empty())
local_args.push_back(payment_id_str);
message_writer() << (boost::format(tr("Donating %s %s to The jyocoin Project (donate.getjyocoin.org or %s).")) % amount_str % cryptonote::get_unit(cryptonote::get_default_decimal_point()) % jyocoin_DONATION_ADDR).str();
transfer(local_args);
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::accept_loaded_tx(const std::function<size_t()> get_num_txes, const std::function<const tools::wallet2::tx_construction_data&(size_t)> &get_tx, const std::string &extra_message)
{
// gather info to ask the user
uint64_t amount = 0, amount_to_dests = 0, change = 0;
size_t min_ring_size = ~0;
std::unordered_map<cryptonote::account_public_address, std::pair<std::string, uint64_t>> dests;
int first_known_non_zero_change_index = -1;
std::string payment_id_string = "";
for (size_t n = 0; n < get_num_txes(); ++n)
{
const tools::wallet2::tx_construction_data &cd = get_tx(n);
std::vector<tx_extra_field> tx_extra_fields;
bool has_encrypted_payment_id = false;
crypto::hash8 payment_id8 = crypto::null_hash8;
if (cryptonote::parse_tx_extra(cd.extra, tx_extra_fields))
{
tx_extra_nonce extra_nonce;
if (find_tx_extra_field_by_type(tx_extra_fields, extra_nonce))
{
crypto::hash payment_id;
if(get_encrypted_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id8))
{
if (!payment_id_string.empty())
payment_id_string += ", ";
payment_id_string = std::string("encrypted payment ID ") + epee::string_tools::pod_to_hex(payment_id8);
has_encrypted_payment_id = true;
}
else if (get_payment_id_from_tx_extra_nonce(extra_nonce.nonce, payment_id))
{
if (!payment_id_string.empty())
payment_id_string += ", ";
payment_id_string = std::string("unencrypted payment ID ") + epee::string_tools::pod_to_hex(payment_id);
}
}
}
for (size_t s = 0; s < cd.sources.size(); ++s)
{
amount += cd.sources[s].amount;
size_t ring_size = cd.sources[s].outputs.size();
if (ring_size < min_ring_size)
min_ring_size = ring_size;
}
for (size_t d = 0; d < cd.splitted_dsts.size(); ++d)
{
const tx_destination_entry &entry = cd.splitted_dsts[d];
std::string address, standard_address = get_account_address_as_str(m_wallet->nettype(), entry.is_subaddress, entry.addr);
if (has_encrypted_payment_id && !entry.is_subaddress)
{
address = get_account_integrated_address_as_str(m_wallet->nettype(), entry.addr, payment_id8);
address += std::string(" (" + standard_address + " with encrypted payment id " + epee::string_tools::pod_to_hex(payment_id8) + ")");
}
else
address = standard_address;
auto i = dests.find(entry.addr);
if (i == dests.end())
dests.insert(std::make_pair(entry.addr, std::make_pair(address, entry.amount)));
else
i->second.second += entry.amount;
amount_to_dests += entry.amount;
}
if (cd.change_dts.amount > 0)
{
auto it = dests.find(cd.change_dts.addr);
if (it == dests.end())
{
fail_msg_writer() << tr("Claimed change does not go to a paid address");
return false;
}
if (it->second.second < cd.change_dts.amount)
{
fail_msg_writer() << tr("Claimed change is larger than payment to the change address");
return false;
}
if (cd.change_dts.amount > 0)
{
if (first_known_non_zero_change_index == -1)
first_known_non_zero_change_index = n;
if (memcmp(&cd.change_dts.addr, &get_tx(first_known_non_zero_change_index).change_dts.addr, sizeof(cd.change_dts.addr)))
{
fail_msg_writer() << tr("Change goes to more than one address");
return false;
}
}
change += cd.change_dts.amount;
it->second.second -= cd.change_dts.amount;
if (it->second.second == 0)
dests.erase(cd.change_dts.addr);
}
}
if (payment_id_string.empty())
payment_id_string = "no payment ID";
std::string dest_string;
size_t n_dummy_outputs = 0;
for (auto i = dests.begin(); i != dests.end(); )
{
if (i->second.second > 0)
{
if (!dest_string.empty())
dest_string += ", ";
dest_string += (boost::format(tr("sending %s to %s")) % print_money(i->second.second) % i->second.first).str();
}
else
++n_dummy_outputs;
++i;
}
if (n_dummy_outputs > 0)
{
if (!dest_string.empty())
dest_string += ", ";
dest_string += std::to_string(n_dummy_outputs) + tr(" dummy output(s)");
}
if (dest_string.empty())
dest_string = tr("with no destinations");
std::string change_string;
if (change > 0)
{
std::string address = get_account_address_as_str(m_wallet->nettype(), get_tx(0).subaddr_account > 0, get_tx(0).change_dts.addr);
change_string += (boost::format(tr("%s change to %s")) % print_money(change) % address).str();
}
else
change_string += tr("no change");
uint64_t fee = amount - amount_to_dests;
std::string prompt_str = (boost::format(tr("Loaded %lu transactions, for %s, fee %s, %s, %s, with min ring size %lu, %s. %sIs this okay? (Y/Yes/N/No): ")) % (unsigned long)get_num_txes() % print_money(amount) % print_money(fee) % dest_string % change_string % (unsigned long)min_ring_size % payment_id_string % extra_message).str();
return command_line::is_yes(input_line(prompt_str));
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::accept_loaded_tx(const tools::wallet2::unsigned_tx_set &txs)
{
std::string extra_message;
if (!txs.transfers.second.empty())
extra_message = (boost::format("%u outputs to import. ") % (unsigned)txs.transfers.second.size()).str();
return accept_loaded_tx([&txs](){return txs.txes.size();}, [&txs](size_t n)->const tools::wallet2::tx_construction_data&{return txs.txes[n];}, extra_message);
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::accept_loaded_tx(const tools::wallet2::signed_tx_set &txs)
{
std::string extra_message;
if (!txs.key_images.empty())
extra_message = (boost::format("%u key images to import. ") % (unsigned)txs.key_images.size()).str();
return accept_loaded_tx([&txs](){return txs.ptx.size();}, [&txs](size_t n)->const tools::wallet2::tx_construction_data&{return txs.ptx[n].construction_data;}, extra_message);
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::sign_transfer(const std::vector<std::string> &args_)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if(m_wallet->multisig())
{
fail_msg_writer() << tr("This is a multisig wallet, it can only sign with sign_multisig");
return true;
}
if(m_wallet->watch_only())
{
fail_msg_writer() << tr("This is a watch only wallet");
return true;
}
if (args_.size() > 1 || (args_.size() == 1 && args_[0] != "export_raw"))
{
fail_msg_writer() << tr("usage: sign_transfer [export_raw]");
return true;
}
SCOPED_WALLET_UNLOCK();
const bool export_raw = args_.size() == 1;
std::vector<tools::wallet2::pending_tx> ptx;
try
{
bool r = m_wallet->sign_tx("unsigned_jyocoin_tx", "signed_jyocoin_tx", ptx, [&](const tools::wallet2::unsigned_tx_set &tx){ return accept_loaded_tx(tx); }, export_raw);
if (!r)
{
fail_msg_writer() << tr("Failed to sign transaction");
return true;
}
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to sign transaction: ") << e.what();
return true;
}
std::string txids_as_text;
for (const auto &t: ptx)
{
if (!txids_as_text.empty())
txids_as_text += (", ");
txids_as_text += epee::string_tools::pod_to_hex(get_transaction_hash(t.tx));
}
success_msg_writer(true) << tr("Transaction successfully signed to file ") << "signed_jyocoin_tx" << ", txid " << txids_as_text;
if (export_raw)
{
std::string rawfiles_as_text;
for (size_t i = 0; i < ptx.size(); ++i)
{
if (i > 0)
rawfiles_as_text += ", ";
rawfiles_as_text += "signed_jyocoin_tx_raw" + (ptx.size() == 1 ? "" : ("_" + std::to_string(i)));
}
success_msg_writer(true) << tr("Transaction raw hex data exported to ") << rawfiles_as_text;
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::submit_transfer(const std::vector<std::string> &args_)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if (!try_connect_to_daemon())
return true;
try
{
std::vector<tools::wallet2::pending_tx> ptx_vector;
bool r = m_wallet->load_tx("signed_jyocoin_tx", ptx_vector, [&](const tools::wallet2::signed_tx_set &tx){ return accept_loaded_tx(tx); });
if (!r)
{
fail_msg_writer() << tr("Failed to load transaction from file");
return true;
}
commit_or_save(ptx_vector, false);
}
catch (const std::exception& e)
{
handle_transfer_exception(std::current_exception(), m_wallet->is_trusted_daemon());
}
catch (...)
{
LOG_ERROR("Unknown error");
fail_msg_writer() << tr("unknown error");
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::get_tx_key(const std::vector<std::string> &args_)
{
std::vector<std::string> local_args = args_;
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if(local_args.size() != 1) {
fail_msg_writer() << tr("usage: get_tx_key <txid>");
return true;
}
crypto::hash txid;
if (!epee::string_tools::hex_to_pod(local_args[0], txid))
{
fail_msg_writer() << tr("failed to parse txid");
return true;
}
SCOPED_WALLET_UNLOCK();
crypto::secret_key tx_key;
std::vector<crypto::secret_key> additional_tx_keys;
if (m_wallet->get_tx_key(txid, tx_key, additional_tx_keys))
{
ostringstream oss;
oss << epee::string_tools::pod_to_hex(tx_key);
for (size_t i = 0; i < additional_tx_keys.size(); ++i)
oss << epee::string_tools::pod_to_hex(additional_tx_keys[i]);
success_msg_writer() << tr("Tx key: ") << oss.str();
return true;
}
else
{
fail_msg_writer() << tr("no tx keys found for this txid");
return true;
}
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::set_tx_key(const std::vector<std::string> &args_)
{
std::vector<std::string> local_args = args_;
if(local_args.size() != 2) {
fail_msg_writer() << tr("usage: set_tx_key <txid> <tx_key>");
return true;
}
crypto::hash txid;
if (!epee::string_tools::hex_to_pod(local_args[0], txid))
{
fail_msg_writer() << tr("failed to parse txid");
return true;
}
crypto::secret_key tx_key;
std::vector<crypto::secret_key> additional_tx_keys;
try
{
if (!epee::string_tools::hex_to_pod(local_args[1].substr(0, 64), tx_key))
{
fail_msg_writer() << tr("failed to parse tx_key");
return true;
}
while(true)
{
local_args[1] = local_args[1].substr(64);
if (local_args[1].empty())
break;
additional_tx_keys.resize(additional_tx_keys.size() + 1);
if (!epee::string_tools::hex_to_pod(local_args[1].substr(0, 64), additional_tx_keys.back()))
{
fail_msg_writer() << tr("failed to parse tx_key");
return true;
}
}
}
catch (const std::out_of_range &e)
{
fail_msg_writer() << tr("failed to parse tx_key");
return true;
}
LOCK_IDLE_SCOPE();
try
{
m_wallet->set_tx_key(txid, tx_key, additional_tx_keys);
success_msg_writer() << tr("Tx key successfully stored.");
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to store tx key: ") << e.what();
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::get_tx_proof(const std::vector<std::string> &args)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if (args.size() != 2 && args.size() != 3)
{
fail_msg_writer() << tr("usage: get_tx_proof <txid> <address> [<message>]");
return true;
}
crypto::hash txid;
if(!epee::string_tools::hex_to_pod(args[0], txid))
{
fail_msg_writer() << tr("failed to parse txid");
return true;
}
cryptonote::address_parse_info info;
if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), args[1], oa_prompter))
{
fail_msg_writer() << tr("failed to parse address");
return true;
}
SCOPED_WALLET_UNLOCK();
try
{
std::string sig_str = m_wallet->get_tx_proof(txid, info.address, info.is_subaddress, args.size() == 3 ? args[2] : "");
const std::string filename = "jyocoin_tx_proof";
if (epee::file_io_utils::save_string_to_file(filename, sig_str))
success_msg_writer() << tr("signature file saved to: ") << filename;
else
fail_msg_writer() << tr("failed to save signature file");
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("error: ") << e.what();
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::check_tx_key(const std::vector<std::string> &args_)
{
std::vector<std::string> local_args = args_;
if(local_args.size() != 3) {
fail_msg_writer() << tr("usage: check_tx_key <txid> <txkey> <address>");
return true;
}
if (!try_connect_to_daemon())
return true;
if (!m_wallet)
{
fail_msg_writer() << tr("wallet is null");
return true;
}
crypto::hash txid;
if(!epee::string_tools::hex_to_pod(local_args[0], txid))
{
fail_msg_writer() << tr("failed to parse txid");
return true;
}
crypto::secret_key tx_key;
std::vector<crypto::secret_key> additional_tx_keys;
if(!epee::string_tools::hex_to_pod(local_args[1].substr(0, 64), tx_key))
{
fail_msg_writer() << tr("failed to parse tx key");
return true;
}
local_args[1] = local_args[1].substr(64);
while (!local_args[1].empty())
{
additional_tx_keys.resize(additional_tx_keys.size() + 1);
if(!epee::string_tools::hex_to_pod(local_args[1].substr(0, 64), additional_tx_keys.back()))
{
fail_msg_writer() << tr("failed to parse tx key");
return true;
}
local_args[1] = local_args[1].substr(64);
}
cryptonote::address_parse_info info;
if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), local_args[2], oa_prompter))
{
fail_msg_writer() << tr("failed to parse address");
return true;
}
try
{
uint64_t received;
bool in_pool;
uint64_t confirmations;
m_wallet->check_tx_key(txid, tx_key, additional_tx_keys, info.address, received, in_pool, confirmations);
if (received > 0)
{
success_msg_writer() << get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address) << " " << tr("received") << " " << print_money(received) << " " << tr("in txid") << " " << txid;
if (in_pool)
{
success_msg_writer() << tr("WARNING: this transaction is not yet included in the blockchain!");
}
else
{
if (confirmations != (uint64_t)-1)
{
success_msg_writer() << boost::format(tr("This transaction has %u confirmations")) % confirmations;
}
else
{
success_msg_writer() << tr("WARNING: failed to determine number of confirmations!");
}
}
}
else
{
fail_msg_writer() << get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address) << " " << tr("received nothing in txid") << " " << txid;
}
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("error: ") << e.what();
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::check_tx_proof(const std::vector<std::string> &args)
{
if(args.size() != 3 && args.size() != 4) {
fail_msg_writer() << tr("usage: check_tx_proof <txid> <address> <signature_file> [<message>]");
return true;
}
if (!try_connect_to_daemon())
return true;
// parse txid
crypto::hash txid;
if(!epee::string_tools::hex_to_pod(args[0], txid))
{
fail_msg_writer() << tr("failed to parse txid");
return true;
}
// parse address
cryptonote::address_parse_info info;
if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), args[1], oa_prompter))
{
fail_msg_writer() << tr("failed to parse address");
return true;
}
// read signature file
std::string sig_str;
if (!epee::file_io_utils::load_file_to_string(args[2], sig_str))
{
fail_msg_writer() << tr("failed to load signature file");
return true;
}
try
{
uint64_t received;
bool in_pool;
uint64_t confirmations;
if (m_wallet->check_tx_proof(txid, info.address, info.is_subaddress, args.size() == 4 ? args[3] : "", sig_str, received, in_pool, confirmations))
{
success_msg_writer() << tr("Good signature");
if (received > 0)
{
success_msg_writer() << get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address) << " " << tr("received") << " " << print_money(received) << " " << tr("in txid") << " " << txid;
if (in_pool)
{
success_msg_writer() << tr("WARNING: this transaction is not yet included in the blockchain!");
}
else
{
if (confirmations != (uint64_t)-1)
{
success_msg_writer() << boost::format(tr("This transaction has %u confirmations")) % confirmations;
}
else
{
success_msg_writer() << tr("WARNING: failed to determine number of confirmations!");
}
}
}
else
{
fail_msg_writer() << get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address) << " " << tr("received nothing in txid") << " " << txid;
}
}
else
{
fail_msg_writer() << tr("Bad signature");
}
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("error: ") << e.what();
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::get_spend_proof(const std::vector<std::string> &args)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if(args.size() != 1 && args.size() != 2) {
fail_msg_writer() << tr("usage: get_spend_proof <txid> [<message>]");
return true;
}
if (m_wallet->watch_only())
{
fail_msg_writer() << tr("wallet is watch-only and cannot generate the proof");
return true;
}
crypto::hash txid;
if (!epee::string_tools::hex_to_pod(args[0], txid))
{
fail_msg_writer() << tr("failed to parse txid");
return true;
}
if (!try_connect_to_daemon())
return true;
SCOPED_WALLET_UNLOCK();
try
{
const std::string sig_str = m_wallet->get_spend_proof(txid, args.size() == 2 ? args[1] : "");
const std::string filename = "jyocoin_spend_proof";
if (epee::file_io_utils::save_string_to_file(filename, sig_str))
success_msg_writer() << tr("signature file saved to: ") << filename;
else
fail_msg_writer() << tr("failed to save signature file");
}
catch (const std::exception &e)
{
fail_msg_writer() << e.what();
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::check_spend_proof(const std::vector<std::string> &args)
{
if(args.size() != 2 && args.size() != 3) {
fail_msg_writer() << tr("usage: check_spend_proof <txid> <signature_file> [<message>]");
return true;
}
crypto::hash txid;
if (!epee::string_tools::hex_to_pod(args[0], txid))
{
fail_msg_writer() << tr("failed to parse txid");
return true;
}
if (!try_connect_to_daemon())
return true;
std::string sig_str;
if (!epee::file_io_utils::load_file_to_string(args[1], sig_str))
{
fail_msg_writer() << tr("failed to load signature file");
return true;
}
try
{
if (m_wallet->check_spend_proof(txid, args.size() == 3 ? args[2] : "", sig_str))
success_msg_writer() << tr("Good signature");
else
fail_msg_writer() << tr("Bad signature");
}
catch (const std::exception& e)
{
fail_msg_writer() << e.what();
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::get_reserve_proof(const std::vector<std::string> &args)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if(args.size() != 1 && args.size() != 2) {
fail_msg_writer() << tr("usage: get_reserve_proof (all|<amount>) [<message>]");
return true;
}
if (m_wallet->watch_only() || m_wallet->multisig())
{
fail_msg_writer() << tr("The reserve proof can be generated only by a full wallet");
return true;
}
boost::optional<std::pair<uint32_t, uint64_t>> account_minreserve;
if (args[0] != "all")
{
account_minreserve = std::pair<uint32_t, uint64_t>();
account_minreserve->first = m_current_subaddress_account;
if (!cryptonote::parse_amount(account_minreserve->second, args[0]))
{
fail_msg_writer() << tr("amount is wrong: ") << args[0];
return true;
}
}
if (!try_connect_to_daemon())
return true;
SCOPED_WALLET_UNLOCK();
try
{
const std::string sig_str = m_wallet->get_reserve_proof(account_minreserve, args.size() == 2 ? args[1] : "");
const std::string filename = "jyocoin_reserve_proof";
if (epee::file_io_utils::save_string_to_file(filename, sig_str))
success_msg_writer() << tr("signature file saved to: ") << filename;
else
fail_msg_writer() << tr("failed to save signature file");
}
catch (const std::exception &e)
{
fail_msg_writer() << e.what();
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::check_reserve_proof(const std::vector<std::string> &args)
{
if(args.size() != 2 && args.size() != 3) {
fail_msg_writer() << tr("usage: check_reserve_proof <address> <signature_file> [<message>]");
return true;
}
if (!try_connect_to_daemon())
return true;
cryptonote::address_parse_info info;
if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), args[0], oa_prompter))
{
fail_msg_writer() << tr("failed to parse address");
return true;
}
if (info.is_subaddress)
{
fail_msg_writer() << tr("Address must not be a subaddress");
return true;
}
std::string sig_str;
if (!epee::file_io_utils::load_file_to_string(args[1], sig_str))
{
fail_msg_writer() << tr("failed to load signature file");
return true;
}
LOCK_IDLE_SCOPE();
try
{
uint64_t total, spent;
if (m_wallet->check_reserve_proof(info.address, args.size() == 3 ? args[2] : "", sig_str, total, spent))
{
success_msg_writer() << boost::format(tr("Good signature -- total: %s, spent: %s, unspent: %s")) % print_money(total) % print_money(spent) % print_money(total - spent);
}
else
{
fail_msg_writer() << tr("Bad signature");
}
}
catch (const std::exception& e)
{
fail_msg_writer() << e.what();
}
return true;
}
//----------------------------------------------------------------------------------------------------
static std::string get_human_readable_timestamp(uint64_t ts)
{
char buffer[64];
if (ts < 1234567890)
return "<unknown>";
time_t tt = ts;
struct tm tm;
#ifdef WIN32
gmtime_s(&tm, &tt);
#else
gmtime_r(&tt, &tm);
#endif
uint64_t now = time(NULL);
uint64_t diff = ts > now ? ts - now : now - ts;
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &tm);
return std::string(buffer);
}
//----------------------------------------------------------------------------------------------------
static std::string get_human_readable_timespan(std::chrono::seconds seconds)
{
uint64_t ts = seconds.count();
if (ts < 60)
return std::to_string(ts) + sw::tr(" seconds");
if (ts < 3600)
return std::to_string((uint64_t)(ts / 60)) + sw::tr(" minutes");
if (ts < 3600 * 24)
return std::to_string((uint64_t)(ts / 3600)) + sw::tr(" hours");
if (ts < 3600 * 24 * 30.5)
return std::to_string((uint64_t)(ts / (3600 * 24))) + sw::tr(" days");
if (ts < 3600 * 24 * 365.25)
return std::to_string((uint64_t)(ts / (3600 * 24 * 30.5))) + sw::tr(" months");
return sw::tr("a long time");
}
//----------------------------------------------------------------------------------------------------
// mutates local_args as it parses and consumes arguments
bool simple_wallet::get_transfers(std::vector<std::string>& local_args, std::vector<transfer_view>& transfers)
{
bool in = true;
bool out = true;
bool pending = true;
bool failed = true;
bool pool = true;
bool coinbase = true;
uint64_t min_height = 0;
uint64_t max_height = (uint64_t)-1;
// optional in/out selector
if (local_args.size() > 0) {
if (local_args[0] == "in" || local_args[0] == "incoming") {
out = pending = failed = false;
local_args.erase(local_args.begin());
}
else if (local_args[0] == "out" || local_args[0] == "outgoing") {
in = pool = coinbase = false;
local_args.erase(local_args.begin());
}
else if (local_args[0] == "pending") {
in = out = failed = coinbase = false;
local_args.erase(local_args.begin());
}
else if (local_args[0] == "failed") {
in = out = pending = pool = coinbase = false;
local_args.erase(local_args.begin());
}
else if (local_args[0] == "pool") {
in = out = pending = failed = coinbase = false;
local_args.erase(local_args.begin());
}
else if (local_args[0] == "coinbase") {
in = out = pending = failed = pool = false;
coinbase = true;
local_args.erase(local_args.begin());
}
else if (local_args[0] == "all" || local_args[0] == "both") {
local_args.erase(local_args.begin());
}
}
// subaddr_index
std::set<uint32_t> subaddr_indices;
if (local_args.size() > 0 && local_args[0].substr(0, 6) == "index=")
{
if (!parse_subaddress_indices(local_args[0], subaddr_indices))
return false;
local_args.erase(local_args.begin());
}
// min height
if (local_args.size() > 0 && local_args[0].find('=') == std::string::npos) {
try {
min_height = boost::lexical_cast<uint64_t>(local_args[0]);
}
catch (const boost::bad_lexical_cast &) {
fail_msg_writer() << tr("bad min_height parameter:") << " " << local_args[0];
return false;
}
local_args.erase(local_args.begin());
}
// max height
if (local_args.size() > 0 && local_args[0].find('=') == std::string::npos) {
try {
max_height = boost::lexical_cast<uint64_t>(local_args[0]);
}
catch (const boost::bad_lexical_cast &) {
fail_msg_writer() << tr("bad max_height parameter:") << " " << local_args[0];
return false;
}
local_args.erase(local_args.begin());
}
if (in || coinbase) {
std::list<std::pair<crypto::hash, tools::wallet2::payment_details>> payments;
m_wallet->get_payments(payments, min_height, max_height, m_current_subaddress_account, subaddr_indices);
for (std::list<std::pair<crypto::hash, tools::wallet2::payment_details>>::const_iterator i = payments.begin(); i != payments.end(); ++i) {
const tools::wallet2::payment_details &pd = i->second;
if (!pd.m_coinbase && !in)
continue;
std::string payment_id = string_tools::pod_to_hex(i->first);
if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
payment_id = payment_id.substr(0,16);
std::string note = m_wallet->get_tx_note(pd.m_tx_hash);
std::string destination = m_wallet->get_subaddress_as_str({m_current_subaddress_account, pd.m_subaddr_index.minor});
const std::string type = pd.m_coinbase ? tr("block") : tr("in");
const bool unlocked = m_wallet->is_tx_spendtime_unlocked(pd.m_unlock_time, pd.m_block_height);
transfers.push_back({
pd.m_block_height,
pd.m_timestamp,
type,
true,
pd.m_amount,
pd.m_tx_hash,
payment_id,
0,
{{destination, pd.m_amount}},
{pd.m_subaddr_index.minor},
note,
(unlocked) ? "unlocked" : "locked"
});
}
}
if (out) {
std::list<std::pair<crypto::hash, tools::wallet2::confirmed_transfer_details>> payments;
m_wallet->get_payments_out(payments, min_height, max_height, m_current_subaddress_account, subaddr_indices);
for (std::list<std::pair<crypto::hash, tools::wallet2::confirmed_transfer_details>>::const_iterator i = payments.begin(); i != payments.end(); ++i) {
const tools::wallet2::confirmed_transfer_details &pd = i->second;
uint64_t change = pd.m_change == (uint64_t)-1 ? 0 : pd.m_change; // change may not be known
uint64_t fee = pd.m_amount_in - pd.m_amount_out;
std::vector<std::pair<std::string, uint64_t>> destinations;
for (const auto &d: pd.m_dests) {
destinations.push_back({get_account_address_as_str(m_wallet->nettype(), d.is_subaddress, d.addr), d.amount});
}
std::string payment_id = string_tools::pod_to_hex(i->second.m_payment_id);
if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
payment_id = payment_id.substr(0,16);
std::string note = m_wallet->get_tx_note(i->first);
transfers.push_back({
pd.m_block_height,
pd.m_timestamp,
"out",
true,
pd.m_amount_in - change - fee,
i->first,
payment_id,
fee,
destinations,
pd.m_subaddr_indices,
note,
"-"
});
}
}
if (pool) {
try
{
m_in_manual_refresh.store(true, std::memory_order_relaxed);
epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){m_in_manual_refresh.store(false, std::memory_order_relaxed);});
m_wallet->update_pool_state();
std::list<std::pair<crypto::hash, tools::wallet2::pool_payment_details>> payments;
m_wallet->get_unconfirmed_payments(payments, m_current_subaddress_account, subaddr_indices);
for (std::list<std::pair<crypto::hash, tools::wallet2::pool_payment_details>>::const_iterator i = payments.begin(); i != payments.end(); ++i) {
const tools::wallet2::payment_details &pd = i->second.m_pd;
std::string payment_id = string_tools::pod_to_hex(i->first);
if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
payment_id = payment_id.substr(0,16);
std::string note = m_wallet->get_tx_note(pd.m_tx_hash);
std::string destination = m_wallet->get_subaddress_as_str({m_current_subaddress_account, pd.m_subaddr_index.minor});
std::string double_spend_note;
if (i->second.m_double_spend_seen)
double_spend_note = tr("[Double spend seen on the network: this transaction may or may not end up being mined] ");
transfers.push_back({
"pool",
pd.m_timestamp,
"in",
false,
pd.m_amount,
pd.m_tx_hash,
payment_id,
0,
{{destination, pd.m_amount}},
{pd.m_subaddr_index.minor},
note + double_spend_note,
"locked"
});
}
}
catch (const std::exception& e)
{
fail_msg_writer() << "Failed to get pool state:" << e.what();
}
}
// print unconfirmed last
if (pending || failed) {
std::list<std::pair<crypto::hash, tools::wallet2::unconfirmed_transfer_details>> upayments;
m_wallet->get_unconfirmed_payments_out(upayments, m_current_subaddress_account, subaddr_indices);
for (std::list<std::pair<crypto::hash, tools::wallet2::unconfirmed_transfer_details>>::const_iterator i = upayments.begin(); i != upayments.end(); ++i) {
const tools::wallet2::unconfirmed_transfer_details &pd = i->second;
uint64_t amount = pd.m_amount_in;
uint64_t fee = amount - pd.m_amount_out;
std::vector<std::pair<std::string, uint64_t>> destinations;
for (const auto &d: pd.m_dests) {
destinations.push_back({get_account_address_as_str(m_wallet->nettype(), d.is_subaddress, d.addr), d.amount});
}
std::string payment_id = string_tools::pod_to_hex(i->second.m_payment_id);
if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
payment_id = payment_id.substr(0,16);
std::string note = m_wallet->get_tx_note(i->first);
bool is_failed = pd.m_state == tools::wallet2::unconfirmed_transfer_details::failed;
if ((failed && is_failed) || (!is_failed && pending)) {
transfers.push_back({
(is_failed ? "failed" : "pending"),
pd.m_timestamp,
"out",
false,
amount - pd.m_change - fee,
i->first,
payment_id,
fee,
destinations,
pd.m_subaddr_indices,
note,
"-"
});
}
}
}
// sort by block, then by timestamp (unconfirmed last)
std::sort(transfers.begin(), transfers.end(), [](const transfer_view& a, const transfer_view& b) -> bool {
if (a.confirmed && !b.confirmed)
return true;
if (a.block == b.block)
return a.timestamp < b.timestamp;
return a.block < b.block;
});
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::show_transfers(const std::vector<std::string> &args_)
{
std::vector<std::string> local_args = args_;
if(local_args.size() > 4) {
fail_msg_writer() << tr("usage: show_transfers [in|out|all|pending|failed|coinbase] [index=<N1>[,<N2>,...]] [<min_height> [<max_height>]]");
return true;
}
LOCK_IDLE_SCOPE();
std::vector<transfer_view> all_transfers;
if (!get_transfers(local_args, all_transfers))
return true;
PAUSE_READLINE();
for (const auto& transfer : all_transfers)
{
const auto color = transfer.confirmed ? ((transfer.direction == "in" || transfer.direction == "block") ? console_color_green : console_color_magenta) : console_color_white;
std::string destinations = "-";
if (!transfer.outputs.empty())
{
destinations = "";
for (const auto& output : transfer.outputs)
{
if (!destinations.empty())
destinations += ", ";
destinations += (transfer.direction == "in" ? output.first.substr(0, 6) : output.first) + ":" + print_money(output.second);
}
}
auto formatter = boost::format("%8.8llu %6.6s %8.8s %25.25s %20.20s %s %s %14.14s %s %s - %s");
message_writer(color, false) << formatter
% transfer.block
% transfer.direction
% transfer.unlocked
% get_human_readable_timestamp(transfer.timestamp)
% print_money(transfer.amount)
% string_tools::pod_to_hex(transfer.hash)
% transfer.payment_id
% print_money(transfer.fee)
% destinations
% boost::algorithm::join(transfer.index | boost::adaptors::transformed([](uint32_t i) { return std::to_string(i); }), ", ")
% transfer.note;
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::export_transfers(const std::vector<std::string>& args_)
{
std::vector<std::string> local_args = args_;
if(local_args.size() > 5) {
fail_msg_writer() << tr("usage: export_transfers [in|out|all|pending|failed|coinbase] [index=<N1>[,<N2>,...]] [<min_height> [<max_height>]] [output=<path>]");
return true;
}
LOCK_IDLE_SCOPE();
std::vector<transfer_view> all_transfers;
// might consumes arguments in local_args
if (!get_transfers(local_args, all_transfers))
return true;
// output filename
std::string filename = (boost::format("output%u.csv") % m_current_subaddress_account).str();
if (local_args.size() > 0 && local_args[0].substr(0, 7) == "output=")
{
filename = local_args[0].substr(7, -1);
local_args.erase(local_args.begin());
}
std::ofstream file(filename);
// header
file <<
boost::format("%8.8s,%9.9s,%8.8s,%25.25s,%20.20s,%20.20s,%64.64s,%16.16s,%14.14s,%100.100s,%20.20s,%s,%s") %
tr("block") % tr("direction") % tr("unlocked") % tr("timestamp") % tr("amount") % tr("running balance") % tr("hash") % tr("payment ID") % tr("fee") % tr("destination") % tr("amount") % tr("index") % tr("note")
<< std::endl;
uint64_t running_balance = 0;
auto formatter = boost::format("%8.8llu,%9.9s,%8.8s,%25.25s,%20.20s,%20.20s,%64.64s,%16.16s,%14.14s,%100.100s,%20.20s,\"%s\",%s");
for (const auto& transfer : all_transfers)
{
// ignore unconfirmed transfers in running balance
if (transfer.confirmed)
{
if (transfer.direction == "in" || transfer.direction == "block")
running_balance += transfer.amount;
else
running_balance -= transfer.amount + transfer.fee;
}
file << formatter
% transfer.block
% transfer.direction
% transfer.unlocked
% get_human_readable_timestamp(transfer.timestamp)
% print_money(transfer.amount)
% print_money(running_balance)
% string_tools::pod_to_hex(transfer.hash)
% transfer.payment_id
% print_money(transfer.fee)
% (transfer.outputs.size() ? transfer.outputs[0].first : "-")
% (transfer.outputs.size() ? print_money(transfer.outputs[0].second) : "")
% boost::algorithm::join(transfer.index | boost::adaptors::transformed([](uint32_t i) { return std::to_string(i); }), ", ")
% transfer.note
<< std::endl;
for (size_t i = 1; i < transfer.outputs.size(); ++i)
{
file << formatter
% ""
% ""
% ""
% ""
% ""
% ""
% ""
% ""
% ""
% transfer.outputs[i].first
% print_money(transfer.outputs[i].second)
% ""
% ""
<< std::endl;
}
}
file.close();
success_msg_writer() << tr("CSV exported to ") << filename;
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::unspent_outputs(const std::vector<std::string> &args_)
{
if(args_.size() > 3)
{
fail_msg_writer() << tr("usage: unspent_outputs [index=<N1>[,<N2>,...]] [<min_amount> [<max_amount>]]");
return true;
}
auto local_args = args_;
std::set<uint32_t> subaddr_indices;
if (local_args.size() > 0 && local_args[0].substr(0, 6) == "index=")
{
if (!parse_subaddress_indices(local_args[0], subaddr_indices))
return true;
local_args.erase(local_args.begin());
}
uint64_t min_amount = 0;
uint64_t max_amount = std::numeric_limits<uint64_t>::max();
if (local_args.size() > 0)
{
if (!cryptonote::parse_amount(min_amount, local_args[0]))
{
fail_msg_writer() << tr("amount is wrong: ") << local_args[0];
return true;
}
local_args.erase(local_args.begin());
if (local_args.size() > 0)
{
if (!cryptonote::parse_amount(max_amount, local_args[0]))
{
fail_msg_writer() << tr("amount is wrong: ") << local_args[0];
return true;
}
local_args.erase(local_args.begin());
}
if (min_amount > max_amount)
{
fail_msg_writer() << tr("<min_amount> should be smaller than <max_amount>");
return true;
}
}
tools::wallet2::transfer_container transfers;
m_wallet->get_transfers(transfers);
std::map<uint64_t, tools::wallet2::transfer_container> amount_to_tds;
uint64_t min_height = std::numeric_limits<uint64_t>::max();
uint64_t max_height = 0;
uint64_t found_min_amount = std::numeric_limits<uint64_t>::max();
uint64_t found_max_amount = 0;
uint64_t count = 0;
for (const auto& td : transfers)
{
uint64_t amount = td.amount();
if (td.m_spent || amount < min_amount || amount > max_amount || td.m_subaddr_index.major != m_current_subaddress_account || (subaddr_indices.count(td.m_subaddr_index.minor) == 0 && !subaddr_indices.empty()))
continue;
amount_to_tds[amount].push_back(td);
if (min_height > td.m_block_height) min_height = td.m_block_height;
if (max_height < td.m_block_height) max_height = td.m_block_height;
if (found_min_amount > amount) found_min_amount = amount;
if (found_max_amount < amount) found_max_amount = amount;
++count;
}
if (amount_to_tds.empty())
{
success_msg_writer() << tr("There is no unspent output in the specified address");
return true;
}
for (const auto& amount_tds : amount_to_tds)
{
auto& tds = amount_tds.second;
success_msg_writer() << tr("\nAmount: ") << print_money(amount_tds.first) << tr(", number of keys: ") << tds.size();
for (size_t i = 0; i < tds.size(); )
{
std::ostringstream oss;
for (size_t j = 0; j < 8 && i < tds.size(); ++i, ++j)
oss << tds[i].m_block_height << tr(" ");
success_msg_writer() << oss.str();
}
}
success_msg_writer()
<< tr("\nMin block height: ") << min_height
<< tr("\nMax block height: ") << max_height
<< tr("\nMin amount found: ") << print_money(found_min_amount)
<< tr("\nMax amount found: ") << print_money(found_max_amount)
<< tr("\nTotal count: ") << count;
const size_t histogram_height = 10;
const size_t histogram_width = 50;
double bin_size = (max_height - min_height + 1.0) / histogram_width;
size_t max_bin_count = 0;
std::vector<size_t> histogram(histogram_width, 0);
for (const auto& amount_tds : amount_to_tds)
{
for (auto& td : amount_tds.second)
{
uint64_t bin_index = (td.m_block_height - min_height + 1) / bin_size;
if (bin_index >= histogram_width)
bin_index = histogram_width - 1;
histogram[bin_index]++;
if (max_bin_count < histogram[bin_index])
max_bin_count = histogram[bin_index];
}
}
for (size_t x = 0; x < histogram_width; ++x)
{
double bin_count = histogram[x];
if (max_bin_count > histogram_height)
bin_count *= histogram_height / (double)max_bin_count;
if (histogram[x] > 0 && bin_count < 1.0)
bin_count = 1.0;
histogram[x] = bin_count;
}
std::vector<std::string> histogram_line(histogram_height, std::string(histogram_width, ' '));
for (size_t y = 0; y < histogram_height; ++y)
{
for (size_t x = 0; x < histogram_width; ++x)
{
if (y < histogram[x])
histogram_line[y][x] = '*';
}
}
double count_per_star = max_bin_count / (double)histogram_height;
if (count_per_star < 1)
count_per_star = 1;
success_msg_writer()
<< tr("\nBin size: ") << bin_size
<< tr("\nOutputs per *: ") << count_per_star;
ostringstream histogram_str;
histogram_str << tr("count\n ^\n");
for (size_t y = histogram_height; y > 0; --y)
histogram_str << tr(" |") << histogram_line[y - 1] << tr("|\n");
histogram_str
<< tr(" +") << std::string(histogram_width, '-') << tr("+--> block height\n")
<< tr(" ^") << std::string(histogram_width - 2, ' ') << tr("^\n")
<< tr(" ") << min_height << std::string(histogram_width - 8, ' ') << max_height;
success_msg_writer() << histogram_str.str();
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::rescan_blockchain(const std::vector<std::string> &args_)
{
bool hard = false;
if (!args_.empty())
{
if (args_[0] != "hard")
{
fail_msg_writer() << tr("usage: rescan_bc [hard]");
return true;
}
hard = true;
}
if (hard)
{
message_writer() << tr("Warning: this will lose any information which can not be recovered from the blockchain.");
message_writer() << tr("This includes destination addresses, tx secret keys, tx notes, etc");
std::string confirm = input_line(tr("Rescan anyway ? (Y/Yes/N/No): "));
if(!std::cin.eof())
{
if (!command_line::is_yes(confirm))
return true;
}
}
return refresh_main(0, hard ? ResetHard : ResetSoft, true);
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::wallet_idle_thread()
{
while (true)
{
boost::unique_lock<boost::mutex> lock(m_idle_mutex);
if (!m_idle_run.load(std::memory_order_relaxed))
break;
// auto refresh
if (m_auto_refresh_enabled)
{
m_auto_refresh_refreshing = true;
try
{
uint64_t fetched_blocks;
if (try_connect_to_daemon(true))
m_wallet->refresh(m_wallet->is_trusted_daemon(), 0, fetched_blocks);
}
catch(...) {}
m_auto_refresh_refreshing = false;
}
if (!m_idle_run.load(std::memory_order_relaxed))
break;
m_idle_cond.wait_for(lock, boost::chrono::seconds(90));
}
}
//----------------------------------------------------------------------------------------------------
std::string simple_wallet::get_prompt() const
{
std::string addr_start = m_wallet->get_subaddress_as_str({m_current_subaddress_account, 0}).substr(0, 6);
std::string prompt = std::string("[") + tr("wallet") + " " + addr_start;
if (!m_wallet->check_connection(NULL))
prompt += tr(" (no daemon)");
else if (!m_wallet->is_synced())
prompt += tr(" (out of sync)");
prompt += "]: ";
return prompt;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::run()
{
// check and display warning, but go on anyway
try_connect_to_daemon();
refresh_main(0, ResetNone, true);
m_auto_refresh_enabled = m_wallet->auto_refresh();
m_idle_thread = boost::thread([&]{wallet_idle_thread();});
message_writer(console_color_green, false) << "Background refresh thread started";
return m_cmd_binder.run_handling([this](){return get_prompt();}, "");
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::stop()
{
m_cmd_binder.stop_handling();
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::account(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
// Usage:
// account
// account new <label text with white spaces allowed>
// account switch <index>
// account label <index> <label text with white spaces allowed>
// account tag <tag_name> <account_index_1> [<account_index_2> ...]
// account untag <account_index_1> [<account_index_2> ...]
// account tag_description <tag_name> <description>
if (args.empty())
{
// print all the existing accounts
LOCK_IDLE_SCOPE();
print_accounts();
return true;
}
std::vector<std::string> local_args = args;
std::string command = local_args[0];
local_args.erase(local_args.begin());
if (command == "new")
{
// create a new account and switch to it
std::string label = boost::join(local_args, " ");
if (label.empty())
label = tr("(Untitled account)");
m_wallet->add_subaddress_account(label);
m_current_subaddress_account = m_wallet->get_num_subaddress_accounts() - 1;
// update_prompt();
LOCK_IDLE_SCOPE();
print_accounts();
}
else if (command == "switch" && local_args.size() == 1)
{
// switch to the specified account
uint32_t index_major;
if (!epee::string_tools::get_xtype_from_string(index_major, local_args[0]))
{
fail_msg_writer() << tr("failed to parse index: ") << local_args[0];
return true;
}
if (index_major >= m_wallet->get_num_subaddress_accounts())
{
fail_msg_writer() << tr("specify an index between 0 and ") << (m_wallet->get_num_subaddress_accounts() - 1);
return true;
}
m_current_subaddress_account = index_major;
// update_prompt();
show_balance();
}
else if (command == "label" && local_args.size() >= 1)
{
// set label of the specified account
uint32_t index_major;
if (!epee::string_tools::get_xtype_from_string(index_major, local_args[0]))
{
fail_msg_writer() << tr("failed to parse index: ") << local_args[0];
return true;
}
local_args.erase(local_args.begin());
std::string label = boost::join(local_args, " ");
try
{
m_wallet->set_subaddress_label({index_major, 0}, label);
LOCK_IDLE_SCOPE();
print_accounts();
}
catch (const std::exception& e)
{
fail_msg_writer() << e.what();
}
}
else if (command == "tag" && local_args.size() >= 2)
{
const std::string tag = local_args[0];
std::set<uint32_t> account_indices;
for (size_t i = 1; i < local_args.size(); ++i)
{
uint32_t account_index;
if (!epee::string_tools::get_xtype_from_string(account_index, local_args[i]))
{
fail_msg_writer() << tr("failed to parse index: ") << local_args[i];
return true;
}
account_indices.insert(account_index);
}
try
{
m_wallet->set_account_tag(account_indices, tag);
print_accounts(tag);
}
catch (const std::exception& e)
{
fail_msg_writer() << e.what();
}
}
else if (command == "untag" && local_args.size() >= 1)
{
std::set<uint32_t> account_indices;
for (size_t i = 0; i < local_args.size(); ++i)
{
uint32_t account_index;
if (!epee::string_tools::get_xtype_from_string(account_index, local_args[i]))
{
fail_msg_writer() << tr("failed to parse index: ") << local_args[i];
return true;
}
account_indices.insert(account_index);
}
try
{
m_wallet->set_account_tag(account_indices, "");
print_accounts();
}
catch (const std::exception& e)
{
fail_msg_writer() << e.what();
}
}
else if (command == "tag_description" && local_args.size() >= 1)
{
const std::string tag = local_args[0];
std::string description;
if (local_args.size() > 1)
{
local_args.erase(local_args.begin());
description = boost::join(local_args, " ");
}
try
{
m_wallet->set_account_tag_description(tag, description);
print_accounts(tag);
}
catch (const std::exception& e)
{
fail_msg_writer() << e.what();
}
}
else
{
fail_msg_writer() << tr("usage:\n"
" account\n"
" account new <label text with white spaces allowed>\n"
" account switch <index>\n"
" account label <index> <label text with white spaces allowed>\n"
" account tag <tag_name> <account_index_1> [<account_index_2> ...]\n"
" account untag <account_index_1> [<account_index_2> ...]\n"
" account tag_description <tag_name> <description>");
}
return true;
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::print_accounts()
{
const std::pair<std::map<std::string, std::string>, std::vector<std::string>>& account_tags = m_wallet->get_account_tags();
size_t num_untagged_accounts = m_wallet->get_num_subaddress_accounts();
for (const std::pair<std::string, std::string>& p : account_tags.first)
{
const std::string& tag = p.first;
print_accounts(tag);
num_untagged_accounts -= std::count(account_tags.second.begin(), account_tags.second.end(), tag);
success_msg_writer() << "";
}
if (num_untagged_accounts > 0)
print_accounts("");
if (num_untagged_accounts < m_wallet->get_num_subaddress_accounts())
success_msg_writer() << tr("\nGrand total:\n Balance: ") << print_money(m_wallet->balance_all()) << tr(", unlocked balance: ") << print_money(m_wallet->unlocked_balance_all());
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::print_accounts(const std::string& tag)
{
const std::pair<std::map<std::string, std::string>, std::vector<std::string>>& account_tags = m_wallet->get_account_tags();
if (tag.empty())
{
success_msg_writer() << tr("Untagged accounts:");
}
else
{
if (account_tags.first.count(tag) == 0)
{
fail_msg_writer() << boost::format(tr("Tag %s is unregistered.")) % tag;
return;
}
success_msg_writer() << tr("Accounts with tag: ") << tag;
success_msg_writer() << tr("Tag's description: ") << account_tags.first.find(tag)->second;
}
success_msg_writer() << boost::format(" %15s %21s %21s %21s") % tr("Account") % tr("Balance") % tr("Unlocked balance") % tr("Label");
uint64_t total_balance = 0, total_unlocked_balance = 0;
for (uint32_t account_index = 0; account_index < m_wallet->get_num_subaddress_accounts(); ++account_index)
{
if (account_tags.second[account_index] != tag)
continue;
success_msg_writer() << boost::format(tr(" %c%8u %6s %21s %21s %21s"))
% (m_current_subaddress_account == account_index ? '*' : ' ')
% account_index
% m_wallet->get_subaddress_as_str({account_index, 0}).substr(0, 6)
% print_money(m_wallet->balance(account_index))
% print_money(m_wallet->unlocked_balance(account_index))
% m_wallet->get_subaddress_label({account_index, 0});
total_balance += m_wallet->balance(account_index);
total_unlocked_balance += m_wallet->unlocked_balance(account_index);
}
success_msg_writer() << tr("----------------------------------------------------------------------------------");
success_msg_writer() << boost::format(tr("%15s %21s %21s")) % "Total" % print_money(total_balance) % print_money(total_unlocked_balance);
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::print_address(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
// Usage:
// address
// address new <label text with white spaces allowed>
// address all
// address <index_min> [<index_max>]
// address label <index> <label text with white spaces allowed>
std::vector<std::string> local_args = args;
tools::wallet2::transfer_container transfers;
m_wallet->get_transfers(transfers);
auto print_address_sub = [this, &transfers](uint32_t index)
{
bool used = std::find_if(
transfers.begin(), transfers.end(),
[this, &index](const tools::wallet2::transfer_details& td) {
return td.m_subaddr_index == cryptonote::subaddress_index{ m_current_subaddress_account, index };
}) != transfers.end();
success_msg_writer() << index << " " << m_wallet->get_subaddress_as_str({m_current_subaddress_account, index}) << " " << (index == 0 ? tr("Primary address") : m_wallet->get_subaddress_label({m_current_subaddress_account, index})) << " " << (used ? tr("(used)") : "");
};
uint32_t index = 0;
if (local_args.empty())
{
print_address_sub(index);
}
else if (local_args.size() == 1 && local_args[0] == "all")
{
local_args.erase(local_args.begin());
for (; index < m_wallet->get_num_subaddresses(m_current_subaddress_account); ++index)
print_address_sub(index);
}
else if (local_args[0] == "new")
{
local_args.erase(local_args.begin());
std::string label;
if (local_args.size() > 0)
label = boost::join(local_args, " ");
if (label.empty())
label = tr("(Untitled address)");
m_wallet->add_subaddress(m_current_subaddress_account, label);
print_address_sub(m_wallet->get_num_subaddresses(m_current_subaddress_account) - 1);
}
else if (local_args.size() >= 2 && local_args[0] == "label")
{
if (!epee::string_tools::get_xtype_from_string(index, local_args[1]))
{
fail_msg_writer() << tr("failed to parse index: ") << local_args[1];
return true;
}
if (index >= m_wallet->get_num_subaddresses(m_current_subaddress_account))
{
fail_msg_writer() << tr("specify an index between 0 and ") << (m_wallet->get_num_subaddresses(m_current_subaddress_account) - 1);
return true;
}
local_args.erase(local_args.begin());
local_args.erase(local_args.begin());
std::string label = boost::join(local_args, " ");
m_wallet->set_subaddress_label({m_current_subaddress_account, index}, label);
print_address_sub(index);
}
else if (local_args.size() <= 2 && epee::string_tools::get_xtype_from_string(index, local_args[0]))
{
local_args.erase(local_args.begin());
uint32_t index_min = index;
uint32_t index_max = index_min;
if (local_args.size() > 0)
{
if (!epee::string_tools::get_xtype_from_string(index_max, local_args[0]))
{
fail_msg_writer() << tr("failed to parse index: ") << local_args[0];
return true;
}
local_args.erase(local_args.begin());
}
if (index_max < index_min)
std::swap(index_min, index_max);
if (index_min >= m_wallet->get_num_subaddresses(m_current_subaddress_account))
{
fail_msg_writer() << tr("<index_min> is already out of bound");
return true;
}
if (index_max >= m_wallet->get_num_subaddresses(m_current_subaddress_account))
{
message_writer() << tr("<index_max> exceeds the bound");
index_max = m_wallet->get_num_subaddresses(m_current_subaddress_account) - 1;
}
for (index = index_min; index <= index_max; ++index)
print_address_sub(index);
}
else
{
fail_msg_writer() << tr("usage: address [ new <label text with white spaces allowed> | all | <index_min> [<index_max>] | label <index> <label text with white spaces allowed> ]");
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::print_integrated_address(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
crypto::hash8 payment_id;
if (args.size() > 1)
{
fail_msg_writer() << tr("usage: integrated_address [payment ID]");
return true;
}
if (args.size() == 0)
{
if (m_current_subaddress_account != 0)
{
fail_msg_writer() << tr("Integrated addresses can only be created for account 0");
return true;
}
payment_id = crypto::rand<crypto::hash8>();
success_msg_writer() << tr("Random payment ID: ") << payment_id;
success_msg_writer() << tr("Matching integrated address: ") << m_wallet->get_account().get_public_integrated_address_str(payment_id, m_wallet->nettype());
return true;
}
if(tools::wallet2::parse_short_payment_id(args.back(), payment_id))
{
if (m_current_subaddress_account != 0)
{
fail_msg_writer() << tr("Integrated addresses can only be created for account 0");
return true;
}
success_msg_writer() << m_wallet->get_account().get_public_integrated_address_str(payment_id, m_wallet->nettype());
return true;
}
else {
address_parse_info info;
if(get_account_address_from_str(info, m_wallet->nettype(), args.back()))
{
if (info.has_payment_id)
{
success_msg_writer() << boost::format(tr("Integrated address: %s, payment ID: %s")) %
get_account_address_as_str(m_wallet->nettype(), false, info.address) % epee::string_tools::pod_to_hex(info.payment_id);
}
else
{
success_msg_writer() << (info.is_subaddress ? tr("Subaddress: ") : tr("Standard address: ")) << get_account_address_as_str(m_wallet->nettype(), info.is_subaddress, info.address);
}
return true;
}
}
fail_msg_writer() << tr("failed to parse payment ID or address");
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::address_book(const std::vector<std::string> &args/* = std::vector<std::string>()*/)
{
if (args.size() == 0)
{
}
else if (args.size() == 1 || (args[0] != "add" && args[0] != "delete"))
{
fail_msg_writer() << tr("usage: address_book [(add (<address> [pid <long or short payment id>])|<integrated address> [<description possibly with whitespaces>])|(delete <index>)]");
return true;
}
else if (args[0] == "add")
{
cryptonote::address_parse_info info;
if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), args[1], oa_prompter))
{
fail_msg_writer() << tr("failed to parse address");
return true;
}
crypto::hash payment_id = crypto::null_hash;
size_t description_start = 2;
if (info.has_payment_id)
{
memcpy(payment_id.data, info.payment_id.data, 8);
}
else if (!info.has_payment_id && args.size() >= 4 && args[2] == "pid")
{
if (tools::wallet2::parse_long_payment_id(args[3], payment_id))
{
description_start += 2;
}
else if (tools::wallet2::parse_short_payment_id(args[3], info.payment_id))
{
memcpy(payment_id.data, info.payment_id.data, 8);
description_start += 2;
}
else
{
fail_msg_writer() << tr("failed to parse payment ID");
return true;
}
}
std::string description;
for (size_t i = description_start; i < args.size(); ++i)
{
if (i > description_start)
description += " ";
description += args[i];
}
m_wallet->add_address_book_row(info.address, payment_id, description, info.is_subaddress);
}
else
{
size_t row_id;
if(!epee::string_tools::get_xtype_from_string(row_id, args[1]))
{
fail_msg_writer() << tr("failed to parse index");
return true;
}
m_wallet->delete_address_book_row(row_id);
}
auto address_book = m_wallet->get_address_book();
if (address_book.empty())
{
success_msg_writer() << tr("Address book is empty.");
}
else
{
for (size_t i = 0; i < address_book.size(); ++i) {
auto& row = address_book[i];
success_msg_writer() << tr("Index: ") << i;
success_msg_writer() << tr("Address: ") << get_account_address_as_str(m_wallet->nettype(), row.m_is_subaddress, row.m_address);
success_msg_writer() << tr("Payment ID: ") << row.m_payment_id;
success_msg_writer() << tr("Description: ") << row.m_description << "\n";
}
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::set_tx_note(const std::vector<std::string> &args)
{
if (args.size() == 0)
{
fail_msg_writer() << tr("usage: set_tx_note [txid] free text note");
return true;
}
cryptonote::blobdata txid_data;
if(!epee::string_tools::parse_hexstr_to_binbuff(args.front(), txid_data) || txid_data.size() != sizeof(crypto::hash))
{
fail_msg_writer() << tr("failed to parse txid");
return true;
}
crypto::hash txid = *reinterpret_cast<const crypto::hash*>(txid_data.data());
std::string note = "";
for (size_t n = 1; n < args.size(); ++n)
{
if (n > 1)
note += " ";
note += args[n];
}
m_wallet->set_tx_note(txid, note);
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::get_tx_note(const std::vector<std::string> &args)
{
if (args.size() != 1)
{
fail_msg_writer() << tr("usage: get_tx_note [txid]");
return true;
}
cryptonote::blobdata txid_data;
if(!epee::string_tools::parse_hexstr_to_binbuff(args.front(), txid_data) || txid_data.size() != sizeof(crypto::hash))
{
fail_msg_writer() << tr("failed to parse txid");
return true;
}
crypto::hash txid = *reinterpret_cast<const crypto::hash*>(txid_data.data());
std::string note = m_wallet->get_tx_note(txid);
if (note.empty())
success_msg_writer() << "no note found";
else
success_msg_writer() << "note found: " << note;
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::set_description(const std::vector<std::string> &args)
{
// 0 arguments allowed, for setting the description to empty string
std::string description = "";
for (size_t n = 0; n < args.size(); ++n)
{
if (n > 0)
description += " ";
description += args[n];
}
m_wallet->set_description(description);
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::get_description(const std::vector<std::string> &args)
{
if (args.size() != 0)
{
fail_msg_writer() << tr("usage: get_description");
return true;
}
std::string description = m_wallet->get_description();
if (description.empty())
success_msg_writer() << tr("no description found");
else
success_msg_writer() << tr("description found: ") << description;
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::status(const std::vector<std::string> &args)
{
uint64_t local_height = m_wallet->get_blockchain_current_height();
uint32_t version = 0;
if (!m_wallet->check_connection(&version))
{
success_msg_writer() << "Refreshed " << local_height << "/?, no daemon connected";
return true;
}
std::string err;
uint64_t bc_height = get_daemon_blockchain_height(err);
if (err.empty())
{
bool synced = local_height == bc_height;
success_msg_writer() << "Refreshed " << local_height << "/" << bc_height << ", " << (synced ? "synced" : "syncing")
<< ", daemon RPC v" << get_version_string(version);
}
else
{
fail_msg_writer() << "Refreshed " << local_height << "/?, daemon connection error";
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::wallet_info(const std::vector<std::string> &args)
{
bool ready;
uint32_t threshold, total;
std::string description = m_wallet->get_description();
if (description.empty())
{
description = "<Not set>";
}
message_writer() << tr("Filename: ") << m_wallet->get_wallet_file();
message_writer() << tr("Description: ") << description;
message_writer() << tr("Address: ") << m_wallet->get_account().get_public_address_str(m_wallet->nettype());
std::string type;
if (m_wallet->watch_only())
type = tr("Watch only");
else if (m_wallet->multisig(&ready, &threshold, &total))
type = (boost::format(tr("%u/%u multisig%s")) % threshold % total % (ready ? "" : " (not yet finalized)")).str();
else
type = tr("Normal");
message_writer() << tr("Type: ") << type;
message_writer() << tr("Network type: ") << (
m_wallet->nettype() == cryptonote::TESTNET ? tr("Testnet") :
m_wallet->nettype() == cryptonote::STAGENET ? tr("Stagenet") : tr("Mainnet"));
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::sign(const std::vector<std::string> &args)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if (args.size() != 1)
{
fail_msg_writer() << tr("usage: sign <filename>");
return true;
}
if (m_wallet->watch_only())
{
fail_msg_writer() << tr("wallet is watch-only and cannot sign");
return true;
}
if (m_wallet->multisig())
{
fail_msg_writer() << tr("This wallet is multisig and cannot sign");
return true;
}
std::string filename = args[0];
std::string data;
bool r = epee::file_io_utils::load_file_to_string(filename, data);
if (!r)
{
fail_msg_writer() << tr("failed to read file ") << filename;
return true;
}
SCOPED_WALLET_UNLOCK();
std::string signature = m_wallet->sign(data);
success_msg_writer() << signature;
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::verify(const std::vector<std::string> &args)
{
if (args.size() != 3)
{
fail_msg_writer() << tr("usage: verify <filename> <address> <signature>");
return true;
}
std::string filename = args[0];
std::string address_string = args[1];
std::string signature= args[2];
std::string data;
bool r = epee::file_io_utils::load_file_to_string(filename, data);
if (!r)
{
fail_msg_writer() << tr("failed to read file ") << filename;
return true;
}
cryptonote::address_parse_info info;
if(!cryptonote::get_account_address_from_str_or_url(info, m_wallet->nettype(), address_string, oa_prompter))
{
fail_msg_writer() << tr("failed to parse address");
return true;
}
r = m_wallet->verify(data, info.address, signature);
if (!r)
{
fail_msg_writer() << tr("Bad signature from ") << address_string;
}
else
{
success_msg_writer() << tr("Good signature from ") << address_string;
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::export_key_images(const std::vector<std::string> &args)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if (args.size() != 1)
{
fail_msg_writer() << tr("usage: export_key_images <filename>");
return true;
}
if (m_wallet->watch_only())
{
fail_msg_writer() << tr("wallet is watch-only and cannot export key images");
return true;
}
std::string filename = args[0];
if (m_wallet->confirm_export_overwrite() && !check_file_overwrite(filename))
return true;
SCOPED_WALLET_UNLOCK();
try
{
if (!m_wallet->export_key_images(filename))
{
fail_msg_writer() << tr("failed to save file ") << filename;
return true;
}
}
catch (const std::exception &e)
{
LOG_ERROR("Error exporting key images: " << e.what());
fail_msg_writer() << "Error exporting key images: " << e.what();
return true;
}
success_msg_writer() << tr("Signed key images exported to ") << filename;
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::import_key_images(const std::vector<std::string> &args)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if (!m_wallet->is_trusted_daemon())
{
fail_msg_writer() << tr("this command requires a trusted daemon. Enable with --trusted-daemon");
return true;
}
if (args.size() != 1)
{
fail_msg_writer() << tr("usage: import_key_images <filename>");
return true;
}
std::string filename = args[0];
LOCK_IDLE_SCOPE();
try
{
uint64_t spent = 0, unspent = 0;
uint64_t height = m_wallet->import_key_images(filename, spent, unspent);
if (height > 0)
{
success_msg_writer() << "Signed key images imported to height " << height << ", "
<< print_money(spent) << " spent, " << print_money(unspent) << " unspent";
} else {
fail_msg_writer() << "Failed to import key images";
}
}
catch (const std::exception &e)
{
fail_msg_writer() << "Failed to import key images: " << e.what();
return true;
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::hw_key_images_sync(const std::vector<std::string> &args)
{
if (!m_wallet->key_on_device())
{
fail_msg_writer() << tr("command only supported by HW wallet");
return true;
}
if (!m_wallet->get_account().get_device().has_ki_cold_sync())
{
fail_msg_writer() << tr("hw wallet does not support cold KI sync");
return true;
}
if (!m_wallet->is_trusted_daemon())
{
fail_msg_writer() << tr("this command requires a trusted daemon. Enable with --trusted-daemon");
return true;
}
LOCK_IDLE_SCOPE();
try
{
message_writer(console_color_white, false) << tr("Please confirm the key image sync on the device");
uint64_t spent = 0, unspent = 0;
uint64_t height = m_wallet->cold_key_image_sync(spent, unspent);
if (height > 0)
{
success_msg_writer() << tr("Signed key images imported to height ") << height << ", "
<< print_money(spent) << tr(" spent, ") << print_money(unspent) << tr(" unspent");
} else {
fail_msg_writer() << tr("Failed to import key images");
}
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to import key images: ") << e.what();
return true;
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::hw_reconnect(const std::vector<std::string> &args)
{
if (!m_wallet->key_on_device())
{
fail_msg_writer() << tr("command only supported by HW wallet");
return true;
}
LOCK_IDLE_SCOPE();
try
{
bool r = m_wallet->reconnect_device();
if (!r){
fail_msg_writer() << tr("Failed to reconnect device");
}
}
catch (const std::exception &e)
{
fail_msg_writer() << tr("Failed to reconnect device: ") << tr(e.what());
return true;
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::export_outputs(const std::vector<std::string> &args)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if (args.size() != 1)
{
fail_msg_writer() << tr("usage: export_outputs <filename>");
return true;
}
std::string filename = args[0];
if (m_wallet->confirm_export_overwrite() && !check_file_overwrite(filename))
return true;
SCOPED_WALLET_UNLOCK();
try
{
std::string data = m_wallet->export_outputs_to_str();
bool r = epee::file_io_utils::save_string_to_file(filename, data);
if (!r)
{
fail_msg_writer() << tr("failed to save file ") << filename;
return true;
}
}
catch (const std::exception &e)
{
LOG_ERROR("Error exporting outputs: " << e.what());
fail_msg_writer() << "Error exporting outputs: " << e.what();
return true;
}
success_msg_writer() << tr("Outputs exported to ") << filename;
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::import_outputs(const std::vector<std::string> &args)
{
if (m_wallet->key_on_device())
{
fail_msg_writer() << tr("command not supported by HW wallet");
return true;
}
if (args.size() != 1)
{
fail_msg_writer() << tr("usage: import_outputs <filename>");
return true;
}
std::string filename = args[0];
std::string data;
bool r = epee::file_io_utils::load_file_to_string(filename, data);
if (!r)
{
fail_msg_writer() << tr("failed to read file ") << filename;
return true;
}
try
{
SCOPED_WALLET_UNLOCK();
size_t n_outputs = m_wallet->import_outputs_from_str(data);
success_msg_writer() << boost::lexical_cast<std::string>(n_outputs) << " outputs imported";
}
catch (const std::exception &e)
{
fail_msg_writer() << "Failed to import outputs " << filename << ": " << e.what();
return true;
}
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::show_transfer(const std::vector<std::string> &args)
{
if (args.size() != 1)
{
fail_msg_writer() << tr("usage: show_transfer <txid>");
return true;
}
cryptonote::blobdata txid_data;
if(!epee::string_tools::parse_hexstr_to_binbuff(args.front(), txid_data) || txid_data.size() != sizeof(crypto::hash))
{
fail_msg_writer() << tr("failed to parse txid");
return true;
}
crypto::hash txid = *reinterpret_cast<const crypto::hash*>(txid_data.data());
const uint64_t last_block_height = m_wallet->get_blockchain_current_height();
std::list<std::pair<crypto::hash, tools::wallet2::payment_details>> payments;
m_wallet->get_payments(payments, 0, (uint64_t)-1, m_current_subaddress_account);
for (std::list<std::pair<crypto::hash, tools::wallet2::payment_details>>::const_iterator i = payments.begin(); i != payments.end(); ++i) {
const tools::wallet2::payment_details &pd = i->second;
if (pd.m_tx_hash == txid) {
std::string payment_id = string_tools::pod_to_hex(i->first);
if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
payment_id = payment_id.substr(0,16);
success_msg_writer() << "Incoming transaction found";
success_msg_writer() << "txid: " << txid;
success_msg_writer() << "Height: " << pd.m_block_height;
success_msg_writer() << "Timestamp: " << get_human_readable_timestamp(pd.m_timestamp);
success_msg_writer() << "Amount: " << print_money(pd.m_amount);
success_msg_writer() << "Payment ID: " << payment_id;
if (pd.m_unlock_time < CRYPTONOTE_MAX_BLOCK_NUMBER)
{
uint64_t bh = std::max(pd.m_unlock_time, pd.m_block_height + CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE);
uint64_t last_block_reward = m_wallet->get_last_block_reward();
uint64_t suggested_threshold = last_block_reward ? (pd.m_amount + last_block_reward - 1) / last_block_reward : 0;
if (bh >= last_block_height)
success_msg_writer() << "Locked: " << (bh - last_block_height) << " blocks to unlock";
else if (suggested_threshold > 0)
success_msg_writer() << std::to_string(last_block_height - bh) << " confirmations (" << suggested_threshold << " suggested threshold)";
else
success_msg_writer() << std::to_string(last_block_height - bh) << " confirmations";
}
else
{
uint64_t current_time = static_cast<uint64_t>(time(NULL));
uint64_t threshold = current_time + (m_wallet->use_fork_rules(2, 0) ? CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS_V2 : CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS_V1);
if (threshold >= pd.m_unlock_time)
success_msg_writer() << "unlocked for " << get_human_readable_timespan(std::chrono::seconds(threshold - pd.m_unlock_time));
else
success_msg_writer() << "locked for " << get_human_readable_timespan(std::chrono::seconds(pd.m_unlock_time - threshold));
}
success_msg_writer() << "Address index: " << pd.m_subaddr_index.minor;
success_msg_writer() << "Note: " << m_wallet->get_tx_note(txid);
return true;
}
}
std::list<std::pair<crypto::hash, tools::wallet2::confirmed_transfer_details>> payments_out;
m_wallet->get_payments_out(payments_out, 0, (uint64_t)-1, m_current_subaddress_account);
for (std::list<std::pair<crypto::hash, tools::wallet2::confirmed_transfer_details>>::const_iterator i = payments_out.begin(); i != payments_out.end(); ++i) {
if (i->first == txid)
{
const tools::wallet2::confirmed_transfer_details &pd = i->second;
uint64_t change = pd.m_change == (uint64_t)-1 ? 0 : pd.m_change; // change may not be known
uint64_t fee = pd.m_amount_in - pd.m_amount_out;
std::string dests;
for (const auto &d: pd.m_dests) {
if (!dests.empty())
dests += ", ";
dests += get_account_address_as_str(m_wallet->nettype(), d.is_subaddress, d.addr) + ": " + print_money(d.amount);
}
std::string payment_id = string_tools::pod_to_hex(i->second.m_payment_id);
if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
payment_id = payment_id.substr(0,16);
success_msg_writer() << "Outgoing transaction found";
success_msg_writer() << "txid: " << txid;
success_msg_writer() << "Height: " << pd.m_block_height;
success_msg_writer() << "Timestamp: " << get_human_readable_timestamp(pd.m_timestamp);
success_msg_writer() << "Amount: " << print_money(pd.m_amount_in - change - fee);
success_msg_writer() << "Payment ID: " << payment_id;
success_msg_writer() << "Change: " << print_money(change);
success_msg_writer() << "Fee: " << print_money(fee);
success_msg_writer() << "Destinations: " << dests;
success_msg_writer() << "Note: " << m_wallet->get_tx_note(txid);
return true;
}
}
try
{
m_wallet->update_pool_state();
std::list<std::pair<crypto::hash, tools::wallet2::pool_payment_details>> pool_payments;
m_wallet->get_unconfirmed_payments(pool_payments, m_current_subaddress_account);
for (std::list<std::pair<crypto::hash, tools::wallet2::pool_payment_details>>::const_iterator i = pool_payments.begin(); i != pool_payments.end(); ++i) {
const tools::wallet2::payment_details &pd = i->second.m_pd;
if (pd.m_tx_hash == txid)
{
std::string payment_id = string_tools::pod_to_hex(i->first);
if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
payment_id = payment_id.substr(0,16);
success_msg_writer() << "Unconfirmed incoming transaction found in the txpool";
success_msg_writer() << "txid: " << txid;
success_msg_writer() << "Timestamp: " << get_human_readable_timestamp(pd.m_timestamp);
success_msg_writer() << "Amount: " << print_money(pd.m_amount);
success_msg_writer() << "Payment ID: " << payment_id;
success_msg_writer() << "Address index: " << pd.m_subaddr_index.minor;
success_msg_writer() << "Note: " << m_wallet->get_tx_note(txid);
if (i->second.m_double_spend_seen)
success_msg_writer() << tr("Double spend seen on the network: this transaction may or may not end up being mined");
return true;
}
}
}
catch (...)
{
fail_msg_writer() << "Failed to get pool state";
}
std::list<std::pair<crypto::hash, tools::wallet2::unconfirmed_transfer_details>> upayments;
m_wallet->get_unconfirmed_payments_out(upayments, m_current_subaddress_account);
for (std::list<std::pair<crypto::hash, tools::wallet2::unconfirmed_transfer_details>>::const_iterator i = upayments.begin(); i != upayments.end(); ++i) {
if (i->first == txid)
{
const tools::wallet2::unconfirmed_transfer_details &pd = i->second;
uint64_t amount = pd.m_amount_in;
uint64_t fee = amount - pd.m_amount_out;
std::string payment_id = string_tools::pod_to_hex(i->second.m_payment_id);
if (payment_id.substr(16).find_first_not_of('0') == std::string::npos)
payment_id = payment_id.substr(0,16);
bool is_failed = pd.m_state == tools::wallet2::unconfirmed_transfer_details::failed;
success_msg_writer() << (is_failed ? "Failed" : "Pending") << " outgoing transaction found";
success_msg_writer() << "txid: " << txid;
success_msg_writer() << "Timestamp: " << get_human_readable_timestamp(pd.m_timestamp);
success_msg_writer() << "Amount: " << print_money(amount - pd.m_change - fee);
success_msg_writer() << "Payment ID: " << payment_id;
success_msg_writer() << "Change: " << print_money(pd.m_change);
success_msg_writer() << "Fee: " << print_money(fee);
success_msg_writer() << "Note: " << m_wallet->get_tx_note(txid);
return true;
}
}
fail_msg_writer() << tr("Transaction ID not found");
return true;
}
//----------------------------------------------------------------------------------------------------
bool simple_wallet::process_command(const std::vector<std::string> &args)
{
return m_cmd_binder.process_command_vec(args);
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::interrupt()
{
if (m_in_manual_refresh.load(std::memory_order_relaxed))
{
m_wallet->stop();
}
else
{
stop();
}
}
//----------------------------------------------------------------------------------------------------
void simple_wallet::commit_or_save(std::vector<tools::wallet2::pending_tx>& ptx_vector, bool do_not_relay)
{
size_t i = 0;
while (!ptx_vector.empty())
{
auto & ptx = ptx_vector.back();
const crypto::hash txid = get_transaction_hash(ptx.tx);
if (do_not_relay)
{
cryptonote::blobdata blob;
tx_to_blob(ptx.tx, blob);
const std::string blob_hex = epee::string_tools::buff_to_hex_nodelimer(blob);
const std::string filename = "raw_jyocoin_tx" + (ptx_vector.size() == 1 ? "" : ("_" + std::to_string(i++)));
if (epee::file_io_utils::save_string_to_file(filename, blob_hex))
success_msg_writer(true) << tr("Transaction successfully saved to ") << filename << tr(", txid ") << txid;
else
fail_msg_writer() << tr("Failed to save transaction to ") << filename << tr(", txid ") << txid;
}
else
{
m_wallet->commit_tx(ptx);
success_msg_writer(true) << tr("Transaction successfully submitted, transaction ") << txid << ENDL
<< tr("You can check its status by using the `show_transfers` command.");
}
// if no exception, remove element from vector
ptx_vector.pop_back();
}
}
//----------------------------------------------------------------------------------------------------
int main(int argc, char* argv[])
{
TRY_ENTRY();
#ifdef WIN32
// Activate UTF-8 support for Boost filesystem classes on Windows
std::locale::global(boost::locale::generator().generate(""));
boost::filesystem::path::imbue(std::locale());
#endif
po::options_description desc_params(wallet_args::tr("Wallet options"));
tools::wallet2::init_options(desc_params);
command_line::add_arg(desc_params, arg_wallet_file);
command_line::add_arg(desc_params, arg_generate_new_wallet);
command_line::add_arg(desc_params, arg_generate_from_device);
command_line::add_arg(desc_params, arg_generate_from_view_key);
command_line::add_arg(desc_params, arg_generate_from_spend_key);
command_line::add_arg(desc_params, arg_generate_from_keys);
command_line::add_arg(desc_params, arg_generate_from_multisig_keys);
command_line::add_arg(desc_params, arg_generate_from_json);
command_line::add_arg(desc_params, arg_mnemonic_language);
command_line::add_arg(desc_params, arg_command);
command_line::add_arg(desc_params, arg_restore_deterministic_wallet );
command_line::add_arg(desc_params, arg_restore_multisig_wallet );
command_line::add_arg(desc_params, arg_non_deterministic );
command_line::add_arg(desc_params, arg_electrum_seed );
command_line::add_arg(desc_params, arg_allow_mismatched_daemon_version);
command_line::add_arg(desc_params, arg_restore_height);
command_line::add_arg(desc_params, arg_do_not_relay);
command_line::add_arg(desc_params, arg_create_address_file);
command_line::add_arg(desc_params, arg_subaddress_lookahead);
command_line::add_arg(desc_params, arg_use_english_language_names);
po::positional_options_description positional_options;
positional_options.add(arg_command.name, -1);
boost::optional<po::variables_map> vm;
bool should_terminate = false;
std::tie(vm, should_terminate) = wallet_args::main(
argc, argv,
"jyocoin-wallet-cli [--wallet-file=<file>|--generate-new-wallet=<file>] [<COMMAND>]",
sw::tr("This is the command line jyocoin wallet. It needs to connect to a jyocoin\ndaemon to work correctly.\nWARNING: Do not reuse your jyocoin keys on another fork, UNLESS this fork has key reuse mitigations built in. Doing so will harm your privacy."),
desc_params,
positional_options,
[](const std::string &s, bool emphasis){ tools::scoped_message_writer(emphasis ? epee::console_color_white : epee::console_color_default, true) << s; },
"jyocoin-wallet-cli.log"
);
if (!vm)
{
return 1;
}
if (should_terminate)
{
return 0;
}
cryptonote::simple_wallet w;
const bool r = w.init(*vm);
CHECK_AND_ASSERT_MES(r, 1, sw::tr("Failed to initialize wallet"));
std::vector<std::string> command = command_line::get_arg(*vm, arg_command);
if (!command.empty())
{
if (!w.process_command(command))
fail_msg_writer() << sw::tr("Unknown command: ") << command.front();
w.stop();
w.deinit();
}
else
{
tools::signal_handler::install([&w](int type) {
if (tools::password_container::is_prompting.load())
{
// must be prompting for password so return and let the signal stop prompt
return;
}
#ifdef WIN32
if (type == CTRL_C_EVENT)
#else
if (type == SIGINT)
#endif
{
// if we're pressing ^C when refreshing, just stop refreshing
w.interrupt();
}
else
{
w.stop();
}
});
w.run();
w.deinit();
}
return 0;
CATCH_ENTRY_L0("main", 1);
}
|
#include "extensions/filters/http/lua/wrappers.h"
#include "common/http/utility.h"
#include "extensions/filters/common/lua/wrappers.h"
namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace Lua {
HeaderMapIterator::HeaderMapIterator(HeaderMapWrapper& parent) : parent_(parent) {
entries_.reserve(parent_.headers_.size());
parent_.headers_.iterate([this](const Http::HeaderEntry& header) -> Http::HeaderMap::Iterate {
entries_.push_back(&header);
return Http::HeaderMap::Iterate::Continue;
});
}
int HeaderMapIterator::luaPairsIterator(lua_State* state) {
if (current_ == entries_.size()) {
parent_.iterator_.reset();
return 0;
} else {
const absl::string_view key_view(entries_[current_]->key().getStringView());
lua_pushlstring(state, key_view.data(), key_view.length());
const absl::string_view value_view(entries_[current_]->value().getStringView());
lua_pushlstring(state, value_view.data(), value_view.length());
current_++;
return 2;
}
}
int HeaderMapWrapper::luaAdd(lua_State* state) {
checkModifiable(state);
const char* key = luaL_checkstring(state, 2);
const char* value = luaL_checkstring(state, 3);
headers_.addCopy(Http::LowerCaseString(key), value);
return 0;
}
int HeaderMapWrapper::luaGet(lua_State* state) {
const char* key = luaL_checkstring(state, 2);
const Http::HeaderEntry* entry = headers_.get(Http::LowerCaseString(key));
if (entry != nullptr) {
lua_pushlstring(state, entry->value().getStringView().data(),
entry->value().getStringView().length());
return 1;
} else {
return 0;
}
}
int HeaderMapWrapper::luaPairs(lua_State* state) {
if (iterator_.get() != nullptr) {
luaL_error(state, "cannot create a second iterator before completing the first");
}
// The way iteration works is we create an iteration wrapper that snaps pointers to all of
// the headers. We don't allow modification while an iterator is active. This means that
// currently if a script breaks out of iteration, further modifications will not be possible
// because we don't know if they may resume iteration in the future and it isn't safe. There
// are potentially better ways of handling this but due to GC of the iterator it's very
// difficult to control safety without tracking every allocated iterator and invalidating them
// if the map is modified.
iterator_.reset(HeaderMapIterator::create(state, *this), true);
lua_pushcclosure(state, HeaderMapIterator::static_luaPairsIterator, 1);
return 1;
}
int HeaderMapWrapper::luaReplace(lua_State* state) {
checkModifiable(state);
const char* key = luaL_checkstring(state, 2);
const char* value = luaL_checkstring(state, 3);
const Http::LowerCaseString lower_key(key);
headers_.setCopy(lower_key, value);
return 0;
}
int HeaderMapWrapper::luaRemove(lua_State* state) {
checkModifiable(state);
const char* key = luaL_checkstring(state, 2);
headers_.remove(Http::LowerCaseString(key));
return 0;
}
void HeaderMapWrapper::checkModifiable(lua_State* state) {
if (iterator_.get() != nullptr) {
luaL_error(state, "header map cannot be modified while iterating");
}
if (!cb_()) {
luaL_error(state, "header map can no longer be modified");
}
}
int StreamInfoWrapper::luaProtocol(lua_State* state) {
lua_pushstring(state, Http::Utility::getProtocolString(stream_info_.protocol().value()).c_str());
return 1;
}
int StreamInfoWrapper::luaDynamicMetadata(lua_State* state) {
if (dynamic_metadata_wrapper_.get() != nullptr) {
dynamic_metadata_wrapper_.pushStack();
} else {
dynamic_metadata_wrapper_.reset(DynamicMetadataMapWrapper::create(state, *this), true);
}
return 1;
}
int StreamInfoWrapper::luaDownstreamSslConnection(lua_State* state) {
const auto& ssl = stream_info_.downstreamSslConnection();
if (ssl != nullptr) {
if (downstream_ssl_connection_.get() != nullptr) {
downstream_ssl_connection_.pushStack();
} else {
downstream_ssl_connection_.reset(
Filters::Common::Lua::SslConnectionWrapper::create(state, *ssl), true);
}
} else {
lua_pushnil(state);
}
return 1;
}
DynamicMetadataMapIterator::DynamicMetadataMapIterator(DynamicMetadataMapWrapper& parent)
: parent_{parent}, current_{parent_.streamInfo().dynamicMetadata().filter_metadata().begin()} {}
StreamInfo::StreamInfo& DynamicMetadataMapWrapper::streamInfo() { return parent_.stream_info_; }
int DynamicMetadataMapIterator::luaPairsIterator(lua_State* state) {
if (current_ == parent_.streamInfo().dynamicMetadata().filter_metadata().end()) {
parent_.iterator_.reset();
return 0;
}
lua_pushstring(state, current_->first.c_str());
Filters::Common::Lua::MetadataMapHelper::createTable(state, current_->second.fields());
current_++;
return 2;
}
int DynamicMetadataMapWrapper::luaGet(lua_State* state) {
const char* filter_name = luaL_checkstring(state, 2);
const auto& metadata = streamInfo().dynamicMetadata().filter_metadata();
const auto filter_it = metadata.find(filter_name);
if (filter_it == metadata.end()) {
return 0;
}
Filters::Common::Lua::MetadataMapHelper::createTable(state, filter_it->second.fields());
return 1;
}
int DynamicMetadataMapWrapper::luaSet(lua_State* state) {
if (iterator_.get() != nullptr) {
luaL_error(state, "dynamic metadata map cannot be modified while iterating");
}
const char* filter_name = luaL_checkstring(state, 2);
const char* key = luaL_checkstring(state, 3);
// MetadataMapHelper::loadValue will convert the value on top of the Lua stack,
// so push a copy of the 3rd arg ("value") to the top.
lua_pushvalue(state, 4);
ProtobufWkt::Struct value;
(*value.mutable_fields())[key] = Filters::Common::Lua::MetadataMapHelper::loadValue(state);
streamInfo().setDynamicMetadata(filter_name, value);
// Pop the copy of the metadata value from the stack.
lua_pop(state, 1);
return 0;
}
int DynamicMetadataMapWrapper::luaPairs(lua_State* state) {
if (iterator_.get() != nullptr) {
luaL_error(state, "cannot create a second iterator before completing the first");
}
iterator_.reset(DynamicMetadataMapIterator::create(state, *this), true);
lua_pushcclosure(state, DynamicMetadataMapIterator::static_luaPairsIterator, 1);
return 1;
}
int PublicKeyWrapper::luaGet(lua_State* state) {
if (public_key_.empty()) {
lua_pushnil(state);
} else {
lua_pushstring(state, public_key_.c_str());
}
return 1;
}
} // namespace Lua
} // namespace HttpFilters
} // namespace Extensions
} // namespace Envoy
|
#include <Eigen/Core>
#include <iostream>
#include <LBFGSB.h>
using namespace LBFGSpp;
typedef double Scalar;
typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Vector;
// Example from the roptim R package
// f(x) = (x[0] - 1)^2 + 4 * (x[1] - x[0]^2)^2 + ... + 4 * (x[end] - x[end - 1]^2)^2
class Rosenbrock
{
private:
int n;
public:
Rosenbrock(int n_) : n(n_) {}
Scalar operator()(const Vector& x, Vector& grad)
{
Scalar fx = (x[0] - 1.0) * (x[0] - 1.0);
grad[0] = 2 * (x[0] - 1) + 16 * (x[0] * x[0] - x[1]) * x[0];
for(int i = 1; i < n; i++)
{
fx += 4 * std::pow(x[i] - x[i - 1] * x[i - 1], 2);
if(i == n - 1)
{
grad[i] = 8 * (x[i] - x[i - 1] * x[i - 1]);
} else {
grad[i] = 8 * (x[i] - x[i - 1] * x[i - 1]) + 16 * (x[i] * x[i] - x[i + 1]) * x[i];
}
}
return fx;
}
};
int main()
{
const int n = 25;
LBFGSBParam<Scalar> param;
LBFGSBSolver<Scalar> solver(param);
Rosenbrock fun(n);
// Variable bounds
Vector lb = Vector::Constant(n, 2.0);
Vector ub = Vector::Constant(n, 4.0);
// The third variable is unbounded
lb[2] = -std::numeric_limits<Scalar>::infinity();
ub[2] = std::numeric_limits<Scalar>::infinity();
// Initial values
Vector x = Vector::Constant(n, 3.0);
// Make some initial values at the bounds
x[0] = x[1] = 2.0;
x[5] = x[7] = 4.0;
Scalar fx;
int niter = solver.minimize(fun, x, fx, lb, ub);
std::cout << niter << " iterations" << std::endl;
std::cout << "x = \n" << x.transpose() << std::endl;
std::cout << "f(x) = " << fx << std::endl;
std::cout << "grad = " << solver.final_grad().transpose() << std::endl;
std::cout << "projected grad norm = " << solver.final_grad_norm() << std::endl;
return 0;
}
|
/***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 <gtest/gtest.h>
#include "ModelFixture.hpp"
#include "../Model.hpp"
#include "../Model_Impl.hpp"
#include "../Material.hpp"
#include "../Material_Impl.hpp"
#include "../StandardOpaqueMaterial.hpp"
#include "../StandardOpaqueMaterial_Impl.hpp"
#include "../StandardsInformationMaterial.hpp"
#include "../StandardsInformationMaterial_Impl.hpp"
#include "../../utilities/geometry/Point3d.hpp"
#include "../../utilities/idf/IdfFile.hpp"
#include <utilities/idd/OS_Construction_FieldEnums.hxx>
#include <utilities/idd/OS_Material_FieldEnums.hxx>
#include <utilities/idd/OS_Material_AirGap_FieldEnums.hxx>
#include <utilities/idd/IddEnums.hxx>
using namespace openstudio;
using namespace openstudio::model;
TEST_F(ModelFixture, Material)
{
Model model;
StandardOpaqueMaterial exterior(model);
MaterialVector materials = model.getModelObjects<Material>();
ASSERT_EQ(static_cast<unsigned>(1), materials.size());
StandardsInformationMaterialVector materialInformations = model.getModelObjects<StandardsInformationMaterial>();
ASSERT_EQ(static_cast<unsigned>(0), materialInformations.size());
{
Model testModel;
exterior.clone(testModel);
materials = model.getModelObjects<Material>();
ASSERT_EQ(static_cast<unsigned>(1), materials.size());
materialInformations = model.getModelObjects<StandardsInformationMaterial>();
ASSERT_EQ(static_cast<unsigned>(0), materialInformations.size());
materials = testModel.getModelObjects<Material>();
ASSERT_EQ(static_cast<unsigned>(1), materials.size());
materialInformations = testModel.getModelObjects<StandardsInformationMaterial>();
ASSERT_EQ(static_cast<unsigned>(0), materialInformations.size());
}
StandardsInformationMaterial info = exterior.standardsInformation();
{
Model testModel;
exterior.clone(testModel);
materials = model.getModelObjects<Material>();
ASSERT_EQ(static_cast<unsigned>(1), materials.size());
materialInformations = model.getModelObjects<StandardsInformationMaterial>();
ASSERT_EQ(static_cast<unsigned>(1), materialInformations.size());
materials = testModel.getModelObjects<Material>();
ASSERT_EQ(static_cast<unsigned>(1), materials.size());
materialInformations = testModel.getModelObjects<StandardsInformationMaterial>();
ASSERT_EQ(static_cast<unsigned>(1), materialInformations.size());
}
{
Model testModel;
info.clone(testModel);
materials = model.getModelObjects<Material>();
ASSERT_EQ(static_cast<unsigned>(1), materials.size());
materialInformations = model.getModelObjects<StandardsInformationMaterial>();
ASSERT_EQ(static_cast<unsigned>(1), materialInformations.size());
materials = testModel.getModelObjects<Material>();
ASSERT_EQ(static_cast<unsigned>(0), materials.size());
materialInformations = testModel.getModelObjects<StandardsInformationMaterial>();
ASSERT_EQ(static_cast<unsigned>(1), materialInformations.size());
}
StandardOpaqueMaterial exteriorClone = exterior.clone().cast<StandardOpaqueMaterial>();
materials = model.getModelObjects<Material>();
ASSERT_EQ(static_cast<unsigned>(2), materials.size());
materialInformations = model.getModelObjects<StandardsInformationMaterial>();
ASSERT_EQ(static_cast<unsigned>(2), materialInformations.size());
}
|
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/taf/v20200210/model/RecognizeTargetAudienceRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Taf::V20200210::Model;
using namespace rapidjson;
using namespace std;
RecognizeTargetAudienceRequest::RecognizeTargetAudienceRequest() :
m_bspDataHasBeenSet(false)
{
}
string RecognizeTargetAudienceRequest::ToJsonString() const
{
Document d;
d.SetObject();
Document::AllocatorType& allocator = d.GetAllocator();
if (m_bspDataHasBeenSet)
{
Value iKey(kStringType);
string key = "BspData";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, Value(kObjectType).Move(), allocator);
m_bspData.ToJsonObject(d[key.c_str()], allocator);
}
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
InputRecognizeTargetAudience RecognizeTargetAudienceRequest::GetBspData() const
{
return m_bspData;
}
void RecognizeTargetAudienceRequest::SetBspData(const InputRecognizeTargetAudience& _bspData)
{
m_bspData = _bspData;
m_bspDataHasBeenSet = true;
}
bool RecognizeTargetAudienceRequest::BspDataHasBeenSet() const
{
return m_bspDataHasBeenSet;
}
|
// Copyright 2017 The Fuchsia 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 "driver_host.h"
#include <dlfcn.h>
#include <fuchsia/device/manager/c/fidl.h>
#include <fuchsia/device/manager/llcpp/fidl.h>
#include <inttypes.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include <lib/async/cpp/receiver.h>
#include <lib/async/cpp/wait.h>
#include <lib/ddk/binding.h>
#include <lib/ddk/debug.h>
#include <lib/ddk/device.h>
#include <lib/ddk/driver.h>
#include <lib/fdio/fdio.h>
#include <lib/fidl/coding.h>
#include <lib/zx/debuglog.h>
#include <lib/zx/process.h>
#include <lib/zx/resource.h>
#include <lib/zx/vmo.h>
#include <lib/zxio/inception.h>
#include <lib/zxio/null.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <zircon/assert.h>
#include <zircon/dlfcn.h>
#include <zircon/process.h>
#include <zircon/processargs.h>
#include <zircon/status.h>
#include <zircon/syscalls.h>
#include <zircon/syscalls/log.h>
#include <memory>
#include <new>
#include <utility>
#include <vector>
#include <fbl/auto_lock.h>
#include <fbl/function.h>
#include <fbl/string_printf.h>
#include "async_loop_owned_rpc_handler.h"
#include "composite_device.h"
#include "connection_destroyer.h"
#include "device_controller_connection.h"
#include "env.h"
#include "fidl_txn.h"
#include "log.h"
#include "main.h"
#include "proxy_iostate.h"
#include "scheduler_profile.h"
#include "tracing.h"
namespace {
bool property_value_type_valid(uint32_t value_type) {
return value_type > ZX_DEVICE_PROPERTY_VALUE_UNDEFINED &&
value_type <= ZX_DEVICE_PROPERTY_VALUE_BOOL;
}
fuchsia_device_manager::wire::DeviceProperty convert_device_prop(const zx_device_prop_t& prop) {
return fuchsia_device_manager::wire::DeviceProperty{
.id = prop.id,
.reserved = prop.reserved,
.value = prop.value,
};
}
fuchsia_device_manager::wire::DeviceStrProperty convert_device_str_prop(
const zx_device_str_prop_t& prop) {
auto str_property = fuchsia_device_manager::wire::DeviceStrProperty{
.key = ::fidl::StringView::FromExternal(prop.key),
};
property_value_type_valid(prop.property_value.value_type);
if (prop.property_value.value_type == ZX_DEVICE_PROPERTY_VALUE_INT) {
auto property_val = prop.property_value.value.int_val;
str_property.value = fuchsia_device_manager::wire::PropertyValue::WithIntValue(
::fidl::ObjectView<uint32_t>::FromExternal(&property_val));
} else if (prop.property_value.value_type == ZX_DEVICE_PROPERTY_VALUE_STRING) {
auto property_val = fidl::StringView::FromExternal(prop.property_value.value.str_val);
str_property.value = fuchsia_device_manager::wire::PropertyValue::WithStrValue(
::fidl::ObjectView<::fidl::StringView>::FromExternal(&property_val));
} else if (prop.property_value.value_type == ZX_DEVICE_PROPERTY_VALUE_BOOL) {
auto property_val = prop.property_value.value.bool_val;
str_property.value = fuchsia_device_manager::wire::PropertyValue::WithBoolValue(
::fidl::ObjectView<bool>::FromExternal(&property_val));
}
return str_property;
}
static fx_log_severity_t log_min_severity(const char* name, const char* flag) {
if (!strcasecmp(flag, "error")) {
return FX_LOG_ERROR;
}
if (!strcasecmp(flag, "warning")) {
return FX_LOG_WARNING;
}
if (!strcasecmp(flag, "info")) {
return FX_LOG_INFO;
}
if (!strcasecmp(flag, "debug")) {
return FX_LOG_DEBUG;
}
if (!strcasecmp(flag, "trace")) {
return FX_LOG_TRACE;
}
if (!strcasecmp(flag, "serial")) {
return DDK_LOG_SERIAL;
}
LOGF(WARNING, "Invalid minimum log severity '%s' for driver '%s', will log all", flag, name);
return FX_LOG_ALL;
}
zx_status_t log_rpc_result(const fbl::RefPtr<zx_device_t>& dev, const char* opname,
zx_status_t status, zx_status_t call_status = ZX_OK) {
if (status != ZX_OK) {
LOGD(ERROR, *dev, "Failed %s RPC: %s", opname, zx_status_get_string(status));
return status;
}
if (call_status != ZX_OK && call_status != ZX_ERR_NOT_FOUND) {
LOGD(ERROR, *dev, "Failed %s: %s", opname, zx_status_get_string(call_status));
}
return call_status;
}
} // namespace
const char* mkdevpath(const zx_device_t& dev, char* const path, size_t max) {
if (max == 0) {
return "";
}
char* end = path + max;
char sep = 0;
auto append_name = [&end, &path, &sep](const zx_device_t& dev) {
*(--end) = sep;
size_t len = strlen(dev.name());
if (len > static_cast<size_t>(end - path)) {
return;
}
end -= len;
memcpy(end, dev.name(), len);
sep = '/';
};
append_name(dev);
fbl::RefPtr<zx_device> itr_dev = dev.parent();
while (itr_dev && end > path) {
append_name(*itr_dev);
itr_dev = itr_dev->parent();
}
// If devpath is longer than |max|, add an ellipsis.
constexpr char ellipsis[] = "...";
constexpr size_t ellipsis_len = sizeof(ellipsis) - 1;
if (*end == sep && max > ellipsis_len) {
if (ellipsis_len > static_cast<size_t>(end - path)) {
end = path;
} else {
end -= ellipsis_len;
}
memcpy(end, ellipsis, ellipsis_len);
}
return end;
}
zx_status_t zx_driver::Create(std::string_view libname, InspectNodeCollection& drivers,
fbl::RefPtr<zx_driver>* out_driver) {
char process_name[ZX_MAX_NAME_LEN] = {};
zx::process::self()->get_property(ZX_PROP_NAME, process_name, sizeof(process_name));
const char* tags[] = {process_name, "driver"};
fx_logger_config_t config{
.min_severity = FX_LOG_SEVERITY_DEFAULT,
.console_fd = getenv_bool("devmgr.log-to-debuglog", false) ? dup(STDOUT_FILENO) : -1,
.log_service_channel = ZX_HANDLE_INVALID,
.tags = tags,
.num_tags = std::size(tags),
};
fx_logger_t* logger;
zx_status_t status = fx_logger_create(&config, &logger);
if (status != ZX_OK) {
return status;
}
*out_driver = fbl::AdoptRef(new zx_driver(logger, libname, drivers));
return ZX_OK;
}
zx_driver::zx_driver(fx_logger_t* logger, std::string_view libname, InspectNodeCollection& drivers)
: logger_(logger), libname_(libname), inspect_(drivers, std::string(libname)) {}
zx_driver::~zx_driver() { fx_logger_destroy(logger_); }
zx_status_t DriverHostContext::SetupRootDevcoordinatorConnection(zx::channel ch) {
auto conn = std::make_unique<internal::DevhostControllerConnection>(this);
if (conn == nullptr) {
return ZX_ERR_NO_MEMORY;
}
conn->set_channel(std::move(ch));
return internal::DevhostControllerConnection::BeginWait(std::move(conn), loop_.dispatcher());
}
// Send message to driver_manager asking to add child device to
// parent device. Called under the api lock.
zx_status_t DriverHostContext::DriverManagerAdd(const fbl::RefPtr<zx_device_t>& parent,
const fbl::RefPtr<zx_device_t>& child,
const char* proxy_args,
const zx_device_prop_t* props, uint32_t prop_count,
const zx_device_str_prop_t* str_props,
uint32_t str_prop_count, zx::vmo inspect,
zx::channel client_remote) {
bool add_invisible = child->flags() & DEV_FLAG_INVISIBLE;
using fuchsia_device_manager::wire::AddDeviceConfig;
AddDeviceConfig add_device_config;
if (child->flags() & DEV_FLAG_ALLOW_MULTI_COMPOSITE) {
add_device_config |= AddDeviceConfig::kAllowMultiComposite;
}
if (add_invisible) {
add_device_config |= AddDeviceConfig::kInvisible;
}
if (child->flags() & DEV_FLAG_UNBINDABLE) {
add_device_config |= AddDeviceConfig::kSkipAutobind;
}
zx_status_t status;
zx::channel coordinator_local, coordinator_remote;
if ((status = zx::channel::create(0, &coordinator_local, &coordinator_remote)) != ZX_OK) {
return status;
}
zx::channel device_controller, device_controller_remote;
if ((status = zx::channel::create(0, &device_controller, &device_controller_remote)) != ZX_OK) {
return status;
}
fidl::Client<fuchsia_device_manager::Coordinator> coordinator;
coordinator.Bind(std::move(coordinator_local), loop_.dispatcher());
std::unique_ptr<DeviceControllerConnection> conn;
status = DeviceControllerConnection::Create(this, child, std::move(device_controller),
std::move(coordinator), &conn);
if (status != ZX_OK) {
return status;
}
std::vector<fuchsia_device_manager::wire::DeviceProperty> props_list = {};
for (size_t i = 0; i < prop_count; i++) {
props_list.push_back(convert_device_prop(props[i]));
}
std::vector<fuchsia_device_manager::wire::DeviceStrProperty> str_props_list = {};
for (size_t i = 0; i < str_prop_count; i++) {
if (!property_value_type_valid(str_props[i].property_value.value_type)) {
return ZX_ERR_INVALID_ARGS;
}
str_props_list.push_back(convert_device_str_prop(str_props[i]));
}
const auto& rpc = parent->coordinator_client;
if (!rpc) {
return ZX_ERR_IO_REFUSED;
}
size_t proxy_args_len = proxy_args ? strlen(proxy_args) : 0;
zx_status_t call_status = ZX_OK;
static_assert(sizeof(zx_device_prop_t) == sizeof(uint64_t));
uint64_t device_id = 0;
::fuchsia_device_manager::wire::DevicePropertyList property_list = {
.props = ::fidl::VectorView<fuchsia_device_manager::wire::DeviceProperty>::FromExternal(
props_list),
.str_props =
::fidl::VectorView<fuchsia_device_manager::wire::DeviceStrProperty>::FromExternal(
str_props_list),
};
auto response = rpc->AddDevice_Sync(
std::move(coordinator_remote), std::move(device_controller_remote), property_list,
::fidl::StringView::FromExternal(child->name()), child->protocol_id(),
::fidl::StringView::FromExternal(child->driver->libname()),
::fidl::StringView::FromExternal(proxy_args, proxy_args_len), add_device_config,
child->ops()->init /* has_init */, std::move(inspect), std::move(client_remote));
status = response.status();
if (status == ZX_OK) {
if (response.Unwrap()->result.is_response()) {
device_id = response.Unwrap()->result.response().local_device_id;
if (add_invisible) {
// Mark child as invisible until the init function is replied.
child->set_flag(DEV_FLAG_INVISIBLE);
}
} else {
call_status = response.Unwrap()->result.err();
}
}
status = log_rpc_result(parent, "add-device", status, call_status);
if (status != ZX_OK) {
return status;
}
child->set_local_id(device_id);
return DeviceControllerConnection::BeginWait(std::move(conn), loop_.dispatcher());
}
// Send message to driver_manager informing it that this device
// is being removed. Called under the api lock.
zx_status_t DriverHostContext::DriverManagerRemove(fbl::RefPtr<zx_device_t> dev) {
DeviceControllerConnection* conn = dev->conn.load();
if (conn == nullptr) {
LOGD(ERROR, *dev, "Invalid device controller connection");
return ZX_ERR_INTERNAL;
}
VLOGD(1, *dev, "Removing device %p", dev.get());
// This must be done before the RemoveDevice message is sent to
// driver_manager, since driver_manager will close the channel in response.
// The async loop may see the channel close before it sees the queued
// shutdown packet, so it needs to check if dev->conn has been nulled to
// handle that gracefully.
dev->conn.store(nullptr);
// Drop the device vnode, since no one should be able to open connections anymore.
// This will break the reference cycle between the DevfsVnode and the zx_device.
dev->vnode.reset();
// respond to the remove fidl call
dev->removal_cb(ZX_OK);
// Forget our local ID, to release the reference stored by the local ID map
dev->set_local_id(0);
// Forget about our rpc channel since after the port_queue below it may be
// closed.
dev->rpc = zx::unowned_channel();
dev->coordinator_client = {};
// queue an event to destroy the connection
ConnectionDestroyer::Get()->QueueDeviceControllerConnection(loop_.dispatcher(), conn);
// shut down our proxy rpc channel if it exists
ProxyIosDestroy(dev);
return ZX_OK;
}
void DriverHostContext::ProxyIosDestroy(const fbl::RefPtr<zx_device_t>& dev) {
fbl::AutoLock guard(&dev->proxy_ios_lock);
if (dev->proxy_ios) {
dev->proxy_ios->CancelLocked(loop_.dispatcher());
}
}
zx_status_t DriverHostContext::FindDriver(std::string_view libname, zx::vmo vmo,
fbl::RefPtr<zx_driver_t>* out) {
// check for already-loaded driver first
for (auto& drv : drivers_) {
if (!libname.compare(drv.libname())) {
*out = fbl::RefPtr(&drv);
return drv.status();
}
}
fbl::RefPtr<zx_driver> new_driver;
zx_status_t status = zx_driver::Create(libname, inspect().drivers(), &new_driver);
if (status != ZX_OK) {
return status;
}
// Let the |drivers_| list and our out parameter each have a refcount.
drivers_.push_back(new_driver);
*out = new_driver;
const char* c_libname = new_driver->libname().c_str();
void* dl = dlopen_vmo(vmo.get(), RTLD_NOW);
if (dl == nullptr) {
LOGF(ERROR, "Cannot load '%s': %s", c_libname, dlerror());
new_driver->set_status(ZX_ERR_IO);
return new_driver->status();
}
auto dn = static_cast<const zircon_driver_note_t*>(dlsym(dl, "__zircon_driver_note__"));
if (dn == nullptr) {
LOGF(ERROR, "Driver '%s' missing __zircon_driver_note__ symbol", c_libname);
new_driver->set_status(ZX_ERR_IO);
return new_driver->status();
}
auto ops = static_cast<const zx_driver_ops_t**>(dlsym(dl, "__zircon_driver_ops__"));
auto dr = static_cast<zx_driver_rec_t*>(dlsym(dl, "__zircon_driver_rec__"));
if (dr == nullptr) {
LOGF(ERROR, "Driver '%s' missing __zircon_driver_rec__ symbol", c_libname);
new_driver->set_status(ZX_ERR_IO);
return new_driver->status();
}
// TODO(kulakowski) Eventually just check __zircon_driver_ops__,
// when bind programs are standalone.
if (ops == nullptr) {
ops = &dr->ops;
}
if (!(*ops)) {
LOGF(ERROR, "Driver '%s' has nullptr ops", c_libname);
new_driver->set_status(ZX_ERR_INVALID_ARGS);
return new_driver->status();
}
if ((*ops)->version != DRIVER_OPS_VERSION) {
LOGF(ERROR, "Driver '%s' has bad driver ops version %#lx, expecting %#lx", c_libname,
(*ops)->version, DRIVER_OPS_VERSION);
new_driver->set_status(ZX_ERR_INVALID_ARGS);
return new_driver->status();
}
new_driver->set_driver_rec(dr);
new_driver->set_name(dn->payload.name);
new_driver->set_ops(*ops);
dr->driver = new_driver.get();
// Check for minimum log severity of driver.
const auto flag_name = fbl::StringPrintf("driver.%s.log", new_driver->name());
const char* flag_value = getenv(flag_name.data());
if (flag_value != nullptr) {
fx_log_severity_t min_severity = log_min_severity(new_driver->name(), flag_value);
status = fx_logger_set_min_severity(new_driver->logger(), min_severity);
if (status != ZX_OK) {
LOGF(ERROR, "Failed to set minimum log severity for driver '%s': %s", new_driver->name(),
zx_status_get_string(status));
} else {
LOGF(INFO, "Driver '%s' set minimum log severity to %d", new_driver->name(), min_severity);
}
}
if (new_driver->has_init_op()) {
new_driver->set_status(new_driver->InitOp());
if (new_driver->status() != ZX_OK) {
LOGF(ERROR, "Driver '%s' failed in init: %s", c_libname,
zx_status_get_string(new_driver->status()));
}
} else {
new_driver->set_status(ZX_OK);
}
return new_driver->status();
}
namespace internal {
namespace {
// We need a global pointer to a DriverHostContext so that we can implement the functions exported
// to drivers. Some of these functions unfortunately do not take an argument that can be used to
// find a context.
DriverHostContext* kContextForApi = nullptr;
} // namespace
void RegisterContextForApi(DriverHostContext* context) {
ZX_ASSERT((context == nullptr) != (kContextForApi == nullptr));
kContextForApi = context;
}
DriverHostContext* ContextForApi() { return kContextForApi; }
void DevhostControllerConnection::CreateDevice(CreateDeviceRequestView request,
CreateDeviceCompleter::Sync& completer) {
std::string_view driver_path(request->driver_path.data(), request->driver_path.size());
// This does not operate under the driver_host api lock,
// since the newly created device is not visible to
// any API surface until a driver is bound to it.
// (which can only happen via another message on this thread)
// named driver -- ask it to create the device
fbl::RefPtr<zx_driver_t> drv;
zx_status_t r = driver_host_context_->FindDriver(driver_path, std::move(request->driver), &drv);
if (r != ZX_OK) {
LOGF(ERROR, "Failed to load driver '%.*s': %s", driver_path.size(), driver_path.data(),
zx_status_get_string(r));
return;
}
if (!drv->has_create_op()) {
LOGF(ERROR, "Driver does not support create operation");
return;
}
fidl::Client<fuchsia_device_manager::Coordinator> coordinator;
coordinator.Bind(std::move(request->coordinator_rpc), driver_host_context_->loop().dispatcher());
// Create a dummy parent device for use in this call to Create
fbl::RefPtr<zx_device> parent;
r = zx_device::Create(driver_host_context_, "device_create dummy", drv.get(), &parent);
if (r != ZX_OK) {
LOGF(ERROR, "Failed to create device: %s", zx_status_get_string(r));
return;
}
// magic cookie for device create handshake
CreationContext creation_context = {
.parent = std::move(parent),
.child = nullptr,
.device_controller_rpc = zx::unowned_channel(request->device_controller_rpc.channel()),
.coordinator_client = coordinator.Clone(),
};
r = drv->CreateOp(&creation_context, creation_context.parent, "proxy", request->proxy_args.data(),
request->parent_proxy.release());
// Suppress a warning about dummy device being in a bad state. The
// message is spurious in this case, since the dummy parent never
// actually begins its device lifecycle. This flag is ordinarily
// set by device_remove().
creation_context.parent->set_flag(DEV_FLAG_DEAD);
if (r != ZX_OK) {
LOGF(ERROR, "Failed to create driver: %s", zx_status_get_string(r));
return;
}
auto new_device = std::move(creation_context.child);
if (new_device == nullptr) {
LOGF(ERROR, "Driver did not create a device");
return;
}
new_device->set_local_id(request->local_device_id);
std::unique_ptr<DeviceControllerConnection> newconn;
r = DeviceControllerConnection::Create(driver_host_context_, std::move(new_device),
request->device_controller_rpc.TakeChannel(),
std::move(coordinator), &newconn);
if (r != ZX_OK) {
return;
}
// TODO: inform devcoord
VLOGF(1, "Created device %p '%.*s'", new_device.get(), driver_path.size(), driver_path.data());
r = DeviceControllerConnection::BeginWait(std::move(newconn),
driver_host_context_->loop().dispatcher());
if (r != ZX_OK) {
LOGF(ERROR, "Failed to wait for device controller connection: %s", zx_status_get_string(r));
return;
}
}
void DevhostControllerConnection::CreateCompositeDevice(
CreateCompositeDeviceRequestView request, CreateCompositeDeviceCompleter::Sync& completer) {
// Convert the fragment IDs into zx_device references
CompositeFragments fragments_list(new CompositeFragment[request->fragments.count()],
request->fragments.count());
{
// Acquire the API lock so that we don't have to worry about concurrent
// device removes
fbl::AutoLock lock(&driver_host_context_->api_lock());
for (size_t i = 0; i < request->fragments.count(); ++i) {
const auto& fragment = request->fragments.data()[i];
uint64_t local_id = fragment.id;
fbl::RefPtr<zx_device_t> dev = zx_device::GetDeviceFromLocalId(local_id);
if (dev == nullptr || (dev->flags() & DEV_FLAG_DEAD)) {
completer.Reply(ZX_ERR_NOT_FOUND);
return;
}
fragments_list[i].name = std::string(fragment.name.data(), fragment.name.size());
fragments_list[i].device = std::move(dev);
}
}
auto driver = GetCompositeDriver(driver_host_context_);
if (driver == nullptr) {
completer.Reply(ZX_ERR_INTERNAL);
return;
}
fbl::RefPtr<zx_device_t> dev;
static_assert(fuchsia_device_manager_DEVICE_NAME_MAX + 1 >= sizeof(dev->name()));
zx_status_t status = zx_device::Create(driver_host_context_,
std::string(request->name.data(), request->name.size()),
driver.get(), &dev);
if (status != ZX_OK) {
completer.Reply(status);
return;
}
dev->set_local_id(request->local_device_id);
fidl::Client<fuchsia_device_manager::Coordinator> coordinator;
coordinator.Bind(std::move(request->coordinator_rpc), driver_host_context_->loop().dispatcher());
std::unique_ptr<DeviceControllerConnection> newconn;
status = DeviceControllerConnection::Create(driver_host_context_, dev,
request->device_controller_rpc.TakeChannel(),
std::move(coordinator), &newconn);
if (status != ZX_OK) {
completer.Reply(status);
return;
}
status = InitializeCompositeDevice(dev, std::move(fragments_list));
if (status != ZX_OK) {
completer.Reply(status);
return;
}
VLOGF(1, "Created composite device %p '%s'", dev.get(), dev->name());
status = DeviceControllerConnection::BeginWait(std::move(newconn),
driver_host_context_->loop().dispatcher());
if (status != ZX_OK) {
completer.Reply(status);
return;
}
completer.Reply(ZX_OK);
}
void DevhostControllerConnection::CreateDeviceStub(CreateDeviceStubRequestView request,
CreateDeviceStubCompleter::Sync& completer) {
// This method is used for creating driverless proxies in case of misc, root, test devices.
// Since there are no proxy drivers backing the device, a dummy proxy driver will be used for
// device creation.
if (!proxy_driver_) {
auto status =
zx_driver::Create("proxy", driver_host_context_->inspect().drivers(), &proxy_driver_);
if (status != ZX_OK) {
return;
}
}
fbl::RefPtr<zx_device_t> dev;
zx_status_t r = zx_device::Create(driver_host_context_, "proxy", proxy_driver_.get(), &dev);
// TODO: dev->ops() and other lifecycle bits
// no name means a dummy proxy device
if (r != ZX_OK) {
return;
}
dev->set_protocol_id(request->protocol_id);
dev->set_ops(&kDeviceDefaultOps);
dev->set_local_id(request->local_device_id);
fidl::Client<fuchsia_device_manager::Coordinator> coordinator;
coordinator.Bind(std::move(request->coordinator_rpc), driver_host_context_->loop().dispatcher());
std::unique_ptr<DeviceControllerConnection> newconn;
r = DeviceControllerConnection::Create(driver_host_context_, dev,
request->device_controller_rpc.TakeChannel(),
std::move(coordinator), &newconn);
if (r != ZX_OK) {
return;
}
VLOGF(1, "Created device stub %p '%s'", dev.get(), dev->name());
r = DeviceControllerConnection::BeginWait(std::move(newconn),
driver_host_context_->loop().dispatcher());
if (r != ZX_OK) {
return;
}
}
// TODO(fxbug.dev/68309): Implement Restart.
void DevhostControllerConnection::Restart(RestartRequestView request,
RestartCompleter::Sync& completer) {
completer.Reply(ZX_OK);
}
zx_status_t DevhostControllerConnection::HandleRead() {
zx::unowned_channel conn = channel();
uint8_t msg[ZX_CHANNEL_MAX_MSG_BYTES];
zx_handle_info_t hin[ZX_CHANNEL_MAX_MSG_HANDLES];
uint32_t msize = sizeof(msg);
uint32_t hcount = std::size(hin);
zx_status_t status = conn->read_etc(0, msg, hin, msize, hcount, &msize, &hcount);
if (status != ZX_OK) {
return status;
}
fidl_incoming_msg_t fidl_msg = {
.bytes = msg,
.handles = hin,
.num_bytes = msize,
.num_handles = hcount,
};
if (fidl_msg.num_bytes < sizeof(fidl_message_header_t)) {
FidlHandleInfoCloseMany(fidl_msg.handles, fidl_msg.num_handles);
return ZX_ERR_IO;
}
auto hdr = static_cast<fidl_message_header_t*>(fidl_msg.bytes);
DevmgrFidlTxn txn(std::move(conn), hdr->txid);
fidl::WireDispatch<fuchsia_device_manager::DevhostController>(
this, fidl::IncomingMessage::FromEncodedCMessage(&fidl_msg), &txn);
return txn.Status();
}
// handles devcoordinator rpc
void DevhostControllerConnection::HandleRpc(std::unique_ptr<DevhostControllerConnection> conn,
async_dispatcher_t* dispatcher, async::WaitBase* wait,
zx_status_t status, const zx_packet_signal_t* signal) {
if (status != ZX_OK) {
LOGF(ERROR, "Failed to wait on %p from driver_manager: %s", conn.get(),
zx_status_get_string(status));
return;
}
if (signal->observed & ZX_CHANNEL_READABLE) {
status = conn->HandleRead();
if (status != ZX_OK) {
LOGF(FATAL, "Unhandled RPC on %p from driver_manager: %s", conn.get(),
zx_status_get_string(status));
}
BeginWait(std::move(conn), dispatcher);
return;
}
if (signal->observed & ZX_CHANNEL_PEER_CLOSED) {
// This is expected in test environments where driver_manager has terminated.
// TODO(fxbug.dev/52627): Support graceful termination.
LOGF(WARNING, "Disconnected %p from driver_manager", conn.get());
zx_process_exit(1);
}
LOGF(WARNING, "Unexpected signal state %#08x", signal->observed);
BeginWait(std::move(conn), dispatcher);
}
int main(int argc, char** argv) {
char process_name[ZX_MAX_NAME_LEN] = {};
zx::process::self()->get_property(ZX_PROP_NAME, process_name, sizeof(process_name));
const char* tags[] = {process_name, "device"};
fx_logger_config_t config{
.min_severity = getenv_bool("devmgr.verbose", false) ? FX_LOG_ALL : FX_LOG_SEVERITY_DEFAULT,
.console_fd = getenv_bool("devmgr.log-to-debuglog", false) ? dup(STDOUT_FILENO) : -1,
.log_service_channel = ZX_HANDLE_INVALID,
.tags = tags,
.num_tags = std::size(tags),
};
zx_status_t status = fx_log_reconfigure(&config);
if (status != ZX_OK) {
return status;
}
zx::resource root_resource(zx_take_startup_handle(PA_HND(PA_RESOURCE, 0)));
if (!root_resource.is_valid()) {
LOGF(WARNING, "No root resource handle");
}
zx::channel root_conn_channel(zx_take_startup_handle(PA_HND(PA_USER0, 0)));
if (!root_conn_channel.is_valid()) {
LOGF(ERROR, "Invalid root connection to driver_manager");
return ZX_ERR_BAD_HANDLE;
}
DriverHostContext ctx(&kAsyncLoopConfigAttachToCurrentThread, std::move(root_resource));
const char* root_driver_path = getenv("devmgr.root_driver_path");
if (root_driver_path != nullptr) {
ctx.set_root_driver_path(root_driver_path);
}
RegisterContextForApi(&ctx);
status = connect_scheduler_profile_provider();
if (status != ZX_OK) {
LOGF(INFO, "Failed to connect to profile provider: %s", zx_status_get_string(status));
return status;
}
if (getenv_bool("driver.tracing.enable", true)) {
status = start_trace_provider();
if (status != ZX_OK) {
LOGF(INFO, "Failed to register trace provider: %s", zx_status_get_string(status));
// This is not a fatal error.
}
}
auto stop_tracing = fit::defer([]() { stop_trace_provider(); });
status = ctx.SetupRootDevcoordinatorConnection(std::move(root_conn_channel));
if (status != ZX_OK) {
LOGF(ERROR, "Failed to watch root connection to driver_manager: %s",
zx_status_get_string(status));
return status;
}
status = ctx.inspect().Serve(zx::channel(zx_take_startup_handle(PA_DIRECTORY_REQUEST)),
ctx.loop().dispatcher());
if (status != ZX_OK) {
LOGF(WARNING, "driver_host: error serving diagnostics directory: %s\n",
zx_status_get_string(status));
// This is not a fatal error
}
return ctx.loop().Run(zx::time::infinite(), false /* once */);
}
} // namespace internal
void DriverHostContext::MakeVisible(const fbl::RefPtr<zx_device_t>& dev,
const device_make_visible_args_t* args) {
ZX_ASSERT_MSG(!dev->ops()->init,
"Cannot call device_make_visible if init hook is implemented."
"The device will automatically be made visible once the init hook is replied to.");
const auto& client = dev->coordinator_client;
if (!client) {
return;
}
if (args && args->power_states && args->power_state_count != 0) {
dev->SetPowerStates(args->power_states, args->power_state_count);
}
if (args && args->performance_states && (args->performance_state_count != 0)) {
dev->SetPerformanceStates(args->performance_states, args->performance_state_count);
}
// TODO(teisenbe): Handle failures here...
VLOGD(1, *dev, "make-visible");
auto response = client->MakeVisible_Sync();
zx_status_t status = response.status();
zx_status_t call_status = ZX_OK;
if (status == ZX_OK) {
if (response.Unwrap()->result.is_err()) {
call_status = response.Unwrap()->result.err();
}
}
log_rpc_result(dev, "make-visible", status, call_status);
dev->unset_flag(DEV_FLAG_INVISIBLE);
// Reply to any pending bind/rebind requests, if all
// the children are initialized.
bool reply_bind_rebind = true;
for (auto& child : dev->parent()->children()) {
if (child.flags() & DEV_FLAG_INVISIBLE) {
reply_bind_rebind = false;
}
}
if (!reply_bind_rebind || !dev->parent()->complete_bind_rebind_after_init()) {
return;
}
status = (status == ZX_OK) ? call_status : status;
if (auto bind_conn = dev->parent()->take_bind_conn(); bind_conn) {
bind_conn(status);
}
if (auto rebind_conn = dev->parent()->take_rebind_conn(); rebind_conn) {
rebind_conn(status);
}
}
zx_status_t DriverHostContext::ScheduleRemove(const fbl::RefPtr<zx_device_t>& dev,
bool unbind_self) {
const auto& client = dev->coordinator_client;
ZX_ASSERT(client);
VLOGD(1, *dev, "schedule-remove");
auto resp = client->ScheduleRemove(unbind_self);
log_rpc_result(dev, "schedule-remove", resp.status());
return resp.status();
}
zx_status_t DriverHostContext::ScheduleUnbindChildren(const fbl::RefPtr<zx_device_t>& dev) {
const auto& client = dev->coordinator_client;
ZX_ASSERT(client);
VLOGD(1, *dev, "schedule-unbind-children");
auto resp = client->ScheduleUnbindChildren();
log_rpc_result(dev, "schedule-unbind-children", resp.status());
return resp.status();
}
zx_status_t DriverHostContext::GetTopoPath(const fbl::RefPtr<zx_device_t>& dev, char* path,
size_t max, size_t* actual) {
fbl::RefPtr<zx_device_t> remote_dev = dev;
if (dev->flags() & DEV_FLAG_INSTANCE) {
// Instances cannot be opened a second time. If dev represents an instance, return the path
// to its parent, prefixed with an '@'.
if (max < 1) {
return ZX_ERR_BUFFER_TOO_SMALL;
}
path[0] = '@';
path++;
max--;
remote_dev = dev->parent();
}
const auto& client = remote_dev->coordinator_client;
if (!client) {
return ZX_ERR_IO_REFUSED;
}
VLOGD(1, *remote_dev, "get-topo-path");
auto response = client->GetTopologicalPath_Sync();
zx_status_t status = response.status();
zx_status_t call_status = ZX_OK;
if (status == ZX_OK) {
if (response.Unwrap()->result.is_err()) {
call_status = response.Unwrap()->result.err();
} else {
auto& r = response.Unwrap()->result.response();
memcpy(path, r.path.data(), r.path.size());
*actual = r.path.size();
}
}
log_rpc_result(dev, "get-topo-path", status, call_status);
if (status != ZX_OK) {
return status;
}
if (call_status != ZX_OK) {
return status;
}
path[*actual] = 0;
*actual += 1;
// Account for the prefixed '@' we may have added above.
if (dev->flags() & DEV_FLAG_INSTANCE) {
*actual += 1;
}
return ZX_OK;
}
zx_status_t DriverHostContext::DeviceBind(const fbl::RefPtr<zx_device_t>& dev,
const char* drv_libname) {
const auto& client = dev->coordinator_client;
if (!client) {
return ZX_ERR_IO_REFUSED;
}
VLOGD(1, *dev, "bind-device");
auto driver_path = ::fidl::StringView::FromExternal(drv_libname);
auto response = client->BindDevice_Sync(std::move(driver_path));
zx_status_t status = response.status();
zx_status_t call_status = ZX_OK;
if (status == ZX_OK && response.Unwrap()->result.is_err()) {
call_status = response.Unwrap()->result.err();
}
log_rpc_result(dev, "bind-device", status, call_status);
if (status != ZX_OK) {
return status;
}
return call_status;
}
zx_status_t DriverHostContext::DeviceRunCompatibilityTests(const fbl::RefPtr<zx_device_t>& dev,
int64_t hook_wait_time) {
const auto& client = dev->coordinator_client;
if (!client) {
return ZX_ERR_IO_REFUSED;
}
VLOGD(1, *dev, "run-compatibility-test");
auto response = client->RunCompatibilityTests_Sync(hook_wait_time);
zx_status_t status = response.status();
zx_status_t call_status = ZX_OK;
if (status == ZX_OK && response.Unwrap()->result.is_err()) {
call_status = response.Unwrap()->result.err();
}
log_rpc_result(dev, "run-compatibility-test", status, call_status);
if (status != ZX_OK) {
return status;
}
return call_status;
}
zx_status_t DriverHostContext::LoadFirmware(const zx_driver_t* drv,
const fbl::RefPtr<zx_device_t>& dev, const char* path,
zx_handle_t* vmo_handle, size_t* size) {
if ((vmo_handle == nullptr) || (size == nullptr)) {
return ZX_ERR_INVALID_ARGS;
}
zx::vmo vmo;
const auto& client = dev->coordinator_client;
if (!client) {
return ZX_ERR_IO_REFUSED;
}
VLOGD(1, *dev, "load-firmware");
auto drv_libname = ::fidl::StringView::FromExternal(drv->libname());
auto str_path = ::fidl::StringView::FromExternal(path);
auto response = client->LoadFirmware_Sync(std::move(drv_libname), std::move(str_path));
zx_status_t status = response.status();
zx_status_t call_status = ZX_OK;
auto result = std::move(response.Unwrap()->result);
if (result.is_err()) {
call_status = result.err();
} else {
auto resp = std::move(result.mutable_response());
*size = resp.size;
vmo = std::move(resp.vmo);
}
log_rpc_result(dev, "load-firmware", status, call_status);
if (status != ZX_OK) {
return status;
}
*vmo_handle = vmo.release();
if (call_status == ZX_OK && *vmo_handle == ZX_HANDLE_INVALID) {
return ZX_ERR_INTERNAL;
}
return call_status;
}
void DriverHostContext::LoadFirmwareAsync(const zx_driver_t* drv,
const fbl::RefPtr<zx_device_t>& dev, const char* path,
load_firmware_callback_t callback, void* context) {
ZX_DEBUG_ASSERT(callback);
fbl::RefPtr<zx_device_t> device_ref = dev;
const auto& client = dev->coordinator_client;
if (!client) {
callback(context, ZX_ERR_IO_REFUSED, ZX_HANDLE_INVALID, 0);
return;
}
VLOGD(1, *dev, "load-firmware-async");
auto drv_libname = ::fidl::StringView::FromExternal(drv->libname());
auto str_path = ::fidl::StringView::FromExternal(path);
auto result = client->LoadFirmware(
std::move(drv_libname), std::move(str_path),
[callback, context, dev = std::move(device_ref)](
fidl::WireResponse<fuchsia_device_manager::Coordinator::LoadFirmware>* response) {
zx_status_t call_status = ZX_OK;
size_t size = 0;
zx::vmo vmo;
if (response->result.is_err()) {
call_status = response->result.err();
} else {
auto& resp = response->result.mutable_response();
size = resp.size;
vmo = std::move(resp.vmo);
}
log_rpc_result(dev, "load-firmware-async", ZX_OK, call_status);
if (call_status == ZX_OK && !vmo.is_valid()) {
call_status = ZX_ERR_INTERNAL;
}
callback(context, call_status, vmo.release(), size);
});
if (result.status() != ZX_OK) {
log_rpc_result(dev, "load-firmware-async", result.status(), ZX_OK);
callback(context, result.status(), ZX_HANDLE_INVALID, 0);
}
}
zx_status_t DriverHostContext::GetMetadata(const fbl::RefPtr<zx_device_t>& dev, uint32_t type,
void* buf, size_t buflen, size_t* actual) {
if (!buf) {
return ZX_ERR_INVALID_ARGS;
}
const auto& client = dev->coordinator_client;
if (!client) {
return ZX_ERR_IO_REFUSED;
}
VLOGD(1, *dev, "get-metadata");
auto response = client->GetMetadata_Sync(type);
zx_status_t status = response.status();
zx_status_t call_status = ZX_OK;
if (status == ZX_OK) {
if (response->result.is_response()) {
const auto& r = response.Unwrap()->result.mutable_response();
if (r.data.count() > buflen) {
return ZX_ERR_BUFFER_TOO_SMALL;
}
memcpy(buf, r.data.data(), r.data.count());
if (actual != nullptr) {
*actual = r.data.count();
}
} else {
call_status = response->result.err();
}
}
return log_rpc_result(dev, "get-metadata", status, call_status);
}
zx_status_t DriverHostContext::GetMetadataSize(const fbl::RefPtr<zx_device_t>& dev, uint32_t type,
size_t* out_length) {
const auto& client = dev->coordinator_client;
if (!client) {
return ZX_ERR_IO_REFUSED;
}
VLOGD(1, *dev, "get-metadata-size");
auto response = client->GetMetadataSize_Sync(type);
zx_status_t status = response.status();
zx_status_t call_status = ZX_OK;
if (status == ZX_OK) {
if (response->result.is_response()) {
*out_length = response->result.response().size;
} else {
call_status = response->result.err();
}
}
return log_rpc_result(dev, "get-metadata-size", status, call_status);
}
zx_status_t DriverHostContext::AddMetadata(const fbl::RefPtr<zx_device_t>& dev, uint32_t type,
const void* data, size_t length) {
if (!data && length) {
return ZX_ERR_INVALID_ARGS;
}
const auto& client = dev->coordinator_client;
if (!client) {
return ZX_ERR_IO_REFUSED;
}
VLOGD(1, *dev, "add-metadata");
auto response = client->AddMetadata_Sync(
type, ::fidl::VectorView<uint8_t>::FromExternal(
reinterpret_cast<uint8_t*>(const_cast<void*>(data)), length));
zx_status_t status = response.status();
zx_status_t call_status = ZX_OK;
if (status == ZX_OK && response->result.is_err()) {
call_status = response->result.err();
}
return log_rpc_result(dev, "add-metadata", status, call_status);
}
zx_status_t DriverHostContext::PublishMetadata(const fbl::RefPtr<zx_device_t>& dev,
const char* path, uint32_t type, const void* data,
size_t length) {
if (!path || (!data && length)) {
return ZX_ERR_INVALID_ARGS;
}
const auto& client = dev->coordinator_client;
if (!client) {
return ZX_ERR_IO_REFUSED;
}
VLOGD(1, *dev, "publish-metadata");
auto response = client->PublishMetadata_Sync(
::fidl::StringView::FromExternal(path), type,
::fidl::VectorView<uint8_t>::FromExternal(reinterpret_cast<uint8_t*>(const_cast<void*>(data)),
length));
zx_status_t status = response.status();
zx_status_t call_status = ZX_OK;
if (status == ZX_OK && response->result.is_err()) {
call_status = response->result.err();
}
return log_rpc_result(dev, "publish-metadata", status, call_status);
}
zx_status_t DriverHostContext::DeviceAddComposite(const fbl::RefPtr<zx_device_t>& dev,
const char* name,
const composite_device_desc_t* comp_desc) {
if (comp_desc == nullptr || (comp_desc->props == nullptr && comp_desc->props_count > 0) ||
comp_desc->fragments == nullptr || name == nullptr) {
return ZX_ERR_INVALID_ARGS;
}
const auto& client = dev->coordinator_client;
if (!client) {
return ZX_ERR_IO_REFUSED;
}
VLOGD(1, *dev, "create-composite");
std::vector<fuchsia_device_manager::wire::DeviceFragment> compvec = {};
for (size_t i = 0; i < comp_desc->fragments_count; i++) {
::fidl::Array<fuchsia_device_manager::wire::DeviceFragmentPart,
fuchsia_device_manager::wire::kDeviceFragmentPartsMax>
parts{};
for (uint32_t j = 0; j < comp_desc->fragments[i].parts_count; j++) {
::fidl::Array<fuchsia_device_manager::wire::BindInstruction,
fuchsia_device_manager::wire::kDeviceFragmentPartInstructionsMax>
bind_instructions{};
for (uint32_t k = 0; k < comp_desc->fragments[i].parts[j].instruction_count; k++) {
bind_instructions[k] = fuchsia_device_manager::wire::BindInstruction{
.op = comp_desc->fragments[i].parts[j].match_program[k].op,
.arg = comp_desc->fragments[i].parts[j].match_program[k].arg,
.debug = comp_desc->fragments[i].parts[j].match_program[k].debug,
};
}
auto part = fuchsia_device_manager::wire::DeviceFragmentPart{
.match_program_count = comp_desc->fragments[i].parts[j].instruction_count,
.match_program = bind_instructions,
};
parts[j] = part;
}
auto dc = fuchsia_device_manager::wire::DeviceFragment{
.name = ::fidl::StringView::FromExternal(comp_desc->fragments[i].name,
strnlen(comp_desc->fragments[i].name, 32)),
.parts_count = comp_desc->fragments[i].parts_count,
.parts = parts,
};
compvec.push_back(std::move(dc));
}
std::vector<fuchsia_device_manager::wire::DeviceMetadata> metadata = {};
for (size_t i = 0; i < comp_desc->metadata_count; i++) {
auto meta = fuchsia_device_manager::wire::DeviceMetadata{
.key = comp_desc->metadata_list[i].type,
.data = fidl::VectorView<uint8_t>::FromExternal(
reinterpret_cast<uint8_t*>(const_cast<void*>(comp_desc->metadata_list[i].data)),
comp_desc->metadata_list[i].length)};
metadata.emplace_back(std::move(meta));
}
std::vector<fuchsia_device_manager::wire::DeviceProperty> props = {};
for (size_t i = 0; i < comp_desc->props_count; i++) {
props.push_back(convert_device_prop(comp_desc->props[i]));
}
fuchsia_device_manager::wire::CompositeDeviceDescriptor comp_dev = {
.props =
::fidl::VectorView<fuchsia_device_manager::wire::DeviceProperty>::FromExternal(props),
.fragments =
::fidl::VectorView<fuchsia_device_manager::wire::DeviceFragment>::FromExternal(compvec),
.coresident_device_index = comp_desc->coresident_device_index,
.metadata =
::fidl::VectorView<fuchsia_device_manager::wire::DeviceMetadata>::FromExternal(metadata)};
static_assert(sizeof(comp_desc->props[0]) == sizeof(uint64_t));
auto response =
client->AddCompositeDevice_Sync(::fidl::StringView::FromExternal(name), std::move(comp_dev));
zx_status_t status = response.status();
zx_status_t call_status = ZX_OK;
if (status == ZX_OK && response->result.is_err()) {
call_status = response->result.err();
}
return log_rpc_result(dev, "create-composite", status, call_status);
}
|
/*
Copyright (c) 2018-2021, John Hurst
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 AS_02_ISXD.cpp
\version $Id$
\brief AS-02 library, ISXD (RDD 47) essence reader and writer implementation
*/
#include "AS_02_internal.h"
#include "AS_02.h"
#include <iostream>
#include <iomanip>
using namespace ASDCP;
using Kumu::GenRandomValue;
//------------------------------------------------------------------------------------------
static std::string AUXDATA_PACKAGE_LABEL = "File Package: RDD 47 frame wrapping of ISXD data";
static std::string PICT_DEF_LABEL = "Isochronous Stream of XML Documents Track";
//------------------------------------------------------------------------------------------
//
// hidden, internal implementation of Aux Data reader
class AS_02::ISXD::MXFReader::h__Reader : public AS_02::h__AS02Reader
{
ASDCP_NO_COPY_CONSTRUCT(h__Reader);
public:
h__Reader(const Dictionary *d) :
AS_02::h__AS02Reader(d) {}
virtual ~h__Reader() {}
Result_t OpenRead(const std::string& filename);
Result_t ReadFrame(ui32_t, ASDCP::FrameBuffer&, AESDecContext*, HMACContext*);
};
//
Result_t
AS_02::ISXD::MXFReader::h__Reader::OpenRead(const std::string& filename)
{
Result_t result = OpenMXFRead(filename);
if( KM_SUCCESS(result) )
{
InterchangeObject* tmp_iobj = 0;
m_HeaderPart.GetMDObjectByType(OBJ_TYPE_ARGS(ISXDDataEssenceDescriptor), &tmp_iobj);
if ( tmp_iobj == 0 )
{
DefaultLogSink().Error("ISXDDataEssenceDescriptor not found.\n");
}
m_HeaderPart.GetMDObjectByType(OBJ_TYPE_ARGS(ISXDDataEssenceDescriptor), &tmp_iobj);
std::list<InterchangeObject*> ObjectList;
m_HeaderPart.GetMDObjectsByType(OBJ_TYPE_ARGS(Track), ObjectList);
if ( ObjectList.empty() )
{
DefaultLogSink().Error("MXF Metadata contains no Track Sets.\n");
return RESULT_AS02_FORMAT;
}
}
return result;
}
//
Result_t
AS_02::ISXD::MXFReader::h__Reader::ReadFrame(ui32_t FrameNum, ASDCP::FrameBuffer& FrameBuf,
ASDCP::AESDecContext* Ctx, ASDCP::HMACContext* HMAC)
{
if ( ! m_File.IsOpen() )
return RESULT_INIT;
assert(m_Dict);
return ReadEKLVFrame(FrameNum, FrameBuf, m_Dict->ul(MDD_FrameWrappedISXDData), Ctx, HMAC);
}
//------------------------------------------------------------------------------------------
//
AS_02::ISXD::MXFReader::MXFReader()
{
m_Reader = new h__Reader(&DefaultCompositeDict());
}
AS_02::ISXD::MXFReader::~MXFReader()
{
}
// Warning: direct manipulation of MXF structures can interfere
// with the normal operation of the wrapper. Caveat emptor!
//
ASDCP::MXF::OP1aHeader&
AS_02::ISXD::MXFReader::OP1aHeader()
{
if ( m_Reader.empty() )
{
assert(g_OP1aHeader);
return *g_OP1aHeader;
}
return m_Reader->m_HeaderPart;
}
// Warning: direct manipulation of MXF structures can interfere
// with the normal operation of the wrapper. Caveat emptor!
//
AS_02::MXF::AS02IndexReader&
AS_02::ISXD::MXFReader::AS02IndexReader()
{
if ( m_Reader.empty() )
{
assert(g_AS02IndexReader);
return *g_AS02IndexReader;
}
return m_Reader->m_IndexAccess;
}
// Warning: direct manipulation of MXF structures can interfere
// with the normal operation of the wrapper. Caveat emptor!
//
ASDCP::MXF::RIP&
AS_02::ISXD::MXFReader::RIP()
{
if ( m_Reader.empty() )
{
assert(g_RIP);
return *g_RIP;
}
return m_Reader->m_RIP;
}
// Open the file for reading. The file must exist. Returns error if the
// operation cannot be completed.
//
Result_t
AS_02::ISXD::MXFReader::OpenRead(const std::string& filename) const
{
return m_Reader->OpenRead(filename);
}
//
Result_t
AS_02::ISXD::MXFReader::Close() const
{
if ( m_Reader && m_Reader->m_File.IsOpen() )
{
m_Reader->Close();
return RESULT_OK;
}
return RESULT_INIT;
}
//
Result_t
AS_02::ISXD::MXFReader::ReadFrame(ui32_t FrameNum, ASDCP::FrameBuffer& FrameBuf,
ASDCP::AESDecContext* Ctx, ASDCP::HMACContext* HMAC) const
{
if ( m_Reader && m_Reader->m_File.IsOpen() )
{
return m_Reader->ReadFrame(FrameNum, FrameBuf, Ctx, HMAC);
}
return RESULT_INIT;
}
//
Result_t
AS_02::ISXD::MXFReader::ReadGenericStreamPartitionPayload(const ui32_t SID, ASDCP::FrameBuffer& frame_buf)
{
if ( m_Reader && m_Reader->m_File.IsOpen() )
{
return m_Reader->ReadGenericStreamPartitionPayload(SID, frame_buf, 0, 0 /*no encryption*/);
}
return RESULT_INIT;
}
// Fill the struct with the values from the file's header.
// Returns RESULT_INIT if the file is not open.
Result_t
AS_02::ISXD::MXFReader::FillWriterInfo(WriterInfo& Info) const
{
if ( m_Reader && m_Reader->m_File.IsOpen() )
{
Info = m_Reader->m_Info;
return RESULT_OK;
}
return RESULT_INIT;
}
//
void
AS_02::ISXD::MXFReader::DumpHeaderMetadata(FILE* stream) const
{
if ( m_Reader && m_Reader->m_File.IsOpen() )
{
m_Reader->m_HeaderPart.Dump(stream);
}
}
//
void
AS_02::ISXD::MXFReader::DumpIndex(FILE* stream) const
{
if ( m_Reader && m_Reader->m_File.IsOpen() )
{
m_Reader->m_IndexAccess.Dump(stream);
}
}
//------------------------------------------------------------------------------------------
//
class AS_02::ISXD::MXFWriter::h__Writer : public AS_02::h__AS02WriterFrame
{
ASDCP_NO_COPY_CONSTRUCT(h__Writer);
h__Writer();
public:
byte_t m_EssenceUL[SMPTE_UL_LENGTH];
ISXDDataEssenceDescriptor *m_DataEssenceDescriptor;
h__Writer(const Dictionary *d) : h__AS02WriterFrame(d) {
memset(m_EssenceUL, 0, SMPTE_UL_LENGTH);
}
virtual ~h__Writer(){}
Result_t OpenWrite(const std::string& filename, const ASDCP::WriterInfo& Info,
const std::string& isxd_document_namespace,
const ASDCP::Rational& edit_rate,
const AS_02::IndexStrategy_t& IndexStrategy,
const ui32_t& PartitionSpace, const ui32_t& HeaderSize);
Result_t SetSourceStream(const std::string& label, const ASDCP::Rational& edit_rate);
Result_t WriteFrame(const ASDCP::FrameBuffer&, ASDCP::AESEncContext*, ASDCP::HMACContext*);
Result_t Finalize();
};
// Open the file for writing. The file must not exist. Returns error if
// the operation cannot be completed.
Result_t
AS_02::ISXD::MXFWriter::h__Writer::OpenWrite(const std::string& filename, const ASDCP::WriterInfo& Info,
const std::string& isxd_document_namespace,
const ASDCP::Rational& edit_rate,
const AS_02::IndexStrategy_t& IndexStrategy,
const ui32_t& PartitionSpace_sec, const ui32_t& HeaderSize)
{
m_DataEssenceDescriptor = new ISXDDataEssenceDescriptor(m_Dict);
m_DataEssenceDescriptor->DataEssenceCoding = m_Dict->ul(MDD_UTF_8_Text_DataEssenceCoding);
m_DataEssenceDescriptor->SampleRate = edit_rate;
m_DataEssenceDescriptor->NamespaceURI = isxd_document_namespace;
if ( ! m_State.Test_BEGIN() )
{
KM_RESULT_STATE_HERE();
return RESULT_STATE;
}
if ( m_IndexStrategy != AS_02::IS_FOLLOW )
{
DefaultLogSink().Error("Only strategy IS_FOLLOW is supported at this time.\n");
return Kumu::RESULT_NOTIMPL;
}
Result_t result = m_File.OpenWrite(filename);
if ( KM_SUCCESS(result) )
{
m_IndexStrategy = IndexStrategy;
m_PartitionSpace = PartitionSpace_sec; // later converted to edit units by SetSourceStream()
m_HeaderSize = HeaderSize;
m_EssenceDescriptor = m_DataEssenceDescriptor;
result = m_State.Goto_INIT();
}
return result;
}
// Automatically sets the MXF file's metadata from the first ISXD data fragment stream.
Result_t
AS_02::ISXD::MXFWriter::h__Writer::SetSourceStream(const std::string& label, const ASDCP::Rational& edit_rate)
{
assert(m_Dict);
if ( ! m_State.Test_INIT() )
{
KM_RESULT_STATE_HERE();
return RESULT_STATE;
}
memcpy(m_EssenceUL, m_Dict->ul(MDD_FrameWrappedISXDData), SMPTE_UL_LENGTH);
m_EssenceUL[SMPTE_UL_LENGTH-1] = 1; // first (and only) essence container
Result_t result = m_State.Goto_READY();
if ( KM_SUCCESS(result) )
{
result = WriteAS02Header(label, UL(m_Dict->ul(MDD_FrameWrappedISXDContainer)),
PICT_DEF_LABEL, UL(m_EssenceUL), UL(m_Dict->ul(MDD_DataDataDef)),
edit_rate);
if ( KM_SUCCESS(result) )
{
this->m_IndexWriter.SetPrimerLookup(&this->m_HeaderPart.m_Primer);
}
}
return result;
}
// Writes a frame of essence to the MXF file. If the optional AESEncContext
// argument is present, the essence is encrypted prior to writing.
// Fails if the file is not open, is finalized, or an operating system
// error occurs.
//
Result_t
AS_02::ISXD::MXFWriter::h__Writer::WriteFrame(const ASDCP::FrameBuffer& FrameBuf,
AESEncContext* Ctx, HMACContext* HMAC)
{
if ( FrameBuf.Size() == 0 )
{
DefaultLogSink().Error("The frame buffer size is zero.\n");
return RESULT_PARAM;
}
Result_t result = RESULT_OK;
if ( m_State.Test_READY() )
{
result = m_State.Goto_RUNNING(); // first time through
}
if ( KM_SUCCESS(result) )
{
result = WriteEKLVPacket(FrameBuf, m_EssenceUL, MXF_BER_LENGTH, Ctx, HMAC);
m_FramesWritten++;
}
return result;
}
// Closes the MXF file, writing the index and other closing information.
//
Result_t
AS_02::ISXD::MXFWriter::h__Writer::Finalize()
{
if ( ! m_State.Test_RUNNING() )
{
KM_RESULT_STATE_HERE();
return RESULT_STATE;
}
Result_t result = m_State.Goto_FINAL();
if ( KM_SUCCESS(result) )
{
result = WriteAS02Footer();
}
return result;
}
//------------------------------------------------------------------------------------------
AS_02::ISXD::MXFWriter::MXFWriter()
{
}
AS_02::ISXD::MXFWriter::~MXFWriter()
{
}
// Warning: direct manipulation of MXF structures can interfere
// with the normal operation of the wrapper. Caveat emptor!
//
ASDCP::MXF::OP1aHeader&
AS_02::ISXD::MXFWriter::OP1aHeader()
{
if ( m_Writer.empty() )
{
assert(g_OP1aHeader);
return *g_OP1aHeader;
}
return m_Writer->m_HeaderPart;
}
// Warning: direct manipulation of MXF structures can interfere
// with the normal operation of the wrapper. Caveat emptor!
//
ASDCP::MXF::RIP&
AS_02::ISXD::MXFWriter::RIP()
{
if ( m_Writer.empty() )
{
assert(g_RIP);
return *g_RIP;
}
return m_Writer->m_RIP;
}
// Open the file for writing. The file must not exist. Returns error if
// the operation cannot be completed.
Result_t
AS_02::ISXD::MXFWriter::OpenWrite(const std::string& filename, const ASDCP::WriterInfo& Info,
const std::string& isxd_document_namespace,
const ASDCP::Rational& edit_rate, const ui32_t& header_size,
const IndexStrategy_t& strategy, const ui32_t& partition_space)
{
m_Writer = new AS_02::ISXD::MXFWriter::h__Writer(&DefaultSMPTEDict());
m_Writer->m_Info = Info;
Result_t result = m_Writer->OpenWrite(filename, Info, isxd_document_namespace, edit_rate,
strategy, partition_space, header_size);
if ( KM_SUCCESS(result) )
result = m_Writer->SetSourceStream(AUXDATA_PACKAGE_LABEL, edit_rate);
if ( KM_FAILURE(result) )
m_Writer.release();
return result;
}
// Writes a frame of essence to the MXF file. If the optional AESEncContext
// argument is present, the essence is encrypted prior to writing.
// Fails if the file is not open, is finalized, or an operating system
// error occurs.
Result_t
AS_02::ISXD::MXFWriter::WriteFrame(const ASDCP::FrameBuffer& FrameBuf, AESEncContext* Ctx, HMACContext* HMAC)
{
if ( m_Writer.empty() )
return RESULT_INIT;
return m_Writer->WriteFrame(FrameBuf, Ctx, HMAC);
}
Result_t
AS_02::ISXD::MXFWriter::AddDmsGenericPartUtf8Text(const ASDCP::FrameBuffer& FrameBuf, ASDCP::AESEncContext* Ctx,
ASDCP::HMACContext* HMAC)
{
if ( m_Writer.empty() )
return RESULT_INIT;
m_Writer->FlushIndexPartition();
return m_Writer->AddDmsGenericPartUtf8Text(FrameBuf, Ctx, HMAC);
}
// Closes the MXF file, writing the index and other closing information.
Result_t
AS_02::ISXD::MXFWriter::Finalize()
{
if ( m_Writer.empty() )
return RESULT_INIT;
return m_Writer->Finalize();
}
//
// end AS_02_ISXD.cpp
//
|
// Copyright (c) 2019 PaddlePaddle 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 <arm_neon.h>
#include "lite/backends/arm/math/conv_block_utils.h"
#include "lite/backends/arm/math/conv_depthwise.h"
#include "lite/backends/arm/math/conv_impl.h"
#include "lite/core/context.h"
#include "lite/core/parallel_defines.h"
#include "lite/operators/op_params.h"
#ifdef ARM_WITH_OMP
#include <omp.h>
#endif
namespace paddle {
namespace lite {
namespace arm {
namespace math {
#define ROUNDUP(a, b) ((((a) + (b)-1) / (b)) * (b))
// clang-format off
#ifdef __aarch64__
#define INIT_S1 \
"PRFM PLDL1KEEP, [%[din_ptr0]] \n" \
"PRFM PLDL1KEEP, [%[din_ptr1]] \n" \
"PRFM PLDL1KEEP, [%[din_ptr2]] \n" \
"PRFM PLDL1KEEP, [%[din_ptr3]] \n" \
"movi v21.4s, #0x0\n" \
"ld1 {v0.8b, v1.8b}, [%[din_ptr0]]\n"\
"ld1 {v2.8b, v3.8b}, [%[din_ptr1]]\n"\
"movi v12.4s, #0x0\n" \
"movi v13.4s, #0x0\n" \
"movi v14.4s, #0x0\n" \
"movi v15.4s, #0x0\n"
#define LEFT_COMPUTE_S1 \
/* r0 */ \
"ext v4.8b, v21.8b, v0.8b, #7 \n" \
"ext v6.8b, v21.8b, v2.8b, #7 \n" \
"smull v16.8h, v0.8b, %[v1].8b \n" \
"smull v18.8h, v2.8b, %[v1].8b \n" \
"ext v5.8b, v0.8b, v1.8b, #1 \n" \
"ext v7.8b, v2.8b, v3.8b, #1 \n" \
"add %[din_ptr0], %[din_ptr0], #7 \n" \
"add %[din_ptr1], %[din_ptr1], #7 \n" \
"smlal v16.8h, v4.8b, %[v0].8b \n" \
"smlal v18.8h, v6.8b, %[v0].8b \n" \
"ld1 {v0.8b, v1.8b}, [%[din_ptr2]]\n" \
"smull v17.8h, v5.8b, %[v2].8b \n" \
"smull v19.8h, v7.8b, %[v2].8b \n" \
"saddw v12.4s, v12.4s, v16.4h \n" \
"saddw2 v13.4s, v13.4s, v16.8h \n" \
"saddw v14.4s, v14.4s, v18.4h \n" \
"saddw2 v15.4s, v15.4s, v18.8h \n" \
/* r1 */ \
"ext v4.8b, v21.8b, v0.8b, #7 \n" \
"ext v5.8b, v0.8b, v1.8b, #1 \n" \
"smlal v17.8h, v2.8b, %[v4].8b \n" \
"smlal v19.8h, v0.8b, %[v4].8b \n" \
"smull v16.8h, v6.8b, %[v3].8b \n" \
"smull v18.8h, v4.8b, %[v3].8b \n" \
"ld1 {v2.8b, v3.8b}, [%[din_ptr3]]\n" \
"saddw v12.4s, v12.4s, v17.4h \n" \
"saddw2 v13.4s, v13.4s, v17.8h \n" \
"saddw v14.4s, v14.4s, v19.4h \n" \
"saddw2 v15.4s, v15.4s, v19.8h \n" \
"smlal v16.8h, v7.8b, %[v5].8b \n" \
"smlal v18.8h, v5.8b, %[v5].8b \n" \
/* r2 */ \
"ext v6.8b, v21.8b, v2.8b, #7 \n" \
"ext v7.8b, v2.8b, v3.8b, #1 \n" \
"smull v17.8h, v0.8b, %[v7].8b \n" \
"smull v19.8h, v2.8b, %[v7].8b \n" \
"saddw v12.4s, v12.4s, v16.4h \n" \
"saddw2 v13.4s, v13.4s, v16.8h \n" \
"saddw v14.4s, v14.4s, v18.4h \n" \
"saddw2 v15.4s, v15.4s, v18.8h \n" \
"smull v16.8h, v4.8b, %[v6].8b \n" \
"smull v18.8h, v6.8b, %[v6].8b \n" \
"smlal v17.8h, v5.8b, %[v8].8b \n" \
"smlal v19.8h, v7.8b, %[v8].8b \n" \
"dup v8.4s, %w[bias] \n" \
"dup v9.4s, %w[bias] \n" \
"dup v10.4s, %w[bias] \n" \
"dup v11.4s, %w[bias] \n" \
"saddw v12.4s, v12.4s, v16.4h \n" \
"saddw2 v13.4s, v13.4s, v16.8h \n" \
"saddw v14.4s, v14.4s, v18.4h \n" \
"saddw2 v15.4s, v15.4s, v18.8h \n" \
"add %[din_ptr2], %[din_ptr2], #7 \n" \
"add %[din_ptr3], %[din_ptr3], #7 \n" \
"saddw v12.4s, v12.4s, v17.4h \n" \
"saddw2 v13.4s, v13.4s, v17.8h \n" \
"saddw v14.4s, v14.4s, v19.4h \n" \
"saddw2 v15.4s, v15.4s, v19.8h \n" \
/* int32 -> fp32 */ \
"scvtf v12.4s, v12.4s \n" \
"scvtf v13.4s, v13.4s \n" \
"scvtf v14.4s, v14.4s \n" \
"scvtf v15.4s, v15.4s \n" \
"fmla v8.4s, v12.4s, %[vscale].4s\n" \
"fmla v9.4s, v13.4s, %[vscale].4s\n" \
"fmla v10.4s, v14.4s, %[vscale].4s\n" \
"fmla v11.4s, v15.4s, %[vscale].4s\n"
#define RELU \
"fmax v8.4s, v8.4s, v21.4s \n" \
"fmax v9.4s, v9.4s, v21.4s \n" \
"fmax v10.4s, v10.4s, v21.4s \n" \
"fmax v11.4s, v11.4s, v21.4s \n"
#define RELU6 \
"ldr q4, [%[vmax], #16] \n" \
"fmax v8.4s, v8.4s, v21.4s \n" \
"fmax v9.4s, v9.4s, v21.4s \n" \
"fmax v10.4s, v10.4s, v21.4s \n" \
"fmax v11.4s, v11.4s, v21.4s \n" \
"fmin v8.4s, v8.4s, v4.4s \n" \
"fmin v9.4s, v9.4s, v4.4s \n" \
"fmin v10.4s, v10.4s, v4.4s \n" \
"fmin v11.4s, v11.4s, v4.4s \n"
#define RESULT_INT8_MAX \
"ld1 {v12.4s}, [%[vmax]] \n" \
"fcmge v4.4s, v8.4s, v12.4s \n" \
"fcmge v5.4s, v9.4s, v12.4s \n" \
"fcmge v6.4s, v10.4s, v12.4s \n" \
"fcmge v7.4s, v11.4s, v12.4s \n" \
"bif v8.16b, v12.16b, v4.16b \n" \
"bif v9.16b, v12.16b, v5.16b \n" \
"bif v10.16b, v12.16b, v6.16b \n" \
"bif v11.16b, v12.16b, v7.16b \n"
#define RESULT_INT8 \
/* fp32 -> int32 */ \
"fcvtas v8.4s, v8.4s \n" \
"fcvtas v9.4s, v9.4s \n" \
"fcvtas v10.4s, v10.4s \n" \
"fcvtas v11.4s, v11.4s \n" \
/* int32 -> int16 */ \
"sqxtn v12.4h, v8.4s \n" \
"sqxtn2 v12.8h, v9.4s \n" \
"sqxtn v13.4h, v10.4s \n" \
"sqxtn2 v13.8h, v11.4s \n" \
/* int16 -> int8 */ \
"sqxtn v8.8b, v12.8h \n" \
"sqxtn v9.8b, v13.8h \n"
#define LEFT_STORE_FLOAT \
"stp q8, q9, [%[dout_ptr0]], #32 \n" \
"stp q10, q11, [%[dout_ptr1]], #32 \n"
#define LEFT_STORE_INT8 \
"st1 {v8.8b}, [%[dout_ptr0]], #8 \n" \
"st1 {v9.8b}, [%[dout_ptr1]], #8 \n"
#define MID_COMPUTE_S1 \
"cmp %[cnt], #1 \n" \
"ld1 {v0.8b, v1.8b}, [%[din_ptr0]]\n" \
"ld1 {v2.8b, v3.8b}, [%[din_ptr1]]\n" \
"movi v12.4s, #0x0\n" \
"movi v13.4s, #0x0\n" \
"movi v14.4s, #0x0\n" \
"movi v15.4s, #0x0\n" \
"blt 1f \n" \
"2: \n" \
/* r0 */ \
"ext v4.8b, v0.8b, v1.8b, #1 \n" \
"ext v6.8b, v2.8b, v3.8b, #1 \n" \
"smull v16.8h, v0.8b, %[v0].8b \n" \
"smull v18.8h, v2.8b, %[v0].8b \n" \
"ext v5.8b, v0.8b, v1.8b, #2 \n" \
"ext v7.8b, v2.8b, v3.8b, #2 \n" \
"smull v17.8h, v4.8b, %[v1].8b \n" \
"smull v19.8h, v6.8b, %[v1].8b \n" \
"ld1 {v0.8b, v1.8b}, [%[din_ptr2]]\n" \
"add %[din_ptr0], %[din_ptr0], #8\n" \
"add %[din_ptr1], %[din_ptr1], #8\n" \
"smlal v16.8h, v5.8b, %[v2].8b \n" \
"smlal v18.8h, v7.8b, %[v2].8b \n" \
/* r1 */ \
"ext v4.8b, v0.8b, v1.8b, #1 \n" \
"ext v5.8b, v0.8b, v1.8b, #2 \n" \
"smlal v17.8h, v2.8b, %[v3].8b \n" \
"smlal v19.8h, v0.8b, %[v3].8b \n" \
"saddw v12.4s, v12.4s, v16.4h \n" \
"saddw2 v13.4s, v13.4s, v16.8h \n" \
"saddw v14.4s, v14.4s, v18.4h \n" \
"saddw2 v15.4s, v15.4s, v18.8h \n" \
"ld1 {v2.8b, v3.8b}, [%[din_ptr3]]\n" \
"smull v16.8h, v6.8b, %[v4].8b \n" \
"smull v18.8h, v4.8b, %[v4].8b \n" \
"saddw v12.4s, v12.4s, v17.4h \n" \
"saddw2 v13.4s, v13.4s, v17.8h \n" \
"saddw v14.4s, v14.4s, v19.4h \n" \
"saddw2 v15.4s, v15.4s, v19.8h \n" \
"add %[din_ptr2], %[din_ptr2], #8\n" \
"add %[din_ptr3], %[din_ptr3], #8\n" \
"smull v17.8h, v7.8b, %[v5].8b \n" \
"smull v19.8h, v5.8b, %[v5].8b \n" \
/* r2 */ \
"ext v6.8b, v2.8b, v3.8b, #1 \n" \
"ext v7.8b, v2.8b, v3.8b, #2 \n" \
"smlal v16.8h, v0.8b, %[v6].8b \n" \
"smlal v18.8h, v2.8b, %[v6].8b \n" \
"ld1 {v0.8b, v1.8b}, [%[din_ptr0]]\n" \
"ld1 {v2.8b, v3.8b}, [%[din_ptr1]]\n" \
"smlal v17.8h, v4.8b, %[v7].8b \n" \
"smlal v19.8h, v6.8b, %[v7].8b \n" \
"saddw v12.4s, v12.4s, v16.4h \n" \
"saddw2 v13.4s, v13.4s, v16.8h \n" \
"saddw v14.4s, v14.4s, v18.4h \n" \
"saddw2 v15.4s, v15.4s, v18.8h \n" \
"smull v16.8h, v5.8b, %[v8].8b \n" \
"smull v18.8h, v7.8b, %[v8].8b \n" \
"saddw v12.4s, v12.4s, v17.4h \n" \
"saddw2 v13.4s, v13.4s, v17.8h \n" \
"saddw v14.4s, v14.4s, v19.4h \n" \
"saddw2 v15.4s, v15.4s, v19.8h \n" \
"dup v8.4s, %w[bias] \n" \
"dup v9.4s, %w[bias] \n" \
"dup v10.4s, %w[bias] \n" \
"dup v11.4s, %w[bias] \n" \
"saddw v12.4s, v12.4s, v16.4h \n" \
"saddw2 v13.4s, v13.4s, v16.8h \n" \
"saddw v14.4s, v14.4s, v18.4h \n" \
"saddw2 v15.4s, v15.4s, v18.8h \n" \
/* int32 -> fp32 */ \
"scvtf v12.4s, v12.4s \n" \
"scvtf v13.4s, v13.4s \n" \
"scvtf v14.4s, v14.4s \n" \
"scvtf v15.4s, v15.4s \n" \
"subs %w[cnt], %w[cnt], #1 \n" \
"fmla v8.4s, v12.4s, %[vscale].4s\n" \
"fmla v9.4s, v13.4s, %[vscale].4s\n" \
"fmla v10.4s, v14.4s, %[vscale].4s\n" \
"fmla v11.4s, v15.4s, %[vscale].4s\n"
#define MID_STORE_FLOAT \
"movi v12.4s, #0x0\n" \
"movi v13.4s, #0x0\n" \
"movi v14.4s, #0x0\n" \
"movi v15.4s, #0x0\n" \
"stp q8, q9, [%[dout_ptr0]], #32 \n" \
"stp q10, q11, [%[dout_ptr1]], #32 \n" \
"bne 2b\n"
#define MID_STORE_INT8 \
"movi v12.4s, #0x0\n" \
"movi v13.4s, #0x0\n" \
"movi v14.4s, #0x0\n" \
"movi v15.4s, #0x0\n" \
"st1 {v8.8b}, [%[dout_ptr0]], #8 \n"\
"st1 {v9.8b}, [%[dout_ptr1]], #8 \n"\
"bne 2b\n"
#define RIGHT_COMPUTE_S1 \
"1: \n" \
"sub %[din_ptr0], %[din_ptr0], %[right_pad_num_in]\n"\
"sub %[din_ptr1], %[din_ptr1], %[right_pad_num_in]\n"\
"sub %[din_ptr2], %[din_ptr2], %[right_pad_num_in]\n"\
"sub %[din_ptr3], %[din_ptr3], %[right_pad_num_in]\n"\
"ld1 {v0.8b, v1.8b}, [%[din_ptr0]]\n" \
"ld1 {v2.8b, v3.8b}, [%[din_ptr1]]\n" \
"ld1 {v9.8b}, [%[vmask]]\n" \
"sub %[dout_ptr0], %[dout_ptr0], %[right_pad_num_out]\n"\
"sub %[dout_ptr1], %[dout_ptr1], %[right_pad_num_out]\n"\
"bif v1.8b, v21.8b, v9.8b \n" \
"bif v3.8b, v21.8b, v9.8b \n" \
/* r0 */ \
"ext v4.8b, v0.8b, v1.8b, #1 \n" \
"ext v6.8b, v2.8b, v3.8b, #1 \n" \
"smull v16.8h, v0.8b, %[v0].8b \n" \
"smull v18.8h, v2.8b, %[v0].8b \n" \
"ext v5.8b, v0.8b, v1.8b, #2 \n" \
"ext v7.8b, v2.8b, v3.8b, #2 \n" \
"ld1 {v0.8b, v1.8b}, [%[din_ptr2]]\n" \
"smull v17.8h, v4.8b, %[v1].8b \n" \
"smull v19.8h, v6.8b, %[v1].8b \n" \
"smlal v16.8h, v5.8b, %[v2].8b \n" \
"smlal v18.8h, v7.8b, %[v2].8b \n" \
"bif v1.8b, v21.8b, v9.8b \n" \
/* r1 */ \
"ext v4.8b, v0.8b, v1.8b, #1 \n" \
"ext v5.8b, v0.8b, v1.8b, #2 \n" \
"smlal v17.8h, v2.8b, %[v3].8b \n" \
"smlal v19.8h, v0.8b, %[v3].8b \n" \
"saddw v12.4s, v12.4s, v16.4h \n" \
"saddw2 v13.4s, v13.4s, v16.8h \n" \
"saddw v14.4s, v14.4s, v18.4h \n" \
"saddw2 v15.4s, v15.4s, v18.8h \n" \
"ld1 {v2.8b, v3.8b}, [%[din_ptr3]]\n" \
"smull v16.8h, v6.8b, %[v4].8b \n" \
"smull v18.8h, v4.8b, %[v4].8b \n" \
"saddw v12.4s, v12.4s, v17.4h \n" \
"saddw2 v13.4s, v13.4s, v17.8h \n" \
"saddw v14.4s, v14.4s, v19.4h \n" \
"saddw2 v15.4s, v15.4s, v19.8h \n" \
"bif v3.8b, v21.8b, v9.8b \n" \
"smull v17.8h, v7.8b, %[v5].8b \n" \
"smull v19.8h, v5.8b, %[v5].8b \n" \
/* r2 */ \
"ext v6.8b, v2.8b, v3.8b, #1 \n" \
"ext v7.8b, v2.8b, v3.8b, #2 \n" \
"smlal v16.8h, v0.8b, %[v6].8b \n" \
"smlal v18.8h, v2.8b, %[v6].8b \n" \
"smlal v17.8h, v4.8b, %[v7].8b \n" \
"smlal v19.8h, v6.8b, %[v7].8b \n" \
"saddw v12.4s, v12.4s, v16.4h \n" \
"saddw2 v13.4s, v13.4s, v16.8h \n" \
"saddw v14.4s, v14.4s, v18.4h \n" \
"saddw2 v15.4s, v15.4s, v18.8h \n" \
"smull v16.8h, v5.8b, %[v8].8b \n" \
"smull v18.8h, v7.8b, %[v8].8b \n" \
"saddw v12.4s, v12.4s, v17.4h \n" \
"saddw2 v13.4s, v13.4s, v17.8h \n" \
"saddw v14.4s, v14.4s, v19.4h \n" \
"saddw2 v15.4s, v15.4s, v19.8h \n" \
"dup v8.4s, %w[bias] \n" \
"dup v9.4s, %w[bias] \n" \
"dup v10.4s, %w[bias] \n" \
"dup v11.4s, %w[bias] \n" \
"saddw v12.4s, v12.4s, v16.4h \n" \
"saddw2 v13.4s, v13.4s, v16.8h \n" \
"saddw v14.4s, v14.4s, v18.4h \n" \
"saddw2 v15.4s, v15.4s, v18.8h \n" \
/* int32 -> fp32 */ \
"scvtf v12.4s, v12.4s \n" \
"scvtf v13.4s, v13.4s \n" \
"scvtf v14.4s, v14.4s \n" \
"scvtf v15.4s, v15.4s \n" \
"fmla v8.4s, v12.4s, %[vscale].4s\n" \
"fmla v9.4s, v13.4s, %[vscale].4s\n" \
"fmla v10.4s, v14.4s, %[vscale].4s\n" \
"fmla v11.4s, v15.4s, %[vscale].4s\n"
#else
#define INIT_S1 \
"vld1.8 {d0-d1}, [%[wei_ptr]] \n" \
"pld [%[din_ptr0]] \n" \
"pld [%[din_ptr1]] \n" \
"pld [%[din_ptr2]] \n" \
"pld [%[din_ptr3]] \n" \
"vdup.s8 d2, d0[0] \n" \
"vdup.s8 d3, d0[1] \n" \
"vdup.s8 d4, d0[2] \n" \
"vld1.8 {d12-d13}, [%[din_ptr0]] \n" \
"vmov.u32 d11, #0 \n" \
"vmov.u32 q12, #0 \n" \
"vld1.8 {d16-d17}, [%[din_ptr1]] \n" \
"vmov.u32 q13, #0 \n" \
"vmov.u32 q14, #0 \n" \
"vmov.u32 q15, #0 \n"
#define LEFT_COMPUTE_S1 \
/* r0 */ \
"vmull.s8 q10, d12, d3 \n" \
"vmull.s8 q11, d16, d3 \n" \
"vext.8 d14, d11, d12, #7 \n" \
"vext.8 d18, d11, d16, #7 \n" \
"vext.8 d15, d12, d13, #1 \n" \
"vext.8 d19, d16, d17, #1 \n" \
"vmlal.s8 q10, d14, d2 \n" \
"vmlal.s8 q11, d18, d2 \n" \
"vdup.s8 d5, d0[3] \n" \
"vdup.s8 d6, d0[4] \n" \
"vdup.s8 d7, d0[5] \n" \
"vld1.8 {d12-d13}, [%[din_ptr2]] \n" \
"vaddw.s16 q12, q12, d20 \n" \
"vaddw.s16 q13, q13, d21 \n" \
"vaddw.s16 q14, q14, d22 \n" \
"vaddw.s16 q15, q15, d23 \n" \
"vmull.s8 q10, d15, d4 \n" \
"vmull.s8 q11, d19, d4 \n" \
"add %[din_ptr0], #7 \n" \
/* r1 */ \
"vext.8 d14, d11, d12, #7 \n" \
"vext.8 d15, d12, d13, #1 \n" \
"vmlal.s8 q10, d16, d6 \n" \
"vmlal.s8 q11, d12, d6 \n" \
"add %[din_ptr1], #7 \n" \
"vld1.8 {d16-d17}, [%[din_ptr3]] \n" \
"vaddw.s16 q12, q12, d20 \n" \
"vaddw.s16 q13, q13, d21 \n" \
"vaddw.s16 q14, q14, d22 \n" \
"vaddw.s16 q15, q15, d23 \n" \
"vmull.s8 q10, d18, d5 \n" \
"vmull.s8 q11, d14, d5 \n" \
"vdup.s8 d8, d0[6] \n" \
"vdup.s8 d9, d0[7] \n" \
"vdup.s8 d10, d1[0] \n" \
"vmlal.s8 q10, d19, d7 \n" \
"vmlal.s8 q11, d15, d7 \n" \
/* r2 */ \
"vext.8 d18, d11, d16, #7 \n" \
"vext.8 d19, d16, d17, #1 \n" \
"vaddw.s16 q12, q12, d20 \n" \
"vaddw.s16 q13, q13, d21 \n" \
"vaddw.s16 q14, q14, d22 \n" \
"vaddw.s16 q15, q15, d23 \n" \
"vmull.s8 q10, d12, d9 \n" \
"vmull.s8 q11, d16, d9 \n" \
"vmull.s8 q6, d14, d8 \n" \
"vmull.s8 q8, d18, d8 \n" \
"add %[din_ptr2], #7 \n" \
"add %[din_ptr3], #7 \n" \
"vmlal.s8 q10, d15, d10 \n" \
"vmlal.s8 q11, d19, d10 \n" \
"vaddw.s16 q12, q12, d12 \n" \
"vaddw.s16 q13, q13, d13 \n" \
"vaddw.s16 q14, q14, d16 \n" \
"vaddw.s16 q15, q15, d17 \n" \
"vld1.32 {d14-d15}, [%[vmax]] \n" \
"vdup.32 q8, %[bias] \n" \
"vdup.32 q9, %[bias] \n" \
"vaddw.s16 q12, q12, d20 \n" \
"vaddw.s16 q13, q13, d21 \n" \
"vaddw.s16 q14, q14, d22 \n" \
"vaddw.s16 q15, q15, d23 \n" \
"vdup.32 q10, %[bias] \n" \
"vdup.32 q11, %[bias] \n" \
"vcvt.f32.s32 q12, q12 \n" \
"vcvt.f32.s32 q13, q13 \n" \
"vcvt.f32.s32 q14, q14 \n" \
"vcvt.f32.s32 q15, q15 \n" \
"vmov.u32 q6, #0 \n" \
"vmla.f32 q8, q12, q7 \n" \
"vmla.f32 q9, q13, q7 \n" \
"vmla.f32 q10, q14, q7 \n" \
"vmla.f32 q11, q15, q7 \n"
#define RELU6 \
"vldr d14, [%[vmax], #32] \n" \
"vldr d15, [%[vmax], #40] \n" \
"vmax.f32 q8, q8, q6 \n" \
"vmax.f32 q9, q9, q6 \n" \
"vmax.f32 q10, q10, q6 \n" \
"vmax.f32 q11, q11, q6 \n" \
"vmin.f32 q8, q8, q7 \n" \
"vmin.f32 q9, q9, q7 \n" \
"vmin.f32 q10, q10, q7 \n" \
"vmin.f32 q11, q11, q7 \n"
#define RELU \
"vmax.f32 q8, q8, q6 \n" \
"vmax.f32 q9, q9, q6 \n" \
"vmax.f32 q10, q10, q6 \n" \
"vmax.f32 q11, q11, q6 \n"
#define RESULT_INT8 \
"vmov.f32 q12, #-0.5 \n" \
"vmov.f32 q13, #0.5 \n" \
"vcgt.f32 q14, q8, q6 \n" \
"vcgt.f32 q15, q9, q6 \n" \
"vldr d14, [%[vmax], #16] \n" \
"vldr d15, [%[vmax], #24] \n" \
"vbif.f32 q13, q12, q14 \n" \
"vcgt.f32 q14, q10, q6 \n" \
"vadd.f32 q8, q8, q13 \n" \
"vmov.f32 q13, #0.5 \n" \
"vbif.f32 q13, q12, q15 \n" \
"vcgt.f32 q15, q11, q6 \n" \
"vadd.f32 q9, q9, q13 \n" \
"vmov.f32 q13, #0.5 \n" \
"vbif.f32 q13, q12, q14 \n" \
"vadd.f32 q10, q10, q13 \n" \
"vmov.f32 q13, #0.5 \n" \
"vbif.f32 q13, q12, q15 \n" \
"vadd.f32 q11, q11, q13 \n" \
/* >= -127 */ \
"vcgt.f32 q12, q8, q7 \n" \
"vcgt.f32 q13, q9, q7 \n" \
"vcgt.f32 q14, q10, q7 \n" \
"vcgt.f32 q15, q11, q7 \n" \
"vbif.f32 q8, q7, q12 \n" \
"vbif.f32 q9, q7, q13 \n" \
"vbif.f32 q10, q7, q14 \n" \
"vbif.f32 q11, q7, q15 \n" \
/* f32 -> int32 */ \
"vcvt.s32.f32 q12, q8 \n" \
"vcvt.s32.f32 q13, q9 \n" \
"vcvt.s32.f32 q14, q10 \n" \
"vcvt.s32.f32 q15, q11 \n" \
/* int32 -> int16 */ \
"vqmovn.s32 d16, q12 \n" \
"vqmovn.s32 d17, q13 \n" \
"vqmovn.s32 d18, q14 \n" \
"vqmovn.s32 d19, q15 \n" \
/* int16 -> int8 */ \
"vqmovn.s16 d20, q8 \n" \
"vqmovn.s16 d21, q9 \n"
#define LEFT_STORE_FLOAT \
"vst1.32 {d16-d19}, [%[dout_ptr0]]!\n" \
"vst1.32 {d20-d23}, [%[dout_ptr1]]!\n"
#define LEFT_STORE_INT8 \
"vst1.32 {d20}, [%[dout_ptr0]]!\n" \
"vst1.32 {d21}, [%[dout_ptr1]]!\n"
#define INIT_P0 \
"vld1.8 {d0-d1}, [%[wei_ptr]] \n" \
"pld [%[din_ptr0]] \n" \
"pld [%[din_ptr1]] \n" \
"pld [%[din_ptr2]] \n" \
"pld [%[din_ptr3]] \n" \
"vdup.s8 d2, d0[0] \n" \
"vdup.s8 d3, d0[1] \n" \
"vdup.s8 d4, d0[2] \n" \
"vdup.s8 d5, d0[3] \n" \
"vdup.s8 d6, d0[4] \n" \
"vdup.s8 d7, d0[5] \n" \
"vdup.s8 d8, d0[6] \n" \
"vdup.s8 d9, d0[7] \n" \
"vdup.s8 d10, d1[0] \n" \
"vmov.u32 d11, #0 \n"
#define MID_COMPUTE_S1 \
"cmp %[cnt], #1 \n" \
"vld1.8 {d12-d13}, [%[din_ptr0]] \n" \
"vld1.8 {d16-d17}, [%[din_ptr1]] \n" \
"vmov.u32 q12, #0 \n" \
"vmov.u32 q13, #0 \n" \
"vmov.u32 q14, #0 \n" \
"vmov.u32 q15, #0 \n" \
"blt 1f \n" \
"2: \n" \
/* r0 */ \
"vmull.s8 q10, d12, d2 \n" \
"vmull.s8 q11, d16, d2 \n" \
"vext.8 d14, d12, d13, #1 \n" \
"vext.8 d18, d16, d17, #1 \n" \
"vext.8 d15, d12, d13, #2 \n" \
"vext.8 d19, d16, d17, #2 \n" \
"vmlal.s8 q10, d14, d3 \n" \
"vmlal.s8 q11, d18, d3 \n" \
"vld1.8 {d12-d13}, [%[din_ptr2]] \n" \
"add %[din_ptr0], #8 \n" \
"vaddw.s16 q12, q12, d20 \n" \
"vaddw.s16 q13, q13, d21 \n" \
"vaddw.s16 q14, q14, d22 \n" \
"vaddw.s16 q15, q15, d23 \n" \
"vmull.s8 q10, d15, d4 \n" \
"vmull.s8 q11, d19, d4 \n" \
/* r1 */ \
"vext.8 d14, d12, d13, #1 \n" \
"vext.8 d15, d12, d13, #2 \n" \
"vmlal.s8 q10, d16, d5 \n" \
"vmlal.s8 q11, d12, d5 \n" \
"add %[din_ptr1], #8 \n" \
"vld1.8 {d16-d17}, [%[din_ptr3]] \n" \
"vaddw.s16 q12, q12, d20 \n" \
"vaddw.s16 q13, q13, d21 \n" \
"vaddw.s16 q14, q14, d22 \n" \
"vaddw.s16 q15, q15, d23 \n" \
"vmull.s8 q10, d18, d6 \n" \
"vmull.s8 q11, d14, d6 \n" \
"add %[din_ptr2], #8 \n" \
"add %[din_ptr3], #8 \n" \
"vmlal.s8 q10, d19, d7 \n" \
"vmlal.s8 q11, d15, d7 \n" \
/* r2 */ \
"vext.8 d18, d16, d17, #1 \n" \
"vext.8 d19, d16, d17, #2 \n" \
"vaddw.s16 q12, q12, d20 \n" \
"vaddw.s16 q13, q13, d21 \n" \
"vaddw.s16 q14, q14, d22 \n" \
"vaddw.s16 q15, q15, d23 \n" \
"vmull.s8 q10, d12, d8 \n" \
"vmull.s8 q11, d16, d8 \n" \
"vmull.s8 q6, d14, d9 \n" \
"vmull.s8 q8, d18, d9 \n" \
"vmlal.s8 q10, d15, d10 \n" \
"vmlal.s8 q11, d19, d10 \n" \
"vaddw.s16 q12, q12, d12 \n" \
"vaddw.s16 q13, q13, d13 \n" \
"vaddw.s16 q14, q14, d16 \n" \
"vaddw.s16 q15, q15, d17 \n" \
"vld1.32 {d14-d15}, [%[vmax]] \n" \
"vdup.32 q8, %[bias] \n" \
"vdup.32 q9, %[bias] \n" \
"vaddw.s16 q12, q12, d20 \n" \
"vaddw.s16 q13, q13, d21 \n" \
"vaddw.s16 q14, q14, d22 \n" \
"vaddw.s16 q15, q15, d23 \n" \
"vdup.32 q10, %[bias] \n" \
"vdup.32 q11, %[bias] \n" \
"vcvt.f32.s32 q12, q12 \n" \
"vcvt.f32.s32 q13, q13 \n" \
"vcvt.f32.s32 q14, q14 \n" \
"vcvt.f32.s32 q15, q15 \n" \
"vmov.u32 q6, #0 \n" \
"subs %[cnt], #1 \n" \
"vmla.f32 q8, q12, q7 \n" \
"vmla.f32 q9, q13, q7 \n" \
"vmla.f32 q10, q14, q7 \n" \
"vmla.f32 q11, q15, q7 \n"
#define MID_STORE_FLOAT \
"vld1.8 {d12-d13}, [%[din_ptr0]] \n" \
"vmov.u32 q12, #0 \n" \
"vmov.u32 q13, #0 \n" \
"vst1.32 {d16-d19}, [%[dout_ptr0]]!\n" \
"vld1.8 {d16-d17}, [%[din_ptr1]] \n" \
"vmov.u32 q14, #0 \n" \
"vmov.u32 q15, #0 \n" \
"vst1.32 {d20-d23}, [%[dout_ptr1]]!\n" \
"bne 2b\n"
#define MID_STORE_INT8 \
"vld1.8 {d12-d13}, [%[din_ptr0]] \n" \
"vld1.8 {d16-d17}, [%[din_ptr1]] \n" \
"vmov.u32 q12, #0 \n" \
"vmov.u32 q13, #0 \n" \
"vmov.u32 q14, #0 \n" \
"vmov.u32 q15, #0 \n" \
"vst1.32 {d20}, [%[dout_ptr0]]! \n" \
"vst1.32 {d21}, [%[dout_ptr1]]! \n" \
"bne 2b\n"
#define RIGHT_COMPUTE_S1 \
"1: \n" \
"vld1.8 {d15}, [%[vmask]] \n" \
"sub %[din_ptr0], %[right_pad_num_in]\n"\
"sub %[din_ptr1], %[right_pad_num_in]\n"\
"sub %[din_ptr2], %[right_pad_num_in]\n"\
"sub %[din_ptr3], %[right_pad_num_in]\n"\
"vld1.8 {d12-d13}, [%[din_ptr0]] \n" \
"vld1.8 {d16-d17}, [%[din_ptr1]] \n" \
"sub %[dout_ptr0], %[right_pad_num_out]\n"\
"sub %[dout_ptr1], %[right_pad_num_out]\n"\
/* r0 */ \
"vbif.s8 d13, d11, d15 \n" \
"vbif.s8 d17, d11, d15 \n" \
"vmull.s8 q10, d12, d2 \n" \
"vmull.s8 q11, d16, d2 \n" \
"vext.8 d14, d12, d13, #1 \n" \
"vext.8 d18, d16, d17, #1 \n" \
"vext.8 d15, d12, d13, #2 \n" \
"vext.8 d19, d16, d17, #2 \n" \
"vmlal.s8 q10, d14, d3 \n" \
"vmlal.s8 q11, d18, d3 \n" \
"vld1.8 {d12-d13}, [%[din_ptr2]] \n" \
"vaddw.s16 q12, q12, d20 \n" \
"vaddw.s16 q13, q13, d21 \n" \
"vmull.s8 q10, d15, d4 \n" \
"vld1.8 {d15}, [%[vmask]] \n" \
"vaddw.s16 q14, q14, d22 \n" \
"vaddw.s16 q15, q15, d23 \n" \
"vmull.s8 q11, d19, d4 \n" \
"vbif.s8 d13, d11, d15 \n" \
/* r1 */ \
"vext.8 d14, d12, d13, #1 \n" \
"vext.8 d15, d12, d13, #2 \n" \
"vmlal.s8 q10, d16, d5 \n" \
"vmlal.s8 q11, d12, d5 \n" \
"vld1.8 {d16-d17}, [%[din_ptr3]] \n" \
"vaddw.s16 q12, q12, d20 \n" \
"vaddw.s16 q13, q13, d21 \n" \
"vmull.s8 q10, d18, d6 \n" \
"vaddw.s16 q14, q14, d22 \n" \
"vaddw.s16 q15, q15, d23 \n" \
"vmull.s8 q11, d14, d6 \n" \
"vmlal.s8 q10, d19, d7 \n" \
"vld1.8 {d19}, [%[vmask]] \n" \
"vmlal.s8 q11, d15, d7 \n" \
"vbif.s8 d17, d11, d19 \n" \
/* r2 */ \
"vaddw.s16 q12, q12, d20 \n" \
"vaddw.s16 q13, q13, d21 \n" \
"vext.8 d18, d16, d17, #1 \n" \
"vext.8 d19, d16, d17, #2 \n" \
"vaddw.s16 q14, q14, d22 \n" \
"vaddw.s16 q15, q15, d23 \n" \
"vmull.s8 q10, d12, d8 \n" \
"vmull.s8 q11, d16, d8 \n" \
"vmull.s8 q6, d14, d9 \n" \
"vmull.s8 q8, d18, d9 \n" \
"vmlal.s8 q10, d15, d10 \n" \
"vmlal.s8 q11, d19, d10 \n" \
"vaddw.s16 q12, q12, d12 \n" \
"vaddw.s16 q13, q13, d13 \n" \
"vaddw.s16 q14, q14, d16 \n" \
"vaddw.s16 q15, q15, d17 \n" \
"vld1.32 {d14-d15}, [%[vmax]] \n" \
"vdup.32 q8, %[bias] \n" \
"vdup.32 q9, %[bias] \n" \
"vaddw.s16 q12, q12, d20 \n" \
"vaddw.s16 q13, q13, d21 \n" \
"vaddw.s16 q14, q14, d22 \n" \
"vaddw.s16 q15, q15, d23 \n" \
"vdup.32 q10, %[bias] \n" \
"vdup.32 q11, %[bias] \n" \
"vcvt.f32.s32 q12, q12 \n" \
"vcvt.f32.s32 q13, q13 \n" \
"vcvt.f32.s32 q14, q14 \n" \
"vcvt.f32.s32 q15, q15 \n" \
"vmov.u32 q6, #0 \n" \
"vmla.f32 q8, q12, q7 \n" \
"vmla.f32 q9, q13, q7 \n" \
"vmla.f32 q10, q14, q7 \n" \
"vmla.f32 q11, q15, q7 \n"
#endif
// clang-format on
template <typename Dtype>
void conv_depthwise_3x3s1_int8(Dtype* dout,
const int8_t* din,
const int8_t* weights,
const float* scale,
const float* bias,
bool flag_bias,
int flag_act,
float* alpha,
int num,
int chin,
int hin,
int win,
int hout,
int wout,
int padw,
int padh,
ARMContext* ctx) {
int threads = ctx->threads();
int llc_size = ctx->llc_size() / 4;
const int hout_c_block = 8;
const int hout_r_kernel = 1;
const int wout_block = 4;
const int wout_round = ((wout + wout_block - 1) / wout_block) * wout_block;
const int win_round = wout_round + 2;
//! get h block
//! llc_size = threads * win_round * hout_c_block * hin_r_block *
//! sizeof(int8_t)
//! + wout_round * hout_c_block * hout_r_block * threads * sizeof(int32_t)
//! win_round = wout_round + 2
//! hin_r_block = hout_r_block + 2
int hout_r_block = (llc_size - 2 * win_round * threads * hout_c_block) /
(win_round * threads * hout_c_block +
hout_c_block * wout_round * threads * 4);
hout_r_block = hout_r_block > hout ? hout : hout_r_block;
hout_r_block =
((hout_r_block + hout_r_kernel - 1) / hout_r_kernel) * hout_r_kernel;
hout_r_block = hout_r_block < hout_r_kernel ? hout_r_kernel : hout_r_block;
const int hin_r_block = hout_r_block + 2;
auto tmp_work_space = ctx->workspace_data<int8_t>();
int8_t ptr_zero[win_round]; // NOLINT
memset(ptr_zero, 0, sizeof(int8_t) * win_round);
Dtype ptr_write[wout_round]; // NOLINT
int in_len = win_round * hout_c_block;
int pre_in_size = hin_r_block * in_len;
pre_in_size = ROUNDUP(pre_in_size, 4);
int pre_out_size = hout_c_block * hout_r_block * wout_round;
int8_t* tmp_din = tmp_work_space;
int size_in_channel = win * hin;
int size_out_channel = wout * hout;
int w_stride = 9; // kernel_w * kernel_h;
int ws = -padw;
int we = ws + win_round;
int w_loop = wout_round / 4;
int chout = chin;
int out_row_stride = hout_c_block * wout_round;
for (int n = 0; n < num; ++n) {
const int8_t* din_batch = din + n * chin * size_in_channel;
int8_t* dout_batch = reinterpret_cast<int8_t*>(dout) +
n * chout * size_out_channel * sizeof(Dtype);
for (int h = 0; h < hout; h += hout_r_block) {
int h_kernel = hout_r_block;
if (h + hout_r_block > hout) {
h_kernel = hout - h;
}
int hs = h - padh;
int he = hs + h_kernel + 2;
LITE_PARALLEL_COMMON_BEGIN(c, tid, chout, 0, hout_c_block) {
#ifdef LITE_USE_THREAD_POOL
int8_t* pre_din = tmp_din + tid * (pre_in_size + pre_out_size * 4);
int32_t* pre_out = reinterpret_cast<int*>(pre_din + pre_in_size);
#elif defined(ARM_WITH_OMP)
int8_t* pre_din =
tmp_din + omp_get_thread_num() * (pre_in_size + pre_out_size * 4);
int32_t* pre_out = reinterpret_cast<int*>(pre_din + pre_in_size);
#else
int32_t* pre_out = reinterpret_cast<int32_t*>(tmp_din + pre_in_size);
auto pre_din = tmp_din;
#endif
prepack_input_nxwc8_int8_dw(
din_batch, pre_din, c, hs, he, ws, we, chin, win, hin);
const int8_t* block_inr0 = pre_din;
const int8_t* block_inr1 = block_inr0 + in_len;
const int8_t* block_inr2 = block_inr1 + in_len;
const int8_t* weight_c = weights + c * w_stride;
#ifdef __aarch64__
int8x8_t vw0 = vld1_s8(weight_c);
int8x8_t vw1 = vld1_s8(weight_c + 8);
int8x8_t vw2 = vld1_s8(weight_c + 16);
int8x8_t vw3 = vld1_s8(weight_c + 24);
int8x8_t vw4 = vld1_s8(weight_c + 32);
int8x8_t vw5 = vld1_s8(weight_c + 40);
int8x8_t vw6 = vld1_s8(weight_c + 48);
int8x8_t vw7 = vld1_s8(weight_c + 56);
int8x8_t vw8 = vld1_s8(weight_c + 64);
#endif
for (int hk = 0; hk < h_kernel; hk += hout_r_kernel) {
int cnt = w_loop;
const int8_t* inr0 = block_inr0;
const int8_t* inr1 = block_inr1;
const int8_t* inr2 = block_inr2;
int32_t* ptr_out0 = pre_out + hk * out_row_stride;
#ifdef __aarch64__
asm volatile(
"ld1 {v0.8b, v1.8b, v2.8b, v3.8b}, [%[r0]], #32\n"
"1:\n"
/* inr0 -> outr0 */
"ldp d4, d5, [%[r0]]\n" /* load r0, 4 */
"smull v20.8h, v0.8b, %[w0].8b\n" /* int16, out0 */
"smull v21.8h, v1.8b, %[w0].8b\n" /* int16, out1 */
"smull v22.8h, v2.8b, %[w0].8b\n" /* int16, out2 */
"smull v23.8h, v3.8b, %[w0].8b\n" /* int16, out3 */
"smlal v20.8h, v1.8b, %[w1].8b\n" /* int16, out0 */
"smlal v21.8h, v2.8b, %[w1].8b\n" /* int16, out1 */
"smlal v22.8h, v3.8b, %[w1].8b\n" /* int16, out2 */
"smlal v23.8h, v4.8b, %[w1].8b\n" /* int16, out3 */
"ldp d0, d1, [%[r1]], #16\n" /* load r1, 0,1 */
"sxtl v24.4s, v20.4h\n"
"sxtl2 v25.4s, v20.8h\n"
"sxtl v26.4s, v21.4h\n"
"sxtl2 v27.4s, v21.8h\n"
"sxtl v28.4s, v22.4h\n"
"sxtl2 v29.4s, v22.8h\n"
"sxtl v30.4s, v23.4h\n"
"sxtl2 v31.4s, v23.8h\n"
"smull v20.8h, v2.8b, %[w2].8b\n" /* int16, out0 */
"smull v21.8h, v3.8b, %[w2].8b\n" /* int16, out1 */
"smull v22.8h, v4.8b, %[w2].8b\n" /* int16, out2 */
"smull v23.8h, v5.8b, %[w2].8b\n" /* int16, out3 */
"ldp d2, d3, [%[r1]], #16\n" /* load r1, 2,3 */
"smlal v20.8h, v0.8b, %[w3].8b\n" /* int16, out0 */
"smlal v21.8h, v1.8b, %[w3].8b\n" /* int16, out1 */
"smlal v22.8h, v2.8b, %[w3].8b\n" /* int16, out2 */
"smlal v23.8h, v3.8b, %[w3].8b\n" /* int16, out3 */
"saddw v24.4s, v24.4s, v20.4h\n"
"saddw2 v25.4s, v25.4s, v20.8h\n"
"saddw v26.4s, v26.4s, v21.4h\n"
"saddw2 v27.4s, v27.4s, v21.8h\n"
"ldp d4, d5, [%[r1]]\n" /* load r1, 4,5 */
"saddw v28.4s, v28.4s, v22.4h\n"
"saddw2 v29.4s, v29.4s, v22.8h\n"
"saddw v30.4s, v30.4s, v23.4h\n"
"saddw2 v31.4s, v31.4s, v23.8h\n"
"smull v20.8h, v1.8b, %[w4].8b\n" /* int16, out0 */
"smull v21.8h, v2.8b, %[w4].8b\n" /* int16, out1 */
"smull v22.8h, v3.8b, %[w4].8b\n" /* int16, out1 */
"smull v23.8h, v4.8b, %[w4].8b\n" /* int16, out1 */
"ldp d0, d1, [%[r2]], #16\n" /* load r2, 0,1 */
"smlal v20.8h, v2.8b, %[w5].8b\n" /* int16, out0 */
"smlal v21.8h, v3.8b, %[w5].8b\n" /* int16, out1 */
"smlal v22.8h, v4.8b, %[w5].8b\n" /* int16, out2 */
"smlal v23.8h, v5.8b, %[w5].8b\n" /* int16, out3 */
"ldp d2, d3, [%[r2]], #16\n" /* load r2, 2,3 */
"saddw v24.4s, v24.4s, v20.4h\n"
"saddw2 v25.4s, v25.4s, v20.8h\n"
"saddw v26.4s, v26.4s, v21.4h\n"
"saddw2 v27.4s, v27.4s, v21.8h\n"
"ldp d4, d5, [%[r2]]\n" /* load r2 */
"saddw v28.4s, v28.4s, v22.4h\n"
"saddw2 v29.4s, v29.4s, v22.8h\n"
"saddw v30.4s, v30.4s, v23.4h\n"
"saddw2 v31.4s, v31.4s, v23.8h\n"
"smull v20.8h, v0.8b, %[w6].8b\n" /* int16, out0 */
"smull v21.8h, v1.8b, %[w6].8b\n" /* int16, out1 */
"smull v22.8h, v2.8b, %[w6].8b\n" /* int16, out1 */
"smull v23.8h, v3.8b, %[w6].8b\n" /* int16, out1 */
"smlal v20.8h, v1.8b, %[w7].8b\n" /* int16, out0 */
"smlal v21.8h, v2.8b, %[w7].8b\n" /* int16, out1 */
"smlal v22.8h, v3.8b, %[w7].8b\n" /* int16, out1 */
"smlal v23.8h, v4.8b, %[w7].8b\n" /* int16, out1 */
"ldp d0, d1, [%[r0]], #16\n" /* load r0, 0,1 */
"saddw v24.4s, v24.4s, v20.4h\n"
"saddw2 v25.4s, v25.4s, v20.8h\n"
"saddw v26.4s, v26.4s, v21.4h\n"
"saddw2 v27.4s, v27.4s, v21.8h\n"
"saddw v28.4s, v28.4s, v22.4h\n"
"saddw2 v29.4s, v29.4s, v22.8h\n"
"saddw v30.4s, v30.4s, v23.4h\n"
"saddw2 v31.4s, v31.4s, v23.8h\n"
"smull v20.8h, v2.8b, %[w8].8b\n" /* int16, out0 */
"smull v21.8h, v3.8b, %[w8].8b\n" /* int16, out1 */
"smull v22.8h, v4.8b, %[w8].8b\n" /* int16, out1 */
"smull v23.8h, v5.8b, %[w8].8b\n" /* int16, out1 */
"ldp d2, d3, [%[r0]], #16\n" /* load r0, 2,3 */
"saddw v24.4s, v24.4s, v20.4h\n"
"saddw2 v25.4s, v25.4s, v20.8h\n"
"saddw v26.4s, v26.4s, v21.4h\n"
"saddw2 v27.4s, v27.4s, v21.8h\n"
"stp q24, q25, [%[ptr_out0]], #32\n"
"saddw v28.4s, v28.4s, v22.4h\n"
"saddw2 v29.4s, v29.4s, v22.8h\n"
"stp q26, q27, [%[ptr_out0]], #32\n"
"saddw v30.4s, v30.4s, v23.4h\n"
"saddw2 v31.4s, v31.4s, v23.8h\n"
"subs %w[cnt], %w[cnt], #1\n"
"stp q28, q29, [%[ptr_out0]], #32\n"
"stp q30, q31, [%[ptr_out0]], #32\n"
"bne 1b\n"
: [cnt] "+r"(cnt),
[r0] "+r"(inr0),
[r1] "+r"(inr1),
[r2] "+r"(inr2),
[ptr_out0] "+r"(ptr_out0)
: [w0] "w"(vw0),
[w1] "w"(vw1),
[w2] "w"(vw2),
[w3] "w"(vw3),
[w4] "w"(vw4),
[w5] "w"(vw5),
[w6] "w"(vw6),
[w7] "w"(vw7),
[w8] "w"(vw8)
: "cc",
"memory",
"v0",
"v1",
"v2",
"v3",
"v4",
"v5",
"v20",
"v21",
"v22",
"v23",
"v24",
"v25",
"v26",
"v27",
"v28",
"v29",
"v30",
"v31"
);
#else
auto wptr = weight_c;
asm volatile(
"vld1.32 {d0-d3}, [%[r0]]!\n" /* load r0, 0-4 */
"vld1.32 {d6-d7}, [%[wptr]]!\n" /* load w0-w1 */
"1:\n"
/* inr0 -> outr0 */
"vld1.32 {d4-d5}, [%[r0]]\n" /* load r0, 5-6 */
"vmull.s8 q4, d0, d6\n" /* int16, out0 */
"vmull.s8 q5, d1, d6\n" /* int16, out1 */
"vmull.s8 q6, d2, d6\n" /* int16, out2 */
"vmull.s8 q7, d3, d6\n" /* int16, out3 */
"vld1.32 {d6}, [%[wptr]]!\n" /* load w2 */
"vmlal.s8 q4, d1, d7\n" /* int16, out0 */
"vmlal.s8 q5, d2, d7\n" /* int16, out1 */
"vmlal.s8 q6, d3, d7\n" /* int16, out2 */
"vmlal.s8 q7, d4, d7\n" /* int16, out3 */
"vld1.32 {d7}, [%[wptr]]!\n" /* load w3 */
"vmovl.s16 q8, d8\n"
"vmovl.s16 q9, d9\n"
"vmovl.s16 q10, d10\n"
"vmovl.s16 q11, d11\n"
"vld1.32 {d0-d1}, [%[r1]]!\n" /* load r1, 0-1 */
"vmovl.s16 q12, d12\n"
"vmovl.s16 q13, d13\n"
"vmovl.s16 q14, d14\n"
"vmovl.s16 q15, d15\n"
"vmull.s8 q4, d2, d6\n" /* int16, out0 */
"vmull.s8 q5, d3, d6\n" /* int16, out1 */
"vld1.32 {d2-d3}, [%[r1]]!\n" /* load r1, 2-3 */
"vmull.s8 q6, d4, d6\n" /* int16, out2 */
"vmull.s8 q7, d5, d6\n" /* int16, out3 */
"vld1.32 {d6}, [%[wptr]]!\n" /* load w4 */
/* inr1 -> outr0 */
"vmlal.s8 q4, d0, d7\n" /* int16, out0 */
"vmlal.s8 q5, d1, d7\n" /* int16, out1 */
"vmlal.s8 q6, d2, d7\n" /* int16, out2 */
"vmlal.s8 q7, d3, d7\n" /* int16, out3 */
"vld1.32 {d4-d5}, [%[r1]]\n" /* load r1, 4-5 */
"vaddw.s16 q8, q8, d8\n"
"vaddw.s16 q9, q9, d9\n"
"vaddw.s16 q10, q10, d10\n"
"vaddw.s16 q11, q11, d11\n"
"vld1.32 {d7}, [%[wptr]]!\n" /* load w5 */
"vaddw.s16 q12, q12, d12\n"
"vaddw.s16 q13, q13, d13\n"
"vaddw.s16 q14, q14, d14\n"
"vaddw.s16 q15, q15, d15\n"
"vmull.s8 q4, d1, d6\n" /* int16, out0 */
"vmull.s8 q5, d2, d6\n" /* int16, out1 */
"vmull.s8 q6, d3, d6\n" /* int16, out2 */
"vmull.s8 q7, d4, d6\n" /* int16, out3 */
"vld1.32 {d6}, [%[wptr]]!\n" /* load w6 */
"vld1.32 {d0-d1}, [%[r2]]!\n" /* load r2, 0-1 */
"vmlal.s8 q4, d2, d7\n" /* int16, out0 */
"vmlal.s8 q5, d3, d7\n" /* int16, out1 */
"vmlal.s8 q6, d4, d7\n" /* int16, out2 */
"vmlal.s8 q7, d5, d7\n" /* int16, out3 */
"vld1.32 {d7}, [%[wptr]]!\n" /* load w7 */
"vaddw.s16 q8, q8, d8\n"
"vaddw.s16 q9, q9, d9\n"
"vaddw.s16 q10, q10, d10\n"
"vaddw.s16 q11, q11, d11\n"
"vld1.32 {d2-d3}, [%[r2]]!\n" /* load r2, 2-3 */
"vaddw.s16 q12, q12, d12\n"
"vaddw.s16 q13, q13, d13\n"
"vaddw.s16 q14, q14, d14\n"
"vaddw.s16 q15, q15, d15\n"
"vld1.32 {d4-d5}, [%[r2]]\n" /* load r2, 4-5 */
/* inr2 -> outr0 */
"vmull.s8 q4, d0, d6\n" /* int16, out0 */
"vmull.s8 q5, d1, d6\n" /* int16, out1 */
"vmull.s8 q6, d2, d6\n" /* int16, out2 */
"vmull.s8 q7, d3, d6\n" /* int16, out3 */
"vld1.32 {d6}, [%[wptr]]!\n" /* load w8 */
"vmlal.s8 q4, d1, d7\n" /* int16, out0 */
"vmlal.s8 q5, d2, d7\n" /* int16, out1 */
"vmlal.s8 q6, d3, d7\n" /* int16, out2 */
"vmlal.s8 q7, d4, d7\n" /* int16, out3 */
"vaddw.s16 q8, q8, d8\n"
"vaddw.s16 q9, q9, d9\n"
"vaddw.s16 q10, q10, d10\n"
"vaddw.s16 q11, q11, d11\n"
"vld1.32 {d0-d1}, [%[r0]]!\n" /* load r0, 0-1 */
"vaddw.s16 q12, q12, d12\n"
"vaddw.s16 q13, q13, d13\n"
"vaddw.s16 q14, q14, d14\n"
"vaddw.s16 q15, q15, d15\n"
"sub %[wptr], %[wptr], #72\n"
"vmull.s8 q4, d2, d6\n" /* int16, out0 */
"vmull.s8 q5, d3, d6\n" /* int16, out1 */
"vmull.s8 q6, d4, d6\n" /* int16, out2 */
"vmull.s8 q7, d5, d6\n" /* int16, out3 */
"vld1.32 {d2-d3}, [%[r0]]!\n" /* load r0, 2-3 */
"vaddw.s16 q8, q8, d8\n"
"vaddw.s16 q9, q9, d9\n"
"vaddw.s16 q10, q10, d10\n"
"vaddw.s16 q11, q11, d11\n"
"vst1.32 {d16-d19}, [%[ptr_out0]]!\n"
"vld1.32 {d6-d7}, [%[wptr]]!\n" /* load w0-w1 */
"vaddw.s16 q12, q12, d12\n"
"vaddw.s16 q13, q13, d13\n"
"vst1.32 {d20-d23}, [%[ptr_out0]]!\n"
"vaddw.s16 q14, q14, d14\n"
"vaddw.s16 q15, q15, d15\n"
"subs %[cnt], #1\n"
"vst1.32 {d24-d27}, [%[ptr_out0]]!\n"
"vst1.32 {d28-d31}, [%[ptr_out0]]!\n"
"bne 1b\n"
: [cnt] "+r"(cnt),
[r0] "+r"(inr0),
[r1] "+r"(inr1),
[r2] "+r"(inr2),
[ptr_out0] "+r"(ptr_out0),
[wptr] "+r"(wptr)
:
: "cc",
"memory",
"q0",
"q1",
"q2",
"q3",
"q4",
"q5",
"q6",
"q7",
"q8",
"q9",
"q10",
"q11",
"q12",
"q13",
"q14",
"q15");
#endif
block_inr0 = block_inr1;
block_inr1 = block_inr2;
block_inr2 = block_inr1 + in_len;
}
write_int32_nchwc8_to_nchw<Dtype>(pre_out,
reinterpret_cast<Dtype*>(dout_batch),
c,
c + hout_c_block,
h,
h + h_kernel,
0,
wout_round,
chout,
hout,
wout,
flag_act,
alpha,
bias + c,
flag_bias,
ptr_write,
scale + c);
}
LITE_PARALLEL_END();
}
}
}
inline std::pair<uint32_t, uint32_t> right_mask_3x3s1p1_int8(int w_in,
int w_out,
uint8_t* vmask) {
const uint8_t right_pad_idx[8] = {8, 9, 10, 11, 12, 13, 14, 15};
uint32_t cnt_col = ((w_out >> 3) - 2);
uint8_t size_right_remain = static_cast<uint8_t>(w_in - (7 + cnt_col * 8));
if (size_right_remain >= 9) {
cnt_col++;
size_right_remain -= 8;
}
uint32_t cnt_remain = (size_right_remain == 8 && w_out % 8 == 0)
? 8
: static_cast<uint32_t>(w_out % 8);
size_right_remain = size_right_remain + 8 - cnt_remain;
uint8x8_t vmask_rp2 =
vcgt_u8(vdup_n_u8(size_right_remain), vld1_u8(right_pad_idx));
vst1_u8(vmask, vmask_rp2);
return std::make_pair(cnt_col, cnt_remain);
}
inline std::pair<uint32_t, uint32_t> right_mask_3x3s1p0_int8(int w_in,
int w_out,
uint8_t* vmask) {
const uint8_t right_pad_idx[8] = {8, 9, 10, 11, 12, 13, 14, 15};
uint32_t cnt_col = ((w_out >> 3) - 1);
uint8_t size_right_remain = static_cast<uint8_t>(w_in - cnt_col * 8);
if (size_right_remain >= 9) {
cnt_col++;
size_right_remain -= 8;
}
uint32_t cnt_remain = (size_right_remain == 8 && w_out % 8 == 0)
? 8
: static_cast<uint32_t>(w_out % 8);
size_right_remain = size_right_remain + 8 - cnt_remain;
uint8x8_t vmask_rp2 =
vcgt_u8(vdup_n_u8(size_right_remain), vld1_u8(right_pad_idx));
vst1_u8(vmask, vmask_rp2);
return std::make_pair(cnt_col, cnt_remain);
}
#define INIT_PTR_3x3_S1_INT8(Dtype, din, w_in) \
Dtype* doutr0 = nullptr; \
Dtype* doutr1 = nullptr; \
const int8_t* dr0 = din; \
const int8_t* dr1 = dr0 + w_in; \
const int8_t* dr2 = dr1 + w_in; \
const int8_t* dr3 = dr2 + w_in; \
const int8_t* din_ptr0 = nullptr; \
const int8_t* din_ptr1 = nullptr; \
const int8_t* din_ptr2 = nullptr; \
const int8_t* din_ptr3 = nullptr;
#define ASSIGN_PTR_3x3_S1_INT8(w_out) \
din_ptr0 = dr0; \
din_ptr1 = dr1; \
din_ptr2 = dr2; \
din_ptr3 = dr3; \
doutr0 = dout_ptr; \
doutr1 = doutr0 + w_out;
#define TOP_BOTTOM_BORDER_3x3_S1P1_INT8(w_in, h_in, h_out) \
if (i == 0) { \
din_ptr0 = zero_ptr; \
din_ptr1 = dr0; \
din_ptr2 = dr1; \
din_ptr3 = dr2; \
dr0 = dr1; \
dr1 = dr2; \
dr2 = dr3; \
dr3 = dr2 + w_in; \
} else { \
dr0 = dr2; \
dr1 = dr3; \
dr2 = dr1 + w_in; \
dr3 = dr2 + w_in; \
} \
if (i + 3 > h_in) { \
switch (i + 3 - h_in) { \
case 3: \
din_ptr1 = zero_ptr; \
case 2: \
din_ptr2 = zero_ptr; \
case 1: \
din_ptr3 = zero_ptr; \
default: \
break; \
} \
} \
if (i + 2 > h_out) { \
doutr1 = write_ptr; \
}
#define TOP_BOTTOM_BORDER_3x3_S1P0_INT8(w_in, h_in, h_out) \
dr0 = dr2; \
dr1 = dr3; \
dr2 = dr1 + w_in; \
dr3 = dr2 + w_in; \
if (i + 3 > h_in) { \
switch (i + 3 - h_in) { \
case 3: \
din_ptr1 = zero_ptr; \
case 2: \
din_ptr2 = zero_ptr; \
case 1: \
din_ptr3 = zero_ptr; \
default: \
break; \
} \
} \
if (i + 2 > h_out) { \
doutr1 = write_ptr; \
}
#define PARAM1 \
[cnt] "+r"(cnt), [din_ptr0] "+r"(din_ptr0), [din_ptr1] "+r"(din_ptr1), \
[din_ptr2] "+r"(din_ptr2), [din_ptr3] "+r"(din_ptr3), \
[dout_ptr0] "+r"(doutr0), [dout_ptr1] "+r"(doutr1)
#ifdef __aarch64__
#define FILL_WEIGHTS_BIAS_INT8(wei_ptr, bias_val, scale_val, max_val, alpha) \
int8x8_t wr00 = vdup_n_s8(wei_ptr[0]); \
int8x8_t wr10 = vdup_n_s8(wei_ptr[3]); \
int8x8_t wr20 = vdup_n_s8(wei_ptr[6]); \
int8x8_t wr01 = vdup_n_s8(wei_ptr[1]); \
int8x8_t wr11 = vdup_n_s8(wei_ptr[4]); \
int8x8_t wr21 = vdup_n_s8(wei_ptr[7]); \
int8x8_t wr02 = vdup_n_s8(wei_ptr[2]); \
int8x8_t wr12 = vdup_n_s8(wei_ptr[5]); \
int8x8_t wr22 = vdup_n_s8(wei_ptr[8]); \
float32x4_t vscale = vdupq_n_f32(scale_val); \
float vmax[8] = { \
max_val, max_val, max_val, max_val, alpha, alpha, alpha, alpha};
#define PARAM2 \
[v0] "w"(wr00), [v1] "w"(wr01), [v2] "w"(wr02), [v3] "w"(wr10), \
[v4] "w"(wr11), [v5] "w"(wr12), [v6] "w"(wr20), [v7] "w"(wr21), \
[v8] "w"(wr22), [bias] "r"(bias_val), [vscale] "w"(vscale), \
[vmask] "r"(vmask), [right_pad_num_out] "r"(right_pad_num_out), \
[right_pad_num_in] "r"(right_pad_num_in)
#define ASM_PARAM \
"cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", \
"v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", \
"v21"
#else
#define FILL_WEIGHTS_BIAS_INT8(wei_ptr, bias_val, scale_val, max_val, alpha) \
float vmax[12] = {scale_val, \
scale_val, \
scale_val, \
scale_val, \
max_val, \
max_val, \
max_val, \
max_val, \
alpha, \
alpha, \
alpha, \
alpha};
#define PARAM2 \
[vmask] "r"(vmask), [bias] "r"(bias_val), [vmax] "r"(vmax), \
[wei_ptr] "r"(wei_ptr), [right_pad_num_out] "r"(right_pad_num_out), \
[right_pad_num_in] "r"(right_pad_num_in)
#define ASM_PARAM \
"cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", \
"q10", "q11", "q12", "q13", "q14", "q15"
#endif
template void conv_depthwise_3x3s1_int8<int8_t>(int8_t* dout,
const int8_t* din,
const int8_t* weights,
const float* scale,
const float* bias,
bool flag_bias,
int flag_act,
float* alpha,
int num,
int chin,
int hin,
int win,
int hout,
int wout,
int padw,
int padh,
ARMContext* ctx);
template void conv_depthwise_3x3s1_int8<float>(float* dout,
const int8_t* din,
const int8_t* weights,
const float* scale,
const float* bias,
bool flag_bias,
int flag_act,
float* alpha,
int num,
int chin,
int hin,
int win,
int hout,
int wout,
int padw,
int padh,
ARMContext* ctx);
void conv_depthwise_3x3s1p1_bias_int8_float(float* dout,
const int8_t* din,
const int8_t* weights,
const float* scale,
const float* bias,
bool flag_bias,
int flag_act,
float* alpha,
int num,
int ch_in,
int h_in,
int w_in,
int h_out,
int w_out,
ARMContext* ctx) {
int8_t* zero_ptr = ctx->workspace_data<int8_t>();
memset(zero_ptr, 0, (w_in + 16) * sizeof(int8_t));
uint8_t vmask[8];
auto&& res = right_mask_3x3s1p1_int8(w_in, w_out, vmask);
uint32_t cnt_col = res.first;
uint32_t cnt_remain = res.second;
uint32_t right_pad_num_out = (cnt_remain == 8) ? 0 : ((8 - cnt_remain) * 4);
uint32_t right_pad_num_in = (cnt_remain == 8) ? 0 : (8 - cnt_remain);
float* write_ptr =
reinterpret_cast<float*>(ctx->workspace_data<int8_t>() + w_in + 16);
int size_in_channel = w_in * h_in;
int size_out_channel = w_out * h_out;
int w_stride = 9;
for (int n = 0; n < num; ++n) {
const int8_t* din_batch = din + n * ch_in * size_in_channel;
float* dout_batch = dout + n * ch_in * size_out_channel;
LITE_PARALLEL_BEGIN(c, tid, ch_in) {
float* dout_ptr = dout_batch + c * size_out_channel;
const int8_t* din_ch_ptr = din_batch + c * size_in_channel;
float bias_val = flag_bias ? bias[c] : 0;
float scale_val = scale[c];
const int8_t* wei_ptr = weights + c * w_stride;
FILL_WEIGHTS_BIAS_INT8(wei_ptr, bias_val, scale_val, -127.f, 0.f)
INIT_PTR_3x3_S1_INT8(float, din_ch_ptr, w_in)
for (int i = 0; i < h_in; i += 2) {
// clang-format off
ASSIGN_PTR_3x3_S1_INT8(w_out)
TOP_BOTTOM_BORDER_3x3_S1P1_INT8(w_in, h_in, h_out)
int cnt = cnt_col;
#ifdef __aarch64__
asm volatile(INIT_S1 LEFT_COMPUTE_S1 LEFT_STORE_FLOAT MID_COMPUTE_S1
MID_STORE_FLOAT RIGHT_COMPUTE_S1 LEFT_STORE_FLOAT
: PARAM1
: PARAM2
: ASM_PARAM);
#else
asm volatile(INIT_S1 LEFT_COMPUTE_S1 LEFT_STORE_FLOAT MID_COMPUTE_S1
MID_STORE_FLOAT RIGHT_COMPUTE_S1 LEFT_STORE_FLOAT
: PARAM1
: PARAM2
: ASM_PARAM);
#endif
// clang-format on
dout_ptr += 2 * w_out;
}
}
LITE_PARALLEL_END();
}
}
void conv_depthwise_3x3s1p1_bias_int8_int8(int8_t* dout,
const int8_t* din,
const int8_t* weights,
const float* scale,
const float* bias,
bool flag_bias,
int flag_act,
float* alpha,
int num,
int ch_in,
int h_in,
int w_in,
int h_out,
int w_out,
ARMContext* ctx) {
int8_t* zero_ptr = ctx->workspace_data<int8_t>();
memset(zero_ptr, 0, (w_in + 16) * sizeof(int8_t));
uint8_t vmask[8];
auto&& res = right_mask_3x3s1p1_int8(w_in, w_out, vmask);
uint32_t cnt_col = res.first;
uint32_t cnt_remain = res.second;
uint32_t right_pad_num_out = (cnt_remain == 8) ? 0 : (8 - cnt_remain);
uint32_t right_pad_num_in = (cnt_remain == 8) ? 0 : (8 - cnt_remain);
int8_t* write_ptr = ctx->workspace_data<int8_t>() + w_in + 16;
int size_in_channel = w_in * h_in;
int size_out_channel = w_out * h_out;
int w_stride = 9;
for (int n = 0; n < num; ++n) {
const int8_t* din_batch = din + n * ch_in * size_in_channel;
int8_t* dout_batch = dout + n * ch_in * size_out_channel;
LITE_PARALLEL_BEGIN(c, tid, ch_in) {
int8_t* dout_ptr = dout_batch + c * size_out_channel;
const int8_t* din_ch_ptr = din_batch + c * size_in_channel;
float bias_val = flag_bias ? bias[c] : 0;
float scale_val = scale[c];
const int8_t* wei_ptr = weights + c * w_stride;
FILL_WEIGHTS_BIAS_INT8(wei_ptr, bias_val, scale_val, -127.f, 0.f)
INIT_PTR_3x3_S1_INT8(int8_t, din_ch_ptr, w_in)
for (int i = 0; i < h_in; i += 2) {
// clang-format off
ASSIGN_PTR_3x3_S1_INT8(w_out)
TOP_BOTTOM_BORDER_3x3_S1P1_INT8(w_in, h_in, h_out)
int cnt = cnt_col;
#ifdef __aarch64__
asm volatile(
INIT_S1 LEFT_COMPUTE_S1 RESULT_INT8_MAX RESULT_INT8 LEFT_STORE_INT8
MID_COMPUTE_S1 RESULT_INT8_MAX RESULT_INT8 MID_STORE_INT8
RIGHT_COMPUTE_S1 RESULT_INT8_MAX RESULT_INT8 LEFT_STORE_INT8
: PARAM1
: [vmax] "r"(vmax), PARAM2
: ASM_PARAM);
#else
asm volatile(INIT_S1 LEFT_COMPUTE_S1 RESULT_INT8 LEFT_STORE_INT8
MID_COMPUTE_S1 RESULT_INT8 MID_STORE_INT8
RIGHT_COMPUTE_S1 RESULT_INT8 LEFT_STORE_INT8
: PARAM1
: PARAM2
: ASM_PARAM);
#endif
// clang-format on
dout_ptr += 2 * w_out;
}
}
LITE_PARALLEL_END();
}
}
void conv_depthwise_3x3s1p0_bias_int8_float(float* dout,
const int8_t* din,
const int8_t* weights,
const float* scale,
const float* bias,
bool flag_bias,
int flag_act,
float* alpha,
int num,
int ch_in,
int h_in,
int w_in,
int h_out,
int w_out,
ARMContext* ctx) {
int8_t* zero_ptr = ctx->workspace_data<int8_t>();
memset(zero_ptr, 0, (w_in + 16) * sizeof(int8_t));
uint8_t vmask[8];
auto&& res = right_mask_3x3s1p0_int8(w_in, w_out, vmask);
uint32_t cnt_col = res.first;
uint32_t cnt_remain = res.second;
uint32_t right_pad_num_out = (cnt_remain == 8) ? 0 : ((8 - cnt_remain) * 4);
uint32_t right_pad_num_in = (cnt_remain == 8) ? 0 : (8 - cnt_remain);
float* write_ptr =
reinterpret_cast<float*>(ctx->workspace_data<int8_t>() + w_in + 16);
int size_in_channel = w_in * h_in;
int size_out_channel = w_out * h_out;
int w_stride = 9;
for (int n = 0; n < num; ++n) {
const int8_t* din_batch = din + n * ch_in * size_in_channel;
float* dout_batch = dout + n * ch_in * size_out_channel;
LITE_PARALLEL_BEGIN(c, tid, ch_in) {
float* dout_ptr = dout_batch + c * size_out_channel;
const int8_t* din_ch_ptr = din_batch + c * size_in_channel;
float bias_val = flag_bias ? bias[c] : 0;
float scale_val = scale[c];
const int8_t* wei_ptr = weights + c * w_stride;
FILL_WEIGHTS_BIAS_INT8(wei_ptr, bias_val, scale_val, -127.f, 0.f)
INIT_PTR_3x3_S1_INT8(float, din_ch_ptr, w_in)
for (int i = 0; i < h_out; i += 2) {
// clang-format off
ASSIGN_PTR_3x3_S1_INT8(w_out)
TOP_BOTTOM_BORDER_3x3_S1P0_INT8(w_in, h_in, h_out)
int cnt = cnt_col;
#ifdef __aarch64__
asm volatile(
MID_COMPUTE_S1 MID_STORE_FLOAT RIGHT_COMPUTE_S1 LEFT_STORE_FLOAT
: PARAM1
: PARAM2
: ASM_PARAM);
#else
asm volatile(
INIT_P0 MID_COMPUTE_S1 MID_STORE_FLOAT
RIGHT_COMPUTE_S1 LEFT_STORE_FLOAT
: PARAM1
: PARAM2
: ASM_PARAM);
#endif
// clang-format off
dout_ptr += 2 * w_out;
}
}
LITE_PARALLEL_END();
}
}
void conv_depthwise_3x3s1p0_bias_int8_int8(int8_t* dout,
const int8_t* din,
const int8_t* weights,
const float* scale,
const float* bias,
bool flag_bias,
int flag_act,
float* alpha,
int num,
int ch_in,
int h_in,
int w_in,
int h_out,
int w_out,
ARMContext* ctx) {
int8_t* zero_ptr = ctx->workspace_data<int8_t>();
memset(zero_ptr, 0, (w_in + 16) * sizeof(int8_t));
uint8_t vmask[8];
auto&& res = right_mask_3x3s1p0_int8(w_in, w_out, vmask);
uint32_t cnt_col = res.first;
uint32_t cnt_remain = res.second;
uint32_t right_pad_num_out = (cnt_remain == 8) ? 0 : (8 - cnt_remain);
uint32_t right_pad_num_in = (cnt_remain == 8) ? 0 : (8 - cnt_remain);
int8_t* write_ptr = ctx->workspace_data<int8_t>() + w_in + 16;
int size_in_channel = w_in * h_in;
int size_out_channel = w_out * h_out;
int w_stride = 9;
for (int n = 0; n < num; ++n) {
const int8_t* din_batch = din + n * ch_in * size_in_channel;
int8_t* dout_batch = dout + n * ch_in * size_out_channel;
LITE_PARALLEL_BEGIN(c, tid, ch_in) {
int8_t* dout_ptr = dout_batch + c * size_out_channel;
const int8_t* din_ch_ptr = din_batch + c * size_in_channel;
float bias_val = flag_bias ? bias[c] : 0;
float scale_val = scale[c];
const int8_t* wei_ptr = weights + c * w_stride;
FILL_WEIGHTS_BIAS_INT8(wei_ptr, bias_val, scale_val, -127.f, 0.f)
INIT_PTR_3x3_S1_INT8(int8_t, din_ch_ptr, w_in)
for (int i = 0; i < h_out; i += 2) {
// clang-format off
ASSIGN_PTR_3x3_S1_INT8(w_out)
TOP_BOTTOM_BORDER_3x3_S1P0_INT8(w_in, h_in, h_out)
int cnt = cnt_col;
#ifdef __aarch64__
asm volatile(
MID_COMPUTE_S1 RESULT_INT8_MAX RESULT_INT8 MID_STORE_INT8
RIGHT_COMPUTE_S1 RESULT_INT8_MAX RESULT_INT8 LEFT_STORE_INT8
: PARAM1
: [vmax] "r"(vmax), PARAM2
: ASM_PARAM);
#else
asm volatile(INIT_P0 MID_COMPUTE_S1 RESULT_INT8 MID_STORE_INT8
RIGHT_COMPUTE_S1 RESULT_INT8 LEFT_STORE_INT8
: PARAM1
: PARAM2
: ASM_PARAM);
#endif
// clang-format on
dout_ptr += 2 * w_out;
}
}
LITE_PARALLEL_END();
}
}
void conv_depthwise_3x3s1p1_bias_relu_int8_float(float* dout,
const int8_t* din,
const int8_t* weights,
const float* scale,
const float* bias,
bool flag_bias,
int flag_act,
float* alpha,
int num,
int ch_in,
int h_in,
int w_in,
int h_out,
int w_out,
ARMContext* ctx) {
int8_t* zero_ptr = ctx->workspace_data<int8_t>();
memset(zero_ptr, 0, (w_in + 16) * sizeof(int8_t));
uint8_t vmask[8];
auto&& res = right_mask_3x3s1p1_int8(w_in, w_out, vmask);
uint32_t cnt_col = res.first;
uint32_t cnt_remain = res.second;
uint32_t right_pad_num_out = (cnt_remain == 8) ? 0 : ((8 - cnt_remain) * 4);
uint32_t right_pad_num_in = (cnt_remain == 8) ? 0 : (8 - cnt_remain);
float* write_ptr =
reinterpret_cast<float*>(ctx->workspace_data<int8_t>() + w_in + 16);
int size_in_channel = w_in * h_in;
int size_out_channel = w_out * h_out;
int w_stride = 9;
for (int n = 0; n < num; ++n) {
const int8_t* din_batch = din + n * ch_in * size_in_channel;
float* dout_batch = dout + n * ch_in * size_out_channel;
LITE_PARALLEL_BEGIN(c, tid, ch_in) {
float* dout_ptr = dout_batch + c * size_out_channel;
const int8_t* din_ch_ptr = din_batch + c * size_in_channel;
float bias_val = flag_bias ? bias[c] : 0;
float scale_val = scale[c];
const int8_t* wei_ptr = weights + c * w_stride;
FILL_WEIGHTS_BIAS_INT8(wei_ptr, bias_val, scale_val, -127.f, 0.f)
INIT_PTR_3x3_S1_INT8(float, din_ch_ptr, w_in)
for (int i = 0; i < h_in; i += 2) {
// clang-format off
ASSIGN_PTR_3x3_S1_INT8(w_out)
TOP_BOTTOM_BORDER_3x3_S1P1_INT8(w_in, h_in, h_out)
int cnt = cnt_col;
#ifdef __aarch64__
asm volatile(INIT_S1 LEFT_COMPUTE_S1 RELU LEFT_STORE_FLOAT
MID_COMPUTE_S1 RELU MID_STORE_FLOAT
RIGHT_COMPUTE_S1 RELU LEFT_STORE_FLOAT
: PARAM1
: PARAM2
: ASM_PARAM);
#else
asm volatile(INIT_S1 LEFT_COMPUTE_S1 RELU LEFT_STORE_FLOAT
MID_COMPUTE_S1 RELU MID_STORE_FLOAT
RIGHT_COMPUTE_S1 RELU LEFT_STORE_FLOAT
: PARAM1
: PARAM2
: ASM_PARAM);
#endif
// clang-format on
dout_ptr += 2 * w_out;
}
}
LITE_PARALLEL_END();
}
}
void conv_depthwise_3x3s1p1_bias_relu6_int8_float(float* dout,
const int8_t* din,
const int8_t* weights,
const float* scale,
const float* bias,
bool flag_bias,
int flag_act,
float* alpha,
int num,
int ch_in,
int h_in,
int w_in,
int h_out,
int w_out,
ARMContext* ctx) {
int8_t* zero_ptr = ctx->workspace_data<int8_t>();
memset(zero_ptr, 0, (w_in + 16) * sizeof(int8_t));
uint8_t vmask[8];
auto&& res = right_mask_3x3s1p1_int8(w_in, w_out, vmask);
uint32_t cnt_col = res.first;
uint32_t cnt_remain = res.second;
uint32_t right_pad_num_out = (cnt_remain == 8) ? 0 : ((8 - cnt_remain) * 4);
uint32_t right_pad_num_in = (cnt_remain == 8) ? 0 : (8 - cnt_remain);
float* write_ptr =
reinterpret_cast<float*>(ctx->workspace_data<int8_t>() + w_in + 16);
int size_in_channel = w_in * h_in;
int size_out_channel = w_out * h_out;
int w_stride = 9;
for (int n = 0; n < num; ++n) {
const int8_t* din_batch = din + n * ch_in * size_in_channel;
float* dout_batch = dout + n * ch_in * size_out_channel;
LITE_PARALLEL_BEGIN(c, tid, ch_in) {
float* dout_ptr = dout_batch + c * size_out_channel;
const int8_t* din_ch_ptr = din_batch + c * size_in_channel;
float bias_val = flag_bias ? bias[c] : 0;
float scale_val = scale[c];
const int8_t* wei_ptr = weights + c * w_stride;
FILL_WEIGHTS_BIAS_INT8(wei_ptr, bias_val, scale_val, -127.f, alpha[0])
INIT_PTR_3x3_S1_INT8(float, din_ch_ptr, w_in)
for (int i = 0; i < h_in; i += 2) {
// clang-format off
ASSIGN_PTR_3x3_S1_INT8(w_out)
TOP_BOTTOM_BORDER_3x3_S1P1_INT8(w_in, h_in, h_out)
int cnt = cnt_col;
#ifdef __aarch64__
asm volatile(INIT_S1 LEFT_COMPUTE_S1 RELU6 LEFT_STORE_FLOAT
MID_COMPUTE_S1 RELU6 MID_STORE_FLOAT
RIGHT_COMPUTE_S1 RELU6 LEFT_STORE_FLOAT
: PARAM1
: [vmax] "r"(vmax), PARAM2
: ASM_PARAM);
#else
asm volatile(INIT_S1 LEFT_COMPUTE_S1 RELU6 LEFT_STORE_FLOAT
MID_COMPUTE_S1 RELU6 MID_STORE_FLOAT
RIGHT_COMPUTE_S1 RELU6 LEFT_STORE_FLOAT
: PARAM1
: PARAM2
: ASM_PARAM);
#endif
// clang-format on
dout_ptr += 2 * w_out;
}
}
LITE_PARALLEL_END();
}
}
void conv_depthwise_3x3s1p1_bias_relu_int8_int8(int8_t* dout,
const int8_t* din,
const int8_t* weights,
const float* scale,
const float* bias,
bool flag_bias,
int flag_act,
float* alpha,
int num,
int ch_in,
int h_in,
int w_in,
int h_out,
int w_out,
ARMContext* ctx) {
int8_t* zero_ptr = ctx->workspace_data<int8_t>();
memset(zero_ptr, 0, (w_in + 16) * sizeof(int8_t));
uint8_t vmask[8];
auto&& res = right_mask_3x3s1p1_int8(w_in, w_out, vmask);
uint32_t cnt_col = res.first;
uint32_t cnt_remain = res.second;
uint32_t right_pad_num_out = (cnt_remain == 8) ? 0 : (8 - cnt_remain);
uint32_t right_pad_num_in = (cnt_remain == 8) ? 0 : (8 - cnt_remain);
int8_t* write_ptr = ctx->workspace_data<int8_t>() + w_in + 16;
int size_in_channel = w_in * h_in;
int size_out_channel = w_out * h_out;
int w_stride = 9;
for (int n = 0; n < num; ++n) {
const int8_t* din_batch = din + n * ch_in * size_in_channel;
int8_t* dout_batch = dout + n * ch_in * size_out_channel;
LITE_PARALLEL_BEGIN(c, tid, ch_in) {
int8_t* dout_ptr = dout_batch + c * size_out_channel;
const int8_t* din_ch_ptr = din_batch + c * size_in_channel;
float bias_val = flag_bias ? bias[c] : 0;
float scale_val = scale[c];
const int8_t* wei_ptr = weights + c * w_stride;
FILL_WEIGHTS_BIAS_INT8(wei_ptr, bias_val, scale_val, -127.f, 0.f)
INIT_PTR_3x3_S1_INT8(int8_t, din_ch_ptr, w_in)
for (int i = 0; i < h_in; i += 2) {
// clang-format off
ASSIGN_PTR_3x3_S1_INT8(w_out)
TOP_BOTTOM_BORDER_3x3_S1P1_INT8(w_in, h_in, h_out)
int cnt = cnt_col;
#ifdef __aarch64__
asm volatile(
INIT_S1 LEFT_COMPUTE_S1 RELU RESULT_INT8 LEFT_STORE_INT8
MID_COMPUTE_S1 RELU RESULT_INT8 MID_STORE_INT8
RIGHT_COMPUTE_S1 RELU RESULT_INT8 LEFT_STORE_INT8
: PARAM1
: [vmax] "r"(vmax), PARAM2
: ASM_PARAM);
#else
asm volatile(INIT_S1 LEFT_COMPUTE_S1 RELU RESULT_INT8 LEFT_STORE_INT8
MID_COMPUTE_S1 RELU RESULT_INT8 MID_STORE_INT8
RIGHT_COMPUTE_S1 RELU RESULT_INT8 LEFT_STORE_INT8
: PARAM1
: PARAM2
: ASM_PARAM);
#endif
// clang-format on
dout_ptr += 2 * w_out;
}
}
LITE_PARALLEL_END();
}
}
void conv_depthwise_3x3s1p1_bias_relu6_int8_int8(int8_t* dout,
const int8_t* din,
const int8_t* weights,
const float* scale,
const float* bias,
bool flag_bias,
int flag_act,
float* alpha,
int num,
int ch_in,
int h_in,
int w_in,
int h_out,
int w_out,
ARMContext* ctx) {
int8_t* zero_ptr = ctx->workspace_data<int8_t>();
memset(zero_ptr, 0, (w_in + 16) * sizeof(int8_t));
uint8_t vmask[8];
auto&& res = right_mask_3x3s1p1_int8(w_in, w_out, vmask);
uint32_t cnt_col = res.first;
uint32_t cnt_remain = res.second;
uint32_t right_pad_num_out = (cnt_remain == 8) ? 0 : (8 - cnt_remain);
uint32_t right_pad_num_in = (cnt_remain == 8) ? 0 : (8 - cnt_remain);
int8_t* write_ptr = ctx->workspace_data<int8_t>() + w_in + 16;
int size_in_channel = w_in * h_in;
int size_out_channel = w_out * h_out;
int w_stride = 9;
for (int n = 0; n < num; ++n) {
const int8_t* din_batch = din + n * ch_in * size_in_channel;
int8_t* dout_batch = dout + n * ch_in * size_out_channel;
LITE_PARALLEL_BEGIN(c, tid, ch_in) {
int8_t* dout_ptr = dout_batch + c * size_out_channel;
const int8_t* din_ch_ptr = din_batch + c * size_in_channel;
float bias_val = flag_bias ? bias[c] : 0;
float scale_val = scale[c];
const int8_t* wei_ptr = weights + c * w_stride;
FILL_WEIGHTS_BIAS_INT8(wei_ptr, bias_val, scale_val, -127.f, alpha[0])
INIT_PTR_3x3_S1_INT8(int8_t, din_ch_ptr, w_in)
for (int i = 0; i < h_in; i += 2) {
// clang-format off
ASSIGN_PTR_3x3_S1_INT8(w_out)
TOP_BOTTOM_BORDER_3x3_S1P1_INT8(w_in, h_in, h_out)
int cnt = cnt_col;
#ifdef __aarch64__
asm volatile(
INIT_S1 LEFT_COMPUTE_S1 RELU6 RESULT_INT8 LEFT_STORE_INT8
MID_COMPUTE_S1 RELU6 RESULT_INT8 MID_STORE_INT8
RIGHT_COMPUTE_S1 RELU6 RESULT_INT8 LEFT_STORE_INT8
: PARAM1
: [vmax] "r"(vmax), PARAM2
: ASM_PARAM);
#else
asm volatile(INIT_S1 LEFT_COMPUTE_S1 RELU6 RESULT_INT8 LEFT_STORE_INT8
MID_COMPUTE_S1 RELU6 RESULT_INT8 MID_STORE_INT8
RIGHT_COMPUTE_S1 RELU6 RESULT_INT8 LEFT_STORE_INT8
: PARAM1
: PARAM2
: ASM_PARAM);
#endif
// clang-format on
dout_ptr += 2 * w_out;
}
}
LITE_PARALLEL_END();
}
}
void conv_depthwise_3x3s1p0_bias_relu_int8_float(float* dout,
const int8_t* din,
const int8_t* weights,
const float* scale,
const float* bias,
bool flag_bias,
int flag_act,
float* alpha,
int num,
int ch_in,
int h_in,
int w_in,
int h_out,
int w_out,
ARMContext* ctx) {
int8_t* zero_ptr = ctx->workspace_data<int8_t>();
memset(zero_ptr, 0, (w_in + 16) * sizeof(int8_t));
uint8_t vmask[8];
auto&& res = right_mask_3x3s1p0_int8(w_in, w_out, vmask);
uint32_t cnt_col = res.first;
uint32_t cnt_remain = res.second;
uint32_t right_pad_num_out = (cnt_remain == 8) ? 0 : ((8 - cnt_remain) * 4);
uint32_t right_pad_num_in = (cnt_remain == 8) ? 0 : (8 - cnt_remain);
float* write_ptr =
reinterpret_cast<float*>(ctx->workspace_data<int8_t>() + w_in + 16);
int threads = ctx->threads();
int size_in_channel = w_in * h_in;
int size_out_channel = w_out * h_out;
int w_stride = 9;
for (int n = 0; n < num; ++n) {
const int8_t* din_batch = din + n * ch_in * size_in_channel;
float* dout_batch = dout + n * ch_in * size_out_channel;
LITE_PARALLEL_BEGIN(c, tid, ch_in) {
float* dout_ptr = dout_batch + c * size_out_channel;
const int8_t* din_ch_ptr = din_batch + c * size_in_channel;
float bias_val = flag_bias ? bias[c] : 0;
float scale_val = scale[c];
const int8_t* wei_ptr = weights + c * w_stride;
FILL_WEIGHTS_BIAS_INT8(wei_ptr, bias_val, scale_val, -127.f, 0.f)
INIT_PTR_3x3_S1_INT8(float, din_ch_ptr, w_in)
for (int i = 0; i < h_out; i += 2) {
// clang-format off
ASSIGN_PTR_3x3_S1_INT8(w_out)
TOP_BOTTOM_BORDER_3x3_S1P0_INT8(w_in, h_in, h_out)
int cnt = cnt_col;
#ifdef __aarch64__
asm volatile(
MID_COMPUTE_S1 RELU MID_STORE_FLOAT
RIGHT_COMPUTE_S1 RELU LEFT_STORE_FLOAT
: PARAM1
: PARAM2
: ASM_PARAM);
#else
asm volatile(
INIT_P0 MID_COMPUTE_S1 RELU MID_STORE_FLOAT
RIGHT_COMPUTE_S1 RELU LEFT_STORE_FLOAT
: PARAM1
: PARAM2
: ASM_PARAM);
#endif
// clang-format off
dout_ptr += 2 * w_out;
}
}
LITE_PARALLEL_END();
}
}
void conv_depthwise_3x3s1p0_bias_relu6_int8_float(float* dout,
const int8_t* din,
const int8_t* weights,
const float* scale,
const float* bias,
bool flag_bias,
int flag_act,
float* alpha,
int num,
int ch_in,
int h_in,
int w_in,
int h_out,
int w_out,
ARMContext* ctx) {
int8_t* zero_ptr = ctx->workspace_data<int8_t>();
memset(zero_ptr, 0, (w_in + 16) * sizeof(int8_t));
uint8_t vmask[8];
auto&& res = right_mask_3x3s1p0_int8(w_in, w_out, vmask);
uint32_t cnt_col = res.first;
uint32_t cnt_remain = res.second;
uint32_t right_pad_num_out = (cnt_remain == 8) ? 0 : ((8 - cnt_remain) * 4);
uint32_t right_pad_num_in = (cnt_remain == 8) ? 0 : (8 - cnt_remain);
float* write_ptr =
reinterpret_cast<float*>(ctx->workspace_data<int8_t>() + w_in + 16);
int size_in_channel = w_in * h_in;
int size_out_channel = w_out * h_out;
int w_stride = 9;
for (int n = 0; n < num; ++n) {
const int8_t* din_batch = din + n * ch_in * size_in_channel;
float* dout_batch = dout + n * ch_in * size_out_channel;
LITE_PARALLEL_BEGIN(c, tid, ch_in) {
float* dout_ptr = dout_batch + c * size_out_channel;
const int8_t* din_ch_ptr = din_batch + c * size_in_channel;
float bias_val = flag_bias ? bias[c] : 0;
float scale_val = scale[c];
const int8_t* wei_ptr = weights + c * w_stride;
FILL_WEIGHTS_BIAS_INT8(wei_ptr, bias_val, scale_val, -127.f, alpha[0])
INIT_PTR_3x3_S1_INT8(float, din_ch_ptr, w_in)
for (int i = 0; i < h_out; i += 2) {
// clang-format off
ASSIGN_PTR_3x3_S1_INT8(w_out)
TOP_BOTTOM_BORDER_3x3_S1P0_INT8(w_in, h_in, h_out)
int cnt = cnt_col;
#ifdef __aarch64__
asm volatile(
MID_COMPUTE_S1 RELU6 MID_STORE_FLOAT
RIGHT_COMPUTE_S1 RELU6 LEFT_STORE_FLOAT
: PARAM1
: [vmax] "r"(vmax), PARAM2
: ASM_PARAM);
#else
asm volatile(
INIT_P0 MID_COMPUTE_S1 RELU6 MID_STORE_FLOAT
RIGHT_COMPUTE_S1 RELU6 LEFT_STORE_FLOAT
: PARAM1
: PARAM2
: ASM_PARAM);
#endif
// clang-format off
dout_ptr += 2 * w_out;
}
}
LITE_PARALLEL_END();
}
}
void conv_depthwise_3x3s1p0_bias_relu_int8_int8(int8_t* dout,
const int8_t* din,
const int8_t* weights,
const float* scale,
const float* bias,
bool flag_bias,
int flag_act,
float* alpha,
int num,
int ch_in,
int h_in,
int w_in,
int h_out,
int w_out,
ARMContext* ctx) {
int8_t* zero_ptr = ctx->workspace_data<int8_t>();
memset(zero_ptr, 0, (w_in + 16) * sizeof(int8_t));
uint8_t vmask[8];
auto&& res = right_mask_3x3s1p0_int8(w_in, w_out, vmask);
uint32_t cnt_col = res.first;
uint32_t cnt_remain = res.second;
uint32_t right_pad_num_out = (cnt_remain == 8) ? 0 : (8 - cnt_remain);
uint32_t right_pad_num_in = (cnt_remain == 8) ? 0 : (8 - cnt_remain);
int8_t* write_ptr = ctx->workspace_data<int8_t>() + w_in + 16;
int size_in_channel = w_in * h_in;
int size_out_channel = w_out * h_out;
int w_stride = 9;
for (int n = 0; n < num; ++n) {
const int8_t* din_batch = din + n * ch_in * size_in_channel;
int8_t* dout_batch = dout + n * ch_in * size_out_channel;
LITE_PARALLEL_BEGIN(c, tid, ch_in) {
int8_t* dout_ptr = dout_batch + c * size_out_channel;
const int8_t* din_ch_ptr = din_batch + c * size_in_channel;
float bias_val = flag_bias ? bias[c] : 0;
float scale_val = scale[c];
const int8_t* wei_ptr = weights + c * w_stride;
FILL_WEIGHTS_BIAS_INT8(wei_ptr, bias_val, scale_val, -127.f, 0.f)
INIT_PTR_3x3_S1_INT8(int8_t, din_ch_ptr, w_in)
for (int i = 0; i < h_out; i += 2) {
// clang-format off
ASSIGN_PTR_3x3_S1_INT8(w_out)
TOP_BOTTOM_BORDER_3x3_S1P0_INT8(w_in, h_in, h_out)
int cnt = cnt_col;
#ifdef __aarch64__
asm volatile(
MID_COMPUTE_S1 RELU RESULT_INT8 MID_STORE_INT8
RIGHT_COMPUTE_S1 RELU RESULT_INT8 LEFT_STORE_INT8
: PARAM1
: [vmax] "r"(vmax), PARAM2
: ASM_PARAM);
#else
asm volatile(INIT_P0 MID_COMPUTE_S1 RELU RESULT_INT8 MID_STORE_INT8
RIGHT_COMPUTE_S1 RELU RESULT_INT8 LEFT_STORE_INT8
: PARAM1
: PARAM2
: ASM_PARAM);
#endif
// clang-format on
dout_ptr += 2 * w_out;
}
}
LITE_PARALLEL_END();
}
}
void conv_depthwise_3x3s1p0_bias_relu6_int8_int8(int8_t* dout,
const int8_t* din,
const int8_t* weights,
const float* scale,
const float* bias,
bool flag_bias,
int flag_act,
float* alpha,
int num,
int ch_in,
int h_in,
int w_in,
int h_out,
int w_out,
ARMContext* ctx) {
int8_t* zero_ptr = ctx->workspace_data<int8_t>();
memset(zero_ptr, 0, (w_in + 16) * sizeof(int8_t));
uint8_t vmask[8];
auto&& res = right_mask_3x3s1p0_int8(w_in, w_out, vmask);
uint32_t cnt_col = res.first;
uint32_t cnt_remain = res.second;
uint32_t right_pad_num_out = (cnt_remain == 8) ? 0 : (8 - cnt_remain);
uint32_t right_pad_num_in = (cnt_remain == 8) ? 0 : (8 - cnt_remain);
int8_t* write_ptr = ctx->workspace_data<int8_t>() + w_in + 16;
int size_in_channel = w_in * h_in;
int size_out_channel = w_out * h_out;
int w_stride = 9;
for (int n = 0; n < num; ++n) {
const int8_t* din_batch = din + n * ch_in * size_in_channel;
int8_t* dout_batch = dout + n * ch_in * size_out_channel;
LITE_PARALLEL_BEGIN(c, tid, ch_in) {
int8_t* dout_ptr = dout_batch + c * size_out_channel;
const int8_t* din_ch_ptr = din_batch + c * size_in_channel;
float bias_val = flag_bias ? bias[c] : 0;
float scale_val = scale[c];
const int8_t* wei_ptr = weights + c * w_stride;
FILL_WEIGHTS_BIAS_INT8(wei_ptr, bias_val, scale_val, -127.f, alpha[0])
INIT_PTR_3x3_S1_INT8(int8_t, din_ch_ptr, w_in)
for (int i = 0; i < h_out; i += 2) {
// clang-format off
ASSIGN_PTR_3x3_S1_INT8(w_out)
TOP_BOTTOM_BORDER_3x3_S1P0_INT8(w_in, h_in, h_out)
int cnt = cnt_col;
#ifdef __aarch64__
asm volatile(
MID_COMPUTE_S1 RELU6 RESULT_INT8 MID_STORE_INT8
RIGHT_COMPUTE_S1 RELU6 RESULT_INT8 LEFT_STORE_INT8
: PARAM1
: [vmax] "r"(vmax), PARAM2
: ASM_PARAM);
#else
asm volatile(INIT_P0 MID_COMPUTE_S1 RELU6 RESULT_INT8 MID_STORE_INT8
RIGHT_COMPUTE_S1 RELU6 RESULT_INT8 LEFT_STORE_INT8
: PARAM1
: PARAM2
: ASM_PARAM);
#endif
// clang-format on
dout_ptr += 2 * w_out;
}
}
LITE_PARALLEL_END();
}
}
void conv_depthwise_3x3s1_int8_float_impl(float* dout,
const int8_t* din,
const int8_t* weights,
const float* scale,
const float* bias,
bool flag_bias,
int flag_act,
float* alpha,
int num,
int chin,
int hin,
int win,
int hout,
int wout,
int padw,
int padh,
ARMContext* ctx) {
if (padw == 1 && padh == 1) {
if (flag_act == 0) {
conv_depthwise_3x3s1p1_bias_int8_float(dout,
din,
weights,
scale,
bias,
flag_bias,
flag_act,
alpha,
num,
chin,
hin,
win,
hout,
wout,
ctx);
} else if (flag_act == 1) {
conv_depthwise_3x3s1p1_bias_relu_int8_float(dout,
din,
weights,
scale,
bias,
flag_bias,
flag_act,
alpha,
num,
chin,
hin,
win,
hout,
wout,
ctx);
} else if (flag_act == 2) {
conv_depthwise_3x3s1p1_bias_relu6_int8_float(dout,
din,
weights,
scale,
bias,
flag_bias,
flag_act,
alpha,
num,
chin,
hin,
win,
hout,
wout,
ctx);
}
} else if (padw == 0 && padh == 0) {
if (flag_act == 0) {
conv_depthwise_3x3s1p0_bias_int8_float(dout,
din,
weights,
scale,
bias,
flag_bias,
flag_act,
alpha,
num,
chin,
hin,
win,
hout,
wout,
ctx);
} else if (flag_act == 1) {
conv_depthwise_3x3s1p0_bias_relu_int8_float(dout,
din,
weights,
scale,
bias,
flag_bias,
flag_act,
alpha,
num,
chin,
hin,
win,
hout,
wout,
ctx);
} else if (flag_act == 2) {
conv_depthwise_3x3s1p0_bias_relu6_int8_float(dout,
din,
weights,
scale,
bias,
flag_bias,
flag_act,
alpha,
num,
chin,
hin,
win,
hout,
wout,
ctx);
}
}
}
void conv_depthwise_3x3s1_int8_int8_impl(int8_t* dout,
const int8_t* din,
const int8_t* weights,
const float* scale,
const float* bias,
bool flag_bias,
int flag_act,
float* alpha,
int num,
int chin,
int hin,
int win,
int hout,
int wout,
int padw,
int padh,
ARMContext* ctx) {
if (padw == 1 && padh == 1) {
if (flag_act == 0) {
conv_depthwise_3x3s1p1_bias_int8_int8(dout,
din,
weights,
scale,
bias,
flag_bias,
flag_act,
alpha,
num,
chin,
hin,
win,
hout,
wout,
ctx);
} else if (flag_act == 1) {
conv_depthwise_3x3s1p1_bias_relu_int8_int8(dout,
din,
weights,
scale,
bias,
flag_bias,
flag_act,
alpha,
num,
chin,
hin,
win,
hout,
wout,
ctx);
} else if (flag_act == 2) {
conv_depthwise_3x3s1p1_bias_relu6_int8_int8(dout,
din,
weights,
scale,
bias,
flag_bias,
flag_act,
alpha,
num,
chin,
hin,
win,
hout,
wout,
ctx);
}
} else if (padw == 0 && padh == 0) {
if (flag_act == 0) {
conv_depthwise_3x3s1p0_bias_int8_int8(dout,
din,
weights,
scale,
bias,
flag_bias,
flag_act,
alpha,
num,
chin,
hin,
win,
hout,
wout,
ctx);
} else if (flag_act == 1) {
conv_depthwise_3x3s1p0_bias_relu_int8_int8(dout,
din,
weights,
scale,
bias,
flag_bias,
flag_act,
alpha,
num,
chin,
hin,
win,
hout,
wout,
ctx);
} else if (flag_act == 2) {
conv_depthwise_3x3s1p0_bias_relu6_int8_int8(dout,
din,
weights,
scale,
bias,
flag_bias,
flag_act,
alpha,
num,
chin,
hin,
win,
hout,
wout,
ctx);
}
}
}
} // namespace math
} // namespace arm
} // namespace lite
} // namespace paddle
|
/*************************************************************************/
/* mobile_vr_interface.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "mobile_vr_interface.h"
#include "core/os/input.h"
#include "core/os/os.h"
#include "servers/visual/visual_server_globals.h"
StringName MobileVRInterface::get_name() const {
return "Native mobile";
};
int MobileVRInterface::get_capabilities() const {
return ARVRInterface::ARVR_STEREO;
};
Vector3 MobileVRInterface::scale_magneto(const Vector3 &p_magnetometer) {
// Our magnetometer doesn't give us nice clean data.
// Well it may on Mac OS X because we're getting a calibrated value in the current implementation but Android we're getting raw data.
// This is a fairly simple adjustment we can do to correct for the magnetometer data being elliptical
Vector3 mag_raw = p_magnetometer;
Vector3 mag_scaled = p_magnetometer;
// update our variables every x frames
if (mag_count > 20) {
mag_current_min = mag_next_min;
mag_current_max = mag_next_max;
mag_count = 0;
} else {
mag_count++;
};
// adjust our min and max
if (mag_raw.x > mag_next_max.x) {
mag_next_max.x = mag_raw.x;
}
if (mag_raw.y > mag_next_max.y) {
mag_next_max.y = mag_raw.y;
}
if (mag_raw.z > mag_next_max.z) {
mag_next_max.z = mag_raw.z;
}
if (mag_raw.x < mag_next_min.x) {
mag_next_min.x = mag_raw.x;
}
if (mag_raw.y < mag_next_min.y) {
mag_next_min.y = mag_raw.y;
}
if (mag_raw.z < mag_next_min.z) {
mag_next_min.z = mag_raw.z;
}
// scale our x, y and z
if (!(mag_current_max.x - mag_current_min.x)) {
mag_raw.x -= (mag_current_min.x + mag_current_max.x) / 2.0;
mag_scaled.x = (mag_raw.x - mag_current_min.x) / ((mag_current_max.x - mag_current_min.x) * 2.0 - 1.0);
};
if (!(mag_current_max.y - mag_current_min.y)) {
mag_raw.y -= (mag_current_min.y + mag_current_max.y) / 2.0;
mag_scaled.y = (mag_raw.y - mag_current_min.y) / ((mag_current_max.y - mag_current_min.y) * 2.0 - 1.0);
};
if (!(mag_current_max.z - mag_current_min.z)) {
mag_raw.z -= (mag_current_min.z + mag_current_max.z) / 2.0;
mag_scaled.z = (mag_raw.z - mag_current_min.z) / ((mag_current_max.z - mag_current_min.z) * 2.0 - 1.0);
};
return mag_scaled;
};
Basis MobileVRInterface::combine_acc_mag(const Vector3 &p_grav, const Vector3 &p_magneto) {
// yup, stock standard cross product solution...
Vector3 up = -p_grav.normalized();
Vector3 magneto_east = up.cross(p_magneto.normalized()); // or is this west?, but should be horizon aligned now
magneto_east.normalize();
Vector3 magneto = up.cross(magneto_east); // and now we have a horizon aligned north
magneto.normalize();
// We use our gravity and magnetometer vectors to construct our matrix
Basis acc_mag_m3;
acc_mag_m3.elements[0] = -magneto_east;
acc_mag_m3.elements[1] = up;
acc_mag_m3.elements[2] = magneto;
return acc_mag_m3;
};
void MobileVRInterface::set_position_from_sensors() {
_THREAD_SAFE_METHOD_
// this is a helper function that attempts to adjust our transform using our 9dof sensors
// 9dof is a misleading marketing term coming from 3 accelerometer axis + 3 gyro axis + 3 magnetometer axis = 9 axis
// but in reality this only offers 3 dof (yaw, pitch, roll) orientation
uint64_t ticks = OS::get_singleton()->get_ticks_usec();
uint64_t ticks_elapsed = ticks - last_ticks;
float delta_time = (double)ticks_elapsed / 1000000.0;
// few things we need
Input *input = Input::get_singleton();
Vector3 down(0.0, -1.0, 0.0); // Down is Y negative
Vector3 north(0.0, 0.0, 1.0); // North is Z positive
// make copies of our inputs
bool has_grav = false;
Vector3 acc = input->get_accelerometer();
Vector3 gyro = input->get_gyroscope();
Vector3 grav = input->get_gravity();
Vector3 magneto = scale_magneto(input->get_magnetometer()); // this may be overkill on iOS because we're already getting a calibrated magnetometer reading
if (sensor_first) {
sensor_first = false;
} else {
acc = scrub(acc, last_accerometer_data, 2, 0.2);
magneto = scrub(magneto, last_magnetometer_data, 3, 0.3);
};
last_accerometer_data = acc;
last_magnetometer_data = magneto;
if (grav.length() < 0.1) {
// not ideal but use our accelerometer, this will contain shakey shakey user behaviour
// maybe look into some math but I'm guessing that if this isn't available, its because we lack the gyro sensor to actually work out
// what a stable gravity vector is
grav = acc;
if (grav.length() > 0.1) {
has_grav = true;
};
} else {
has_grav = true;
};
bool has_magneto = magneto.length() > 0.1;
if (gyro.length() > 0.1) {
/* this can return to 0.0 if the user doesn't move the phone, so once on, it's on */
has_gyro = true;
};
if (has_gyro) {
// start with applying our gyro (do NOT smooth our gyro!)
Basis rotate;
rotate.rotate(orientation.get_axis(0), gyro.x * delta_time);
rotate.rotate(orientation.get_axis(1), gyro.y * delta_time);
rotate.rotate(orientation.get_axis(2), gyro.z * delta_time);
orientation = rotate * orientation;
tracking_state = ARVRInterface::ARVR_NORMAL_TRACKING;
};
///@TODO improve this, the magnetometer is very fidgity sometimes flipping the axis for no apparent reason (probably a bug on my part)
// if you have a gyro + accelerometer that combo tends to be better then combining all three but without a gyro you need the magnetometer..
if (has_magneto && has_grav && !has_gyro) {
// convert to quaternions, easier to smooth those out
Quat transform_quat(orientation);
Quat acc_mag_quat(combine_acc_mag(grav, magneto));
transform_quat = transform_quat.slerp(acc_mag_quat, 0.1);
orientation = Basis(transform_quat);
tracking_state = ARVRInterface::ARVR_NORMAL_TRACKING;
} else if (has_grav) {
// use gravity vector to make sure down is down...
// transform gravity into our world space
grav.normalize();
Vector3 grav_adj = orientation.xform(grav);
float dot = grav_adj.dot(down);
if ((dot > -1.0) && (dot < 1.0)) {
// axis around which we have this rotation
Vector3 axis = grav_adj.cross(down);
axis.normalize();
Basis drift_compensation(axis, acos(dot) * delta_time * 10);
orientation = drift_compensation * orientation;
};
};
// JIC
orientation.orthonormalize();
last_ticks = ticks;
};
void MobileVRInterface::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_eye_height", "eye_height"), &MobileVRInterface::set_eye_height);
ClassDB::bind_method(D_METHOD("get_eye_height"), &MobileVRInterface::get_eye_height);
ClassDB::bind_method(D_METHOD("set_iod", "iod"), &MobileVRInterface::set_iod);
ClassDB::bind_method(D_METHOD("get_iod"), &MobileVRInterface::get_iod);
ClassDB::bind_method(D_METHOD("set_display_width", "display_width"), &MobileVRInterface::set_display_width);
ClassDB::bind_method(D_METHOD("get_display_width"), &MobileVRInterface::get_display_width);
ClassDB::bind_method(D_METHOD("set_display_to_lens", "display_to_lens"), &MobileVRInterface::set_display_to_lens);
ClassDB::bind_method(D_METHOD("get_display_to_lens"), &MobileVRInterface::get_display_to_lens);
ClassDB::bind_method(D_METHOD("set_oversample", "oversample"), &MobileVRInterface::set_oversample);
ClassDB::bind_method(D_METHOD("get_oversample"), &MobileVRInterface::get_oversample);
ClassDB::bind_method(D_METHOD("set_k1", "k"), &MobileVRInterface::set_k1);
ClassDB::bind_method(D_METHOD("get_k1"), &MobileVRInterface::get_k1);
ClassDB::bind_method(D_METHOD("set_k2", "k"), &MobileVRInterface::set_k2);
ClassDB::bind_method(D_METHOD("get_k2"), &MobileVRInterface::get_k2);
ADD_PROPERTY(PropertyInfo(Variant::REAL, "eye_height", PROPERTY_HINT_RANGE, "0.0,3.0,0.1"), "set_eye_height", "get_eye_height");
ADD_PROPERTY(PropertyInfo(Variant::REAL, "iod", PROPERTY_HINT_RANGE, "4.0,10.0,0.1"), "set_iod", "get_iod");
ADD_PROPERTY(PropertyInfo(Variant::REAL, "display_width", PROPERTY_HINT_RANGE, "5.0,25.0,0.1"), "set_display_width", "get_display_width");
ADD_PROPERTY(PropertyInfo(Variant::REAL, "display_to_lens", PROPERTY_HINT_RANGE, "5.0,25.0,0.1"), "set_display_to_lens", "get_display_to_lens");
ADD_PROPERTY(PropertyInfo(Variant::REAL, "oversample", PROPERTY_HINT_RANGE, "1.0,2.0,0.1"), "set_oversample", "get_oversample");
ADD_PROPERTY(PropertyInfo(Variant::REAL, "k1", PROPERTY_HINT_RANGE, "0.1,10.0,0.0001"), "set_k1", "get_k1");
ADD_PROPERTY(PropertyInfo(Variant::REAL, "k2", PROPERTY_HINT_RANGE, "0.1,10.0,0.0001"), "set_k2", "get_k2");
}
void MobileVRInterface::set_eye_height(const real_t p_eye_height) {
eye_height = p_eye_height;
}
real_t MobileVRInterface::get_eye_height() const {
return eye_height;
}
void MobileVRInterface::set_iod(const real_t p_iod) {
intraocular_dist = p_iod;
};
real_t MobileVRInterface::get_iod() const {
return intraocular_dist;
};
void MobileVRInterface::set_display_width(const real_t p_display_width) {
display_width = p_display_width;
};
real_t MobileVRInterface::get_display_width() const {
return display_width;
};
void MobileVRInterface::set_display_to_lens(const real_t p_display_to_lens) {
display_to_lens = p_display_to_lens;
};
real_t MobileVRInterface::get_display_to_lens() const {
return display_to_lens;
};
void MobileVRInterface::set_oversample(const real_t p_oversample) {
oversample = p_oversample;
};
real_t MobileVRInterface::get_oversample() const {
return oversample;
};
void MobileVRInterface::set_k1(const real_t p_k1) {
k1 = p_k1;
};
real_t MobileVRInterface::get_k1() const {
return k1;
};
void MobileVRInterface::set_k2(const real_t p_k2) {
k2 = p_k2;
};
real_t MobileVRInterface::get_k2() const {
return k2;
};
bool MobileVRInterface::is_stereo() {
// needs stereo...
return true;
};
bool MobileVRInterface::is_initialized() const {
return (initialized);
};
bool MobileVRInterface::initialize() {
ARVRServer *arvr_server = ARVRServer::get_singleton();
ERR_FAIL_NULL_V(arvr_server, false);
if (!initialized) {
// reset our sensor data and orientation
mag_count = 0;
has_gyro = false;
sensor_first = true;
mag_next_min = Vector3(10000, 10000, 10000);
mag_next_max = Vector3(-10000, -10000, -10000);
mag_current_min = Vector3(0, 0, 0);
mag_current_max = Vector3(0, 0, 0);
// reset our orientation
orientation = Basis();
// make this our primary interface
arvr_server->set_primary_interface(this);
last_ticks = OS::get_singleton()->get_ticks_usec();
initialized = true;
};
return true;
};
void MobileVRInterface::uninitialize() {
if (initialized) {
ARVRServer *arvr_server = ARVRServer::get_singleton();
if (arvr_server != nullptr) {
// no longer our primary interface
arvr_server->clear_primary_interface_if(this);
}
initialized = false;
};
};
Size2 MobileVRInterface::get_render_targetsize() {
_THREAD_SAFE_METHOD_
// we use half our window size
Size2 target_size = OS::get_singleton()->get_window_size();
target_size.x *= 0.5 * oversample;
target_size.y *= oversample;
return target_size;
};
Transform MobileVRInterface::get_transform_for_eye(ARVRInterface::Eyes p_eye, const Transform &p_cam_transform) {
_THREAD_SAFE_METHOD_
Transform transform_for_eye;
ARVRServer *arvr_server = ARVRServer::get_singleton();
ERR_FAIL_NULL_V(arvr_server, transform_for_eye);
if (initialized) {
float world_scale = arvr_server->get_world_scale();
// we don't need to check for the existence of our HMD, doesn't effect our values...
// note * 0.01 to convert cm to m and * 0.5 as we're moving half in each direction...
if (p_eye == ARVRInterface::EYE_LEFT) {
transform_for_eye.origin.x = -(intraocular_dist * 0.01 * 0.5 * world_scale);
} else if (p_eye == ARVRInterface::EYE_RIGHT) {
transform_for_eye.origin.x = intraocular_dist * 0.01 * 0.5 * world_scale;
} else {
// for mono we don't reposition, we want our center position.
};
// just scale our origin point of our transform
Transform hmd_transform;
hmd_transform.basis = orientation;
hmd_transform.origin = Vector3(0.0, eye_height * world_scale, 0.0);
transform_for_eye = p_cam_transform * (arvr_server->get_reference_frame()) * hmd_transform * transform_for_eye;
} else {
// huh? well just return what we got....
transform_for_eye = p_cam_transform;
};
return transform_for_eye;
};
CameraMatrix MobileVRInterface::get_projection_for_eye(ARVRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far) {
_THREAD_SAFE_METHOD_
CameraMatrix eye;
if (p_eye == ARVRInterface::EYE_MONO) {
///@TODO for now hardcode some of this, what is really needed here is that this needs to be in sync with the real cameras properties
// which probably means implementing a specific class for iOS and Android. For now this is purely here as an example.
// Note also that if you use a normal viewport with AR/VR turned off you can still use the tracker output of this interface
// to position a stock standard Godot camera and have control over this.
// This will make more sense when we implement ARkit on iOS (probably a separate interface).
eye.set_perspective(60.0, p_aspect, p_z_near, p_z_far, false);
} else {
eye.set_for_hmd(p_eye == ARVRInterface::EYE_LEFT ? 1 : 2, p_aspect, intraocular_dist, display_width, display_to_lens, oversample, p_z_near, p_z_far);
};
return eye;
};
void MobileVRInterface::commit_for_eye(ARVRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect) {
_THREAD_SAFE_METHOD_
// We must have a valid render target
ERR_FAIL_COND(!p_render_target.is_valid());
// Because we are rendering to our device we must use our main viewport!
ERR_FAIL_COND(p_screen_rect == Rect2());
Rect2 dest = p_screen_rect;
Vector2 eye_center;
// we output half a screen
dest.size.x *= 0.5;
if (p_eye == ARVRInterface::EYE_LEFT) {
eye_center.x = ((-intraocular_dist / 2.0) + (display_width / 4.0)) / (display_width / 2.0);
} else if (p_eye == ARVRInterface::EYE_RIGHT) {
dest.position.x = dest.size.x;
eye_center.x = ((intraocular_dist / 2.0) - (display_width / 4.0)) / (display_width / 2.0);
}
// we don't offset the eye center vertically (yet)
eye_center.y = 0.0;
// unset our render target so we are outputting to our main screen by making RasterizerStorageGLES3::system_fbo our current FBO
VSG::rasterizer->set_current_render_target(RID());
// and output
VSG::rasterizer->output_lens_distorted_to_screen(p_render_target, dest, k1, k2, eye_center, oversample);
};
void MobileVRInterface::process() {
_THREAD_SAFE_METHOD_
if (initialized) {
set_position_from_sensors();
};
};
void MobileVRInterface::notification(int p_what){
_THREAD_SAFE_METHOD_
// nothing to do here, I guess we could pauze our sensors...
}
MobileVRInterface::MobileVRInterface() {
initialized = false;
// Just set some defaults for these. At some point we need to look at adding a lookup table for common device + headset combos and/or support reading cardboard QR codes
eye_height = 1.85;
intraocular_dist = 6.0;
display_width = 14.5;
display_to_lens = 4.0;
oversample = 1.5;
k1 = 0.215;
k2 = 0.215;
last_ticks = 0;
};
MobileVRInterface::~MobileVRInterface() {
// and make sure we cleanup if we haven't already
if (is_initialized()) {
uninitialize();
};
};
|
/*ckwg +29
* Copyright 2014 by Kitware, 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 name of Kitware, Inc. nor the names of any 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 AUTHORS 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 <test_common.h>
#include <test_math.h>
#include <test_scene.h>
#include <maptk/core/projected_track_set.h>
#include <maptk/core/metrics.h>
#include <maptk/vxl/register.h>
#include <maptk/vxl/estimate_essential_matrix.h>
#include <boost/foreach.hpp>
#define TEST_ARGS ()
DECLARE_TEST_MAP();
int
main(int argc, char* argv[])
{
CHECK_ARGS(1);
maptk::vxl::register_algorithms();
testname_t const testname = argv[1];
RUN_TEST(testname);
}
IMPLEMENT_TEST(create)
{
using namespace maptk;
algo::estimate_essential_matrix_sptr est_e = algo::estimate_essential_matrix::create("vxl");
if (!est_e)
{
TEST_ERROR("Unable to create vxl::estimate_essential_matrix by name");
}
}
// Compute the essential matrix from cameras
maptk::matrix_3x3d
essential_matrix_from_cameras(const maptk::camera& right_cam,
const maptk::camera& left_cam)
{
using namespace maptk;
rotation_d R1 = right_cam.rotation();
rotation_d R2 = left_cam.rotation();
vector_3d t1 = right_cam.translation();
vector_3d t2 = left_cam.translation();
matrix_3x3d R(R2 * R1.inverse());
matrix_3x3d tx = cross_product(t2 - R*t1);
matrix_3x3d E(tx * R);
E /= E.frobenius_norm();
if (E(0,0) < 0)
{
E *= -1;
}
return E;
}
// Convert the essential matrix to a fundamental matrix
maptk::matrix_3x3d
essential_matrix_to_fundamental(const maptk::matrix_3x3d& E,
const maptk::camera_intrinsics_d& right_cal,
const maptk::camera_intrinsics_d& left_cal)
{
using namespace maptk;
matrix_3x3d Kr_inv = inverse(matrix_3x3d(right_cal));
matrix_3x3d Kl_invt = inverse(matrix_3x3d(left_cal).transpose());
return Kl_invt * E * Kr_inv;
}
// Print epipolar distance of pairs of points given a fundamental matrix
void print_epipolar_distances(const maptk::matrix_3x3d& F,
const std::vector<maptk::vector_2d> right_pts,
const std::vector<maptk::vector_2d> left_pts)
{
using namespace maptk;
matrix_3x3d Ft = F.transpose();
for(unsigned i=0; i<right_pts.size(); ++i)
{
const vector_2d& pr = right_pts[i];
const vector_2d& pl = left_pts[i];
vector_3d vr(pr.x(), pr.y(), 1.0);
vector_3d vl(pl.x(), pl.y(), 1.0);
vector_3d lr = F * vr;
vector_3d ll = Ft * vl;
double sr = 1.0 / sqrt(lr.x()*lr.x() + lr.y()*lr.y());
double sl = 1.0 / sqrt(ll.x()*ll.x() + ll.y()*ll.y());
// sum of point to epipolar line distance in both images
double d = inner_product(vr, ll);
std::cout <<" dist right = "<<d*sr<<" dist left = "<<d*sl << std::endl;
}
}
// test essential matrix estimation with ideal points
IMPLEMENT_TEST(ideal_points)
{
using namespace maptk;
vxl::estimate_essential_matrix est_e;
// create landmarks at the random locations
landmark_map_sptr landmarks = testing::init_landmarks(100);
landmarks = testing::noisy_landmarks(landmarks, 1.0);
// create a camera sequence (elliptical path)
camera_map_sptr cameras = testing::camera_seq();
// create tracks from the projections
track_set_sptr tracks = projected_tracks(landmarks, cameras);
const frame_id_t frame1 = 0;
const frame_id_t frame2 = 10;
camera_map::map_camera_t cams = cameras->cameras();
camera_sptr cam1 = cams[frame1];
camera_sptr cam2 = cams[frame2];
camera_intrinsics_d cal1 = cam1->intrinsics();
camera_intrinsics_d cal2 = cam2->intrinsics();
// compute the true essential matrix from the cameras
matrix_3x3d true_E = essential_matrix_from_cameras(*cam1, *cam2);
// extract coresponding image points
std::vector<track_sptr> trks = tracks->tracks();
std::vector<vector_2d> pts1, pts2;
for(unsigned int i=0; i<trks.size(); ++i)
{
pts1.push_back(trks[i]->find(frame1)->feat->loc());
pts2.push_back(trks[i]->find(frame2)->feat->loc());
}
// print the epipolar distances using this essential matrix
matrix_3x3d F = essential_matrix_to_fundamental(true_E, cal1, cal2);
print_epipolar_distances(F, pts1, pts2);
// compute the essential matrix from the corresponding points
std::vector<bool> inliers;
matrix_3x3d E = est_e.estimate(pts1, pts2, cal1, cal2, inliers, 1.5);
E /= E.frobenius_norm();
if (E(0,0) < 0)
{
E *= -1;
}
// compare true and computed essential matrices
std::cout << "true E = "<<true_E<<std::endl;
std::cout << "Estimated E = "<< E <<std::endl;
TEST_NEAR("Essential Matrix Estimate", E, true_E, 1e-8);
unsigned num_inliers = static_cast<unsigned>(std::count(inliers.begin(),
inliers.end(), true));
std::cout << "num inliers "<<num_inliers<<std::endl;
TEST_EQUAL("All points are inliers", num_inliers, pts1.size());
}
// test essential matrix estimation with noisy points
IMPLEMENT_TEST(noisy_points)
{
using namespace maptk;
vxl::estimate_essential_matrix est_e;
// create landmarks at the random locations
landmark_map_sptr landmarks = testing::init_landmarks(100);
landmarks = testing::noisy_landmarks(landmarks, 1.0);
// create a camera sequence (elliptical path)
camera_map_sptr cameras = testing::camera_seq();
// create tracks from the projections
track_set_sptr tracks = projected_tracks(landmarks, cameras);
// add random noise to track image locations
tracks = testing::noisy_tracks(tracks, 0.5);
const frame_id_t frame1 = 0;
const frame_id_t frame2 = 10;
camera_map::map_camera_t cams = cameras->cameras();
camera_sptr cam1 = cams[frame1];
camera_sptr cam2 = cams[frame2];
camera_intrinsics_d cal1 = cam1->intrinsics();
camera_intrinsics_d cal2 = cam2->intrinsics();
// compute the true essential matrix from the cameras
matrix_3x3d true_E = essential_matrix_from_cameras(*cam1, *cam2);
// extract coresponding image points
std::vector<track_sptr> trks = tracks->tracks();
std::vector<vector_2d> pts1, pts2;
for(unsigned int i=0; i<trks.size(); ++i)
{
pts1.push_back(trks[i]->find(frame1)->feat->loc());
pts2.push_back(trks[i]->find(frame2)->feat->loc());
}
// print the epipolar distances using this essential matrix
matrix_3x3d F = essential_matrix_to_fundamental(true_E, cal1, cal2);
print_epipolar_distances(F, pts1, pts2);
// compute the essential matrix from the corresponding points
std::vector<bool> inliers;
matrix_3x3d E = est_e.estimate(pts1, pts2, cal1, cal2, inliers, 1.5);
E /= E.frobenius_norm();
if (E(0,0) < 0)
{
E *= -1;
}
// compare true and computed essential matrices
std::cout << "true E = "<<true_E<<std::endl;
std::cout << "Estimated E = "<< E <<std::endl;
TEST_NEAR("Essential Matrix Estimate", E, true_E, 0.01);
unsigned num_inliers = static_cast<unsigned>(std::count(inliers.begin(),
inliers.end(), true));
std::cout << "num inliers "<<num_inliers<<std::endl;
bool enough_inliers = num_inliers > pts1.size() / 3;
TEST_EQUAL("Enough inliers", enough_inliers, true);
}
|
#include "../../../inc/synchronizer/messages/release_signal.h"
release_signal::release_signal() {}
release_signal::release_signal(uint8_t* buf) {
deserialize(buf);
}
release_signal::release_signal(uint16_t tag, uint32_t time, const lock_request* released_request): synchronization_message(tag, time) {
this->released_request = *released_request;
}
void release_signal::serialize_synchronization_members(uint8_t* buf) {
released_request.serialize(buf);
}
void release_signal::deserialize_synchronization_members(uint8_t* serialized) {
released_request.deserialize(serialized);
}
size_t release_signal::calculate_synchronization_members_size() {
return released_request.get_size();
}
release_signal::~release_signal() {}
|
//=================================================================================================
/*!
// \file src/mathtest/smatdmatsub/LCaDDa.cpp
// \brief Source file for the LCaDDa sparse matrix/dense matrix subtraction math test
//
// Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group 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 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/CompressedMatrix.h>
#include <blaze/math/DiagonalMatrix.h>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/LowerMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/smatdmatsub/OperationTest.h>
#include <blazetest/system/MathTest.h>
#ifdef BLAZE_USE_HPX_THREADS
# include <hpx/hpx_main.hpp>
#endif
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'LCaDDa'..." << std::endl;
using blazetest::mathtest::TypeA;
try
{
// Matrix type definitions
using LCa = blaze::LowerMatrix< blaze::CompressedMatrix<TypeA> >;
using DDa = blaze::DiagonalMatrix< blaze::DynamicMatrix<TypeA> >;
// Creator type definitions
using CLCa = blazetest::Creator<LCa>;
using CDDa = blazetest::Creator<DDa>;
// Running tests with small matrices
for( size_t i=0UL; i<=6UL; ++i ) {
for( size_t j=0UL; j<=LCa::maxNonZeros( i ); ++j ) {
RUN_SMATDMATSUB_OPERATION_TEST( CLCa( i, j ), CDDa( i ) );
}
}
// Running tests with large matrices
RUN_SMATDMATSUB_OPERATION_TEST( CLCa( 67UL, 7UL ), CDDa( 67UL ) );
RUN_SMATDMATSUB_OPERATION_TEST( CLCa( 128UL, 16UL ), CDDa( 128UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during sparse matrix/dense matrix subtraction:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2021 Advanced Micro Devices, Inc.
*
* 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 GUARD_MIOPEN_NOGPU_HANDLE_IMPL_HPP_
#define GUARD_MIOPEN_NOGPU_HANDLE_IMPL_HPP_
namespace miopen {
struct HandleImpl
{
using StreamPtr = std::shared_ptr<typename std::remove_pointer<hipStream_t>::type>;
HandleImpl() : ctx() {}
void elapsed_time(hipEvent_t start, hipEvent_t stop)
{
if(enable_profiling)
hipEventElapsedTime(&this->profiling_result, start, stop);
}
std::function<void(hipEvent_t, hipEvent_t)> elapsed_time_handler()
{
return std::bind(
&HandleImpl::elapsed_time, this, std::placeholders::_1, std::placeholders::_2);
}
bool enable_profiling = false;
StreamPtr stream = nullptr;
float profiling_result = 0.0;
int device = -1;
std::string device_name;
std::size_t num_cu = 0;
std::size_t local_mem_size = 0;
std::size_t global_mem_size = 0;
std::size_t img3d_max_width = 0;
std::size_t warp_size = 64;
std::size_t max_mem_alloc_size = 0;
Allocator allocator{};
KernelCache cache;
std::int64_t ctx;
TargetProperties target_properties;
};
}
#endif // GUARD_MIOPEN_NOGPU_HANDLE_IMPL_HPP_
|
// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2019 The Zaarde Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "signverifymessagedialog.h"
#include "ui_signverifymessagedialog.h"
#include "addressbookpage.h"
#include "guiutil.h"
#include "walletmodel.h"
#include "base58.h"
#include "init.h"
#include "wallet.h"
#include <string>
#include <vector>
#include <QClipboard>
SignVerifyMessageDialog::SignVerifyMessageDialog(QWidget* parent) : QDialog(parent),
ui(new Ui::SignVerifyMessageDialog),
model(0)
{
ui->setupUi(this);
#if QT_VERSION >= 0x040700
ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature"));
#endif
GUIUtil::setupAddressWidget(ui->addressIn_SM, this);
GUIUtil::setupAddressWidget(ui->addressIn_VM, this);
ui->addressIn_SM->installEventFilter(this);
ui->messageIn_SM->installEventFilter(this);
ui->signatureOut_SM->installEventFilter(this);
ui->addressIn_VM->installEventFilter(this);
ui->messageIn_VM->installEventFilter(this);
ui->signatureIn_VM->installEventFilter(this);
ui->addressIn_SM->setAttribute(Qt::WA_MacShowFocusRect, 0);
ui->messageIn_SM->setAttribute(Qt::WA_MacShowFocusRect, 0);
ui->signatureOut_SM->setAttribute(Qt::WA_MacShowFocusRect, 0);
ui->addressIn_VM->setAttribute(Qt::WA_MacShowFocusRect, 0);
ui->messageIn_VM->setAttribute(Qt::WA_MacShowFocusRect, 0);
ui->signatureIn_VM->setAttribute(Qt::WA_MacShowFocusRect, 0);
ui->signatureOut_SM->setFont(GUIUtil::bitcoinAddressFont());
ui->signatureIn_VM->setFont(GUIUtil::bitcoinAddressFont());
}
SignVerifyMessageDialog::~SignVerifyMessageDialog()
{
delete ui;
}
void SignVerifyMessageDialog::setModel(WalletModel* model)
{
this->model = model;
}
void SignVerifyMessageDialog::setAddress_SM(const QString& address)
{
ui->addressIn_SM->setText(address);
ui->messageIn_SM->setFocus();
}
void SignVerifyMessageDialog::setAddress_VM(const QString& address)
{
ui->addressIn_VM->setText(address);
ui->messageIn_VM->setFocus();
}
void SignVerifyMessageDialog::showTab_SM(bool fShow)
{
ui->tabWidget->setCurrentIndex(0);
if (fShow)
this->show();
}
void SignVerifyMessageDialog::showTab_VM(bool fShow)
{
ui->tabWidget->setCurrentIndex(1);
if (fShow)
this->show();
}
void SignVerifyMessageDialog::on_addressBookButton_SM_clicked()
{
if (model && model->getAddressTableModel()) {
AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::ReceivingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec()) {
setAddress_SM(dlg.getReturnValue());
}
}
}
void SignVerifyMessageDialog::on_pasteButton_SM_clicked()
{
setAddress_SM(QApplication::clipboard()->text());
}
void SignVerifyMessageDialog::on_signMessageButton_SM_clicked()
{
if (!model)
return;
/* Clear old signature to ensure users don't get confused on error with an old signature displayed */
ui->signatureOut_SM->clear();
if (!IsValidDestinationString(ui->addressIn_SM->text().toStdString())) {
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
return;
}
CTxDestination addr = DecodeDestination(ui->addressIn_SM->text().toStdString());
CKeyID *keyID = boost::get<CKeyID>(&addr);
if (!keyID) {
ui->addressIn_SM->setValid(false);
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock(true));
if (!ctx.isValid()) {
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled."));
return;
}
CKey key;
if (!pwalletMain->GetKey(*keyID, key)) {
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("Private key for the entered address is not available."));
return;
}
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << ui->messageIn_SM->document()->toPlainText().toStdString();
std::vector<unsigned char> vchSig;
if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig)) {
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>"));
return;
}
ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }");
ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>"));
ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size())));
}
void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked()
{
GUIUtil::setClipboard(ui->signatureOut_SM->text());
}
void SignVerifyMessageDialog::on_clearButton_SM_clicked()
{
ui->addressIn_SM->clear();
ui->messageIn_SM->clear();
ui->signatureOut_SM->clear();
ui->statusLabel_SM->clear();
ui->addressIn_SM->setFocus();
}
void SignVerifyMessageDialog::on_addressBookButton_VM_clicked()
{
if (model && model->getAddressTableModel()) {
AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec()) {
setAddress_VM(dlg.getReturnValue());
}
}
}
void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked()
{
if (!IsValidDestinationString(ui->addressIn_VM->text().toStdString())) {
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
return;
}
CTxDestination addr = DecodeDestination(ui->addressIn_VM->text().toStdString());
CKeyID *keyID = boost::get<CKeyID>(&addr);
if (!keyID) {
ui->addressIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
return;
}
bool fInvalid = false;
std::vector<unsigned char> vchSig = DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid);
if (fInvalid) {
ui->signatureIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again."));
return;
}
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << ui->messageIn_VM->document()->toPlainText().toStdString();
CPubKey pubkey;
if (!pubkey.RecoverCompact(Hash(ss.begin(), ss.end()), vchSig)) {
ui->signatureIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again."));
return;
}
if (!(CTxDestination(pubkey.GetID()) == addr)) {
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>"));
return;
}
ui->statusLabel_VM->setStyleSheet("QLabel { color: green; }");
ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verified.") + QString("</nobr>"));
}
void SignVerifyMessageDialog::on_clearButton_VM_clicked()
{
ui->addressIn_VM->clear();
ui->signatureIn_VM->clear();
ui->messageIn_VM->clear();
ui->statusLabel_VM->clear();
ui->addressIn_VM->setFocus();
}
bool SignVerifyMessageDialog::eventFilter(QObject* object, QEvent* event)
{
if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn) {
if (ui->tabWidget->currentIndex() == 0) {
/* Clear status message on focus change */
ui->statusLabel_SM->clear();
/* Select generated signature */
if (object == ui->signatureOut_SM) {
ui->signatureOut_SM->selectAll();
return true;
}
} else if (ui->tabWidget->currentIndex() == 1) {
/* Clear status message on focus change */
ui->statusLabel_VM->clear();
}
}
return QDialog::eventFilter(object, event);
}
|
/*
* Copyright 2019 Xilinx, 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 Name : hls_ssr_fft_butterfly_traits.hpp
#ifndef HLS_SSR_FFT_BUTTERFLY_TRAITS_H_
#define HLS_SSR_FFT_BUTTERFLY_TRAITS_H_
#include <ap_fixed.h>
//#include <complex>
#include "vitis_fft/hls_ssr_fft_utilities.hpp"
#include "vitis_fft/hls_ssr_fft_enums.hpp"
#include "vitis_fft/hls_ssr_fft_dsp48.hpp"
#include "vitis_fft/fft_complex.hpp"
//#include "DEBUG_CONSTANTS.hpp"
/*
=========================================================================================
-_- -_-
-_- -_-
-_- -_-
-_- -_-
-_- -_-
-_- -_-
-_- Given the input type for accumulator the butterfly traits defines the output -_-
-_- type to be used for storing the output of accumulator based on the input type -_-
-_- and the scaling mode selected for accumulation. Three different scaling modes -_-
-_- are defined: -_-
-_- SSR_FFT_NO_SCALING : No scaling is done to prevent any overflows -_-
-_- bit growth is allowed every addition -_-
-_- SSR_FFT_SCALE : Scale the output by one bit ever binary -_-
-_- addition -_-
-_- SSR_FFT_GROW_TO_MAX_WIDTH : Initially the bit growth allowed until max -_-
-_- width reached and then scaling used after that -_-
-_- Note : m_butterflyType is defined for debug purposes only -_-
-_- -_-
-_- -_-
-_- -_-
-_- -_-
-_- -_-
-_- -_-
========================================================================================
*/
// Traits for Butterfly input and output
#define HLS_SSR_FFT_ENABLE_ADDER_TREE_SCALING
namespace vitis {
namespace dsp {
namespace fft {
#if 1
template <bool isFirtStage, typename T_in>
struct ButterflyTraitsDefault {
// typedef T_in T_butterflyAccumType;
// typedef T_in T_butterflyComplexRotatedType;
};
template <bool isFirtStage, scaling_mode_enum t_scalingMode, typename T_in>
struct ButterflyTraits : public ButterflyTraitsDefault<isFirtStage, T_in> {
static const int m_butterflyType = 0;
};
//=====================================================================================================
// Integer Type Butterfly Traits
//=====================================================================================================
template <bool isFirtStage, scaling_mode_enum t_scalingMode>
struct ButterflyTraits<isFirtStage, t_scalingMode, complex_wrapper<int> >
: public ButterflyTraitsDefault<isFirtStage, complex_wrapper<int> > {
typedef complex_wrapper<int> T_butterflyAccumType;
typedef complex_wrapper<int> T_butterflyComplexRotatedType;
static const int m_butterflyType = 10;
};
//=====================================================================================================
//=====================================================================================================
// double Type Butterfly Traits
//=====================================================================================================
template <bool isFirtStage, scaling_mode_enum t_scalingMode>
struct ButterflyTraits<isFirtStage, t_scalingMode, complex_wrapper<double> >
: public ButterflyTraitsDefault<isFirtStage, complex_wrapper<double> > {
typedef complex_wrapper<double> T_butterflyAccumType;
typedef complex_wrapper<double> T_butterflyComplexRotatedType;
static const int m_butterflyType = 20;
};
//=====================================================================================================
//=====================================================================================================
// float Type Butterfly Traits
//=====================================================================================================
template <bool isFirtStage, scaling_mode_enum t_scalingMode>
struct ButterflyTraits<isFirtStage, t_scalingMode, complex_wrapper<float> >
: public ButterflyTraitsDefault<isFirtStage, complex_wrapper<float> > {
typedef complex_wrapper<float> T_butterflyAccumType;
typedef complex_wrapper<float> T_butterflyComplexRotatedType;
static const int m_butterflyType = 30;
};
//=====================================================================================================
//=====================================================================================================
// ap_fixed Type Butterfly Traits : Generic scaling mode
//=====================================================================================================
template <bool isFirtStage, scaling_mode_enum t_scalingMode, int t_inputSizeBits, int t_integerPartBits>
struct ButterflyTraits<isFirtStage, t_scalingMode, complex_wrapper<ap_fixed<t_inputSizeBits, t_integerPartBits> > > {
typedef complex_wrapper<ap_fixed<t_inputSizeBits + 1, t_integerPartBits + 1, AP_TRN, AP_WRAP, 0> >
T_butterflyAccumType;
static const int COMPLEX_ROTATED_BIT_GROWTH = isFirtStage ? 1 : 0;
typedef complex_wrapper<
ap_fixed<t_inputSizeBits + 1, t_integerPartBits + COMPLEX_ROTATED_BIT_GROWTH, AP_TRN, AP_WRAP, 0> >
T_butterflyComplexRotatedType;
static const int m_butterflyType = 1;
};
//=====================================================================================================
//=====================================================================================================
// ap_fixed Type Butterfly Traits : SSR_FFT_NO_SCALING
//=====================================================================================================
template <bool isFirtStage, int t_inputSizeBits, int t_integerPartBits>
struct ButterflyTraits<isFirtStage,
SSR_FFT_NO_SCALING,
complex_wrapper<ap_fixed<t_inputSizeBits, t_integerPartBits> > > {
typedef complex_wrapper<ap_fixed<t_inputSizeBits + 1, t_integerPartBits + 1, AP_TRN, AP_WRAP, 0> >
T_butterflyAccumType;
static const int COMPLEX_ROTATED_BIT_GROWTH = isFirtStage ? 1 : 0;
typedef complex_wrapper<
ap_fixed<t_inputSizeBits + 1, t_integerPartBits + COMPLEX_ROTATED_BIT_GROWTH, AP_TRN, AP_WRAP, 0> >
T_butterflyComplexRotatedType;
static const int m_butterflyType = 2;
};
//=====================================================================================================
//=====================================================================================================
// ap_fixed Type Butterfly Traits : SSR_FFT_SCALE
//=====================================================================================================
template <bool isFirtStage, int t_inputSizeBits, int t_integerPartBits>
struct ButterflyTraits<isFirtStage, SSR_FFT_SCALE, complex_wrapper<ap_fixed<t_inputSizeBits, t_integerPartBits> > > {
#ifdef HLS_SSR_FFT_ENABLE_ADDER_TREE_SCALING
static const int BIT_GROWTH_WL = 0;
static const int BIT_GROWTH_IL = 1;
static const int OUTPUT_WL = ((t_inputSizeBits + BIT_GROWTH_WL) <= DSP48_OP2_BIT_WIDTH)
? (t_inputSizeBits + BIT_GROWTH_WL)
: DSP48_OP2_BIT_WIDTH;
static const int OUTPUT_IL =
((t_integerPartBits + BIT_GROWTH_IL) <= OUTPUT_WL) ? (t_integerPartBits + BIT_GROWTH_IL) : OUTPUT_WL;
#else
static const int BIT_GROWTH_WL = 1;
static const int BIT_GROWTH_IL = 1;
static const int OUTPUT_WL = (t_inputSizeBits + BIT_GROWTH_WL);
static const int OUTPUT_IL = (t_integerPartBits + BIT_GROWTH_IL);
#endif
typedef complex_wrapper<ap_fixed<OUTPUT_WL, OUTPUT_IL, AP_TRN, AP_WRAP, 0> > T_butterflyAccumType;
static const int COMPLEX_ROTATED_BIT_GROWTH = isFirtStage ? 1 : 0;
typedef complex_wrapper<
ap_fixed<t_inputSizeBits, t_integerPartBits + COMPLEX_ROTATED_BIT_GROWTH, AP_TRN, AP_WRAP, 0> >
T_butterflyComplexRotatedType;
static const int m_butterflyType = 3;
};
//=====================================================================================================
//=====================================================================================================
// ap_fixed Type Butterfly Traits : SSR_FFT_GROW_TO_MAX_WIDTH
//=====================================================================================================
template <bool isFirtStage, int t_inputSizeBits, int t_integerPartBits>
struct ButterflyTraits<isFirtStage,
SSR_FFT_GROW_TO_MAX_WIDTH,
complex_wrapper<ap_fixed<t_inputSizeBits, t_integerPartBits> > > {
// typedef ap_fixed<t_inputSizeBits,t_integerPartBits,AP_TRN,AP_WRAP,0> TTR_bflyProductType;
#ifdef HLS_SSR_FFT_ENABLE_ADDER_TREE_SCALING
static const int BIT_GROWTH_WL = 1;
static const int BIT_GROWTH_IL = 1;
static const int OUTPUT_WL = ((t_inputSizeBits + BIT_GROWTH_WL) <= DSP48_OP2_BIT_WIDTH)
? (t_inputSizeBits + BIT_GROWTH_WL)
: DSP48_OP2_BIT_WIDTH;
static const int OUTPUT_IL = ((t_integerPartBits + BIT_GROWTH_IL) <= DSP48_OP2_BIT_WIDTH)
? (t_integerPartBits + BIT_GROWTH_IL)
: DSP48_OP2_BIT_WIDTH;
#else
static const int BIT_GROWTH_WL = 1;
static const int BIT_GROWTH_IL = 1;
static const int OUTPUT_WL = (t_inputSizeBits + BIT_GROWTH_WL);
static const int OUTPUT_IL = (t_integerPartBits + BIT_GROWTH_IL);
#endif
typedef complex_wrapper<ap_fixed<OUTPUT_WL, OUTPUT_IL, AP_TRN, AP_WRAP, 0> > T_butterflyAccumType;
static const int COMPLEX_ROTATED_BIT_GROWTH = isFirtStage ? 1 : 0;
static const int GRWON_ROT_WL = COMPLEX_ROTATED_BIT_GROWTH + t_inputSizeBits;
static const int ROL_WL = (GRWON_ROT_WL <= DSP48_OP2_BIT_WIDTH) ? GRWON_ROT_WL : t_inputSizeBits;
static const int GRWON_ROT_IL = COMPLEX_ROTATED_BIT_GROWTH + t_integerPartBits;
static const int ROL_IL = (GRWON_ROT_IL <= DSP48_OP2_BIT_WIDTH) ? GRWON_ROT_IL : t_integerPartBits;
typedef complex_wrapper<ap_fixed<ROL_WL, ROL_IL, AP_TRN, AP_WRAP, 0> > T_butterflyComplexRotatedType;
static const int m_butterflyType = 4;
};
//=====================================================================================================
//=====================================================================================================
// ap_fixed Type Butterfly Traits : Generic with quantization and rounding mode input
//=====================================================================================================
template <bool isFirtStage,
scaling_mode_enum t_scalingMode,
int t_inputSizeBits,
int t_integerPartBits,
ap_q_mode Q,
ap_o_mode O,
int sat_bits>
struct ButterflyTraits<isFirtStage,
t_scalingMode,
complex_wrapper<ap_fixed<t_inputSizeBits, t_integerPartBits, Q, O, sat_bits> > > {
typedef complex_wrapper<ap_fixed<t_inputSizeBits + 1, t_integerPartBits + 1, Q, O, sat_bits> > T_butterflyAccumType;
static const int m_butterflyType = 5;
};
//=====================================================================================================
//=====================================================================================================
// ap_fixed Type Butterfly Traits : SSR_FFT_NO_SCALING with quantization and rounding mode input
//=====================================================================================================
template <bool isFirtStage, int t_inputSizeBits, int t_integerPartBits, ap_q_mode Q, ap_o_mode O, int sat_bits>
struct ButterflyTraits<isFirtStage,
SSR_FFT_NO_SCALING,
complex_wrapper<ap_fixed<t_inputSizeBits, t_integerPartBits, Q, O, sat_bits> > > {
static const int COMPLEX_ROTATED_BIT_GROWTH = isFirtStage ? 1 : 0;
typedef complex_wrapper<ap_fixed<t_inputSizeBits + 1, t_integerPartBits + 1, AP_TRN, AP_WRAP, 0> >
T_butterflyAccumType;
typedef complex_wrapper<ap_fixed<t_inputSizeBits + COMPLEX_ROTATED_BIT_GROWTH,
t_integerPartBits + COMPLEX_ROTATED_BIT_GROWTH,
AP_TRN,
AP_WRAP,
0> >
T_butterflyComplexRotatedType;
static const int m_butterflyType = 6;
};
//=====================================================================================================
//=====================================================================================================
// ap_fixed Type Butterfly Traits : SSR_FFT_SCALE with quantization and rounding mode input
//=====================================================================================================
template <bool isFirtStage, int t_inputSizeBits, int t_integerPartBits, ap_q_mode Q, ap_o_mode O, int sat_bits>
struct ButterflyTraits<isFirtStage,
SSR_FFT_SCALE,
complex_wrapper<ap_fixed<t_inputSizeBits, t_integerPartBits, Q, O, sat_bits> > > {
#ifdef HLS_SSR_FFT_ENABLE_ADDER_TREE_SCALING
static const int BIT_GROWTH_WL = 0;
static const int BIT_GROWTH_IL = 1;
static const int OUTPUT_WL = ((t_inputSizeBits + BIT_GROWTH_WL) <= DSP48_OP2_BIT_WIDTH)
? (t_inputSizeBits + BIT_GROWTH_WL)
: DSP48_OP2_BIT_WIDTH;
static const int OUTPUT_IL =
((t_integerPartBits + BIT_GROWTH_IL) <= OUTPUT_WL) ? (t_integerPartBits + BIT_GROWTH_IL) : OUTPUT_WL;
#else
static const int BIT_GROWTH_WL = 1;
static const int BIT_GROWTH_IL = 1;
static const int OUTPUT_WL = (t_inputSizeBits + BIT_GROWTH_WL);
static const int OUTPUT_IL = (t_integerPartBits + BIT_GROWTH_IL);
#endif
typedef complex_wrapper<ap_fixed<OUTPUT_WL, OUTPUT_IL, Q, O, sat_bits> > T_butterflyAccumType;
static const int COMPLEX_ROTATED_BIT_GROWTH = isFirtStage ? 1 : 0;
typedef complex_wrapper<
ap_fixed<t_inputSizeBits, t_integerPartBits + COMPLEX_ROTATED_BIT_GROWTH, AP_TRN, AP_WRAP, 0> >
T_butterflyComplexRotatedType;
static const int m_butterflyType = 7;
};
//=====================================================================================================
//=====================================================================================================
// ap_fixed Type Butterfly Traits : SSR_FFT_GROW_TO_MAX_WIDTH with quantization and rounding mode input
//=====================================================================================================
template <bool isFirtStage, int t_inputSizeBits, int t_integerPartBits, ap_q_mode Q, ap_o_mode O, int sat_bits>
struct ButterflyTraits<isFirtStage,
SSR_FFT_GROW_TO_MAX_WIDTH,
complex_wrapper<ap_fixed<t_inputSizeBits, t_integerPartBits, Q, O, sat_bits> > > {
#ifdef HLS_SSR_FFT_ENABLE_ADDER_TREE_SCALING
static const int BIT_GROWTH_WL = 1;
static const int BIT_GROWTH_IL = 1;
static const int OUTPUT_WL = ((t_inputSizeBits + BIT_GROWTH_WL) <= DSP48_OP2_BIT_WIDTH)
? (t_inputSizeBits + BIT_GROWTH_WL)
: DSP48_OP2_BIT_WIDTH;
static const int OUTPUT_IL = ((t_integerPartBits + BIT_GROWTH_IL) <= DSP48_OP2_BIT_WIDTH)
? (t_inputSizeBits + BIT_GROWTH_IL)
: DSP48_OP2_BIT_WIDTH;
#else
static const int OUTPUT_WL = (t_inputSizeBits + 1);
static const int OUTPUT_IL = (t_integerPartBits + 1);
#endif
typedef complex_wrapper<ap_fixed<OUTPUT_WL, OUTPUT_IL, Q, O, sat_bits> > T_butterflyAccumType;
static const int COMPLEX_ROTATED_BIT_GROWTH = isFirtStage ? 1 : 0;
static const int GRWON_ROT_WL = COMPLEX_ROTATED_BIT_GROWTH + t_inputSizeBits;
static const int ROL_WL = (GRWON_ROT_WL <= DSP48_OP2_BIT_WIDTH) ? GRWON_ROT_WL : t_inputSizeBits;
static const int GRWON_ROT_IL = COMPLEX_ROTATED_BIT_GROWTH + t_integerPartBits;
static const int ROL_IL = (GRWON_ROT_IL <= DSP48_OP2_BIT_WIDTH) ? GRWON_ROT_IL : t_integerPartBits;
typedef complex_wrapper<ap_fixed<ROL_WL, ROL_IL, AP_TRN, AP_WRAP, 0> > T_butterflyComplexRotatedType;
static const int m_butterflyType = 8;
};
//=====================================================================================================
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#endif
} // end namespace fft
} // end namespace dsp
} // end namespace vitis
#endif // HLS_SSR_FFT_BUTTERFLY_TRAITS_H_
|
//
// Copyright (c) 2020, 219 Design, LLC
// See LICENSE.txt
//
// https://www.219design.com
// Software | Electrical | Mechanical | Product Design
//
#include "resource_helper.h"
#include <QtQml/QQmlContext>
namespace project
{
namespace
{
ResourceHelper helper;
} // namespace
/*static*/ void ResourceHelper::ExportContextPropertiesToQml( QQmlEngine* engine )
{
engine->rootContext()->setContextProperty( "resourceHelper", &helper );
}
} // namespace project
|
#ifndef POSIX_TIME_DURATION_HPP___
#define POSIX_TIME_DURATION_HPP___
/* Copyright (c) 2002,2003 CrystalClear Software, Inc.
* Use, modification and distribution is subject to the
* Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
* Author: Jeff Garland
* $Date$
*/
#include <boost/core/enable_if.hpp>
#include <boost/date_time/compiler_config.hpp>
#include <boost/date_time/posix_time/posix_time_config.hpp>
#include <boost/numeric/conversion/cast.hpp>
#include <boost/type_traits/is_integral.hpp>
namespace boost {
namespace posix_time {
//! Allows expression of durations as an hour count
//! The argument must be an integral type
/*! \ingroup time_basics
*/
class BOOST_SYMBOL_VISIBLE hours : public time_duration
{
public:
template <typename T>
explicit hours(T const& h,
typename boost::enable_if<boost::is_integral<T>, void>::type* = 0) :
time_duration(numeric_cast<hour_type>(h), 0, 0)
{}
};
//! Allows expression of durations as a minute count
//! The argument must be an integral type
/*! \ingroup time_basics
*/
class BOOST_SYMBOL_VISIBLE minutes : public time_duration
{
public:
template <typename T>
explicit minutes(T const& m,
typename boost::enable_if<boost::is_integral<T>, void>::type* = 0) :
time_duration(0, numeric_cast<min_type>(m),0)
{}
};
//! Allows expression of durations as a seconds count
//! The argument must be an integral type
/*! \ingroup time_basics
*/
class BOOST_SYMBOL_VISIBLE seconds : public time_duration
{
public:
template <typename T>
explicit seconds(T const& s,
typename boost::enable_if<boost::is_integral<T>, void>::type* = 0) :
time_duration(0,0, numeric_cast<sec_type>(s))
{}
};
//! Allows expression of durations as milli seconds
/*! \ingroup time_basics
*/
typedef date_time::subsecond_duration<time_duration,1000> millisec;
typedef date_time::subsecond_duration<time_duration,1000> milliseconds;
//! Allows expression of durations as micro seconds
/*! \ingroup time_basics
*/
typedef date_time::subsecond_duration<time_duration,1000000> microsec;
typedef date_time::subsecond_duration<time_duration,1000000> microseconds;
//This is probably not needed anymore...
#if defined(BOOST_DATE_TIME_HAS_NANOSECONDS)
//! Allows expression of durations as nano seconds
/*! \ingroup time_basics
*/
typedef date_time::subsecond_duration<time_duration,1000000000> nanosec;
typedef date_time::subsecond_duration<time_duration,1000000000> nanoseconds;
#endif
} }//namespace posix_time
#endif
|
/*=========================================================================
Program: ParaView
Module: vtkPVHistogramChartRepresentation.cxx
Copyright (c) Kitware, Inc.
All rights reserved.
See Copyright.txt or http://www.paraview.org/HTML/Copyright.html 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 "vtkPVHistogramChartRepresentation.h"
#include "vtkAnnotationLink.h"
#include "vtkAxis.h"
#include "vtkChartXY.h"
#include "vtkCommand.h"
#include "vtkCompositeDataIterator.h"
#include "vtkCompositeDataSet.h"
#include "vtkContextView.h"
#include "vtkDataArray.h"
#include "vtkDoubleArray.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkNew.h"
#include "vtkObjectFactory.h"
#include "vtkPExtractHistogram.h"
#include "vtkPVContextView.h"
#include "vtkSelection.h"
#include "vtkSelectionNode.h"
#include "vtkTable.h"
#include <cmath>
static const char* BIN_EXTENTS = "bin_extents";
static const char* BIN_VALUES = "bin_values";
namespace
{
template <class T>
T vtkRound(double value)
{
return static_cast<T>(std::floor(value + 0.5));
}
}
vtkStandardNewMacro(vtkPVHistogramChartRepresentation);
//----------------------------------------------------------------------------
vtkPVHistogramChartRepresentation::vtkPVHistogramChartRepresentation()
{
this->ExtractHistogram = vtkPExtractHistogram::New();
this->SetChartTypeToBar();
this->SetUseIndexForXAxis(false);
this->SetXAxisSeriesName(BIN_EXTENTS);
this->SetSeriesVisibility(BIN_VALUES, true);
this->SetFieldAssociation(vtkDataObject::FIELD_ASSOCIATION_ROWS);
this->SetHistogramColor(0, 0, 255);
this->AttributeType = vtkDataObject::POINT;
}
//----------------------------------------------------------------------------
vtkPVHistogramChartRepresentation::~vtkPVHistogramChartRepresentation()
{
if (this->ExtractHistogram)
{
this->ExtractHistogram->Delete();
}
}
//----------------------------------------------------------------------------
void vtkPVHistogramChartRepresentation::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
//----------------------------------------------------------------------------
void vtkPVHistogramChartRepresentation::SetBinCount(int bins)
{
if (this->ExtractHistogram->GetBinCount() != bins)
{
this->ExtractHistogram->SetBinCount(bins);
this->MarkModified();
}
}
//----------------------------------------------------------------------------
int vtkPVHistogramChartRepresentation::GetBinCount()
{
return this->ExtractHistogram->GetBinCount();
}
//----------------------------------------------------------------------------
void vtkPVHistogramChartRepresentation::SetUseCustomBinRanges(bool b)
{
if (this->ExtractHistogram->GetUseCustomBinRanges() != b)
{
this->ExtractHistogram->SetUseCustomBinRanges(b);
this->MarkModified();
}
}
//----------------------------------------------------------------------------
bool vtkPVHistogramChartRepresentation::GetUseCustomBinRanges()
{
return this->ExtractHistogram->GetUseCustomBinRanges();
}
//----------------------------------------------------------------------------
void vtkPVHistogramChartRepresentation::SetCustomBinRanges(double min, double max)
{
double curRanges[2];
this->ExtractHistogram->GetCustomBinRanges(curRanges);
if (curRanges[0] != min || curRanges[1] != max)
{
this->ExtractHistogram->SetCustomBinRanges(min, max);
this->MarkModified();
}
}
//----------------------------------------------------------------------------
double* vtkPVHistogramChartRepresentation::GetCustomBinRanges()
{
return this->ExtractHistogram->GetCustomBinRanges();
}
//----------------------------------------------------------------------------
void vtkPVHistogramChartRepresentation::SetComponent(int c)
{
if (this->ExtractHistogram->GetComponent() != c)
{
this->ExtractHistogram->SetComponent(c);
this->MarkModified();
}
}
//----------------------------------------------------------------------------
int vtkPVHistogramChartRepresentation::GetComponent()
{
return this->ExtractHistogram->GetComponent();
}
//----------------------------------------------------------------------------
void vtkPVHistogramChartRepresentation::SetHistogramColor(double r, double g, double b)
{
this->SetColor(BIN_VALUES, r, g, b);
}
//----------------------------------------------------------------------------
void vtkPVHistogramChartRepresentation::SetUseColorMapping(bool colorMapping)
{
this->vtkXYChartRepresentation::SetUseColorMapping(BIN_VALUES, colorMapping);
}
//----------------------------------------------------------------------------
void vtkPVHistogramChartRepresentation::SetLookupTable(vtkScalarsToColors* lut)
{
this->vtkXYChartRepresentation::SetLookupTable(BIN_VALUES, lut);
}
//----------------------------------------------------------------------------
void vtkPVHistogramChartRepresentation::SetHistogramLineStyle(int val)
{
this->SetLineStyle(BIN_VALUES, val);
}
//----------------------------------------------------------------------------
vtkDataObject* vtkPVHistogramChartRepresentation::TransformInputData(
vtkInformationVector** vtkNotUsed(inputVector), vtkDataObject* data)
{
// NOTE: This method gets called in RequestData() and only on
// the server-side, so avoid doing anything that modifies the MTime.
if (this->ArrayName.empty())
{
return NULL;
}
this->ExtractHistogram->SetInputArrayToProcess(
0, 0, 0, this->AttributeType, this->ArrayName.c_str());
this->ExtractHistogram->CalculateAveragesOff();
this->ExtractHistogram->SetInputData(data);
this->ExtractHistogram->Update();
return this->ExtractHistogram->GetOutputDataObject(0);
}
//----------------------------------------------------------------------------
void vtkPVHistogramChartRepresentation::PrepareForRendering()
{
this->Superclass::PrepareForRendering();
vtkChartXY* chart = this->GetChart();
chart->SetBarWidthFraction(1.0);
vtkAxis* axis = chart->GetAxis(vtkAxis::LEFT);
axis->SetMinimum(0);
axis->SetMinimumLimit(0);
}
//----------------------------------------------------------------------------
bool vtkPVHistogramChartRepresentation::MapSelectionToInput(vtkSelection* sel)
{
assert(sel != NULL);
// Now we do the magic: convert chart row selection to threshold selection
vtkNew<vtkDoubleArray> selRanges;
selRanges->SetName(this->ArrayName.c_str());
selRanges->SetNumberOfComponents(1);
vtkTable* table = this->GetLocalOutput();
vtkDoubleArray* binExtents = vtkDoubleArray::SafeDownCast(table->GetColumnByName(BIN_EXTENTS));
double delta = 1.;
if (binExtents->GetNumberOfTuples() >= 2)
{
delta = (binExtents->GetValue(1) - binExtents->GetValue(0)) * 0.5;
}
vtkIdType nbNodes = sel->GetNumberOfNodes();
for (vtkIdType i = 0; i < nbNodes; i++)
{
vtkSelectionNode* node = sel->GetNode(i);
vtkDataArray* selRows = vtkDataArray::SafeDownCast(node->GetSelectionList());
if (selRows)
{
vtkIdType nbRows = selRows->GetNumberOfTuples();
for (vtkIdType j = 0; j < nbRows; j++)
{
// FIXME: make this smart to collapse adjacent bins and specify a
// single range instead of multiple ones. That'll be faster to execute.
vtkIdType row = (vtkIdType)selRows->GetTuple1(j);
double binExtent = binExtents->GetValue(row);
selRanges->InsertNextTuple1(binExtent - delta);
selRanges->InsertNextTuple1(binExtent + delta);
}
}
}
// Construct threshold selection on input
vtkNew<vtkSelection> newSel;
vtkNew<vtkSelectionNode> selNode;
selNode->SetContentType(vtkSelectionNode::THRESHOLDS);
selNode->SetFieldType(
vtkSelectionNode::ConvertAttributeTypeToSelectionField(this->AttributeType));
newSel->AddNode(selNode.Get());
selNode->SetSelectionList(selRanges.Get());
sel->ShallowCopy(newSel.GetPointer());
return true;
}
//----------------------------------------------------------------------------
bool vtkPVHistogramChartRepresentation::MapSelectionToView(vtkSelection* sel)
{
assert(sel != NULL);
// For vtkPVHistogramChartRepresentation (in the ServerManagerConfiguration
// xml), we set the SelectionRepresentation up so that the original input
// selection is passed to the vtkChartSelectionRepresentation rather than the
// id-based selection. Here, we see if the sel is of type
// vtkSelection::THRESHOLDS and if so, are the thresholds applicable to the
// bins we are showing.
// build a list of vtkSelectionNode instances that are potentially relevant.
int fieldType = vtkSelectionNode::ConvertAttributeTypeToSelectionField(this->AttributeType);
std::vector<vtkSmartPointer<vtkSelectionNode> > nodes;
for (unsigned int cc = 0, max = sel->GetNumberOfNodes(); cc < max; ++cc)
{
vtkSelectionNode* node = sel->GetNode(cc);
if (node && node->GetFieldType() == fieldType &&
node->GetContentType() == vtkSelectionNode::THRESHOLDS && node->GetSelectionList() != NULL &&
node->GetSelectionList()->GetName() != NULL &&
this->ArrayName == node->GetSelectionList()->GetName() &&
node->GetSelectionList()->GetNumberOfTuples() > 0)
{
// potentially applicable selection node.
nodes.push_back(node);
}
}
sel->RemoveAllNodes();
if (nodes.size() == 0)
{
return true;
}
// now, check if the thresholds are applicable to the histogram being shown.
vtkTable* table = this->GetLocalOutput();
vtkDoubleArray* binExtents =
table ? vtkDoubleArray::SafeDownCast(table->GetColumnByName(BIN_EXTENTS)) : NULL;
if (binExtents == NULL)
{
// Seems like the vtkPVHistogramChartRepresentation hasn't updated yet and
// the selection is being updated before it. Shouldn't happen, but let's
// handle it.
return false;
}
double delta = 1.;
if (binExtents->GetNumberOfTuples() >= 2)
{
delta = (binExtents->GetValue(1) - binExtents->GetValue(0));
}
const double halfDelta = delta / 2.0;
double dataRange[2];
binExtents->GetRange(dataRange); // this is range of bin-midpoints.
double episilon = delta * 1e-5; // we make this a factor of the delta.
std::set<vtkIdType> selectedBins;
for (size_t cc = 0; cc < nodes.size(); cc++)
{
vtkSelectionNode* node = nodes[cc];
vtkDoubleArray* selectionList = vtkDoubleArray::SafeDownCast(node->GetSelectionList());
for (vtkIdType j = 0; (j + 1) < selectionList->GetNumberOfTuples(); j += 2)
{
double range[2] = { selectionList->GetValue(j), selectionList->GetValue(j + 1) };
// since range is bin-range, convert that to bin-mid-points based range.
range[0] += halfDelta;
range[1] -= halfDelta;
// now get the bin index for this range.
vtkIdType index[2];
index[0] = vtkRound<vtkIdType>((range[0] - dataRange[0]) / delta);
index[1] = vtkRound<vtkIdType>((range[1] - dataRange[0]) / delta);
// now only accept the range if it nearly matches the bins
if (index[0] >= 0 && index[0] < binExtents->GetNumberOfTuples() &&
std::abs(range[0] - binExtents->GetValue(index[0])) < episilon && index[1] >= 0 &&
index[1] < binExtents->GetNumberOfTuples() &&
std::abs(range[1] - binExtents->GetValue(index[1])) < episilon)
{
for (vtkIdType i = index[0]; i <= index[1]; ++i)
{
selectedBins.insert(i);
}
}
}
}
vtkNew<vtkSelectionNode> node;
node->SetContentType(vtkSelectionNode::INDICES);
node->SetFieldType(vtkSelectionNode::POINT);
vtkNew<vtkIdTypeArray> convertedSelectionList;
convertedSelectionList->SetNumberOfTuples(static_cast<vtkIdType>(selectedBins.size()));
if (selectedBins.size())
{
std::copy(selectedBins.begin(), selectedBins.end(), convertedSelectionList->GetPointer(0));
}
node->SetSelectionList(convertedSelectionList.GetPointer());
sel->AddNode(node.GetPointer());
return true;
}
//----------------------------------------------------------------------------
void vtkPVHistogramChartRepresentation::SetInputArrayToProcess(
int idx, int port, int connection, int fieldAssociation, const char* name)
{
this->Superclass::SetInputArrayToProcess(idx, port, connection, fieldAssociation, name);
if (this->AttributeType != fieldAssociation)
{
this->AttributeType = fieldAssociation;
this->MarkModified();
}
std::string arrayName(name ? name : "");
if (this->ArrayName != name)
{
this->ArrayName = name;
this->SetLabel(BIN_VALUES, this->ArrayName.c_str());
this->MarkModified();
}
}
|
// 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 "webkit/tools/test_shell/test_shell_webkit_init.h"
#include "base/metrics/stats_counters.h"
#include "base/path_service.h"
#include "media/base/media.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebCache.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDatabase.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebRuntimeFeatures.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebScriptController.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityPolicy.h"
#include "ui/gl/gl_bindings_skia_in_process.h"
#include "v8/include/v8.h"
#include "webkit/plugins/npapi/plugin_list.h"
#include "webkit/plugins/webplugininfo.h"
#include "webkit/tools/test_shell/simple_socket_stream_bridge.h"
#include "webkit/tools/test_shell/test_shell.h"
#if defined(OS_WIN)
#include "webkit/tools/test_shell/test_shell_webthemeengine.h"
#endif
TestShellWebKitInit::TestShellWebKitInit(bool layout_test_mode)
: real_clipboard_(&clipboard_client_) {
v8::V8::SetCounterFunction(base::StatsTable::FindLocation);
WebKit::initialize(this);
WebKit::setLayoutTestMode(layout_test_mode);
WebKit::WebSecurityPolicy::registerURLSchemeAsLocal(
WebKit::WebString::fromUTF8("test-shell-resource"));
WebKit::WebSecurityPolicy::registerURLSchemeAsNoAccess(
WebKit::WebString::fromUTF8("test-shell-resource"));
WebKit::WebScriptController::enableV8SingleThreadMode();
WebKit::WebRuntimeFeatures::enableSockets(true);
WebKit::WebRuntimeFeatures::enableApplicationCache(true);
WebKit::WebRuntimeFeatures::enableDatabase(true);
WebKit::WebRuntimeFeatures::enableNotifications(true);
WebKit::WebRuntimeFeatures::enableTouch(true);
WebKit::WebRuntimeFeatures::enableIndexedDatabase(true);
WebKit::WebRuntimeFeatures::enableSpeechInput(true);
WebKit::WebRuntimeFeatures::enableFileSystem(true);
// TODO(hwennborg): Enable this once the implementation supports it.
WebKit::WebRuntimeFeatures::enableDeviceMotion(false);
WebKit::WebRuntimeFeatures::enableDeviceOrientation(true);
// Enable experimental I18N API for testing.
WebKit::WebRuntimeFeatures::enableJavaScriptI18NAPI(true);
// Load libraries for media and enable the media player.
base::FilePath module_path;
WebKit::WebRuntimeFeatures::enableMediaPlayer(
PathService::Get(base::DIR_MODULE, &module_path) &&
media::InitializeMediaLibrary(module_path));
WebKit::WebRuntimeFeatures::enableGeolocation(true);
// Construct and initialize an appcache system for this scope.
// A new empty temp directory is created to house any cached
// content during the run. Upon exit that directory is deleted.
// If we can't create a tempdir, we'll use in-memory storage.
if (!appcache_dir_.CreateUniqueTempDir()) {
LOG(WARNING) << "Failed to create a temp dir for the appcache, "
"using in-memory storage.";
DCHECK(appcache_dir_.path().empty());
}
SimpleAppCacheSystem::InitializeOnUIThread(appcache_dir_.path());
WebKit::WebDatabase::setObserver(&database_system_);
blob_registry_ = new TestShellWebBlobRegistryImpl();
file_utilities_.set_sandbox_enabled(false);
// Restrict the supported media types when running in layout test mode.
if (layout_test_mode)
mime_registry_.reset(new TestShellWebMimeRegistryImpl());
else
mime_registry_.reset(new webkit_glue::SimpleWebMimeRegistryImpl());
#if defined(OS_WIN)
// Ensure we pick up the default theme engine.
SetThemeEngine(NULL);
#endif
}
TestShellWebKitInit::~TestShellWebKitInit() {
if (RunningOnValgrind())
WebKit::WebCache::clear();
WebKit::shutdown();
}
WebKit::WebMimeRegistry* TestShellWebKitInit::mimeRegistry() {
return mime_registry_.get();
}
WebKit::WebClipboard* TestShellWebKitInit::clipboard() {
// Mock out clipboard calls in layout test mode so that tests don't mess
// with each other's copies/pastes when running in parallel.
if (TestShell::layout_test_mode()) {
return &mock_clipboard_;
} else {
return &real_clipboard_;
}
}
WebKit::WebFileUtilities* TestShellWebKitInit::fileUtilities() {
return &file_utilities_;
}
WebKit::WebSandboxSupport* TestShellWebKitInit::sandboxSupport() {
return NULL;
}
WebKit::WebCookieJar* TestShellWebKitInit::cookieJar() {
return &cookie_jar_;
}
WebKit::WebBlobRegistry* TestShellWebKitInit::blobRegistry() {
return blob_registry_.get();
}
WebKit::WebFileSystem* TestShellWebKitInit::fileSystem() {
return &file_system_;
}
bool TestShellWebKitInit::sandboxEnabled() {
return true;
}
WebKit::Platform::FileHandle
TestShellWebKitInit::databaseOpenFile(
const WebKit::WebString& vfs_file_name, int desired_flags) {
return SimpleDatabaseSystem::GetInstance()->OpenFile(
vfs_file_name, desired_flags);
}
int TestShellWebKitInit::databaseDeleteFile(
const WebKit::WebString& vfs_file_name,
bool sync_dir) {
return SimpleDatabaseSystem::GetInstance()->DeleteFile(
vfs_file_name, sync_dir);
}
long TestShellWebKitInit::databaseGetFileAttributes(
const WebKit::WebString& vfs_file_name) {
return SimpleDatabaseSystem::GetInstance()->GetFileAttributes(
vfs_file_name);
}
long long TestShellWebKitInit::databaseGetFileSize(
const WebKit::WebString& vfs_file_name) {
return SimpleDatabaseSystem::GetInstance()->GetFileSize(vfs_file_name);
}
long long TestShellWebKitInit::databaseGetSpaceAvailableForOrigin(
const WebKit::WebString& origin_identifier) {
return SimpleDatabaseSystem::GetInstance()->GetSpaceAvailable(
origin_identifier);
}
unsigned long long TestShellWebKitInit::visitedLinkHash(
const char* canonicalURL,
size_t length) {
return 0;
}
bool TestShellWebKitInit::isLinkVisited(unsigned long long linkHash) {
return false;
}
WebKit::WebMessagePortChannel* TestShellWebKitInit::createMessagePortChannel() {
return NULL;
}
void TestShellWebKitInit::prefetchHostName(const WebKit::WebString&) {
}
WebKit::WebData TestShellWebKitInit::loadResource(const char* name) {
if (!strcmp(name, "deleteButton")) {
// Create a red 30x30 square.
const char red_square[] =
"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52"
"\x00\x00\x00\x1e\x00\x00\x00\x1e\x04\x03\x00\x00\x00\xc9\x1e\xb3"
"\x91\x00\x00\x00\x30\x50\x4c\x54\x45\x00\x00\x00\x80\x00\x00\x00"
"\x80\x00\x80\x80\x00\x00\x00\x80\x80\x00\x80\x00\x80\x80\x80\x80"
"\x80\xc0\xc0\xc0\xff\x00\x00\x00\xff\x00\xff\xff\x00\x00\x00\xff"
"\xff\x00\xff\x00\xff\xff\xff\xff\xff\x7b\x1f\xb1\xc4\x00\x00\x00"
"\x09\x70\x48\x59\x73\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a"
"\x9c\x18\x00\x00\x00\x17\x49\x44\x41\x54\x78\x01\x63\x98\x89\x0a"
"\x18\x50\xb9\x33\x47\xf9\xa8\x01\x32\xd4\xc2\x03\x00\x33\x84\x0d"
"\x02\x3a\x91\xeb\xa5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60"
"\x82";
return WebKit::WebData(red_square, arraysize(red_square));
}
return webkit_glue::WebKitPlatformSupportImpl::loadResource(name);
}
WebKit::WebString TestShellWebKitInit::queryLocalizedString(
WebKit::WebLocalizedString::Name name) {
switch (name) {
case WebKit::WebLocalizedString::ValidationValueMissing:
case WebKit::WebLocalizedString::ValidationValueMissingForCheckbox:
case WebKit::WebLocalizedString::ValidationValueMissingForFile:
case WebKit::WebLocalizedString::ValidationValueMissingForMultipleFile:
case WebKit::WebLocalizedString::ValidationValueMissingForRadio:
case WebKit::WebLocalizedString::ValidationValueMissingForSelect:
return ASCIIToUTF16("value missing");
case WebKit::WebLocalizedString::ValidationTypeMismatch:
case WebKit::WebLocalizedString::ValidationTypeMismatchForEmail:
case WebKit::WebLocalizedString::ValidationTypeMismatchForMultipleEmail:
case WebKit::WebLocalizedString::ValidationTypeMismatchForURL:
return ASCIIToUTF16("type mismatch");
case WebKit::WebLocalizedString::ValidationPatternMismatch:
return ASCIIToUTF16("pattern mismatch");
case WebKit::WebLocalizedString::ValidationTooLong:
return ASCIIToUTF16("too long");
case WebKit::WebLocalizedString::ValidationRangeUnderflow:
return ASCIIToUTF16("range underflow");
case WebKit::WebLocalizedString::ValidationRangeOverflow:
return ASCIIToUTF16("range overflow");
case WebKit::WebLocalizedString::ValidationStepMismatch:
return ASCIIToUTF16("step mismatch");
default:
return WebKitPlatformSupportImpl::queryLocalizedString(name);
}
}
WebKit::WebString TestShellWebKitInit::queryLocalizedString(
WebKit::WebLocalizedString::Name name, const WebKit::WebString& value) {
if (name == WebKit::WebLocalizedString::ValidationRangeUnderflow)
return ASCIIToUTF16("range underflow");
if (name == WebKit::WebLocalizedString::ValidationRangeOverflow)
return ASCIIToUTF16("range overflow");
return WebKitPlatformSupportImpl::queryLocalizedString(name, value);
}
WebKit::WebString TestShellWebKitInit::queryLocalizedString(
WebKit::WebLocalizedString::Name name,
const WebKit::WebString& value1,
const WebKit::WebString& value2) {
if (name == WebKit::WebLocalizedString::ValidationTooLong)
return ASCIIToUTF16("too long");
if (name == WebKit::WebLocalizedString::ValidationStepMismatch)
return ASCIIToUTF16("step mismatch");
return WebKitPlatformSupportImpl::queryLocalizedString(name, value1, value2);
}
WebKit::WebString TestShellWebKitInit::defaultLocale() {
return ASCIIToUTF16("en-US");
}
WebKit::WebStorageNamespace* TestShellWebKitInit::createLocalStorageNamespace(
const WebKit::WebString& path, unsigned quota) {
return dom_storage_system_.CreateLocalStorageNamespace();
}
WebKit::WebIDBFactory* TestShellWebKitInit::idbFactory() {
return WebKit::WebIDBFactory::create();
}
WebKit::WebGraphicsContext3D*
TestShellWebKitInit::createOffscreenGraphicsContext3D(
const WebKit::WebGraphicsContext3D::Attributes& attributes) {
return webkit::gpu::WebGraphicsContext3DInProcessImpl::CreateForWebView(
attributes, false);
}
void TestShellWebKitInit::GetPlugins(
bool refresh, std::vector<webkit::WebPluginInfo>* plugins) {
if (refresh)
webkit::npapi::PluginList::Singleton()->RefreshPlugins();
webkit::npapi::PluginList::Singleton()->GetPlugins(plugins);
// Don't load the forked TestNetscapePlugIn in the chromium code, use
// the copy in webkit.org's repository instead.
const base::FilePath::StringType kPluginBlackList[] = {
FILE_PATH_LITERAL("npapi_layout_test_plugin.dll"),
FILE_PATH_LITERAL("WebKitTestNetscapePlugIn.plugin"),
FILE_PATH_LITERAL("libnpapi_layout_test_plugin.so"),
};
for (int i = plugins->size() - 1; i >= 0; --i) {
webkit::WebPluginInfo plugin_info = plugins->at(i);
for (size_t j = 0; j < arraysize(kPluginBlackList); ++j) {
if (plugin_info.path.BaseName() == base::FilePath(kPluginBlackList[j])) {
plugins->erase(plugins->begin() + i);
}
}
}
}
webkit_glue::ResourceLoaderBridge*
TestShellWebKitInit::CreateResourceLoader(
const webkit_glue::ResourceLoaderBridge::RequestInfo& request_info) {
return SimpleResourceLoaderBridge::Create(request_info);
}
webkit_glue::WebSocketStreamHandleBridge*
TestShellWebKitInit::CreateWebSocketBridge(
WebKit::WebSocketStreamHandle* handle,
webkit_glue::WebSocketStreamHandleDelegate* delegate) {
return SimpleSocketStreamBridge::Create(handle, delegate);
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Crowncoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcserver.h"
#include "rpcclient.h"
#include "init.h"
#include <boost/algorithm/string/predicate.hpp>
void DetectShutdownThread(boost::thread_group* threadGroup)
{
bool shutdown = ShutdownRequested();
// Tell the main threads to shutdown.
while (!shutdown)
{
MilliSleep(200);
shutdown = ShutdownRequested();
}
if (threadGroup)
threadGroup->interrupt_all();
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
bool AppInit(int argc, char* argv[])
{
boost::thread_group threadGroup;
boost::thread* detectShutdownThread = NULL;
bool fRet = false;
try
{
//
// Parameters
//
// If Qt is used, parameters/Crowncoin.conf are parsed in qt/Crowncoin.cpp's main()
ParseParameters(argc, argv);
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified directory does not exist\n");
Shutdown();
}
ReadConfigFile(mapArgs, mapMultiArgs);
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
// First part of help message is specific to Crowncoind / RPC client
std::string strUsage = _("Crowncoin version") + " " + FormatFullVersion() + "\n\n" +
_("Usage:") + "\n" +
" Crowncoind [options] " + "\n" +
" Crowncoind [options] <command> [params] " + _("Send command to -server or Crowncoind") + "\n" +
" Crowncoind [options] help " + _("List commands") + "\n" +
" Crowncoind [options] help <command> " + _("Get help for a command") + "\n";
strUsage += "\n" + HelpMessage(HMM_BITCOIND);
strUsage += "\n" + HelpMessageCli(false);
fprintf(stdout, "%s", strUsage.c_str());
return false;
}
// Command-line RPC
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "Crowncoin:") && !boost::algorithm::istarts_with(argv[i], "ppcoin:"))
fCommandLine = true;
if (fCommandLine)
{
int ret = CommandLineRPC(argc, argv);
exit(ret);
}
#if !defined(WIN32)
fDaemon = GetBoolArg("-daemon", false);
if (fDaemon)
{
// Daemonize
pid_t pid = fork();
if (pid < 0)
{
fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
return false;
}
if (pid > 0) // Parent process, pid is child process id
{
CreatePidFile(GetPidFile(), pid);
return true;
}
// Child process falls through to rest of initialization
pid_t sid = setsid();
if (sid < 0)
fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
}
#endif
detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup));
fRet = AppInit2(threadGroup);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "AppInit()");
} catch (...) {
PrintExceptionContinue(NULL, "AppInit()");
}
if (!fRet) {
if (detectShutdownThread)
detectShutdownThread->interrupt();
threadGroup.interrupt_all();
}
if (detectShutdownThread)
{
detectShutdownThread->join();
delete detectShutdownThread;
detectShutdownThread = NULL;
}
Shutdown();
return fRet;
}
extern void noui_connect();
int main(int argc, char* argv[])
{
bool fRet = false;
// Connect Crowncoind signal handlers
noui_connect();
fRet = AppInit(argc, argv);
if (fRet && fDaemon)
return 0;
return (fRet ? 0 : 1);
}
|
#include <memory>
#include <cstring>
#include "trop.h"
//=======================================================================
class HalfCord
{
std::unique_ptr<int[]> m_array;
int m_radius;
public:
HalfCord(int radius)
: m_radius(radius)
, m_array(new int[radius + 1])
{
assert(radius >= 0);
memset(m_array.get(), 0, (m_radius + 1) * sizeof(int));
float dCircle = 1.25f - m_radius; // inizializza decision variable
int y = m_radius; // inizializzazione indice scanline
int x = 0; // inizializzazione indice colonna
do {
m_array[y] = tmax(x, m_array[y]);
m_array[x] = y;
if (dCircle <= 0) {
dCircle = dCircle + 2 * x + 3;
} else {
y--;
dCircle = dCircle + 2 * (x - y) + 5;
}
x++;
} while (y >= x);
}
inline int getCord(int x)
{
assert(0 <= x && x <= m_radius);
return m_array[x];
};
private:
// not implemented
HalfCord(const HalfCord &);
HalfCord &operator=(const HalfCord &);
};
//=======================================================================
void TRop::brush(
TRaster32P ras,
const TPoint &aa,
const TPoint &bb,
int radius,
const TPixel32 &col)
{
TPoint a = aa;
TPoint b = bb;
if (a.y > b.y)
tswap(a, b); // a e' piu' in basso di b
int lx = ras->getLx();
int ly = ras->getLy();
ras->lock();
// ----- radius = 0
if (radius == 0) {
// k = +1/-1 se il rettangolo e' inclinato positivamente (0<=m)/negativamente (m<0)
// (se k<0 viene fatta una riflessione sulle ascisse prima di tornare alle
// coordinate "di schermo")
int k = 1;
int dy = b.y - a.y;
int dx = b.x - a.x;
if (dx < 0) {
dx = -dx;
k = -1;
}
assert(dx >= 0);
assert(dy >= 0);
double m; // m sara' definita solo per dx!=0)
if (dx > 0) {
m = dy / (double)dx;
}
//double length = sqrt(dx*dx + dy*dy);
const int alpha = dy, beta = -dx;
const int incE = alpha;
const int incNE = alpha + beta;
const int incN = beta;
// N.B. le coordinate sono relative ad un sist. di rif. con l'origine in a
// l'eq. della retta e' alpha * x + beta * y = 0
int yMin = tmax(a.y, 0) - a.y; // clipping y + cambio riferimento
int yMax = tmin(b.y, ly - 1) - a.y; // (trasporto dell'origine in a)
if (dx > 0 && m <= 1) {
// midpoint algorithm
TPoint segm;
if (dy == 0) // segmento orizzontale: inizializza segm
{
segm.x = 0;
segm.y = yMin;
} else // 0<m<=1 : inizializza segm
{
segm.x = tceil((yMin - 0.5) / m);
segm.y = yMin;
}
int dSegm = tfloor(alpha * (segm.x + 1) + beta * (segm.y + 0.5));
while (segm.y <= yMax) {
int count = 0; // i trati orizzontali di segm vengono disegnati in "blocco"
while (dSegm < 0 && segm.x <= dx) // Est: segm.x<=dx evita il ciclo
{ // infinito quando m=0 (incE=0)
dSegm = dSegm + incE;
segm.x++;
count++;
}
// NordEst
int xMin, xMax;
if (k > 0) {
xMin = tmax(a.x + segm.x - count, a.x, 0); // clipping x + ritorno alle
xMax = tmin(a.x + segm.x, b.x, lx - 1); // coordinate "di schermo"
} else {
xMin = tmax(a.x - segm.x, a.x - dx, 0); // clipping x + riflessione + ritorno
xMax = tmin(a.x - segm.x + count, a.x, lx - 1); // alle coordinate "di schermo"
}
TPixel32 *p = ras->pixels(segm.y + a.y) + xMin;
TPixel32 *q = p + (xMax - xMin);
while (p <= q)
*p++ = col;
dSegm = dSegm + incNE;
segm.x++;
segm.y++;
}
} else // m>1 oppure segmento verticale
{
// midpoint algorithm
TPoint segm;
if (dx == 0) // segmento verticale: inizializza segm
{
segm.x = 0;
segm.y = yMin;
} else // m>1 : inizializza segm
{
segm.x = tround(yMin / m);
segm.y = yMin;
}
int dSegm = tfloor(alpha * (segm.x + 0.5) + beta * (segm.y + 1));
while (segm.y <= yMax) {
int xMin, xMax;
if (k > 0) {
xMin = tmax(a.x + segm.x, 0); // clipping x + ritorno alle
xMax = tmin(a.x + segm.x, lx - 1); // coordinate "di schermo"
} else {
xMin = tmax(a.x - segm.x, 0); // clipping x + riflessione + ritorno
xMax = tmin(a.x - segm.x, lx - 1); // alle coordinate "di schermo"
}
TPixel32 *p = ras->pixels(segm.y + a.y) + xMin;
TPixel32 *q = p + (xMax - xMin);
while (p <= q)
*p++ = col;
if (dSegm <= 0) // NordEst
{
dSegm = dSegm + incNE;
segm.x++;
} else // Nord
{
dSegm = dSegm + incN;
}
segm.y++;
}
}
ras->unlock();
return;
}
HalfCord halfCord(radius);
int x, y;
// ----- punti iniziali coincidenti: disegna un cerchio
if (a == b) {
int yMin = tmax(a.y - radius, 0); // clipping y
int yMax = tmin(a.y + radius, ly - 1); // clipping y
for (y = yMin; y <= yMax; y++) {
int deltay = abs(y - a.y);
int xMin = tmax(a.x - halfCord.getCord(deltay), 0); // clipping x
int xMax = tmin(a.x + halfCord.getCord(deltay), lx - 1); // clipping x
TPixel32 *p = ras->pixels(y) + xMin;
TPixel32 *q = p + (xMax - xMin);
while (p <= q)
*p++ = col;
}
ras->unlock();
return;
}
// ----- rettangolo orizzontale (a.y = b.y, a.x != b.x)
if (a.y == b.y) {
int yMin = tmax((a.y - radius), 0); // clipping y
int yMax = tmin((a.y + radius), ly - 1); // clipping y
int xLeft = tmin(a.x, b.x);
int xRight = tmax(a.x, b.x);
for (y = yMin; y <= yMax; y++) {
int deltay = abs(y - a.y);
int xMin = tmax(xLeft - halfCord.getCord(deltay), 0); // clipping x
int xMax = tmin(xRight + halfCord.getCord(deltay), lx - 1); // clipping x
TPixel32 *p = ras->pixels(y) + xMin;
TPixel32 *q = p + (xMax - xMin);
while (p <= q)
*p++ = col;
}
ras->unlock();
return;
}
// ----- rettangolo verticale (a.x = b.x, a.y != b.y)
if (a.x == b.x) {
int xMin = tmax(a.x - radius, 0); // clipping x
int xMax = tmin(a.x + radius, lx - 1); // clipping x
for (x = xMin; x <= xMax; x++) {
int deltax = abs(x - a.x);
int yMin = tmax(a.y - halfCord.getCord(deltax), 0); // clipping y
int yMax = tmin(b.y + halfCord.getCord(deltax), ly - 1); // clipping y
if (yMin <= yMax) {
TPixel32 *p = ras->pixels(yMin) + x;
TPixel32 *q = ras->pixels(yMax) + x;
int wrap = ras->getWrap();
while (p <= q) {
*p = col;
p += wrap;
}
}
}
ras->unlock();
return;
}
// ----- rettangolo inclinato
// k = +1/-1 se il rettangolo e' inclinato positivamente/negativamente
int k = 1;
int dx = b.x - a.x;
if (dx < 0) {
dx = -dx;
k = -1;
}
int dy = b.y - a.y;
assert(dx > 0);
assert(dy > 0);
double length = sqrt((double)(dx * dx + dy * dy));
const double m = dy / (double)dx;
//punto di tangenza superiore nel sistema di riferimento del cerchio
TPointD up(-radius * dy / length, radius * dx / length);
//semi-ampiezza orizzontale delle "calotte" circolari
int halfAmplCap = tfloor(-up.x);
// A meno di intersezioni relative tra le diverse zone:
// le scanline della "calotta" circolare superiore sono (b.y+cutExt,b.y+radius]
// le scanline del trapezoide circolare superiore sono [b.y-cutIn,b.y+cutExt]
// le scanline del parallelogramma sono (a.y+cutIn,b.y-cutIn)
// le scanline del trapezoide circolare inferiore sono [a.y-cutExt,a.y+cutIn]
// le scanline della "calotta" circolare inferiore sono [a.y-radius,a.y-cutExt)
int cutExt, cutIn;
// vertici del parallelogramma
TPointD rightUp;
TPointD rightDown;
TPointD leftUp;
TPointD leftDown;
double mParall; //coeff. angolare parallelogramma
// NOTA BENE: halfAmplCap=0 <=> (radius=0 (caso a parte) , 1)
if (radius > 1) {
for (cutExt = radius; cutExt >= 0 && halfCord.getCord(cutExt) <= halfAmplCap; cutExt--)
;
cutIn = cutExt; // vedi else successivo
rightUp.x = dx + halfCord.getCord(cutIn);
rightUp.y = dy - cutIn;
rightDown.x = halfCord.getCord(cutIn);
rightDown.y = -cutIn;
leftUp.x = dx - halfCord.getCord(cutIn);
leftUp.y = dy + cutIn;
leftDown.x = -halfCord.getCord(cutIn);
leftDown.y = cutIn;
mParall = dy / (double)dx;
} else // N.B. cutExt != cutIn solo quando radius=1
{
cutExt = radius; // radius=1 => halfAmplCap=0 (non ci sono mai le "calotte" circolari)
cutIn = 0; // anche per radius=1 il limite "interno" dei trapezoidi circolari e' < radius
rightUp.x = dx - up.x;
rightUp.y = dy - up.y;
rightDown.x = -up.x;
rightDown.y = -up.y;
leftUp.x = dx + up.x;
leftUp.y = dy + up.y;
leftDown.x = up.x;
leftDown.y = up.y;
mParall = m;
}
// ----- riempie "calotte" circolari
// ----- riempie "calotta" circolare inferiore
int yMin = tmax(a.y - radius, 0); // clipping y
int yMax = tmin(a.y - cutExt - 1, ly - 1); // clipping y
for (y = yMin; y <= yMax; y++) {
int r = halfCord.getCord(a.y - y);
int xMin = tmax(a.x - r, 0); // clipping x
int xMax = tmin(a.x + r, lx - 1); // clipping x
TPixel32 *p = ras->pixels(y) + xMin;
TPixel32 *q = p + (xMax - xMin);
while (p <= q)
*p++ = col;
}
// ----- riempie "calotta" circolare superiore
yMin = tmax(b.y + cutExt + 1, 0); // clipping y
yMax = tmin(b.y + radius, ly - 1); // clipping y
for (y = yMin; y <= yMax; y++) {
int r = halfCord.getCord(y - b.y);
int xMin = tmax(b.x - r, 0); // clipping x
int xMax = tmin(b.x + r, lx - 1); // clipping x
TPixel32 *p = ras->pixels(y) + xMin;
TPixel32 *q = p + (xMax - xMin);
while (p <= q)
*p++ = col;
}
// ----- riempie trapezoidi
// (se k<0 viene fatta una riflessione sulle ascisse prima di tornare alle
// coordinate "di schermo")
// limite destro assoluto delle scanline trapezoide:
int xSegmMax = tround(dx - up.x); // coordinata x del punto di tangenza inferiore sul cerchio superiore
// limite sinistro assoluto delle scanline:
int xSegmMin = tround(up.x); // coordinata x del punto di tangenza superiore sul cerchio inferiore
// ----- riempie trapezoide inferiore
// N.B. le coordinate sono relative ad un sist. di rif. con l'origine sul centro
// del cerchio inferiore
yMin = tmax(a.y - cutExt, 0) - a.y; // clipping y
yMax = tmin(a.y + cutIn, b.y - cutIn - 1, ly - 1) - a.y; // clipping y
// l'eq. della retta e' alpha * x + beta * y + gammaRight = 0
const int alpha = dy, beta = -dx;
const double gammaRight = rightDown.y * dx - rightDown.x * dy;
const int incE = alpha;
const int incNE = alpha + beta;
const int incN = beta;
if (m <= 1) {
// midpoint algorithm; le scanline vengono disegnate solo
// sul NordEst. L'ultima scanline non viene disegnata
TPoint segmRight(tceil((yMin + 0.5 - rightDown.y) / mParall + rightDown.x) - 1, yMin);
int dSegmRight = tfloor(alpha * (segmRight.x + 1) + beta * (segmRight.y + 0.5) + gammaRight);
while (segmRight.y <= yMax) {
if (dSegmRight < 0) // Est
{
dSegmRight = dSegmRight + incE;
segmRight.x++;
} else // NordEst
{
int xMin, xMax;
if (k > 0) {
xMin = tmax(a.x - halfCord.getCord(abs(segmRight.y)), 0); // clipping x
xMax = tmin(a.x + tmin(segmRight.x, xSegmMax), lx - 1); // clipping x
} else {
xMin = tmax(a.x - tmin(segmRight.x, xSegmMax), 0); // clipping x + ritorno alle
xMax = tmin(a.x + halfCord.getCord(abs(segmRight.y)), lx - 1); // coordinate "di schermo"
}
TPixel32 *p = ras->pixels(segmRight.y + a.y) + xMin;
TPixel32 *q = p + (xMax - xMin);
while (p <= q)
*p++ = col;
dSegmRight = dSegmRight + incNE;
segmRight.x++;
segmRight.y++;
}
}
} else // m>1
{
// midpoint algorithm; le scanline vengono disegnate sempre
TPoint segmRight(tround((yMin - rightDown.y) / mParall + rightDown.x), yMin);
int dSegmRight = tfloor(alpha * (segmRight.x + 0.5) + beta * (segmRight.y + 1) + gammaRight);
while (segmRight.y <= yMax) {
int xMin, xMax;
if (k > 0) {
xMin = tmax(a.x - halfCord.getCord(abs(segmRight.y)), 0); // clipping x
xMax = tmin(a.x + segmRight.x, lx - 1); // clipping x
} else {
xMin = tmax(a.x - segmRight.x, 0); // clipping x + ritorno alle coordinate
xMax = tmin(a.x + halfCord.getCord(abs(segmRight.y)), lx - 1); // "di schermo"
}
TPixel32 *p = ras->pixels(segmRight.y + a.y) + xMin;
TPixel32 *q = p + (xMax - xMin);
while (p <= q)
*p++ = col;
if (dSegmRight <= 0) // NordEst
{
dSegmRight = dSegmRight + incNE;
segmRight.x++;
} else // Nord
{
dSegmRight = dSegmRight + incN;
}
segmRight.y++;
}
}
// ----- riempie trapezoide superiore
// N.B. le coordinate sono relative ad un sist. di rif. con l'origine sul centro
// del cerchio superiore
yMin = tmax(b.y - cutIn, a.y + cutIn + 1, 0) - b.y; // clipping y
yMax = tmin(b.y + cutExt, ly - 1) - b.y; // clipping y
// l'eq. della retta e' alpha * x + beta * y + gammaLeft = 0
const double gammaLeft = leftDown.y * dx - leftDown.x * dy;
if (m <= 1) {
// midpoint algorithm; le scanline vengono disegnate solo
// sul NordEst. L'ultima scanline non viene disegnata
TPoint segmLeft(tceil((yMin - 0.5 - leftDown.y) / mParall + leftDown.x), yMin);
int dSegmLeft = tfloor(alpha * (segmLeft.x + 1) + beta * (segmLeft.y + 0.5) + gammaLeft);
while (segmLeft.y <= yMax) {
int xMin, xMax;
if (k > 0) {
xMin = tmax(b.x + tmax(segmLeft.x, xSegmMin - dx), 0); // clipping x
xMax = tmin(b.x + halfCord.getCord(abs(segmLeft.y)), lx - 1); // clipping x
} else {
xMin = tmax(b.x - halfCord.getCord(abs(segmLeft.y)), 0); // clipping x + ritorno alle
xMax = tmin(b.x - tmax(segmLeft.x, xSegmMin - dx), lx - 1); // coordinate "di schermo"
}
TPixel32 *p = ras->pixels(segmLeft.y + b.y) + xMin;
TPixel32 *q = p + (xMax - xMin);
while (p <= q)
*p++ = col;
while (dSegmLeft < 0) {
dSegmLeft = dSegmLeft + incE;
segmLeft.x++;
}
dSegmLeft = dSegmLeft + incNE;
segmLeft.x++;
segmLeft.y++;
}
} else // m>1
{
// midpoint algorithm; le scanline vengono disegnate sempre
TPoint segmLeft(tround((yMin - leftDown.y) / mParall + leftDown.x), yMin);
int dSegmLeft = tfloor(alpha * (segmLeft.x + 0.5) + beta * (segmLeft.y + 1) + gammaLeft);
while (segmLeft.y <= yMax) {
int xMin, xMax;
if (k > 0) {
xMin = tmax(b.x + segmLeft.x, 0); // clipping x
xMax = tmin(b.x + halfCord.getCord(abs(segmLeft.y)), lx - 1); // clipping x
} else {
xMin = tmax(b.x - halfCord.getCord(abs(segmLeft.y)), 0); // clipping x + ritorno alle
xMax = tmin(b.x - segmLeft.x, lx - 1); // coordinate "di schermo"
}
TPixel32 *p = ras->pixels(segmLeft.y + b.y) + xMin;
TPixel32 *q = p + (xMax - xMin);
while (p <= q)
*p++ = col;
if (dSegmLeft <= 0) // NordEst
{
dSegmLeft = dSegmLeft + incNE;
segmLeft.x++;
} else // Nord
{
dSegmLeft = dSegmLeft + incN;
}
segmLeft.y++;
}
}
// ----- parallelogramma (in alternativa a "parallelogrammoide circolare")
// N.B. le coordinate sono relative ad un sist. di rif. con l'origine sul centro
// del cerchio inferiore
// retta destra di equaz. alpha * x + beta * y + gammaRight = 0
// retta sinistra di equaz. alpha * x + beta * y + gammaLeft = 0
yMin = tmax(a.y + cutIn + 1, 0) - a.y; //clipping y
yMax = tmin(b.y - cutIn - 1, ly - 1) - a.y; //clipping y
if (m <= 1) {
// midpoint algorithm; le scanline vengono disegnate solo
// sul NordEst. L'ultima scanline non viene disegnata
TPoint segmRight(tceil((yMin + 0.5 - rightDown.y) / mParall + rightDown.x) - 1, yMin);
TPoint segmLeft = TPoint(tceil((yMin - 0.5 - leftDown.y) / mParall + leftDown.x), yMin);
int dSegmRight = tfloor(alpha * (segmRight.x + 1) + beta * (segmRight.y + 0.5) + gammaRight);
int dSegmLeft = tfloor(alpha * (segmLeft.x + 1) + beta * (segmLeft.y + 0.5) + gammaLeft);
while (segmRight.y <= yMax) {
if (dSegmRight < 0) // segmRight a Est
{
dSegmRight = dSegmRight + incE;
segmRight.x++;
} else // segmRight a NordEst
{
int xMin, xMax;
if (k > 0) {
xMin = tmax(a.x + tmax(segmLeft.x, xSegmMin), 0); // clipping x
xMax = tmin(a.x + tmin(segmRight.x, xSegmMax), lx - 1); // clipping x
} else {
xMin = tmax(a.x - tmin(segmRight.x, xSegmMax), 0); // clipping x + ritorno alle
xMax = tmin(a.x - tmax(segmLeft.x, xSegmMin), lx - 1); // coordinate "di schermo"
}
TPixel32 *p = ras->pixels(segmRight.y + a.y) + xMin;
TPixel32 *q = p + (xMax - xMin);
while (p <= q)
*p++ = col;
dSegmRight = dSegmRight + incNE;
segmRight.x++;
segmRight.y++;
while (dSegmLeft < 0) // segmLeft a Est
{
dSegmLeft = dSegmLeft + incE;
segmLeft.x++;
}
// segmLeft a NordEst
dSegmLeft = dSegmLeft + incNE;
segmLeft.x++;
segmLeft.y++;
}
}
} else // m>1
{
// midpoint algorithm; le scanline vengono disegnate sempre
TPoint segmRight(tround((yMin - rightDown.y) / mParall + rightDown.x), yMin);
TPoint segmLeft(tround((yMin - leftDown.y) / mParall + leftDown.x), yMin);
int dSegmRight = tfloor(alpha * (segmRight.x + 0.5) + beta * (segmRight.y + 1) + gammaRight);
int dSegmLeft = tfloor(alpha * (segmLeft.x + 0.5) + beta * (segmLeft.y + 1) + gammaLeft);
while (segmRight.y <= yMax) {
int xMin, xMax;
if (k > 0) {
xMin = tmax(a.x + segmLeft.x, 0); // clipping x
xMax = tmin(a.x + segmRight.x, lx - 1); // clipping x
} else {
xMin = tmax(a.x - segmRight.x, 0); // clipping x + ritorno alle
xMax = tmin(a.x - segmLeft.x, lx - 1); // coordinate "di schermo"
}
TPixel32 *p = ras->pixels(segmRight.y + a.y) + xMin;
TPixel32 *q = p + (xMax - xMin);
while (p <= q)
*p++ = col;
if (dSegmRight <= 0) // segmRight a NordEst
{
dSegmRight = dSegmRight + incNE;
segmRight.x++;
} else // segmRight a Nord
{
dSegmRight = dSegmRight + incN;
}
segmRight.y++;
if (dSegmLeft <= 0) // segmLeft a NordEst
{
dSegmLeft = dSegmLeft + incNE;
segmLeft.x++;
} else // segmLeft a Nord
{
dSegmLeft = dSegmLeft + incN;
}
}
}
// ---- parallelogrammoide circolare (in alternativa a parallelogramma)
// N.B. coordinate di schermo (riflessione per k<0 )
yMin = tmax(b.y - cutIn, 0);
yMax = tmin(a.y + cutIn, ly - 1);
for (y = yMin; y <= yMax; y++) {
int xMin, xMax;
if (k > 0) {
xMin = tmax(a.x - halfCord.getCord(abs(y - a.y)), 0); // clipping x
xMax = tmin(b.x + halfCord.getCord(abs(b.y - y)), lx - 1); // clipping x
} else {
xMin = tmax(b.x - halfCord.getCord(abs(b.y - y)), 0); // clipping x + ritorno alle
xMax = tmin(a.x + halfCord.getCord(abs(y - a.y)), lx - 1); // coordinate "di schermo"
}
TPixel32 *p = ras->pixels(y) + xMin;
TPixel32 *q = p + (xMax - xMin);
while (p <= q)
*p++ = col;
}
ras->unlock();
}
|
// (C) Copyright John Maddock 2005.
// Use, modification and distribution are 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).
//
// See http://www.boost.org/libs/type_traits for most recent version including documentation.
#ifndef BOOST_TT_IS_UNSIGNED_HPP_INCLUDED
#define BOOST_TT_IS_UNSIGNED_HPP_INCLUDED
#include <boost/type_traits/is_integral.hpp>
#include <boost/type_traits/is_enum.hpp>
#include <boost/type_traits/remove_cv.hpp>
#include <boost/type_traits/detail/ice_or.hpp>
// should be the last #include
#include <boost/type_traits/detail/bool_trait_def.hpp>
namespace riakboost{} namespace boost = riakboost; namespace riakboost{
#if !defined( __CODEGEARC__ )
namespace detail{
#if !(defined(__EDG_VERSION__) && __EDG_VERSION__ <= 238) && !defined(BOOST_NO_INCLASS_MEMBER_INITIALIZATION)
template <class T>
struct is_unsigned_values
{
//
// Note that we cannot use BOOST_STATIC_CONSTANT here, using enum's
// rather than "real" static constants simply doesn't work or give
// the correct answer.
//
typedef typename remove_cv<T>::type no_cv_t;
static const no_cv_t minus_one = (static_cast<no_cv_t>(-1));
static const no_cv_t zero = (static_cast<no_cv_t>(0));
};
template <class T>
struct is_ununsigned_helper
{
BOOST_STATIC_CONSTANT(bool, value = (::riakboost::detail::is_unsigned_values<T>::minus_one > ::riakboost::detail::is_unsigned_values<T>::zero));
};
template <bool integral_type>
struct is_ununsigned_select_helper
{
template <class T>
struct rebind
{
typedef is_ununsigned_helper<T> type;
};
};
template <>
struct is_ununsigned_select_helper<false>
{
template <class T>
struct rebind
{
typedef false_type type;
};
};
template <class T>
struct is_unsigned_imp
{
typedef is_ununsigned_select_helper<
::riakboost::type_traits::ice_or<
::riakboost::is_integral<T>::value,
::riakboost::is_enum<T>::value>::value
> selector;
typedef typename selector::template rebind<T> binder;
typedef typename binder::type type;
BOOST_STATIC_CONSTANT(bool, value = type::value);
};
#else
template <class T> struct is_unsigned_imp : public false_type{};
template <> struct is_unsigned_imp<unsigned char> : public true_type{};
template <> struct is_unsigned_imp<const unsigned char> : public true_type{};
template <> struct is_unsigned_imp<volatile unsigned char> : public true_type{};
template <> struct is_unsigned_imp<const volatile unsigned char> : public true_type{};
template <> struct is_unsigned_imp<unsigned short> : public true_type{};
template <> struct is_unsigned_imp<const unsigned short> : public true_type{};
template <> struct is_unsigned_imp<volatile unsigned short> : public true_type{};
template <> struct is_unsigned_imp<const volatile unsigned short> : public true_type{};
template <> struct is_unsigned_imp<unsigned int> : public true_type{};
template <> struct is_unsigned_imp<const unsigned int> : public true_type{};
template <> struct is_unsigned_imp<volatile unsigned int> : public true_type{};
template <> struct is_unsigned_imp<const volatile unsigned int> : public true_type{};
template <> struct is_unsigned_imp<unsigned long> : public true_type{};
template <> struct is_unsigned_imp<const unsigned long> : public true_type{};
template <> struct is_unsigned_imp<volatile unsigned long> : public true_type{};
template <> struct is_unsigned_imp<const volatile unsigned long> : public true_type{};
#ifdef BOOST_HAS_LONG_LONG
template <> struct is_unsigned_imp<unsigned long long> : public true_type{};
template <> struct is_unsigned_imp<const unsigned long long> : public true_type{};
template <> struct is_unsigned_imp<volatile unsigned long long> : public true_type{};
template <> struct is_unsigned_imp<const volatile unsigned long long> : public true_type{};
#endif
#if defined(CHAR_MIN) && (CHAR_MIN == 0)
template <> struct is_unsigned_imp<char> : public true_type{};
template <> struct is_unsigned_imp<const char> : public true_type{};
template <> struct is_unsigned_imp<volatile char> : public true_type{};
template <> struct is_unsigned_imp<const volatile char> : public true_type{};
#endif
#if defined(WCHAR_MIN) && (WCHAR_MIN == 0)
template <> struct is_unsigned_imp<wchar_t> : public true_type{};
template <> struct is_unsigned_imp<const wchar_t> : public true_type{};
template <> struct is_unsigned_imp<volatile wchar_t> : public true_type{};
template <> struct is_unsigned_imp<const volatile wchar_t> : public true_type{};
#endif
#endif
}
#endif // !defined( __CODEGEARC__ )
#if defined( __CODEGEARC__ )
BOOST_TT_AUX_BOOL_TRAIT_DEF1(is_unsigned,T,__is_unsigned(T))
#else
BOOST_TT_AUX_BOOL_TRAIT_DEF1(is_unsigned,T,::riakboost::detail::is_unsigned_imp<T>::value)
#endif
} // namespace riakboost
#include <boost/type_traits/detail/bool_trait_undef.hpp>
#endif // BOOST_TT_IS_MEMBER_FUNCTION_POINTER_HPP_INCLUDED
|
/*
* File: Codechef - Golu and Sweetness
* Algorithm: Euler's totient function
* Created Date: Saturday August 1st 2020
* Author: preetam rane
*/
#include <bits/stdc++.h>
using namespace std;
int main(){
int n,q;
cin>>n>>q;
long long a[n];
for(int i=0;i<n;i++)
cin>>a[i];
for(int i=0;i<n;i++){
if(a[i]==3 or a[i]==4 or a[i]==6)
a[i]=1;
else
a[i]=0;
}
for(int i=1;i<=n-1;i++)
a[i]+=a[i-1];
while(q--){
int l,r;
cin>>l>>r;
l--,r--;
if(l==0)
cout<<a[r]<<"\n";
else
cout<<a[r]-a[l-1]<<"\n";
}
return 0;
}
|
/**
* Copyright (C) 2020 Elisha Riedlinger
*
* This software is provided 'as-is', without any express or implied warranty. In no event will the
* authors be held liable for any damages arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose, including commercial
* applications, and to alter it and redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not claim that you wrote the
* original software. If you use this software in a product, an acknowledgment in the product
* documentation would be appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be misrepresented as
* being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*
* ValidatePixelShader and ValidateVertexShader created from source code found in Wine
* https://github.com/alexhenrie/wine/tree/master/dlls/d3d8
*/
#define WIN32_LEAN_AND_MEAN
#include "d3d9\d3d9wrapper.h"
#include <Shlwapi.h>
#include "External\d3d8to9\source\d3d8to9.hpp"
#include "External\d3d8to9\source\d3dx9.hpp"
#include "wrapper.h"
#include "d3d8to9.h"
#include "External\Hooking\Hook.h"
#include "Common\Utils.h"
#include "Common\LoadModules.h"
#include "Common\Settings.h"
#include "Logging\Logging.h"
#include "BuildNo.rc"
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define APP_VERSION TOSTRING(FILEVERSION)
Direct3DCreate9Proc p_Direct3DCreate9 = nullptr;
PFN_D3DXAssembleShader D3DXAssembleShader = nullptr;
PFN_D3DXDisassembleShader D3DXDisassembleShader = nullptr;
PFN_D3DXLoadSurfaceFromSurface D3DXLoadSurfaceFromSurface = nullptr;
// Redirects or hooks 'Direct3DCreate8' to go to d3d8to9
void EnableD3d8to9()
{
d3d8::ValidatePixelShader_var = (FARPROC)*d8_ValidatePixelShader;
d3d8::ValidateVertexShader_var = (FARPROC)*d8_ValidateVertexShader;
d3d8::Direct3DCreate8_var = (FARPROC)*Direct3DCreate8to9;
m_pDirect3DCreate8 = (Direct3DCreate8Proc)*Direct3DCreate8to9;
}
// Initializes d3d9 and Direct3DCreate9 for d3d8to9
void Initd3d8to9()
{
if (!EnableCustomShaders)
{
Initd3d9();
p_Direct3DCreate9 = m_pDirect3DCreate9;
}
else
{
p_Direct3DCreate9 = rs_Direct3DCreate9;
}
}
HRESULT WINAPI d8_ValidatePixelShader(DWORD* pixelshader, DWORD* reserved1, BOOL flag, DWORD* toto)
{
UNREFERENCED_PARAMETER(flag);
UNREFERENCED_PARAMETER(toto);
LOG_LIMIT(1, __FUNCTION__);
if (!pixelshader)
{
return D3DERR_INVALIDCALL;
}
if (reserved1)
{
return D3DERR_INVALIDCALL;
}
switch (*pixelshader)
{
case 0xFFFF0100:
case 0xFFFF0101:
case 0xFFFF0102:
case 0xFFFF0103:
case 0xFFFF0104:
return D3D_OK;
break;
default:
return D3DERR_INVALIDCALL;
}
}
HRESULT WINAPI d8_ValidateVertexShader(DWORD* vertexshader, DWORD* reserved1, DWORD* reserved2, BOOL flag, DWORD* toto)
{
UNREFERENCED_PARAMETER(flag);
UNREFERENCED_PARAMETER(toto);
LOG_LIMIT(1, __FUNCTION__);
if (!vertexshader)
{
return D3DERR_INVALIDCALL;
}
if (reserved1 || reserved2)
{
return D3DERR_INVALIDCALL;
}
switch (*vertexshader)
{
case 0xFFFE0100:
case 0xFFFE0101:
return D3D_OK;
break;
default:
return D3DERR_INVALIDCALL;
}
}
// Handles calls to 'Direct3DCreate8' for d3d8to9
Direct3D8 *WINAPI Direct3DCreate8to9(UINT SDKVersion)
{
UNREFERENCED_PARAMETER(SDKVersion);
Initd3d8to9();
if (!p_Direct3DCreate9)
{
Logging::Log() << __FUNCTION__ << " Error finding 'Direct3DCreate9'";
return nullptr;
}
LOG_ONCE("Starting D3d8to9 v" << APP_VERSION);
Logging::Log() << "Redirecting 'Direct3DCreate8' to --> 'Direct3DCreate9' (" << SDKVersion << ")";
IDirect3D9 *const d3d = p_Direct3DCreate9(D3D_SDK_VERSION);
if (d3d == nullptr)
{
Logging::Log() << __FUNCTION__ << " Error: Failed to create 'Direct3DCreate9'!";
return nullptr;
}
// Load D3DX
if (!D3DXAssembleShader || !D3DXDisassembleShader || !D3DXLoadSurfaceFromSurface)
{
// Declare module vars
static HMODULE d3dx9Module = nullptr;
// Declare d3dx9_xx.dll name
wchar_t d3dx9name[MAX_PATH] = { 0 };
// Declare d3dx9_xx.dll version
for (int x = 99; x > 9 && !d3dx9Module; x--)
{
// Get dll name
swprintf_s(d3dx9name, L"d3dx9_%d.dll", x);
// Load dll
d3dx9Module = LoadLibrary(d3dx9name);
}
// Extract d3dx9 tools from binary
if (!d3dx9Module)
{
ExtractD3DX9Tools();
d3dx9Module = LoadLibrary(L"d3dx9_43.dll");
}
if (d3dx9Module)
{
Logging::Log() << "Loaded " << d3dx9name;
D3DXAssembleShader = reinterpret_cast<PFN_D3DXAssembleShader>(GetProcAddress(d3dx9Module, "D3DXAssembleShader"));
D3DXDisassembleShader = reinterpret_cast<PFN_D3DXDisassembleShader>(GetProcAddress(d3dx9Module, "D3DXDisassembleShader"));
D3DXLoadSurfaceFromSurface = reinterpret_cast<PFN_D3DXLoadSurfaceFromSurface>(GetProcAddress(d3dx9Module, "D3DXLoadSurfaceFromSurface"));
}
else
{
// Should never get here
Logging::Log() << __FUNCTION__ << " Error: Failed to load d3dx9_xx.dll! Some features will not work correctly.";
}
}
// Check if WineD3D is loaded
if (GetModuleHandle(L"libwine.dll") || GetModuleHandle(L"wined3d.dll"))
{
Logging::Log() << __FUNCTION__ << " Warning: WineD3D detected! It is not recommended to use WineD3D with Silent Hill 2 Enhancements.";
}
return new Direct3D8(d3d);
}
|
#ifndef CLOVER_GUI_CALLBACK_HPP
#define CLOVER_GUI_CALLBACK_HPP
#include "build.hpp"
// .tpp
#include "global/event.hpp"
#include <functional>
namespace clover {
namespace gui {
template <typename ElementType>
using CallbackFunction = std::function<void (ElementType&)>;
class GuiMgr;
class BaseCallback {
public:
virtual const Element& getOwner() const = 0;
protected:
friend class GuiMgr;
// Calls the actual callback-function
virtual void call()=0;
};
template <typename T>
class Callback : public BaseCallback {
public:
typedef T ElementType;
Callback();
Callback(Callback&& other)= default;
Callback& operator=(Callback&& other)= default;
void assign(const CallbackFunction<ElementType>& f);
/// Notifies GuiMgr which fires callback after updating every element
/// "element" must always be *this where called
void trigger(ElementType& element);
Callback& operator()(ElementType& element){ trigger(element); return *this; }
virtual const ElementType& getOwner() const { ensure(owner); return *owner; }
private:
virtual void call();
ElementType* owner;
CallbackFunction<ElementType> callback;
};
#include "callback.tpp"
} // gui
} // clover
#endif // CLOVER_GUI_CALLBACK_HPP
|
/*
* Copyright (C) 2009 Apple Inc. All Rights Reserved.
* Copyright (C) 2009 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:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if ENABLE(WEBGL)
#include "WebGLGetInfo.h"
#include "WebGLBuffer.h"
#include "WebGLFramebuffer.h"
#include "WebGLProgram.h"
#include "WebGLRenderbuffer.h"
#include "WebGLTexture.h"
#include "WebGLVertexArrayObjectOES.h"
#include <wtf/Float32Array.h>
#include <wtf/Int32Array.h>
#include <wtf/Uint32Array.h>
#include <wtf/Uint8Array.h>
namespace WebCore {
WebGLGetInfo::WebGLGetInfo(bool value)
: m_type(kTypeBool)
, m_bool(value)
, m_float(0)
, m_int(0)
, m_unsignedInt(0)
{
}
WebGLGetInfo::WebGLGetInfo(const bool* value, int size)
: m_type(kTypeBoolArray)
, m_bool(false)
, m_float(0)
, m_int(0)
, m_unsignedInt(0)
{
if (!value || size <=0)
return;
m_boolArray.resize(size);
for (int ii = 0; ii < size; ++ii)
m_boolArray[ii] = value[ii];
}
WebGLGetInfo::WebGLGetInfo(float value)
: m_type(kTypeFloat)
, m_bool(false)
, m_float(value)
, m_int(0)
, m_unsignedInt(0)
{
}
WebGLGetInfo::WebGLGetInfo(int value)
: m_type(kTypeInt)
, m_bool(false)
, m_float(0)
, m_int(value)
, m_unsignedInt(0)
{
}
WebGLGetInfo::WebGLGetInfo()
: m_type(kTypeNull)
, m_bool(false)
, m_float(0)
, m_int(0)
, m_unsignedInt(0)
{
}
WebGLGetInfo::WebGLGetInfo(const String& value)
: m_type(kTypeString)
, m_bool(false)
, m_float(0)
, m_int(0)
, m_string(value)
, m_unsignedInt(0)
{
}
WebGLGetInfo::WebGLGetInfo(unsigned int value)
: m_type(kTypeUnsignedInt)
, m_bool(false)
, m_float(0)
, m_int(0)
, m_unsignedInt(value)
{
}
WebGLGetInfo::WebGLGetInfo(PassRefPtr<WebGLBuffer> value)
: m_type(kTypeWebGLBuffer)
, m_bool(false)
, m_float(0)
, m_int(0)
, m_unsignedInt(0)
, m_webglBuffer(value)
{
}
WebGLGetInfo::WebGLGetInfo(PassRefPtr<Float32Array> value)
: m_type(kTypeWebGLFloatArray)
, m_bool(false)
, m_float(0)
, m_int(0)
, m_unsignedInt(0)
, m_webglFloatArray(value)
{
}
WebGLGetInfo::WebGLGetInfo(PassRefPtr<WebGLFramebuffer> value)
: m_type(kTypeWebGLFramebuffer)
, m_bool(false)
, m_float(0)
, m_int(0)
, m_unsignedInt(0)
, m_webglFramebuffer(value)
{
}
WebGLGetInfo::WebGLGetInfo(PassRefPtr<Int32Array> value)
: m_type(kTypeWebGLIntArray)
, m_bool(false)
, m_float(0)
, m_int(0)
, m_unsignedInt(0)
, m_webglIntArray(value)
{
}
WebGLGetInfo::WebGLGetInfo(PassRefPtr<WebGLProgram> value)
: m_type(kTypeWebGLProgram)
, m_bool(false)
, m_float(0)
, m_int(0)
, m_unsignedInt(0)
, m_webglProgram(value)
{
}
WebGLGetInfo::WebGLGetInfo(PassRefPtr<WebGLRenderbuffer> value)
: m_type(kTypeWebGLRenderbuffer)
, m_bool(false)
, m_float(0)
, m_int(0)
, m_unsignedInt(0)
, m_webglRenderbuffer(value)
{
}
WebGLGetInfo::WebGLGetInfo(PassRefPtr<WebGLTexture> value)
: m_type(kTypeWebGLTexture)
, m_bool(false)
, m_float(0)
, m_int(0)
, m_unsignedInt(0)
, m_webglTexture(value)
{
}
WebGLGetInfo::WebGLGetInfo(PassRefPtr<Uint8Array> value)
: m_type(kTypeWebGLUnsignedByteArray)
, m_bool(false)
, m_float(0)
, m_int(0)
, m_unsignedInt(0)
, m_webglUnsignedByteArray(value)
{
}
WebGLGetInfo::WebGLGetInfo(PassRefPtr<Uint32Array> value)
: m_type(kTypeWebGLUnsignedIntArray)
, m_bool(false)
, m_float(0)
, m_int(0)
, m_unsignedInt(0)
, m_webglUnsignedIntArray(value)
{
}
WebGLGetInfo::WebGLGetInfo(PassRefPtr<WebGLVertexArrayObjectOES> value)
: m_type(kTypeWebGLVertexArrayObjectOES)
, m_bool(false)
, m_float(0)
, m_int(0)
, m_unsignedInt(0)
, m_webglVertexArrayObject(value)
{
}
WebGLGetInfo::~WebGLGetInfo()
{
}
WebGLGetInfo::Type WebGLGetInfo::getType() const
{
return m_type;
}
bool WebGLGetInfo::getBool() const
{
ASSERT(getType() == kTypeBool);
return m_bool;
}
const Vector<bool>& WebGLGetInfo::getBoolArray() const
{
ASSERT(getType() == kTypeBoolArray);
return m_boolArray;
}
float WebGLGetInfo::getFloat() const
{
ASSERT(getType() == kTypeFloat);
return m_float;
}
int WebGLGetInfo::getInt() const
{
ASSERT(getType() == kTypeInt);
return m_int;
}
const String& WebGLGetInfo::getString() const
{
ASSERT(getType() == kTypeString);
return m_string;
}
unsigned int WebGLGetInfo::getUnsignedInt() const
{
ASSERT(getType() == kTypeUnsignedInt);
return m_unsignedInt;
}
PassRefPtr<WebGLBuffer> WebGLGetInfo::getWebGLBuffer() const
{
ASSERT(getType() == kTypeWebGLBuffer);
return m_webglBuffer;
}
PassRefPtr<Float32Array> WebGLGetInfo::getWebGLFloatArray() const
{
ASSERT(getType() == kTypeWebGLFloatArray);
return m_webglFloatArray;
}
PassRefPtr<WebGLFramebuffer> WebGLGetInfo::getWebGLFramebuffer() const
{
ASSERT(getType() == kTypeWebGLFramebuffer);
return m_webglFramebuffer;
}
PassRefPtr<Int32Array> WebGLGetInfo::getWebGLIntArray() const
{
ASSERT(getType() == kTypeWebGLIntArray);
return m_webglIntArray;
}
PassRefPtr<WebGLProgram> WebGLGetInfo::getWebGLProgram() const
{
ASSERT(getType() == kTypeWebGLProgram);
return m_webglProgram;
}
PassRefPtr<WebGLRenderbuffer> WebGLGetInfo::getWebGLRenderbuffer() const
{
ASSERT(getType() == kTypeWebGLRenderbuffer);
return m_webglRenderbuffer;
}
PassRefPtr<WebGLTexture> WebGLGetInfo::getWebGLTexture() const
{
ASSERT(getType() == kTypeWebGLTexture);
return m_webglTexture;
}
PassRefPtr<Uint8Array> WebGLGetInfo::getWebGLUnsignedByteArray() const
{
ASSERT(getType() == kTypeWebGLUnsignedByteArray);
return m_webglUnsignedByteArray;
}
PassRefPtr<Uint32Array> WebGLGetInfo::getWebGLUnsignedIntArray() const
{
ASSERT(getType() == kTypeWebGLUnsignedIntArray);
return m_webglUnsignedIntArray;
}
PassRefPtr<WebGLVertexArrayObjectOES> WebGLGetInfo::getWebGLVertexArrayObjectOES() const
{
ASSERT(getType() == kTypeWebGLVertexArrayObjectOES);
return m_webglVertexArrayObject;
}
} // namespace WebCore
#endif // ENABLE(WEBGL)
|
/*
main.cpp
Copyright (c) 2019, Martin Knoblauch Revuelta
See accompanying LICENSE
https://github.com/mkrevuelta/CppMoveBase64
*/
#include <iostream>
#include <string>
#include <exception>
#include <CppMoveBase64.h>
void testEncodeHello ();
void testEncodeVectorInt ();
void testEncodeStreamed ();
void testEncodeRecycle ();
void testDecodeHello ();
void testDecodeStreamed ();
void testDecodeOldStyleHello ();
struct
{
const char * name;
void (* function) ();
}
testsTable [] =
{
{ "EncodeHello", testEncodeHello },
{ "EncodeVectorInt", testEncodeVectorInt },
{ "EncodeStreamed", testEncodeStreamed },
{ "EncodeRecycle", testEncodeRecycle },
{ "DecodeHello", testDecodeHello },
{ "DecodeStreamed", testDecodeStreamed },
{ "DecodeOldStyleHello", testDecodeOldStyleHello },
{ "TABLE END", nullptr }
};
const char * allTestsName = "All";
int main (int argc, const char * argv[])
{
try
{
if (argc != 2)
throw std::runtime_error ("Error: incorrect parameters");
std::string testName (argv[1]);
unsigned count = 0;
for (unsigned i=0; testsTable[i].function; i++)
if (testName==allTestsName || testName==testsTable[i].name)
{
std::cout << std::string (40, '=') << std::endl;
std::cout << "Running test "
<< testsTable[i].name << std::endl;
testsTable[i].function ();
count ++;
}
std::cout << std::string (40, '=') << std::endl;
std::cout << "Total: " << count << " test(s)" << std::endl;
if (count == 0)
throw std::runtime_error ("Error: unknown test " +
testName);
}
catch (const std::exception & ex)
{
std::cerr << ex.what () << std::endl;
throw;
}
return 0;
}
|
// Copyright (c) 2011-2016 The Bitcoin Core developers
// Copyright (c) 2017 The Raven Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "transactiondesc.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include "paymentserver.h"
#include "transactionrecord.h"
#include "base58.h"
#include "consensus/consensus.h"
#include "validation.h"
#include "script/script.h"
#include "timedata.h"
#include "util.h"
#include "wallet/db.h"
#include "wallet/wallet.h"
#include <stdint.h>
#include <string>
QString TransactionDesc::FormatTxStatus(const CWalletTx& wtx)
{
AssertLockHeld(cs_main);
if (!CheckFinalTx(wtx))
{
if (wtx.tx->nLockTime < LOCKTIME_THRESHOLD)
return tr("Open for %n more block(s)", "", wtx.tx->nLockTime - chainActive.Height());
else
return tr("Open until %1").arg(GUIUtil::dateTimeStr(wtx.tx->nLockTime));
}
else
{
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < 0)
return tr("conflicted with a transaction with %1 confirmations").arg(-nDepth);
else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
return tr("%1/offline").arg(nDepth);
else if (nDepth == 0)
return tr("0/unconfirmed, %1").arg((wtx.InMempool() ? tr("in memory pool") : tr("not in memory pool"))) + (wtx.isAbandoned() ? ", "+tr("abandoned") : "");
else if (nDepth < 6)
return tr("%1/unconfirmed").arg(nDepth);
else
return tr("%1 confirmations").arg(nDepth);
}
}
QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionRecord *rec, int unit)
{
QString strHTML;
if (rec->assetName != "BLAST") {
return toAssetHTML(wallet, wtx, rec, unit);
}
LOCK2(cs_main, wallet->cs_wallet);
strHTML.reserve(4000);
strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>";
int64_t nTime = wtx.GetTxTime();
CAmount nCredit = wtx.GetCredit(ISMINE_ALL);
CAmount nDebit = wtx.GetDebit(ISMINE_ALL);
CAmount nNet = nCredit - nDebit;
strHTML += "<b>" + tr("Status") + ":</b> " + FormatTxStatus(wtx);
int nRequests = wtx.GetRequestCount();
if (nRequests != -1)
{
if (nRequests == 0)
strHTML += tr(", has not been successfully broadcast yet");
else if (nRequests > 0)
strHTML += tr(", broadcast through %n node(s)", "", nRequests);
}
strHTML += "<br>";
strHTML += "<b>" + tr("Date") + ":</b> " + (nTime ? GUIUtil::dateTimeStr(nTime) : "") + "<br>";
//
// From
//
if (wtx.IsCoinBase())
{
strHTML += "<b>" + tr("Source") + ":</b> " + tr("Generated") + "<br>";
}
else if (wtx.mapValue.count("from") && !wtx.mapValue["from"].empty())
{
// Online transaction
strHTML += "<b>" + tr("From") + ":</b> " + GUIUtil::HtmlEscape(wtx.mapValue["from"]) + "<br>";
}
else
{
// Offline transaction
if (nNet > 0)
{
// Credit
CTxDestination address = DecodeDestination(rec->address);
if (IsValidDestination(address)) {
if (wallet->mapAddressBook.count(address))
{
strHTML += "<b>" + tr("From") + ":</b> " + tr("unknown") + "<br>";
strHTML += "<b>" + tr("To") + ":</b> ";
strHTML += GUIUtil::HtmlEscape(rec->address);
QString addressOwned = (::IsMine(*wallet, address) == ISMINE_SPENDABLE) ? tr("own address") : tr("watch-only");
if (!wallet->mapAddressBook[address].name.empty())
strHTML += " (" + addressOwned + ", " + tr("label") + ": " + GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + ")";
else
strHTML += " (" + addressOwned + ")";
strHTML += "<br>";
}
}
}
}
//
// To
//
if (wtx.mapValue.count("to") && !wtx.mapValue["to"].empty())
{
// Online transaction
std::string strAddress = wtx.mapValue["to"];
strHTML += "<b>" + tr("To") + ":</b> ";
CTxDestination dest = DecodeDestination(strAddress);
if (wallet->mapAddressBook.count(dest) && !wallet->mapAddressBook[dest].name.empty())
strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[dest].name) + " ";
strHTML += GUIUtil::HtmlEscape(strAddress) + "<br>";
}
//
// Amount
//
if (wtx.IsCoinBase() && nCredit == 0)
{
//
// Coinbase
//
CAmount nUnmatured = 0;
for (const CTxOut& txout : wtx.tx->vout)
nUnmatured += wallet->GetCredit(txout, ISMINE_ALL);
strHTML += "<b>" + tr("Credit") + ":</b> ";
if (wtx.IsInMainChain())
strHTML += BitcoinUnits::formatHtmlWithUnit(unit, nUnmatured)+ " (" + tr("matures in %n more block(s)", "", wtx.GetBlocksToMaturity()) + ")";
else
strHTML += "(" + tr("not accepted") + ")";
strHTML += "<br>";
}
else if (nNet > 0)
{
//
// Credit
//
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, nNet) + "<br>";
}
else
{
isminetype fAllFromMe = ISMINE_SPENDABLE;
for (const CTxIn& txin : wtx.tx->vin)
{
isminetype mine = wallet->IsMine(txin);
if(fAllFromMe > mine) fAllFromMe = mine;
}
isminetype fAllToMe = ISMINE_SPENDABLE;
for (const CTxOut& txout : wtx.tx->vout)
{
isminetype mine = wallet->IsMine(txout);
if(fAllToMe > mine) fAllToMe = mine;
}
if (fAllFromMe)
{
if(fAllFromMe & ISMINE_WATCH_ONLY)
strHTML += "<b>" + tr("From") + ":</b> " + tr("watch-only") + "<br>";
//
// Debit
//
for (const CTxOut& txout : wtx.tx->vout)
{
// Ignore change
isminetype toSelf = wallet->IsMine(txout);
if ((toSelf == ISMINE_SPENDABLE) && (fAllFromMe == ISMINE_SPENDABLE))
continue;
if (!wtx.mapValue.count("to") || wtx.mapValue["to"].empty())
{
// Offline transaction
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address))
{
strHTML += "<b>" + tr("To") + ":</b> ";
if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].name.empty())
strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + " ";
strHTML += GUIUtil::HtmlEscape(EncodeDestination(address));
if(toSelf == ISMINE_SPENDABLE)
strHTML += " (own address)";
else if(toSelf & ISMINE_WATCH_ONLY)
strHTML += " (watch-only)";
strHTML += "<br>";
}
}
strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -txout.nValue) + "<br>";
if(toSelf)
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, txout.nValue) + "<br>";
}
if (fAllToMe)
{
// Payment to self
CAmount nChange = wtx.GetChange();
CAmount nValue = nCredit - nChange;
strHTML += "<b>" + tr("Total debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -nValue) + "<br>";
strHTML += "<b>" + tr("Total credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, nValue) + "<br>";
}
CAmount nTxFee = nDebit - wtx.tx->GetValueOut();
if (nTxFee > 0)
strHTML += "<b>" + tr("Transaction fee") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -nTxFee) + "<br>";
}
else
{
//
// Mixed debit transaction
//
for (const CTxIn& txin : wtx.tx->vin)
if (wallet->IsMine(txin))
strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, -wallet->GetDebit(txin, ISMINE_ALL)) + "<br>";
for (const CTxOut& txout : wtx.tx->vout)
if (wallet->IsMine(txout))
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + "<br>";
}
}
strHTML += "<b>" + tr("Net amount") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, nNet, true) + "<br>";
//
// Message
//
if (wtx.mapValue.count("message") && !wtx.mapValue["message"].empty())
strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["message"], true) + "<br>";
if (wtx.mapValue.count("comment") && !wtx.mapValue["comment"].empty())
strHTML += "<br><b>" + tr("Comment") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["comment"], true) + "<br>";
strHTML += "<b>" + tr("Transaction ID") + ":</b> " + rec->getTxID() + "<br>";
strHTML += "<b>" + tr("Transaction total size") + ":</b> " + QString::number(wtx.tx->GetTotalSize()) + " bytes<br>";
strHTML += "<b>" + tr("Output index") + ":</b> " + QString::number(rec->getOutputIndex()) + "<br>";
// Message from normal blast:URI (blast:123...?message=example)
for (const std::pair<std::string, std::string>& r : wtx.vOrderForm)
if (r.first == "Message")
strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(r.second, true) + "<br>";
//
// PaymentRequest info:
//
for (const std::pair<std::string, std::string>& r : wtx.vOrderForm)
{
if (r.first == "PaymentRequest")
{
PaymentRequestPlus req;
req.parse(QByteArray::fromRawData(r.second.data(), r.second.size()));
QString merchant;
if (req.getMerchant(PaymentServer::getCertStore(), merchant))
strHTML += "<b>" + tr("Merchant") + ":</b> " + GUIUtil::HtmlEscape(merchant) + "<br>";
}
}
if (wtx.IsCoinBase())
{
quint32 numBlocksToMaturity = COINBASE_MATURITY + 1;
strHTML += "<br>" + tr("Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to \"not accepted\" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.").arg(QString::number(numBlocksToMaturity)) + "<br>";
}
//
// Debug view
//
if (logCategories != BCLog::NONE)
{
CreateDebugString(strHTML, wallet, wtx, unit);
}
strHTML += "</font></html>";
return strHTML;
}
QString TransactionDesc::toAssetHTML(CWallet *wallet, CWalletTx &wtx, TransactionRecord *rec, int unit)
{
QString strHTML;
LOCK2(cs_main, wallet->cs_wallet);
strHTML.reserve(4000);
strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>";
CNewAsset asset;
auto currentActiveAssetCache = GetCurrentAssetCache();
if (IsAssetNameAnOwner(rec->assetName))
rec->units = OWNER_UNITS;
else if (currentActiveAssetCache && currentActiveAssetCache->GetAssetMetaDataIfExists(rec->assetName, asset))
rec->units = asset.units;
else
rec->units = MAX_ASSET_UNITS;
int64_t nTime = wtx.GetTxTime();
CAmount nCredit = wtx.GetCredit(ISMINE_ALL);
CAmount nDebit = wtx.GetDebit(ISMINE_ALL);
CAmount nNet = nCredit - nDebit;
CAmount nAssetsRec = rec->credit;
// Status
strHTML += "<b>" + tr("Status") + ":</b> " + FormatTxStatus(wtx);
int nRequests = wtx.GetRequestCount();
if (nRequests != -1)
{
if (nRequests == 0)
strHTML += tr(", has not been successfully broadcast yet");
else if (nRequests > 0)
strHTML += tr(", broadcast through %n node(s)", "", nRequests);
}
strHTML += "<br>";
strHTML += "<b>" + tr("Date") + ":</b> " + (nTime ? GUIUtil::dateTimeStr(nTime) : "") + "<br>";
//
// From
//
if (wtx.mapValue.count("from") && !wtx.mapValue["from"].empty())
{
// Online transaction
strHTML += "<b>" + tr("From") + ":</b> " + GUIUtil::HtmlEscape(wtx.mapValue["from"]) + "<br>";
}
else
{
// Offline transaction
if (nAssetsRec > 0)
{
// Credit
CTxDestination address = DecodeDestination(rec->address);
if (IsValidDestination(address)) {
if (wallet->mapAddressBook.count(address))
{
strHTML += "<b>" + tr("From") + ":</b> " + tr("unknown") + "<br>";
strHTML += "<b>" + tr("To") + ":</b> ";
strHTML += GUIUtil::HtmlEscape(rec->address);
QString addressOwned = (::IsMine(*wallet, address) == ISMINE_SPENDABLE) ? tr("own address") : tr("watch-only");
if (!wallet->mapAddressBook[address].name.empty())
strHTML += " (" + addressOwned + ", " + tr("label") + ": " + GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + ")";
else
strHTML += " (" + addressOwned + ")";
strHTML += "<br>";
}
}
}
}
//
// To
//
if (wtx.mapValue.count("to") && !wtx.mapValue["to"].empty())
{
// Online transaction
std::string strAddress = wtx.mapValue["to"];
strHTML += "<b>" + tr("To") + ":</b> ";
CTxDestination dest = DecodeDestination(strAddress);
if (wallet->mapAddressBook.count(dest) && !wallet->mapAddressBook[dest].name.empty())
strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[dest].name) + " ";
strHTML += GUIUtil::HtmlEscape(strAddress) + "<br>";
}
//
// Amount
//
if (nAssetsRec > 0)
{
//
// Credit
//
strHTML += "<b>" + tr("Credit") + ":</b> " + BitcoinUnits::formatWithCustomName(QString::fromStdString(rec->assetName), nAssetsRec, rec->units) + "<br>";
} else {
strHTML += "<b>" + tr("Debit") + ":</b> " + BitcoinUnits::formatWithCustomName(QString::fromStdString(rec->assetName), nAssetsRec, rec->units, true) + "<br>";
}
strHTML += "<b>" + tr("Net BLAST amount") + ":</b> " + BitcoinUnits::formatHtmlWithUnit(unit, nNet, true) + "<br>";
//
// Message
//
if (wtx.mapValue.count("message") && !wtx.mapValue["message"].empty())
strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["message"], true) + "<br>";
if (wtx.mapValue.count("comment") && !wtx.mapValue["comment"].empty())
strHTML += "<br><b>" + tr("Comment") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["comment"], true) + "<br>";
strHTML += "<b>" + tr("Transaction ID") + ":</b> " + rec->getTxID() + "<br>";
strHTML += "<b>" + tr("Transaction total size") + ":</b> " + QString::number(wtx.tx->GetTotalSize()) + " bytes<br>";
strHTML += "<b>" + tr("Output index") + ":</b> " + QString::number(rec->getOutputIndex()) + "<br>";
// Message from normal blast:URI (blast:123...?message=example)
for (const std::pair<std::string, std::string>& r : wtx.vOrderForm)
if (r.first == "Message")
strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(r.second, true) + "<br>";
//
// PaymentRequest info:
//
for (const std::pair<std::string, std::string>& r : wtx.vOrderForm)
{
if (r.first == "PaymentRequest")
{
PaymentRequestPlus req;
req.parse(QByteArray::fromRawData(r.second.data(), r.second.size()));
QString merchant;
if (req.getMerchant(PaymentServer::getCertStore(), merchant))
strHTML += "<b>" + tr("Merchant") + ":</b> " + GUIUtil::HtmlEscape(merchant) + "<br>";
}
}
if (wtx.IsCoinBase())
{
quint32 numBlocksToMaturity = COINBASE_MATURITY + 1;
strHTML += "<br>" + tr("Generated coins must mature %1 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to \"not accepted\" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.").arg(QString::number(numBlocksToMaturity)) + "<br>";
}
//
// Debug view
//
if (logCategories != BCLog::NONE)
{
CreateDebugString(strHTML, wallet, wtx, unit);
}
strHTML += "</font></html>";
return strHTML;
}
void TransactionDesc::CreateDebugString(QString& strHTML, CWallet *wallet, CWalletTx &wtx, int unit)
{
strHTML += "<hr><br>" + tr("Debug information") + "<br><br>";
for (const CTxIn& txin : wtx.tx->vin)
if (wallet->IsMine(txin)) {
CAssetOutputEntry assetData;
CAmount debit = wallet->GetDebit(txin, ISMINE_ALL, assetData);
if (assetData.nAmount > 0) {
strHTML += "<b>" + tr("Debit") + ":</b> " +
BitcoinUnits::formatWithCustomName(QString::fromStdString(assetData.assetName), -assetData.nAmount) + "<br>";
}
strHTML += "<b>" + tr("Debit") + ":</b> " +
BitcoinUnits::formatHtmlWithUnit(unit, -debit) + "<br>";
}
for (const CTxOut& txout : wtx.tx->vout)
if (wallet->IsMine(txout)) {
if (txout.scriptPubKey.IsAssetScript()) {
CAssetOutputEntry assetData;
GetAssetData(txout.scriptPubKey, assetData);
strHTML += "<b>" + tr("Credit") + ":</b> " +
BitcoinUnits::formatWithCustomName(QString::fromStdString(assetData.assetName), assetData.nAmount) + "<br>";
} else
strHTML += "<b>" + tr("Credit") + ":</b> " +
BitcoinUnits::formatHtmlWithUnit(unit, wallet->GetCredit(txout, ISMINE_ALL)) + "<br>";
}
strHTML += "<br><b>" + tr("Transaction") + ":</b><br>";
strHTML += GUIUtil::HtmlEscape(wtx.tx->ToString(), true);
strHTML += "<br><b>" + tr("Inputs") + ":</b>";
strHTML += "<ul>";
for (const CTxIn& txin : wtx.tx->vin)
{
COutPoint prevout = txin.prevout;
Coin prev;
if(pcoinsTip->GetCoin(prevout, prev))
{
{
strHTML += "<li>";
const CTxOut &vout = prev.out;
CTxDestination address;
if (ExtractDestination(vout.scriptPubKey, address))
{
if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].name.empty())
strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address].name) + " ";
strHTML += QString::fromStdString(EncodeDestination(address));
}
strHTML = strHTML + " " + tr("Amount") + "=" + BitcoinUnits::formatHtmlWithUnit(unit, vout.nValue);
strHTML = strHTML + " IsMine=" + (wallet->IsMine(vout) & ISMINE_SPENDABLE ? tr("true") : tr("false")) + "</li>";
strHTML = strHTML + " IsWatchOnly=" + (wallet->IsMine(vout) & ISMINE_WATCH_ONLY ? tr("true") : tr("false")) + "</li>";
}
}
}
strHTML += "</ul>";
}
|
/////////////////////////////////////////////////////////////////////////////////
//
// Thor C++ Library
// Copyright (c) 2011-2019 Jan Haller
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
/////////////////////////////////////////////////////////////////////////////////
/// @file
/// @brief Complete header for the Shapes module
#ifndef THOR_MODULE_SHAPES_HPP
#define THOR_MODULE_SHAPES_HPP
#include <Thor/Shapes/Arrow.hpp>
#include <Thor/Shapes/ConcaveShape.hpp>
#include <Thor/Shapes/Shapes.hpp>
#endif // THOR_MODULE_SHAPES_HPP
|
// Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <vector>
#include <algorithm>
#include <utility>
#include <limits>
#include <string>
#include <map>
#include <legacy/ie_layers.h>
#include "gna_upstream_iterator.hpp"
#include "layers/gna_layer_info.hpp"
#include "gna_plugin_log.hpp"
#include "gna_slope_scale.h"
namespace GNAPluginNS {
namespace frontend {
struct ScaleFactorUpdateResult {
InferenceEngine::CNNLayer *restartLayer = nullptr;
ScaleFactorUpdateResult() = default;
explicit ScaleFactorUpdateResult(InferenceEngine::CNNLayer * restartlayer) : restartLayer(restartlayer) {
}
operator bool() {
return restartLayer == nullptr;
}
};
/**
* @brief calculates output scale factor per layer
* @tparam T
*/
template<class T>
class ScaleFactorPerLayer {
public:
/**
* @brief calculates weights scale factor for fit dynamic range into target bitsize,
* also calculates output scale factor for the given layer
* @param cnnLayer
* @param weightsSize
* @param result
* @return
*/
bool operator()(T cnnLayer, int weightsSize, ScaleFactorUpdateResult &result) {
return false;
}
};
template<>
class ScaleFactorPerLayer<InferenceEngine::CNNLayer *> {
private :
const float activation_scale_factor = 2048.f;
const float identity_scale_factor = 2049.0f;
const float k = 5;
const float k_identity = 6;
const double pow_domain = 16;
protected :
static bool fp32eq(float p1, float p2) {
return (std::abs(p1 - p2) <= 0.00001f * std::min(std::abs(p1), std::abs(p2)));
}
float getActivationScale(InferenceEngine::CNNLayer const* cnnLayer,
GNAPluginNS::LayerInfo const& layer,
QuantizedLayerParams const* quantizedParams) {
// todo: calculate proper scale factor where we need to expand it a bit to be safe to stay in int16 weights
// set the initial value
float result = activation_scale_factor;
if (layer.isIdentity()) {
// #define accurate_identity_scale_factor
#ifdef accurate_identity_scale_factor
// searching more accurate scale factor for identity
const double min_range = 1024.0;
const double max_range = 2049.0;
// gna encoded scale factor - the max this is the more accurate PWL approximation
double optimalK = 0.0f;
result = min_range;
for (int slope_scale_index = 1; slope_scale_index != 5; slope_scale_index ++) {
auto slope_scale = static_cast<double>(static_cast<uint64_t>(1) << (8 * slope_scale_index));
auto mink = min_range * slope_scale / quantizedParams->_src_quant.scale;
auto maxk = max_range * slope_scale / quantizedParams->_src_quant.scale;
if (mink < std::numeric_limits<int16_t>::max()) {
auto localMaxK = std::min(static_cast<double>(std::numeric_limits<int16_t>::max()), maxk);
if (localMaxK > optimalK) {
result = localMaxK / slope_scale * quantizedParams->_src_quant.scale;
optimalK = localMaxK;
}
}
}
#else
// GNA scale factor encoding might poor represent target slop scale, we are probing 2 values
auto s = gna_slope(1.0, quantizedParams->_src_quant.scale, identity_scale_factor);
auto scale_default = s.slope * s.slope_scale;
// probing one more quite good approximation for identity
s = gna_slope(1.0, quantizedParams->_src_quant.scale, identity_scale_factor / 2);
auto scale_extra = s.slope * s.slope_scale;
result = fabs(scale_extra) > fabs(scale_default) ? identity_scale_factor / 2 : identity_scale_factor;
#endif
} else if (layer.isRelu() &&
static_cast<uint64_t>(activation_scale_factor * quantizedParams->_src_quant.scale)
> std::numeric_limits<int32_t>::max()-1) {
// if activation is one from relu family, we need to apply heuristic to avoid activation output overflow
result = (activation_scale_factor * 0.5);
} else if (layer.isPower()) {
auto powerLayer = dynamic_cast<InferenceEngine::PowerLayer const*>(cnnLayer);
if (!powerLayer) {
THROW_IE_EXCEPTION << "Incorrect Power Layer pointer \n";
}
auto input_min_value = static_cast<double>(std::numeric_limits<int32_t>::min());
auto input_max_value = static_cast<double>(std::numeric_limits<int32_t>::max());
auto output_max_value = static_cast<double>(std::numeric_limits<int16_t>::max());
auto x_min = fp32eq(fmod(powerLayer->power, 1.0), 0) ? input_min_value / quantizedParams->_src_quant.scale : 0.0;
x_min = std::max(x_min, -pow_domain);
auto x_max = input_max_value / quantizedParams->_src_quant.scale;
x_max = std::min(x_max, pow_domain);
auto val1 = pow(x_min * powerLayer->scale + powerLayer->offset, powerLayer->power);
auto val2 = pow(x_max * powerLayer->scale + powerLayer->offset, powerLayer->power);
auto abs_val = std::max(std::abs(val1), std::abs(val2));
auto scale_val = output_max_value / abs_val;
if (!std::isinf(scale_val)) {
result = scale_val;
}
}
return result;
}
public :
bool operator()(InferenceEngine::CNNLayer *cnnLayer, int weightsSize, ScaleFactorUpdateResult &result) {
if ( !cnnLayer ) {
THROW_IE_EXCEPTION << "Incorrect Convolutional Layer pointer \n";
}
LayerInfo layerInfo(*cnnLayer);
// TODO: current approach set input scale factor for true input layer(s) equals to provided factor,
auto quant = InferenceEngine::getInjectedData<QuantizedLayerParams>(*cnnLayer);
if (InferenceEngine::details::CaselessEq<std::string>()(cnnLayer->type, "Memory")) {
if (CNNNetHasPrevLayer(cnnLayer)) {
auto prevLayer = CNNNetPrevLayer(cnnLayer);
auto prevInfo = LayerInfo(prevLayer);
auto inputQuant = InferenceEngine::getInjectedData<QuantizedLayerParams>(prevLayer);
// locating corresponding memory layers with same ID
for (auto && input : CNNNetGetAllInputLayers(cnnLayer)) {
LayerInfo ll(input);
if (!ll.isMemory() ||
!InferenceEngine::details::CaselessEq<std::string>()(input->params["id"], cnnLayer->params["id"])) {
continue;
}
auto quantSibling = InferenceEngine::getInjectedData<QuantizedLayerParams>(input);
// after restarting from memory input - quant is fine
if (fp32eq(quantSibling->_dst_quant.scale, inputQuant->_dst_quant.scale)) {
quant->_src_quant.scale = quant->_dst_quant.scale = inputQuant->_dst_quant.scale;
return true;
}
if (!fp32eq(quantSibling->_dst_quant.scale, 1)) {
// means we already restarted propagation input memory layer
// need to search for requantiseable layer prior memory output layer
InferenceEngine::CNNLayerPtr restartedLayer;
gnalog() << "Memory layer :"<< input->name << " scale factor: " << quantSibling->_dst_quant.scale
<< " doesn't match its outputs counterpart: " << cnnLayer->name << " scale factor: " << inputQuant->_dst_quant.scale << "\n";
gnalog() << "[UFS] searching for quantizeable input layer for: "<< cnnLayer->name << "\n";
CNNNetDFS(InferenceEngine::CNNLayerPtr(cnnLayer, [](InferenceEngine::CNNLayer *) {}),
[&restartedLayer, cnnLayer](InferenceEngine::CNNLayerPtr layer) {
gnalog() << "[UFS] from : " << cnnLayer->name << " reached: " << layer->name;
// found that direct input to concat is a indirect parent of align filter - so no link required
auto info = LayerInfo(layer);
if (!info.isWeightable() && !info.isActivation()) {
gnalog() << "... skipped\n";
return;
}
restartedLayer = layer;
gnalog() << "... OK, need requantize\n";
}, true, [&restartedLayer, &cnnLayer](InferenceEngine::CNNLayer *from) {
// aborting UFS once found suitable layer
return make_upstream_order(restartedLayer == nullptr ? from : nullptr);
});
if (restartedLayer == nullptr) {
THROW_GNA_EXCEPTION << "cannot requantize input to " << cnnLayer->name;
}
auto quantDataForMemoryOutput = InferenceEngine::getInjectedData<QuantizedLayerParams>(*restartedLayer);
auto restarLayerInfo = LayerInfo(restartedLayer);
if (restarLayerInfo.isActivation()) {
// requantize activation by just changing it's output scale factor
quantDataForMemoryOutput->_dst_quant.scale = quantSibling->_dst_quant.scale;
} else {
THROW_GNA_EXCEPTION << "quantization error : input scale factor ( " << inputQuant->_dst_quant.scale <<") "
<< " for " << cnnLayer->name << ", that is child of " << prevLayer->name <<" doesnt match : "
<< activation_scale_factor;
}
result = ScaleFactorUpdateResult(restartedLayer.get());
return true;
}
gnawarn() << "[INFO] quantization : input scale factor (" << inputQuant->_dst_quant.scale <<")"
<< " for " << cnnLayer->name << ", that is child of " << prevLayer->name <<" doesnt match : "
<< activation_scale_factor << ", restarting from corresponding memory: "<< input->name << std::endl;
// try updating memory input layer scale factor and restart from it
quantSibling->_src_quant.scale = quantSibling->_dst_quant.scale = inputQuant->_dst_quant.scale;
result = ScaleFactorUpdateResult(input.get());
return true;
}
}
return true;
}
if (cnnLayer->type == "Const") {
auto blob = cnnLayer->blobs["custom"];
auto blob_precision = blob->getTensorDesc().getPrecision();
if (blob_precision != InferenceEngine::Precision::FP32 && blob_precision != InferenceEngine::Precision::FP16) {
quant->_dst_quant.scale = 1.0f;
return true;
}
if (blob_precision == InferenceEngine::Precision::FP16) {
blob = make_fp32_blob(blob);
}
auto max_val = std::numeric_limits<float>::min();
auto min_val = std::numeric_limits<float>::max();
auto flt_buf = blob->buffer().as<float*>();
auto size = blob->size();
for (int i=0; i < size; i++) {
auto val = flt_buf[i];
if (val > max_val) max_val = val;
if (val < min_val) min_val = val;
}
auto abs_val = std::max(std::abs(max_val), std::abs(min_val));
auto scale_val = static_cast<float>(std::numeric_limits<int16_t>::max()) / abs_val;
// TODO: Investigate what should be the scale in such cases (31910)
if (std::isinf(scale_val)) {
quant->_dst_quant.scale = quant->_src_quant.scale;
} else {
quant->_dst_quant.scale = scale_val;
}
return ScaleFactorUpdateResult();
}
if (!CNNNetHasPrevLayer(cnnLayer)) {
quant->_dst_quant.scale = quant->_src_quant.scale;
return ScaleFactorUpdateResult();
}
// by default layer is pass thru its scale factor
auto inputQuant = InferenceEngine::getInjectedData<QuantizedLayerParams>(CNNNetPrevLayer(cnnLayer));
if (!inputQuant) {
THROW_GNA_EXCEPTION << "layer: " << CNNNetPrevLayer(cnnLayer)->name << "not quantized";
}
quant->_dst_quant.scale = inputQuant->_dst_quant.scale;
quant->_src_quant.scale = inputQuant->_dst_quant.scale;
if (layerInfo.isActivation()) {
// todo: calculate proper scale factor where we need to expand it a bit to be safe to stay in int16 weights
// set the initial value
quant->_dst_quant.scale = getActivationScale(cnnLayer, layerInfo, quant);
}
return true;
}
};
template<>
class ScaleFactorPerLayer<InferenceEngine::EltwiseLayer*> {
public:
bool operator()(InferenceEngine::EltwiseLayer* eltwiseLayer, int weightsSize, ScaleFactorUpdateResult &result) {
if ( !eltwiseLayer ) {
THROW_GNA_EXCEPTION << "Incorrect Eltwise Layer pointer \n";
}
auto in0 = InferenceEngine::CNNNetPrevLayer(eltwiseLayer, 0);
auto in1 = InferenceEngine::CNNNetPrevLayer(eltwiseLayer, 1);
auto quantParams0 = InferenceEngine::getInjectedData<QuantizedLayerParams>(in0);
auto quantParams1 = InferenceEngine::getInjectedData<QuantizedLayerParams>(in1);
auto quantData = InferenceEngine::getInjectedData<QuantizedLayerParams>(*eltwiseLayer);
switch (eltwiseLayer->_operation) {
case InferenceEngine::EltwiseLayer::Prod: {
quantData->_weights_quant.scale = quantParams1->_dst_quant.scale;
quantData->_dst_quant.scale = quantParams0->_dst_quant.scale * quantParams1->_dst_quant.scale;
break;
}
case InferenceEngine::EltwiseLayer::Sub:
case InferenceEngine::EltwiseLayer::Sum: {
// detect which input will be used as biases
auto findPrevFunctional = [](InferenceEngine::CNNLayerPtr layer) {
auto prev = InferenceEngine::CNNNetPrevLayer(layer, 0);
while (CNNNetHasPrevLayer(prev.get(), 0) && LayerInfo(prev).isNonFunctional()) {
prev = InferenceEngine::CNNNetPrevLayer(prev, 0);
}
return prev;
};
if (LayerInfo(in0).has32BOutput() ||
(LayerInfo(in0).isNonFunctional() && CNNNetHasPrevLayer(in0.get(), 0) && LayerInfo(findPrevFunctional(in0)).has32BOutput())) {
std::swap(in0, in1);
std::swap(quantParams0, quantParams1);
}
// this path might result in significant data loss
quantData->_bias_quant.scale = quantParams1->_dst_quant.scale / quantParams0->_dst_quant.scale;
quantData->_weights_quant.scale = quantParams1->_dst_quant.scale / quantParams0->_dst_quant.scale;
quantData->_dst_quant.scale = quantParams1->_dst_quant.scale;
// eltwise will always work in int16
auto maxValue = std::numeric_limits<int16_t>::max() - 1;
if (quantData->_weights_quant.scale > maxValue + 1) {
// rescaling it's activation input
// iterating thru previous layers of eltwise
for (uint8_t i = 0; i < 2; ++i) {
InferenceEngine::CNNLayerPtr in = InferenceEngine::CNNNetPrevLayer(eltwiseLayer, i);
// trick to get opposite index (for 0 -> 1 for 1 -> 0) by inversing i.
auto quantParams =
InferenceEngine::getInjectedData<QuantizedLayerParams>(InferenceEngine::CNNNetPrevLayer(eltwiseLayer, !i));
for (; InferenceEngine::CNNNetHasPrevLayer(in.get()); in = CNNNetPrevLayer(in)) {
auto info = LayerInfo(in);
// we skipping only split layers so far, also need to work on memory layers
// this case for input from port 0
if (info.isSplit() || info.isSlice()) {
continue;
} else if (info.has16BOutput() && info.isActivation()) {
auto newOutputScale = quantParams->_dst_quant.scale / maxValue;
if (newOutputScale > static_cast<float>(std::numeric_limits<int16_t>::max()) / 2) {
break;
}
auto quantDataForActivation = InferenceEngine::getInjectedData<QuantizedLayerParams>(*in);
gnawarn() << "[WARNING] saturated weights for " << eltwiseLayer->name
<< ". Layer new output scale: " << in->name << ", output_scale=" << newOutputScale
<< ", was " << quantDataForActivation->_dst_quant.scale <<"\n" << std::flush;
quantDataForActivation->_dst_quant.scale = newOutputScale;
result = ScaleFactorUpdateResult(in.get());
return true;
} else if (info.has16BOutput()) {
break;
}
// if we are here it means that we are in the port 1
if (info.isFullyConnected() || info.isConvolution()) {
auto quantDataForInputLayer = InferenceEngine::getInjectedData<QuantizedLayerParams>(*in);
auto newOutputScale = quantParams->_dst_quant.scale * maxValue;
auto newWeightScale = newOutputScale / quantDataForInputLayer->_src_quant.scale;
quantDataForInputLayer->_dst_quant.scale = newOutputScale;
quantDataForInputLayer->_weights_quant.scale = newWeightScale;
result = ScaleFactorUpdateResult(in.get());
return true;
}
}
}
// we unable to rescale the input - results might be bad
gnawarn() << "[INFO] weights saturated for " << eltwiseLayer->name << "\n";
}
break;
}
default : THROW_GNA_EXCEPTION << "Unsupported Eltwise layer for quantisation: " << eltwiseLayer->_operation;
}
return true;
}
};
template<>
class ScaleFactorPerLayer<InferenceEngine::ConcatLayer*> {
public:
bool operator()(InferenceEngine::ConcatLayer* concatLayer, int weightsSize, ScaleFactorUpdateResult &result) {
if ( !concatLayer ) {
THROW_GNA_EXCEPTION << "Incorrect Concat Layer pointer \n";
}
if (concatLayer->insData.size() < 2) {
THROW_GNA_EXCEPTION << "Concat layer has unsupported number of incoming layers.";
}
auto fp32eq = [](float p1, float p2) -> bool {
return (std::abs(p1 - p2) <= 0.00001f * std::min(std::abs(p1), std::abs(p2)));
};
auto quantData = InferenceEngine::getInjectedData<QuantizedLayerParams>(*concatLayer);
std::vector<InferenceEngine::CNNLayerPtr> inputLayers;
for (auto input_idx = 0; input_idx != concatLayer->insData.size(); input_idx++) {
inputLayers.push_back(InferenceEngine::CNNNetPrevLayer(concatLayer, input_idx));
}
// if all inputs have same quant value - trivial propagation
auto in0 = inputLayers.front();
auto quantParams0 = InferenceEngine::getInjectedData<QuantizedLayerParams>(in0);
auto scaleFactor = quantParams0->_dst_quant.scale;
auto scaleFactorCheck = [scaleFactor, &fp32eq](InferenceEngine::CNNLayerPtr& inputLayer) {
auto quantParams = InferenceEngine::getInjectedData<QuantizedLayerParams>(inputLayer);
return fp32eq(quantParams->_dst_quant.scale, scaleFactor);
};
if (std::find_if_not(inputLayers.begin() + 1, inputLayers.end(), scaleFactorCheck) == inputLayers.end()) {
quantData->_dst_quant.scale = quantParams0->_dst_quant.scale;
quantData->_src_quant.scale = quantParams0->_dst_quant.scale;
return true;
}
// check if all inputs have the same quant value
auto inputLayerCheck = [](InferenceEngine::CNNLayerPtr& inputLayer) {
auto info = LayerInfo(inputLayer);
return info.isInput();
};
GNAPluginNS::QuantizedLayerParams* sourceQuantParams = nullptr;
auto firstInputIt = std::find_if(inputLayers.begin(), inputLayers.end(), inputLayerCheck);
if (firstInputIt != inputLayers.end()) {
auto quantParamsFirst = InferenceEngine::getInjectedData<QuantizedLayerParams>(*firstInputIt);
auto nextInputIt = firstInputIt + 1;
while ((nextInputIt = std::find_if(nextInputIt, inputLayers.end(), inputLayerCheck)) != inputLayers.end()) {
auto quantParamsSecond = InferenceEngine::getInjectedData<QuantizedLayerParams>(*nextInputIt);
if (!fp32eq(quantParamsSecond->_dst_quant.scale, quantParamsFirst->_dst_quant.scale)) {
THROW_GNA_EXCEPTION << "Two Input layers " << (*firstInputIt)->name
<< " and " << (*nextInputIt)->name << " have different scales in concat!!! \n";
}
}
}
// find a source quant value
// - 1st candidate - input layer
// - 2nd candidate - non-activation layer with non-1 scale factor
// - 3rd candidate - 1st layer with non-1 scale factor
auto sourceLayerCheck = [&fp32eq](InferenceEngine::CNNLayerPtr& inputLayer) {
auto quantParams = InferenceEngine::getInjectedData<QuantizedLayerParams>(inputLayer);
LayerInfo info(inputLayer);
return !info.isActivation() && !fp32eq(quantParams->_dst_quant.scale, 1.0f);
};
static std::map<std::string, size_t> restarted_counter;
auto restartedCountIt = restarted_counter.find(concatLayer->name);
if (restartedCountIt == restarted_counter.end()) {
auto pos = restarted_counter.insert({ concatLayer->name, 0 });
restartedCountIt = pos.first;
}
if (((restartedCountIt->second) / 2) % 2 == 1) {
std::reverse(inputLayers.begin(), inputLayers.end());
}
++restartedCountIt->second;
auto sourceLayerIt = (firstInputIt != inputLayers.end()) ? firstInputIt
: std::find_if(inputLayers.begin(), inputLayers.end(), sourceLayerCheck);
if (sourceLayerIt == inputLayers.end()) {
auto nonDefaultScaleFactor = [&fp32eq](InferenceEngine::CNNLayerPtr& inputLayer) {
auto quantParams = InferenceEngine::getInjectedData<QuantizedLayerParams>(inputLayer);
return !fp32eq(quantParams->_dst_quant.scale, 1.0f);
};
sourceLayerIt = std::find_if(inputLayers.begin(), inputLayers.end(), nonDefaultScaleFactor);
}
std::set<size_t> concatIdxToUpdate;
if (sourceLayerIt != inputLayers.end()) {
auto quantParams = InferenceEngine::getInjectedData<QuantizedLayerParams>(*sourceLayerIt);
auto scaleFactor = quantParams->_dst_quant.scale;
sourceQuantParams = quantParams;
for (auto it = inputLayers.begin(); it != inputLayers.end(); ++it) {
auto quantParamsIn = InferenceEngine::getInjectedData<QuantizedLayerParams>(*it);
if (fp32eq(quantParamsIn->_dst_quant.scale, scaleFactor)) {
continue;
}
// possible case when some of the concat inputs are free to select scale ex: const->concat<-affine
if (!fp32eq(quantParamsIn->_dst_quant.scale, 1.0f) && !LayerInfo(*it).isActivation()) {
concatIdxToUpdate.insert(std::distance(inputLayers.begin(), it));
}
quantParamsIn->_weights_quant = quantParams->_dst_quant;
quantParamsIn->_dst_quant = quantParams->_dst_quant;
}
}
auto updatedScaleFactor = InferenceEngine::getInjectedData<QuantizedLayerParams>(in0)->_dst_quant.scale;
auto equalScaleFactor = [updatedScaleFactor, &fp32eq](InferenceEngine::CNNLayerPtr& inputLayer) {
auto quantParams = InferenceEngine::getInjectedData<QuantizedLayerParams>(inputLayer);
return fp32eq(quantParams->_dst_quant.scale, updatedScaleFactor);
};
auto layerIt = std::find_if_not(inputLayers.begin() + 1, inputLayers.end(), equalScaleFactor);
if (layerIt != inputLayers.end()) {
THROW_GNA_EXCEPTION << "layers entered into concat have different scale factors" << concatLayer->name;
}
quantData->_dst_quant.scale = sourceQuantParams->_dst_quant.scale;
quantData->_src_quant.scale = sourceQuantParams->_dst_quant.scale;
if (layerIt == inputLayers.end() && concatIdxToUpdate.empty()) {
return true;
}
for (auto& layerIdToUpdate : concatIdxToUpdate) {
auto destinationQuantParams = InferenceEngine::getInjectedData<QuantizedLayerParams>(*concatLayer);
destinationQuantParams->_dst_quant.scale = sourceQuantParams->_dst_quant.scale;
InferenceEngine::CNNLayerPtr restartedLayer;
// making a link activation possible without extra layer if first input to concat not a parent / indirect parent of second input
// using ufs - upper first search
gnalog() << "[UFS] searching for quantizeable layer prior: " << concatLayer->name << ", via " << layerIdToUpdate << "\n";
CNNNetDFS(InferenceEngine::CNNLayerPtr(concatLayer, [](InferenceEngine::CNNLayer*) {}),
[&restartedLayer, concatLayer](InferenceEngine::CNNLayerPtr layer) {
gnalog() << "[UFS] from : " << concatLayer->name << " reached: " << layer->name;
// found that direct input to concat is a indirect parent of align filter - so no link required
auto info = LayerInfo(layer);
if (!info.isWeightable() && !info.isActivation() && !info.isConst()) {
gnalog() << "... skipped\n";
return;
}
restartedLayer = layer;
gnalog() << "... OK, need requantize\n";
}, true, [&restartedLayer, &concatLayer, &layerIdToUpdate](InferenceEngine::CNNLayer* from) {
// aborting UFS once found functional layer, and using only specified input of concat
return make_upstream_order(restartedLayer == nullptr ? from : nullptr,
from == concatLayer ? layerIdToUpdate : -1);
});
if (restartedLayer == nullptr) {
THROW_GNA_EXCEPTION << "cannot requantize " << layerIdToUpdate << "input to concat: " << concatLayer->name;
}
auto quantDataForConCatInput = InferenceEngine::getInjectedData<QuantizedLayerParams>(*restartedLayer);
auto restarLayerInfo = LayerInfo(restartedLayer);
if (restarLayerInfo.isActivation()) {
// requantize activation by just changing it's output scale factor
quantDataForConCatInput->_dst_quant.scale = sourceQuantParams->_dst_quant.scale;
}
if (restarLayerInfo.isConst()) {
gnalog() << "... warning const layer will be requantized\n";
quantDataForConCatInput->_dst_quant.scale = sourceQuantParams->_dst_quant.scale;
}
result = ScaleFactorUpdateResult(restartedLayer.get());
}
return true;
}
};
template<>
class ScaleFactorPerLayer<InferenceEngine::WeightableLayer*> {
private:
float const _scale_reduction_50 = 0.50;
float const _scale_reduction_45 = 0.45;
float const _scale_reduction_40 = 0.40;
float const _scale_reduction_35 = 0.35;
uint16_t const _scale_change_req_threshold = 30;
uint16_t const _scale_change_threshold_100 = 100;
uint16_t const _scale_change_threshold_150 = 150;
uint16_t const _scale_change_threshold_200 = 200;
public:
bool operator()(InferenceEngine::WeightableLayer *wl, int weightsSize, ScaleFactorUpdateResult &result) {
if ( !wl ) {
THROW_GNA_EXCEPTION << "Incorrect Weightable Layer pointer \n";
} else if (!wl->_weights) {
THROW_GNA_EXCEPTION << "Incorrect weight value for " << wl->name << ":" << wl->type << "\n";
}
auto prevLayer = CNNNetPrevLayer(wl);
auto quantDataForInputLayer =
InferenceEngine::getInjectedData<QuantizedLayerParams>(*InferenceEngine::CNNNetPrevLayer(wl).get());
auto quant = InferenceEngine::getInjectedData<QuantizedLayerParams>(*wl);
quant->_src_quant.scale = quantDataForInputLayer->_dst_quant.scale;
// TODO: pass 8 bits somehow
if (quant->_weights_quant.scale == 1.0f) {
size_t scaleRange = 0;
if (weightsSize == 2) {
scaleRange = MAX_VAL_2B_WEIGHT;
} else if (weightsSize == 1) {
scaleRange = MAX_VAL_1B_WEIGHT;
} else {
THROW_GNA_EXCEPTION << "Unsupported weights size of: " << weightsSize;
}
quant->_weights_quant.scale =
ScaleFactorForQuantization(wl->_weights->buffer().as<float *>(), scaleRange, wl->_weights->size());
if (quant->_weights_quant.scale == -1.0f) {
quant->_weights_quant.scale = 1.0f;
}
if (wl->_biases) {
quant->_bias_quant.scale = ScaleFactorForQuantization(wl->_biases->buffer().as<float *>(),
MAX_VAL_4B_BIAS,
wl->_biases->size());
if (quant->_bias_quant.scale != -1.0f) {
quant->_bias_quant.scale = std::min(quant->_weights_quant.scale * quant->_src_quant.scale, quant->_bias_quant.scale);
quant->_weights_quant.scale = quant->_bias_quant.scale / quant->_src_quant.scale;
}
}
// TODO: findout why ???
if (weightsSize == 1) {
quant->_weights_quant.scale *= MAX_OUT_MULTIPLIER;
}
double weights_reducer = 1.0;
auto conv = dynamic_cast<InferenceEngine::ConvolutionLayer*>(wl);
if (conv) {
auto dims = conv->insData.front().lock()->getDims();
weights_reducer = MAX_VAL_2B_FEAT * scaleRange * dims[1] / std::numeric_limits<int32_t>::max();
weights_reducer = std::max(1.0, weights_reducer);
}
quant->_weights_quant.scale /= weights_reducer;
}
double tmp_dst_quant_scale = quant->_weights_quant.scale * quantDataForInputLayer->_dst_quant.scale;
if (weightsSize == 1 &&
static_cast<uint64_t>(tmp_dst_quant_scale * quant->_src_quant.scale) >
static_cast<uint64_t>(std::numeric_limits<int32_t>::max()-1) * _scale_change_req_threshold) {
gnawarn() << "Output scale for " << wl->name
<< " too large and are being reduced. Else saturations likely will happen \n";
// reduce weight scale according experimental heuristic
if (quant->_dst_quant.scale * quant->_src_quant.scale /
static_cast<float>(std::numeric_limits<int32_t>::max()) < _scale_change_threshold_100) {
quant->_weights_quant.scale *= _scale_reduction_50;
tmp_dst_quant_scale *= _scale_reduction_50;
} else if (quant->_dst_quant.scale * quant->_src_quant.scale /
static_cast<float>(std::numeric_limits<int32_t>::max()) < _scale_change_threshold_150) {
quant->_weights_quant.scale *= _scale_reduction_45;
tmp_dst_quant_scale *= _scale_reduction_45;
} else if (quant->_dst_quant.scale * quant->_src_quant.scale /
static_cast<float>(std::numeric_limits<int32_t>::max()) < _scale_change_threshold_200) {
quant->_weights_quant.scale *= _scale_reduction_40;
tmp_dst_quant_scale *= _scale_reduction_40;
} else {
quant->_weights_quant.scale *= _scale_reduction_35;
tmp_dst_quant_scale *= _scale_reduction_35;
}
}
quant->_dst_quant.scale = tmp_dst_quant_scale;
return true;
}
};
template<>
class ScaleFactorPerLayer<InferenceEngine::ScaleShiftLayer*> : public ScaleFactorPerLayer<InferenceEngine::WeightableLayer*> {
public:
bool operator()(InferenceEngine::WeightableLayer *wl, int weightsSize, ScaleFactorUpdateResult &result) {
return ScaleFactorPerLayer<InferenceEngine::WeightableLayer*>::operator()(wl, 2, result);
}
};
/**
* GNA convolutions cannot be quantized in int8, remove when library starts support that
*/
template<>
class ScaleFactorPerLayer<InferenceEngine::ConvolutionLayer*> : public ScaleFactorPerLayer<InferenceEngine::ScaleShiftLayer*> {
};
} // namespace frontend
/**
* @brief scale factor calculator will calculate only output scale factors for the layer
* if scale factor propagation not possible, it will fall indicate a restart condition
*/
class ScaleFactorCalculator {
using Cnt = std::vector<InferenceEngine::CNNLayerPtr>;
Cnt net;
mutable Cnt::const_iterator idx;
mutable bool needRestart = false;
int weightsBytesSize;
public:
ScaleFactorCalculator(Cnt &net, int weightsBytesSize)
: net(net), weightsBytesSize(weightsBytesSize) {
idx = std::begin(this->net);
}
bool needToRestart() const {
return needRestart;
}
bool allLayersProcessed() const {
return idx == std::end(net);
}
std::vector<InferenceEngine::CNNLayerPtr> getStartLayers() const {
return std::vector<InferenceEngine::CNNLayerPtr>(idx, std::end(net));
}
template<class T>
bool operator()(T ptr) const {
needRestart = false;
frontend::ScaleFactorUpdateResult result;
if (!frontend::ScaleFactorPerLayer<T>()(ptr, weightsBytesSize, result)) {
return false;
}
if (result) {
idx++;
return true;
}
idx = std::find_if(net.begin(), net.end(), [&](InferenceEngine::CNNLayerPtr cnnLayer) {
if (!result) {
return result.restartLayer == cnnLayer.get();
}
return ptr == cnnLayer.get();
});
if (idx != net.end()) {
idx++;
}
needRestart = true;
return true;
}
};
} // namespace GNAPluginNS
|
/*
* This software is distributed under BSD 3-clause license (see LICENSE file).
*
* Authors: Kevin Hughes, Heiko Strathmann, Bjoern Esser
*/
#include <shogun/converter/ica/UWedgeSep.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/mathematics/Math.h>
#include <shogun/mathematics/eigen3.h>
#include <shogun/mathematics/ajd/UWedge.h>
using namespace shogun;
using namespace Eigen;
namespace { MatrixXd cor(MatrixXd x, int tau = 0, bool mean_flag = true); };
CUWedgeSep::CUWedgeSep() : CICAConverter()
{
init();
}
void CUWedgeSep::init()
{
m_tau = SGVector<float64_t>(4);
m_tau[0]=0; m_tau[1]=1; m_tau[2]=2; m_tau[3]=3;
m_covs = SGNDArray<float64_t>();
SG_ADD(&m_tau, "tau", "tau vector", ParameterProperties::HYPER);
}
CUWedgeSep::~CUWedgeSep()
{
}
void CUWedgeSep::set_tau(SGVector<float64_t> tau)
{
m_tau = tau;
}
SGVector<float64_t> CUWedgeSep::get_tau() const
{
return m_tau;
}
SGNDArray<float64_t> CUWedgeSep::get_covs() const
{
return m_covs;
}
void CUWedgeSep::fit_dense(CDenseFeatures<float64_t>* features)
{
auto X = features->get_feature_matrix();
int n = X.num_rows;
int m = X.num_cols;
int N = m_tau.vlen;
Map<MatrixXd> EX(X.matrix,n,m);
// Compute Correlation Matrices
index_t * M_dims = SG_MALLOC(index_t, 3);
M_dims[0] = n;
M_dims[1] = n;
M_dims[2] = N;
m_covs = SGNDArray< float64_t >(M_dims, 3);
for (int t = 0; t < N; t++)
{
Map<MatrixXd> EM(m_covs.get_matrix(t),n,n);
EM = cor(EX,m_tau[t]);
}
// Diagonalize
SGMatrix<float64_t> Q = CUWedge::diagonalize(m_covs, m_mixing_matrix, tol, max_iter);
Map<MatrixXd> EQ(Q.matrix,n,n);
// Compute Mixing Matrix
m_mixing_matrix = SGMatrix<float64_t>(n,n);
Map<MatrixXd> C(m_mixing_matrix.matrix,n,n);
C = EQ.inverse();
// Normalize Estimated Mixing Matrix
for (int t = 0; t < C.cols(); t++)
C.col(t) /= C.col(t).maxCoeff();
}
// Computing time delayed correlation matrix
namespace
{
MatrixXd cor(MatrixXd x, int tau, bool mean_flag)
{
int m = x.rows();
int n = x.cols();
// Center the data
if ( mean_flag )
{
VectorXd mean = x.rowwise().sum();
mean /= n;
x = x.colwise() - mean;
}
// Time-delayed Signal Matrix
MatrixXd L = x.leftCols(n-tau);
MatrixXd R = x.rightCols(n-tau);
// Compute Correlations
MatrixXd K(m,m);
K = (L * R.transpose()) / (n-tau);
// Symmetrize
K = (K + K.transpose()) / 2.0;
return K;
}
};
|
/*
https://practice.geeksforgeeks.org/problems/delete-nodes-having-greater-value-on-right/1
Delete nodes having greater value on right
Medium Accuracy: 37.92% Submissions: 50140 Points: 4
Given a singly linked list, remove all the nodes which have a greater value on its following nodes.
Example 1:
Input:
LinkedList = 12->15->10->11->5->6->2->3
Output: 15 11 6 3
Explanation: Since, 12, 10, 5 and 2 are
the elements which have greater elements
on the following nodes. So, after deleting
them, the linked list would like be 15,
11, 6, 3.
Example 2:
Input:
LinkedList = 10->20->30->40->50->60
Output: 60
Your Task:
The task is to complete the function compute() which should modify the list as required and return the head of the modified linked list. The printing is done by the driver code,
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ size of linked list ≤ 1000
1 ≤ element of linked list ≤ 1000
Note: Try to solve the problem without using any extra space.
*/
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node *next;
Node(int x)
{
data = x;
next = NULL;
}
};
void print(Node *root)
{
Node *temp = root;
while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
}
// } Driver Code Ends
/*
The structure of linked list is the following
struct Node
{
int data;
Node* next;
Node(int x){
data = x;
next = NULL;
}
};
*/
class Solution
{
public:
Node *compute(Node *head)
{
if (head->next == NULL)
return head;
struct Node *temp = compute(head->next);
if (temp->data > head->data)
return temp;
else
head->next = temp;
return head;
}
};
// { Driver Code Starts.
int main()
{
int T;
cin >> T;
while (T--)
{
int K;
cin >> K;
struct Node *head = NULL;
struct Node *temp = head;
for (int i = 0; i < K; i++)
{
int data;
cin >> data;
if (head == NULL)
head = temp = new Node(data);
else
{
temp->next = new Node(data);
temp = temp->next;
}
}
Solution ob;
Node *result = ob.compute(head);
print(result);
cout << endl;
}
}
// } Driver Code Ends
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 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 "validationinterface.h"
#include "util.h"
static CMainSignals g_signals;
CMainSignals& GetMainSignals()
{
return g_signals;
}
void RegisterValidationInterface(CValidationInterface* pwalletIn) {
g_signals.AcceptedBlockHeader.connect(boost::bind(&CValidationInterface::AcceptedBlockHeader, pwalletIn, boost::placeholders::_1));
g_signals.NotifyHeaderTip.connect(boost::bind(&CValidationInterface::NotifyHeaderTip, pwalletIn, boost::placeholders::_1, boost::placeholders::_2));
g_signals.UpdatedBlockTip.connect(boost::bind(&CValidationInterface::UpdatedBlockTip, pwalletIn, boost::placeholders::_1, boost::placeholders::_2, boost::placeholders::_3));
g_signals.SyncTransaction.connect(boost::bind(&CValidationInterface::SyncTransaction, pwalletIn, boost::placeholders::_1, boost::placeholders::_2, boost::placeholders::_3));
g_signals.UpdatedTransaction.connect(boost::bind(&CValidationInterface::UpdatedTransaction, pwalletIn, boost::placeholders::_1));
g_signals.SetBestChain.connect(boost::bind(&CValidationInterface::SetBestChain, pwalletIn, boost::placeholders::_1));
g_signals.Inventory.connect(boost::bind(&CValidationInterface::Inventory, pwalletIn, boost::placeholders::_1));
g_signals.Broadcast.connect(boost::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn, boost::placeholders::_1, boost::placeholders::_2));
g_signals.BlockChecked.connect(boost::bind(&CValidationInterface::BlockChecked, pwalletIn, boost::placeholders::_1, boost::placeholders::_2));
g_signals.ScriptForMining.connect(boost::bind(&CValidationInterface::GetScriptForMining, pwalletIn, boost::placeholders::_1));
g_signals.BlockFound.connect(boost::bind(&CValidationInterface::ResetRequestCount, pwalletIn, boost::placeholders::_1));
g_signals.NewPoWValidBlock.connect(boost::bind(&CValidationInterface::NewPoWValidBlock, pwalletIn, boost::placeholders::_1, boost::placeholders::_2));
}
void UnregisterValidationInterface(CValidationInterface* pwalletIn) {
g_signals.BlockFound.disconnect(boost::bind(&CValidationInterface::ResetRequestCount, pwalletIn, boost::placeholders::_1));
g_signals.ScriptForMining.disconnect(boost::bind(&CValidationInterface::GetScriptForMining, pwalletIn, boost::placeholders::_1));
g_signals.BlockChecked.disconnect(boost::bind(&CValidationInterface::BlockChecked, pwalletIn, boost::placeholders::_1, boost::placeholders::_2));
g_signals.Broadcast.disconnect(boost::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn, boost::placeholders::_1, boost::placeholders::_2));
g_signals.Inventory.disconnect(boost::bind(&CValidationInterface::Inventory, pwalletIn, boost::placeholders::_1));
g_signals.SetBestChain.disconnect(boost::bind(&CValidationInterface::SetBestChain, pwalletIn, boost::placeholders::_1));
g_signals.UpdatedTransaction.disconnect(boost::bind(&CValidationInterface::UpdatedTransaction, pwalletIn, boost::placeholders::_1));
g_signals.SyncTransaction.disconnect(boost::bind(&CValidationInterface::SyncTransaction, pwalletIn, boost::placeholders::_1, boost::placeholders::_2, boost::placeholders::_3));
g_signals.UpdatedBlockTip.disconnect(boost::bind(&CValidationInterface::UpdatedBlockTip, pwalletIn, boost::placeholders::_1, boost::placeholders::_2, boost::placeholders::_3));
g_signals.NewPoWValidBlock.disconnect(boost::bind(&CValidationInterface::NewPoWValidBlock, pwalletIn, boost::placeholders::_1, boost::placeholders::_2));
g_signals.NotifyHeaderTip.disconnect(boost::bind(&CValidationInterface::NotifyHeaderTip, pwalletIn, boost::placeholders::_1, boost::placeholders::_2));
g_signals.AcceptedBlockHeader.disconnect(boost::bind(&CValidationInterface::AcceptedBlockHeader, pwalletIn, boost::placeholders::_1));
}
void UnregisterAllValidationInterfaces() {
g_signals.BlockFound.disconnect_all_slots();
g_signals.ScriptForMining.disconnect_all_slots();
g_signals.BlockChecked.disconnect_all_slots();
g_signals.Broadcast.disconnect_all_slots();
g_signals.Inventory.disconnect_all_slots();
g_signals.SetBestChain.disconnect_all_slots();
g_signals.UpdatedTransaction.disconnect_all_slots();
g_signals.SyncTransaction.disconnect_all_slots();
g_signals.UpdatedBlockTip.disconnect_all_slots();
g_signals.NewPoWValidBlock.disconnect_all_slots();
g_signals.NotifyHeaderTip.disconnect_all_slots();
g_signals.AcceptedBlockHeader.disconnect_all_slots();
}
|
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/rtp_rtcp/source/rtp_rtcp_impl.h"
#include <string.h>
#include <algorithm>
#include <cstdint>
#include <set>
#include <string>
#include <utility>
#include "absl/memory/memory.h"
#include "api/transport/field_trial_based_config.h"
#include "modules/rtp_rtcp/source/rtcp_packet/dlrr.h"
#include "modules/rtp_rtcp/source/rtp_rtcp_config.h"
#include "rtc_base/checks.h"
#include "rtc_base/logging.h"
#ifdef _WIN32
// Disable warning C4355: 'this' : used in base member initializer list.
#pragma warning(disable : 4355)
#endif
namespace webrtc {
namespace {
const int64_t kRtpRtcpMaxIdleTimeProcessMs = 5;
const int64_t kRtpRtcpRttProcessTimeMs = 1000;
const int64_t kRtpRtcpBitrateProcessTimeMs = 10;
const int64_t kDefaultExpectedRetransmissionTimeMs = 125;
constexpr int32_t kDefaultVideoReportInterval = 1000;
constexpr int32_t kDefaultAudioReportInterval = 5000;
} // namespace
RtpRtcp::Configuration::Configuration() = default;
std::unique_ptr<RtpRtcp> RtpRtcp::Create(const Configuration& configuration) {
RTC_DCHECK(configuration.clock);
return absl::make_unique<ModuleRtpRtcpImpl>(configuration);
}
RtpRtcp* RtpRtcp::CreateRtpRtcp(const RtpRtcp::Configuration& configuration) {
if (configuration.clock) {
return new ModuleRtpRtcpImpl(configuration);
} else {
// No clock implementation provided, use default clock.
RtpRtcp::Configuration configuration_copy;
memcpy(&configuration_copy, &configuration, sizeof(RtpRtcp::Configuration));
configuration_copy.clock = Clock::GetRealTimeClock();
return new ModuleRtpRtcpImpl(configuration_copy);
}
}
ModuleRtpRtcpImpl::ModuleRtpRtcpImpl(const Configuration& configuration)
: rtcp_sender_(configuration.audio,
configuration.clock,
configuration.receive_statistics,
configuration.rtcp_packet_type_counter_observer,
configuration.event_log,
configuration.outgoing_transport,
configuration.rtcp_report_interval_ms > 0
? configuration.rtcp_report_interval_ms
: (configuration.audio ? kDefaultAudioReportInterval
: kDefaultVideoReportInterval)),
rtcp_receiver_(configuration.clock,
configuration.receiver_only,
configuration.rtcp_packet_type_counter_observer,
configuration.bandwidth_callback,
configuration.intra_frame_callback,
configuration.rtcp_loss_notification_observer,
configuration.transport_feedback_callback,
configuration.bitrate_allocation_observer,
configuration.rtcp_report_interval_ms > 0
? configuration.rtcp_report_interval_ms
: (configuration.audio ? kDefaultAudioReportInterval
: kDefaultVideoReportInterval),
this),
clock_(configuration.clock),
last_bitrate_process_time_(clock_->TimeInMilliseconds()),
last_rtt_process_time_(clock_->TimeInMilliseconds()),
next_process_time_(clock_->TimeInMilliseconds() +
kRtpRtcpMaxIdleTimeProcessMs),
packet_overhead_(28), // IPV4 UDP.
nack_last_time_sent_full_ms_(0),
nack_last_seq_number_sent_(0),
key_frame_req_method_(kKeyFrameReqPliRtcp),
remote_bitrate_(configuration.remote_bitrate_estimator),
ack_observer_(configuration.ack_observer),
rtt_stats_(configuration.rtt_stats),
rtt_ms_(0) {
FieldTrialBasedConfig default_trials;
if (!configuration.receiver_only) {
rtp_sender_.reset(new RTPSender(
configuration.audio, configuration.clock,
configuration.outgoing_transport, configuration.paced_sender,
configuration.flexfec_sender
? absl::make_optional(configuration.flexfec_sender->ssrc())
: absl::nullopt,
configuration.transport_sequence_number_allocator,
configuration.transport_feedback_callback,
configuration.send_bitrate_observer,
configuration.send_side_delay_observer, configuration.event_log,
configuration.send_packet_observer,
configuration.retransmission_rate_limiter,
configuration.overhead_observer,
configuration.populate_network2_timestamp,
configuration.frame_encryptor, configuration.require_frame_encryption,
configuration.extmap_allow_mixed,
configuration.field_trials ? *configuration.field_trials
: default_trials));
// Make sure rtcp sender use same timestamp offset as rtp sender.
rtcp_sender_.SetTimestampOffset(rtp_sender_->TimestampOffset());
}
// Set default packet size limit.
// TODO(nisse): Kind-of duplicates
// webrtc::VideoSendStream::Config::Rtp::kDefaultMaxPacketSize.
const size_t kTcpOverIpv4HeaderSize = 40;
SetMaxRtpPacketSize(IP_PACKET_SIZE - kTcpOverIpv4HeaderSize);
}
ModuleRtpRtcpImpl::~ModuleRtpRtcpImpl() = default;
// Returns the number of milliseconds until the module want a worker thread
// to call Process.
int64_t ModuleRtpRtcpImpl::TimeUntilNextProcess() {
return std::max<int64_t>(0,
next_process_time_ - clock_->TimeInMilliseconds());
}
// Process any pending tasks such as timeouts (non time critical events).
void ModuleRtpRtcpImpl::Process() {
const int64_t now = clock_->TimeInMilliseconds();
next_process_time_ = now + kRtpRtcpMaxIdleTimeProcessMs;
if (rtp_sender_) {
if (now >= last_bitrate_process_time_ + kRtpRtcpBitrateProcessTimeMs) {
rtp_sender_->ProcessBitrate();
last_bitrate_process_time_ = now;
next_process_time_ =
std::min(next_process_time_, now + kRtpRtcpBitrateProcessTimeMs);
}
}
bool process_rtt = now >= last_rtt_process_time_ + kRtpRtcpRttProcessTimeMs;
if (rtcp_sender_.Sending()) {
// Process RTT if we have received a report block and we haven't
// processed RTT for at least |kRtpRtcpRttProcessTimeMs| milliseconds.
if (rtcp_receiver_.LastReceivedReportBlockMs() > last_rtt_process_time_ &&
process_rtt) {
std::vector<RTCPReportBlock> receive_blocks;
rtcp_receiver_.StatisticsReceived(&receive_blocks);
int64_t max_rtt = 0;
for (std::vector<RTCPReportBlock>::iterator it = receive_blocks.begin();
it != receive_blocks.end(); ++it) {
int64_t rtt = 0;
rtcp_receiver_.RTT(it->sender_ssrc, &rtt, NULL, NULL, NULL);
max_rtt = (rtt > max_rtt) ? rtt : max_rtt;
}
// Report the rtt.
if (rtt_stats_ && max_rtt != 0)
rtt_stats_->OnRttUpdate(max_rtt);
}
// Verify receiver reports are delivered and the reported sequence number
// is increasing.
if (rtcp_receiver_.RtcpRrTimeout()) {
RTC_LOG_F(LS_WARNING) << "Timeout: No RTCP RR received.";
} else if (rtcp_receiver_.RtcpRrSequenceNumberTimeout()) {
RTC_LOG_F(LS_WARNING) << "Timeout: No increase in RTCP RR extended "
"highest sequence number.";
}
if (remote_bitrate_ && rtcp_sender_.TMMBR()) {
unsigned int target_bitrate = 0;
std::vector<unsigned int> ssrcs;
if (remote_bitrate_->LatestEstimate(&ssrcs, &target_bitrate)) {
if (!ssrcs.empty()) {
target_bitrate = target_bitrate / ssrcs.size();
}
rtcp_sender_.SetTargetBitrate(target_bitrate);
}
}
} else {
// Report rtt from receiver.
if (process_rtt) {
int64_t rtt_ms;
if (rtt_stats_ && rtcp_receiver_.GetAndResetXrRrRtt(&rtt_ms)) {
rtt_stats_->OnRttUpdate(rtt_ms);
}
}
}
// Get processed rtt.
if (process_rtt) {
last_rtt_process_time_ = now;
next_process_time_ = std::min(
next_process_time_, last_rtt_process_time_ + kRtpRtcpRttProcessTimeMs);
if (rtt_stats_) {
// Make sure we have a valid RTT before setting.
int64_t last_rtt = rtt_stats_->LastProcessedRtt();
if (last_rtt >= 0)
set_rtt_ms(last_rtt);
}
}
if (rtcp_sender_.TimeToSendRTCPReport())
rtcp_sender_.SendRTCP(GetFeedbackState(), kRtcpReport);
if (TMMBR() && rtcp_receiver_.UpdateTmmbrTimers()) {
rtcp_receiver_.NotifyTmmbrUpdated();
}
}
void ModuleRtpRtcpImpl::SetRtxSendStatus(int mode) {
rtp_sender_->SetRtxStatus(mode);
}
int ModuleRtpRtcpImpl::RtxSendStatus() const {
return rtp_sender_ ? rtp_sender_->RtxStatus() : kRtxOff;
}
void ModuleRtpRtcpImpl::SetRtxSsrc(uint32_t ssrc) {
rtp_sender_->SetRtxSsrc(ssrc);
}
void ModuleRtpRtcpImpl::SetRtxSendPayloadType(int payload_type,
int associated_payload_type) {
rtp_sender_->SetRtxPayloadType(payload_type, associated_payload_type);
}
absl::optional<uint32_t> ModuleRtpRtcpImpl::FlexfecSsrc() const {
if (rtp_sender_)
return rtp_sender_->FlexfecSsrc();
return absl::nullopt;
}
void ModuleRtpRtcpImpl::IncomingRtcpPacket(const uint8_t* rtcp_packet,
const size_t length) {
rtcp_receiver_.IncomingPacket(rtcp_packet, length);
}
void ModuleRtpRtcpImpl::RegisterSendPayloadFrequency(int payload_type,
int payload_frequency) {
rtcp_sender_.SetRtpClockRate(payload_type, payload_frequency);
}
int32_t ModuleRtpRtcpImpl::DeRegisterSendPayload(const int8_t payload_type) {
return 0;
}
uint32_t ModuleRtpRtcpImpl::StartTimestamp() const {
return rtp_sender_->TimestampOffset();
}
// Configure start timestamp, default is a random number.
void ModuleRtpRtcpImpl::SetStartTimestamp(const uint32_t timestamp) {
rtcp_sender_.SetTimestampOffset(timestamp);
rtp_sender_->SetTimestampOffset(timestamp);
}
uint16_t ModuleRtpRtcpImpl::SequenceNumber() const {
return rtp_sender_->SequenceNumber();
}
// Set SequenceNumber, default is a random number.
void ModuleRtpRtcpImpl::SetSequenceNumber(const uint16_t seq_num) {
rtp_sender_->SetSequenceNumber(seq_num);
}
void ModuleRtpRtcpImpl::SetRtpState(const RtpState& rtp_state) {
rtp_sender_->SetRtpState(rtp_state);
rtcp_sender_.SetTimestampOffset(rtp_state.start_timestamp);
}
void ModuleRtpRtcpImpl::SetRtxState(const RtpState& rtp_state) {
rtp_sender_->SetRtxRtpState(rtp_state);
}
RtpState ModuleRtpRtcpImpl::GetRtpState() const {
return rtp_sender_->GetRtpState();
}
RtpState ModuleRtpRtcpImpl::GetRtxState() const {
return rtp_sender_->GetRtxRtpState();
}
uint32_t ModuleRtpRtcpImpl::SSRC() const {
return rtcp_sender_.SSRC();
}
void ModuleRtpRtcpImpl::SetSSRC(const uint32_t ssrc) {
if (rtp_sender_) {
rtp_sender_->SetSSRC(ssrc);
}
rtcp_sender_.SetSSRC(ssrc);
SetRtcpReceiverSsrcs(ssrc);
}
void ModuleRtpRtcpImpl::SetRid(const std::string& rid) {
if (rtp_sender_) {
rtp_sender_->SetRid(rid);
}
}
void ModuleRtpRtcpImpl::SetMid(const std::string& mid) {
if (rtp_sender_) {
rtp_sender_->SetMid(mid);
}
// TODO(bugs.webrtc.org/4050): If we end up supporting the MID SDES item for
// RTCP, this will need to be passed down to the RTCPSender also.
}
void ModuleRtpRtcpImpl::SetCsrcs(const std::vector<uint32_t>& csrcs) {
rtcp_sender_.SetCsrcs(csrcs);
rtp_sender_->SetCsrcs(csrcs);
}
// TODO(pbos): Handle media and RTX streams separately (separate RTCP
// feedbacks).
RTCPSender::FeedbackState ModuleRtpRtcpImpl::GetFeedbackState() {
RTCPSender::FeedbackState state;
// This is called also when receiver_only is true. Hence below
// checks that rtp_sender_ exists.
if (rtp_sender_) {
StreamDataCounters rtp_stats;
StreamDataCounters rtx_stats;
rtp_sender_->GetDataCounters(&rtp_stats, &rtx_stats);
state.packets_sent =
rtp_stats.transmitted.packets + rtx_stats.transmitted.packets;
state.media_bytes_sent = rtp_stats.transmitted.payload_bytes +
rtx_stats.transmitted.payload_bytes;
state.send_bitrate = rtp_sender_->BitrateSent();
}
state.module = this;
LastReceivedNTP(&state.last_rr_ntp_secs, &state.last_rr_ntp_frac,
&state.remote_sr);
state.last_xr_rtis = rtcp_receiver_.ConsumeReceivedXrReferenceTimeInfo();
return state;
}
// TODO(nisse): This method shouldn't be called for a receive-only
// stream. Delete rtp_sender_ check as soon as all applications are
// updated.
int32_t ModuleRtpRtcpImpl::SetSendingStatus(const bool sending) {
if (rtcp_sender_.Sending() != sending) {
// Sends RTCP BYE when going from true to false
if (rtcp_sender_.SetSendingStatus(GetFeedbackState(), sending) != 0) {
RTC_LOG(LS_WARNING) << "Failed to send RTCP BYE";
}
if (sending && rtp_sender_) {
// Update Rtcp receiver config, to track Rtx config changes from
// the SetRtxStatus and SetRtxSsrc methods.
SetRtcpReceiverSsrcs(rtp_sender_->SSRC());
}
}
return 0;
}
bool ModuleRtpRtcpImpl::Sending() const {
return rtcp_sender_.Sending();
}
// TODO(nisse): This method shouldn't be called for a receive-only
// stream. Delete rtp_sender_ check as soon as all applications are
// updated.
void ModuleRtpRtcpImpl::SetSendingMediaStatus(const bool sending) {
if (rtp_sender_) {
rtp_sender_->SetSendingMediaStatus(sending);
} else {
RTC_DCHECK(!sending);
}
}
bool ModuleRtpRtcpImpl::SendingMedia() const {
return rtp_sender_ ? rtp_sender_->SendingMedia() : false;
}
void ModuleRtpRtcpImpl::SetAsPartOfAllocation(bool part_of_allocation) {
RTC_CHECK(rtp_sender_);
rtp_sender_->SetAsPartOfAllocation(part_of_allocation);
}
bool ModuleRtpRtcpImpl::OnSendingRtpFrame(uint32_t timestamp,
int64_t capture_time_ms,
int payload_type,
bool force_sender_report) {
if (!Sending())
return false;
rtcp_sender_.SetLastRtpTime(timestamp, capture_time_ms, payload_type);
// Make sure an RTCP report isn't queued behind a key frame.
if (rtcp_sender_.TimeToSendRTCPReport(force_sender_report))
rtcp_sender_.SendRTCP(GetFeedbackState(), kRtcpReport);
return true;
}
bool ModuleRtpRtcpImpl::TimeToSendPacket(uint32_t ssrc,
uint16_t sequence_number,
int64_t capture_time_ms,
bool retransmission,
const PacedPacketInfo& pacing_info) {
return rtp_sender_->TimeToSendPacket(ssrc, sequence_number, capture_time_ms,
retransmission, pacing_info);
}
size_t ModuleRtpRtcpImpl::TimeToSendPadding(
size_t bytes,
const PacedPacketInfo& pacing_info) {
return rtp_sender_->TimeToSendPadding(bytes, pacing_info);
}
size_t ModuleRtpRtcpImpl::MaxRtpPacketSize() const {
return rtp_sender_->MaxRtpPacketSize();
}
void ModuleRtpRtcpImpl::SetMaxRtpPacketSize(size_t rtp_packet_size) {
RTC_DCHECK_LE(rtp_packet_size, IP_PACKET_SIZE)
<< "rtp packet size too large: " << rtp_packet_size;
RTC_DCHECK_GT(rtp_packet_size, packet_overhead_)
<< "rtp packet size too small: " << rtp_packet_size;
rtcp_sender_.SetMaxRtpPacketSize(rtp_packet_size);
if (rtp_sender_)
rtp_sender_->SetMaxRtpPacketSize(rtp_packet_size);
}
RtcpMode ModuleRtpRtcpImpl::RTCP() const {
return rtcp_sender_.Status();
}
// Configure RTCP status i.e on/off.
void ModuleRtpRtcpImpl::SetRTCPStatus(const RtcpMode method) {
rtcp_sender_.SetRTCPStatus(method);
}
int32_t ModuleRtpRtcpImpl::SetCNAME(const char* c_name) {
return rtcp_sender_.SetCNAME(c_name);
}
int32_t ModuleRtpRtcpImpl::AddMixedCNAME(uint32_t ssrc, const char* c_name) {
return rtcp_sender_.AddMixedCNAME(ssrc, c_name);
}
int32_t ModuleRtpRtcpImpl::RemoveMixedCNAME(const uint32_t ssrc) {
return rtcp_sender_.RemoveMixedCNAME(ssrc);
}
int32_t ModuleRtpRtcpImpl::RemoteCNAME(const uint32_t remote_ssrc,
char c_name[RTCP_CNAME_SIZE]) const {
return rtcp_receiver_.CNAME(remote_ssrc, c_name);
}
int32_t ModuleRtpRtcpImpl::RemoteNTP(uint32_t* received_ntpsecs,
uint32_t* received_ntpfrac,
uint32_t* rtcp_arrival_time_secs,
uint32_t* rtcp_arrival_time_frac,
uint32_t* rtcp_timestamp) const {
return rtcp_receiver_.NTP(received_ntpsecs, received_ntpfrac,
rtcp_arrival_time_secs, rtcp_arrival_time_frac,
rtcp_timestamp)
? 0
: -1;
}
// Get RoundTripTime.
int32_t ModuleRtpRtcpImpl::RTT(const uint32_t remote_ssrc,
int64_t* rtt,
int64_t* avg_rtt,
int64_t* min_rtt,
int64_t* max_rtt) const {
int32_t ret = rtcp_receiver_.RTT(remote_ssrc, rtt, avg_rtt, min_rtt, max_rtt);
if (rtt && *rtt == 0) {
// Try to get RTT from RtcpRttStats class.
*rtt = rtt_ms();
}
return ret;
}
int64_t ModuleRtpRtcpImpl::ExpectedRetransmissionTimeMs() const {
int64_t expected_retransmission_time_ms = rtt_ms();
if (expected_retransmission_time_ms > 0) {
return expected_retransmission_time_ms;
}
// No rtt available (|kRtpRtcpRttProcessTimeMs| not yet passed?), so try to
// poll avg_rtt_ms directly from rtcp receiver.
if (rtcp_receiver_.RTT(rtcp_receiver_.RemoteSSRC(), nullptr,
&expected_retransmission_time_ms, nullptr,
nullptr) == 0) {
return expected_retransmission_time_ms;
}
return kDefaultExpectedRetransmissionTimeMs;
}
// Force a send of an RTCP packet.
// Normal SR and RR are triggered via the process function.
int32_t ModuleRtpRtcpImpl::SendRTCP(RTCPPacketType packet_type) {
return rtcp_sender_.SendRTCP(GetFeedbackState(), packet_type);
}
// Force a send of an RTCP packet.
// Normal SR and RR are triggered via the process function.
int32_t ModuleRtpRtcpImpl::SendCompoundRTCP(
const std::set<RTCPPacketType>& packet_types) {
return rtcp_sender_.SendCompoundRTCP(GetFeedbackState(), packet_types);
}
int32_t ModuleRtpRtcpImpl::SetRTCPApplicationSpecificData(
const uint8_t sub_type,
const uint32_t name,
const uint8_t* data,
const uint16_t length) {
return rtcp_sender_.SetApplicationSpecificData(sub_type, name, data, length);
}
void ModuleRtpRtcpImpl::SetRtcpXrRrtrStatus(bool enable) {
rtcp_receiver_.SetRtcpXrRrtrStatus(enable);
rtcp_sender_.SendRtcpXrReceiverReferenceTime(enable);
}
bool ModuleRtpRtcpImpl::RtcpXrRrtrStatus() const {
return rtcp_sender_.RtcpXrReceiverReferenceTime();
}
// TODO(asapersson): Replace this method with the one below.
int32_t ModuleRtpRtcpImpl::DataCountersRTP(size_t* bytes_sent,
uint32_t* packets_sent) const {
StreamDataCounters rtp_stats;
StreamDataCounters rtx_stats;
rtp_sender_->GetDataCounters(&rtp_stats, &rtx_stats);
if (bytes_sent) {
*bytes_sent = rtp_stats.transmitted.payload_bytes +
rtp_stats.transmitted.padding_bytes +
rtp_stats.transmitted.header_bytes +
rtx_stats.transmitted.payload_bytes +
rtx_stats.transmitted.padding_bytes +
rtx_stats.transmitted.header_bytes;
}
if (packets_sent) {
*packets_sent =
rtp_stats.transmitted.packets + rtx_stats.transmitted.packets;
}
return 0;
}
void ModuleRtpRtcpImpl::GetSendStreamDataCounters(
StreamDataCounters* rtp_counters,
StreamDataCounters* rtx_counters) const {
rtp_sender_->GetDataCounters(rtp_counters, rtx_counters);
}
void ModuleRtpRtcpImpl::GetRtpPacketLossStats(
bool outgoing,
uint32_t ssrc,
struct RtpPacketLossStats* loss_stats) const {
if (!loss_stats)
return;
const PacketLossStats* stats_source = NULL;
if (outgoing) {
if (SSRC() == ssrc) {
stats_source = &send_loss_stats_;
}
} else {
if (rtcp_receiver_.RemoteSSRC() == ssrc) {
stats_source = &receive_loss_stats_;
}
}
if (stats_source) {
loss_stats->single_packet_loss_count = stats_source->GetSingleLossCount();
loss_stats->multiple_packet_loss_event_count =
stats_source->GetMultipleLossEventCount();
loss_stats->multiple_packet_loss_packet_count =
stats_source->GetMultipleLossPacketCount();
}
}
// Received RTCP report.
int32_t ModuleRtpRtcpImpl::RemoteRTCPStat(
std::vector<RTCPReportBlock>* receive_blocks) const {
return rtcp_receiver_.StatisticsReceived(receive_blocks);
}
// (REMB) Receiver Estimated Max Bitrate.
void ModuleRtpRtcpImpl::SetRemb(int64_t bitrate_bps,
std::vector<uint32_t> ssrcs) {
rtcp_sender_.SetRemb(bitrate_bps, std::move(ssrcs));
}
void ModuleRtpRtcpImpl::UnsetRemb() {
rtcp_sender_.UnsetRemb();
}
void ModuleRtpRtcpImpl::SetExtmapAllowMixed(bool extmap_allow_mixed) {
rtp_sender_->SetExtmapAllowMixed(extmap_allow_mixed);
}
int32_t ModuleRtpRtcpImpl::RegisterSendRtpHeaderExtension(
const RTPExtensionType type,
const uint8_t id) {
return rtp_sender_->RegisterRtpHeaderExtension(type, id);
}
bool ModuleRtpRtcpImpl::RegisterRtpHeaderExtension(const std::string& uri,
int id) {
return rtp_sender_->RegisterRtpHeaderExtension(uri, id);
}
int32_t ModuleRtpRtcpImpl::DeregisterSendRtpHeaderExtension(
const RTPExtensionType type) {
return rtp_sender_->DeregisterRtpHeaderExtension(type);
}
bool ModuleRtpRtcpImpl::HasBweExtensions() const {
return rtp_sender_->IsRtpHeaderExtensionRegistered(
kRtpExtensionTransportSequenceNumber) ||
rtp_sender_->IsRtpHeaderExtensionRegistered(
kRtpExtensionAbsoluteSendTime) ||
rtp_sender_->IsRtpHeaderExtensionRegistered(
kRtpExtensionTransmissionTimeOffset);
}
// (TMMBR) Temporary Max Media Bit Rate.
bool ModuleRtpRtcpImpl::TMMBR() const {
return rtcp_sender_.TMMBR();
}
void ModuleRtpRtcpImpl::SetTMMBRStatus(const bool enable) {
rtcp_sender_.SetTMMBRStatus(enable);
}
void ModuleRtpRtcpImpl::SetTmmbn(std::vector<rtcp::TmmbItem> bounding_set) {
rtcp_sender_.SetTmmbn(std::move(bounding_set));
}
// Send a Negative acknowledgment packet.
int32_t ModuleRtpRtcpImpl::SendNACK(const uint16_t* nack_list,
const uint16_t size) {
for (int i = 0; i < size; ++i) {
receive_loss_stats_.AddLostPacket(nack_list[i]);
}
uint16_t nack_length = size;
uint16_t start_id = 0;
int64_t now_ms = clock_->TimeInMilliseconds();
if (TimeToSendFullNackList(now_ms)) {
nack_last_time_sent_full_ms_ = now_ms;
} else {
// Only send extended list.
if (nack_last_seq_number_sent_ == nack_list[size - 1]) {
// Last sequence number is the same, do not send list.
return 0;
}
// Send new sequence numbers.
for (int i = 0; i < size; ++i) {
if (nack_last_seq_number_sent_ == nack_list[i]) {
start_id = i + 1;
break;
}
}
nack_length = size - start_id;
}
// Our RTCP NACK implementation is limited to kRtcpMaxNackFields sequence
// numbers per RTCP packet.
if (nack_length > kRtcpMaxNackFields) {
nack_length = kRtcpMaxNackFields;
}
nack_last_seq_number_sent_ = nack_list[start_id + nack_length - 1];
return rtcp_sender_.SendRTCP(GetFeedbackState(), kRtcpNack, nack_length,
&nack_list[start_id]);
}
void ModuleRtpRtcpImpl::SendNack(
const std::vector<uint16_t>& sequence_numbers) {
rtcp_sender_.SendRTCP(GetFeedbackState(), kRtcpNack, sequence_numbers.size(),
sequence_numbers.data());
}
bool ModuleRtpRtcpImpl::TimeToSendFullNackList(int64_t now) const {
// Use RTT from RtcpRttStats class if provided.
int64_t rtt = rtt_ms();
if (rtt == 0) {
rtcp_receiver_.RTT(rtcp_receiver_.RemoteSSRC(), NULL, &rtt, NULL, NULL);
}
const int64_t kStartUpRttMs = 100;
int64_t wait_time = 5 + ((rtt * 3) >> 1); // 5 + RTT * 1.5.
if (rtt == 0) {
wait_time = kStartUpRttMs;
}
// Send a full NACK list once within every |wait_time|.
return now - nack_last_time_sent_full_ms_ > wait_time;
}
// Store the sent packets, needed to answer to Negative acknowledgment requests.
void ModuleRtpRtcpImpl::SetStorePacketsStatus(const bool enable,
const uint16_t number_to_store) {
rtp_sender_->SetStorePacketsStatus(enable, number_to_store);
}
bool ModuleRtpRtcpImpl::StorePackets() const {
return rtp_sender_->StorePackets();
}
void ModuleRtpRtcpImpl::RegisterRtcpStatisticsCallback(
RtcpStatisticsCallback* callback) {
rtcp_receiver_.RegisterRtcpStatisticsCallback(callback);
}
RtcpStatisticsCallback* ModuleRtpRtcpImpl::GetRtcpStatisticsCallback() {
return rtcp_receiver_.GetRtcpStatisticsCallback();
}
bool ModuleRtpRtcpImpl::SendFeedbackPacket(
const rtcp::TransportFeedback& packet) {
return rtcp_sender_.SendFeedbackPacket(packet);
}
int32_t ModuleRtpRtcpImpl::SetKeyFrameRequestMethod(
const KeyFrameRequestMethod method) {
key_frame_req_method_ = method;
return 0;
}
int32_t ModuleRtpRtcpImpl::RequestKeyFrame() {
switch (key_frame_req_method_) {
case kKeyFrameReqPliRtcp:
return SendRTCP(kRtcpPli);
case kKeyFrameReqFirRtcp:
return SendRTCP(kRtcpFir);
}
return -1;
}
int32_t ModuleRtpRtcpImpl::SendLossNotification(uint16_t last_decoded_seq_num,
uint16_t last_received_seq_num,
bool decodability_flag) {
return rtcp_sender_.SendLossNotification(
GetFeedbackState(), last_decoded_seq_num, last_received_seq_num,
decodability_flag);
}
void ModuleRtpRtcpImpl::SetRemoteSSRC(const uint32_t ssrc) {
// Inform about the incoming SSRC.
rtcp_sender_.SetRemoteSSRC(ssrc);
rtcp_receiver_.SetRemoteSSRC(ssrc);
}
// TODO(nisse): Delete video_rate amd fec_rate arguments.
void ModuleRtpRtcpImpl::BitrateSent(uint32_t* total_rate,
uint32_t* video_rate,
uint32_t* fec_rate,
uint32_t* nack_rate) const {
*total_rate = rtp_sender_->BitrateSent();
if (video_rate)
*video_rate = 0;
if (fec_rate)
*fec_rate = 0;
*nack_rate = rtp_sender_->NackOverheadRate();
}
void ModuleRtpRtcpImpl::OnRequestSendReport() {
SendRTCP(kRtcpSr);
}
void ModuleRtpRtcpImpl::OnReceivedNack(
const std::vector<uint16_t>& nack_sequence_numbers) {
if (!rtp_sender_)
return;
for (uint16_t nack_sequence_number : nack_sequence_numbers) {
send_loss_stats_.AddLostPacket(nack_sequence_number);
}
if (!rtp_sender_->StorePackets() || nack_sequence_numbers.size() == 0) {
return;
}
// Use RTT from RtcpRttStats class if provided.
int64_t rtt = rtt_ms();
if (rtt == 0) {
rtcp_receiver_.RTT(rtcp_receiver_.RemoteSSRC(), NULL, &rtt, NULL, NULL);
}
rtp_sender_->OnReceivedNack(nack_sequence_numbers, rtt);
}
void ModuleRtpRtcpImpl::OnReceivedRtcpReportBlocks(
const ReportBlockList& report_blocks) {
if (ack_observer_) {
uint32_t ssrc = SSRC();
for (const RTCPReportBlock& report_block : report_blocks) {
if (ssrc == report_block.source_ssrc) {
ack_observer_->OnReceivedAck(
report_block.extended_highest_sequence_number);
}
}
}
}
bool ModuleRtpRtcpImpl::LastReceivedNTP(
uint32_t* rtcp_arrival_time_secs, // When we got the last report.
uint32_t* rtcp_arrival_time_frac,
uint32_t* remote_sr) const {
// Remote SR: NTP inside the last received (mid 16 bits from sec and frac).
uint32_t ntp_secs = 0;
uint32_t ntp_frac = 0;
if (!rtcp_receiver_.NTP(&ntp_secs, &ntp_frac, rtcp_arrival_time_secs,
rtcp_arrival_time_frac, NULL)) {
return false;
}
*remote_sr =
((ntp_secs & 0x0000ffff) << 16) + ((ntp_frac & 0xffff0000) >> 16);
return true;
}
// Called from RTCPsender.
std::vector<rtcp::TmmbItem> ModuleRtpRtcpImpl::BoundingSet(bool* tmmbr_owner) {
return rtcp_receiver_.BoundingSet(tmmbr_owner);
}
void ModuleRtpRtcpImpl::SetRtcpReceiverSsrcs(uint32_t main_ssrc) {
std::set<uint32_t> ssrcs;
ssrcs.insert(main_ssrc);
if (RtxSendStatus() != kRtxOff)
ssrcs.insert(rtp_sender_->RtxSsrc());
absl::optional<uint32_t> flexfec_ssrc = FlexfecSsrc();
if (flexfec_ssrc)
ssrcs.insert(*flexfec_ssrc);
rtcp_receiver_.SetSsrcs(main_ssrc, ssrcs);
}
void ModuleRtpRtcpImpl::set_rtt_ms(int64_t rtt_ms) {
rtc::CritScope cs(&critical_section_rtt_);
rtt_ms_ = rtt_ms;
if (rtp_sender_)
rtp_sender_->SetRtt(rtt_ms);
}
int64_t ModuleRtpRtcpImpl::rtt_ms() const {
rtc::CritScope cs(&critical_section_rtt_);
return rtt_ms_;
}
void ModuleRtpRtcpImpl::RegisterSendChannelRtpStatisticsCallback(
StreamDataCountersCallback* callback) {
rtp_sender_->RegisterRtpStatisticsCallback(callback);
}
StreamDataCountersCallback*
ModuleRtpRtcpImpl::GetSendChannelRtpStatisticsCallback() const {
return rtp_sender_->GetRtpStatisticsCallback();
}
void ModuleRtpRtcpImpl::SetVideoBitrateAllocation(
const VideoBitrateAllocation& bitrate) {
rtcp_sender_.SetVideoBitrateAllocation(bitrate);
}
RTPSender* ModuleRtpRtcpImpl::RtpSender() {
return rtp_sender_.get();
}
const RTPSender* ModuleRtpRtcpImpl::RtpSender() const {
return rtp_sender_.get();
}
} // namespace webrtc
|
// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2018-2019 The esbcoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "addresstablemodel.h"
#include "guiutil.h"
#include "walletmodel.h"
#include "base58.h"
#include "wallet.h"
#include <QDebug>
#include <QFont>
const QString AddressTableModel::Send = "S";
const QString AddressTableModel::Receive = "R";
struct AddressTableEntry {
enum Type {
Sending,
Receiving,
Hidden /* QSortFilterProxyModel will filter these out */
};
Type type;
QString label;
QString address;
AddressTableEntry() {}
AddressTableEntry(Type type, const QString& label, const QString& address) : type(type), label(label), address(address) {}
};
struct AddressTableEntryLessThan {
bool operator()(const AddressTableEntry& a, const AddressTableEntry& b) const
{
return a.address < b.address;
}
bool operator()(const AddressTableEntry& a, const QString& b) const
{
return a.address < b;
}
bool operator()(const QString& a, const AddressTableEntry& b) const
{
return a < b.address;
}
};
/* Determine address type from address purpose */
static AddressTableEntry::Type translateTransactionType(const QString& strPurpose, bool isMine)
{
AddressTableEntry::Type addressType = AddressTableEntry::Hidden;
// "refund" addresses aren't shown, and change addresses aren't in mapAddressBook at all.
if (strPurpose == "send")
addressType = AddressTableEntry::Sending;
else if (strPurpose == "receive")
addressType = AddressTableEntry::Receiving;
else if (strPurpose == "unknown" || strPurpose == "") // if purpose not set, guess
addressType = (isMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending);
return addressType;
}
// Private implementation
class AddressTablePriv
{
public:
CWallet* wallet;
QList<AddressTableEntry> cachedAddressTable;
AddressTableModel* parent;
AddressTablePriv(CWallet* wallet, AddressTableModel* parent) : wallet(wallet), parent(parent) {}
void refreshAddressTable()
{
cachedAddressTable.clear();
{
LOCK(wallet->cs_wallet);
for (const PAIRTYPE(CTxDestination, CAddressBookData) & item : wallet->mapAddressBook) {
const CBitcoinAddress& address = item.first;
bool fMine = IsMine(*wallet, address.Get());
AddressTableEntry::Type addressType = translateTransactionType(
QString::fromStdString(item.second.purpose), fMine);
const std::string& strName = item.second.name;
cachedAddressTable.append(AddressTableEntry(addressType,
QString::fromStdString(strName),
QString::fromStdString(address.ToString())));
}
}
// qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order
// Even though the map is already sorted this re-sorting step is needed because the originating map
// is sorted by binary address, not by base58() address.
qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan());
}
void updateEntry(const QString& address, const QString& label, bool isMine, const QString& purpose, int status)
{
// Find address / label in model
QList<AddressTableEntry>::iterator lower = qLowerBound(
cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
QList<AddressTableEntry>::iterator upper = qUpperBound(
cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
int lowerIndex = (lower - cachedAddressTable.begin());
int upperIndex = (upper - cachedAddressTable.begin());
bool inModel = (lower != upper);
AddressTableEntry::Type newEntryType = translateTransactionType(purpose, isMine);
switch (status) {
case CT_NEW:
if (inModel) {
qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_NEW, but entry is already in model";
break;
}
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);
cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address));
parent->endInsertRows();
break;
case CT_UPDATED:
if (!inModel) {
qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_UPDATED, but entry is not in model";
break;
}
lower->type = newEntryType;
lower->label = label;
parent->emitDataChanged(lowerIndex);
break;
case CT_DELETED:
if (!inModel) {
qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_DELETED, but entry is not in model";
break;
}
parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex - 1);
cachedAddressTable.erase(lower, upper);
parent->endRemoveRows();
break;
}
}
int size()
{
return cachedAddressTable.size();
}
AddressTableEntry* index(int idx)
{
if (idx >= 0 && idx < cachedAddressTable.size()) {
return &cachedAddressTable[idx];
} else {
return 0;
}
}
};
AddressTableModel::AddressTableModel(CWallet* wallet, WalletModel* parent) : QAbstractTableModel(parent), walletModel(parent), wallet(wallet), priv(0)
{
columns << tr("Label") << tr("Address");
priv = new AddressTablePriv(wallet, this);
priv->refreshAddressTable();
}
AddressTableModel::~AddressTableModel()
{
delete priv;
}
int AddressTableModel::rowCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int AddressTableModel::columnCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant AddressTableModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid())
return QVariant();
AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer());
if (role == Qt::DisplayRole || role == Qt::EditRole) {
switch (index.column()) {
case Label:
if (rec->label.isEmpty() && role == Qt::DisplayRole) {
return tr("(no label)");
} else {
return rec->label;
}
case Address:
return rec->address;
}
} else if (role == Qt::FontRole) {
QFont font;
if (index.column() == Address) {
font = GUIUtil::bitcoinAddressFont();
}
return font;
} else if (role == TypeRole) {
switch (rec->type) {
case AddressTableEntry::Sending:
return Send;
case AddressTableEntry::Receiving:
return Receive;
default:
break;
}
}
return QVariant();
}
bool AddressTableModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
if (!index.isValid())
return false;
AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer());
std::string strPurpose = (rec->type == AddressTableEntry::Sending ? "send" : "receive");
editStatus = OK;
if (role == Qt::EditRole) {
LOCK(wallet->cs_wallet); /* For SetAddressBook / DelAddressBook */
CTxDestination curAddress = CBitcoinAddress(rec->address.toStdString()).Get();
if (index.column() == Label) {
// Do nothing, if old label == new label
if (rec->label == value.toString()) {
editStatus = NO_CHANGES;
return false;
}
wallet->SetAddressBook(curAddress, value.toString().toStdString(), strPurpose);
} else if (index.column() == Address) {
CTxDestination newAddress = CBitcoinAddress(value.toString().toStdString()).Get();
// Refuse to set invalid address, set error status and return false
if (boost::get<CNoDestination>(&newAddress)) {
editStatus = INVALID_ADDRESS;
return false;
}
// Do nothing, if old address == new address
else if (newAddress == curAddress) {
editStatus = NO_CHANGES;
return false;
}
// Check for duplicate addresses to prevent accidental deletion of addresses, if you try
// to paste an existing address over another address (with a different label)
else if (wallet->mapAddressBook.count(newAddress)) {
editStatus = DUPLICATE_ADDRESS;
return false;
}
// Double-check that we're not overwriting a receiving address
else if (rec->type == AddressTableEntry::Sending) {
// Remove old entry
wallet->DelAddressBook(curAddress);
// Add new entry with new address
wallet->SetAddressBook(newAddress, rec->label.toStdString(), strPurpose);
}
}
return true;
}
return false;
}
QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal) {
if (role == Qt::DisplayRole && section < columns.size()) {
return columns[section];
}
}
return QVariant();
}
Qt::ItemFlags AddressTableModel::flags(const QModelIndex& index) const
{
if (!index.isValid())
return 0;
AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer());
Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
// Can edit address and label for sending addresses,
// and only label for receiving addresses.
if (rec->type == AddressTableEntry::Sending ||
(rec->type == AddressTableEntry::Receiving && index.column() == Label)) {
retval |= Qt::ItemIsEditable;
}
return retval;
}
QModelIndex AddressTableModel::index(int row, int column, const QModelIndex& parent) const
{
Q_UNUSED(parent);
AddressTableEntry* data = priv->index(row);
if (data) {
return createIndex(row, column, priv->index(row));
} else {
return QModelIndex();
}
}
void AddressTableModel::updateEntry(const QString& address,
const QString& label,
bool isMine,
const QString& purpose,
int status)
{
// Update address book model from esbcoin core
priv->updateEntry(address, label, isMine, purpose, status);
}
QString AddressTableModel::addRow(const QString& type, const QString& label, const QString& address)
{
std::string strLabel = label.toStdString();
std::string strAddress = address.toStdString();
editStatus = OK;
if (type == Send) {
if (!walletModel->validateAddress(address)) {
editStatus = INVALID_ADDRESS;
return QString();
}
// Check for duplicate addresses
{
LOCK(wallet->cs_wallet);
if (wallet->mapAddressBook.count(CBitcoinAddress(strAddress).Get())) {
editStatus = DUPLICATE_ADDRESS;
return QString();
}
}
} else if (type == Receive) {
// Generate a new address to associate with given label
CPubKey newKey;
if (!wallet->GetKeyFromPool(newKey)) {
WalletModel::UnlockContext ctx(walletModel->requestUnlock(true));
if (!ctx.isValid()) {
// Unlock wallet failed or was cancelled
editStatus = WALLET_UNLOCK_FAILURE;
return QString();
}
if (!wallet->GetKeyFromPool(newKey)) {
editStatus = KEY_GENERATION_FAILURE;
return QString();
}
}
strAddress = CBitcoinAddress(newKey.GetID()).ToString();
} else {
return QString();
}
// Add entry
{
LOCK(wallet->cs_wallet);
wallet->SetAddressBook(CBitcoinAddress(strAddress).Get(), strLabel,
(type == Send ? "send" : "receive"));
}
return QString::fromStdString(strAddress);
}
bool AddressTableModel::removeRows(int row, int count, const QModelIndex& parent)
{
Q_UNUSED(parent);
AddressTableEntry* rec = priv->index(row);
if (count != 1 || !rec || rec->type == AddressTableEntry::Receiving) {
// Can only remove one row at a time, and cannot remove rows not in model.
// Also refuse to remove receiving addresses.
return false;
}
{
LOCK(wallet->cs_wallet);
wallet->DelAddressBook(CBitcoinAddress(rec->address.toStdString()).Get());
}
return true;
}
/* Look up label for address in address book, if not found return empty string.
*/
QString AddressTableModel::labelForAddress(const QString& address) const
{
{
LOCK(wallet->cs_wallet);
CBitcoinAddress address_parsed(address.toStdString());
std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(address_parsed.Get());
if (mi != wallet->mapAddressBook.end()) {
return QString::fromStdString(mi->second.name);
}
}
return QString();
}
int AddressTableModel::lookupAddress(const QString& address) const
{
QModelIndexList lst = match(index(0, Address, QModelIndex()),
Qt::EditRole, address, 1, Qt::MatchExactly);
if (lst.isEmpty()) {
return -1;
} else {
return lst.at(0).row();
}
}
void AddressTableModel::emitDataChanged(int idx)
{
emit dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length() - 1, QModelIndex()));
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2016-2019 The ROCKETFUNDCOIN developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "txmempool.h"
#include "clientversion.h"
#include "main.h"
#include "streams.h"
#include "util.h"
#include "utilmoneystr.h"
#include "version.h"
#include <boost/circular_buffer.hpp>
CTxMemPoolEntry::CTxMemPoolEntry() : nFee(0), nTxSize(0), nModSize(0), nTime(0), dPriority(0.0)
{
nHeight = MEMPOOL_HEIGHT;
}
CTxMemPoolEntry::CTxMemPoolEntry(const CTransaction& _tx, const CAmount& _nFee, int64_t _nTime, double _dPriority, unsigned int _nHeight) : tx(_tx), nFee(_nFee), nTime(_nTime), dPriority(_dPriority), nHeight(_nHeight)
{
nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
nModSize = tx.CalculateModifiedSize(nTxSize);
}
CTxMemPoolEntry::CTxMemPoolEntry(const CTxMemPoolEntry& other)
{
*this = other;
}
double
CTxMemPoolEntry::GetPriority(unsigned int currentHeight) const
{
CAmount nValueIn = tx.GetValueOut() + nFee;
double deltaPriority = ((double)(currentHeight - nHeight) * nValueIn) / nModSize;
double dResult = dPriority + deltaPriority;
return dResult;
}
/**
* Keep track of fee/priority for transactions confirmed within N blocks
*/
class CBlockAverage
{
private:
boost::circular_buffer<CFeeRate> feeSamples;
boost::circular_buffer<double> prioritySamples;
template <typename T>
std::vector<T> buf2vec(boost::circular_buffer<T> buf) const
{
std::vector<T> vec(buf.begin(), buf.end());
return vec;
}
public:
CBlockAverage() : feeSamples(100), prioritySamples(100) {}
void RecordFee(const CFeeRate& feeRate)
{
feeSamples.push_back(feeRate);
}
void RecordPriority(double priority)
{
prioritySamples.push_back(priority);
}
size_t FeeSamples() const { return feeSamples.size(); }
size_t GetFeeSamples(std::vector<CFeeRate>& insertInto) const
{
for (const CFeeRate& f : feeSamples)
insertInto.push_back(f);
return feeSamples.size();
}
size_t PrioritySamples() const { return prioritySamples.size(); }
size_t GetPrioritySamples(std::vector<double>& insertInto) const
{
for (double d : prioritySamples)
insertInto.push_back(d);
return prioritySamples.size();
}
/**
* Used as belt-and-suspenders check when reading to detect
* file corruption
*/
static bool AreSane(const CFeeRate fee, const CFeeRate& minRelayFee)
{
if (fee < CFeeRate(0))
return false;
if (fee.GetFeePerK() > minRelayFee.GetFeePerK() * 10000)
return false;
return true;
}
static bool AreSane(const std::vector<CFeeRate>& vecFee, const CFeeRate& minRelayFee)
{
for (CFeeRate fee : vecFee) {
if (!AreSane(fee, minRelayFee))
return false;
}
return true;
}
static bool AreSane(const double priority)
{
return priority >= 0;
}
static bool AreSane(const std::vector<double> vecPriority)
{
for (double priority : vecPriority) {
if (!AreSane(priority))
return false;
}
return true;
}
void Write(CAutoFile& fileout) const
{
std::vector<CFeeRate> vecFee = buf2vec(feeSamples);
fileout << vecFee;
std::vector<double> vecPriority = buf2vec(prioritySamples);
fileout << vecPriority;
}
void Read(CAutoFile& filein, const CFeeRate& minRelayFee)
{
std::vector<CFeeRate> vecFee;
filein >> vecFee;
if (AreSane(vecFee, minRelayFee))
feeSamples.insert(feeSamples.end(), vecFee.begin(), vecFee.end());
else
throw std::runtime_error("Corrupt fee value in estimates file.");
std::vector<double> vecPriority;
filein >> vecPriority;
if (AreSane(vecPriority))
prioritySamples.insert(prioritySamples.end(), vecPriority.begin(), vecPriority.end());
else
throw std::runtime_error("Corrupt priority value in estimates file.");
if (feeSamples.size() + prioritySamples.size() > 0)
LogPrint("estimatefee", "Read %d fee samples and %d priority samples\n",
feeSamples.size(), prioritySamples.size());
}
};
class CMinerPolicyEstimator
{
private:
/**
* Records observed averages transactions that confirmed within one block, two blocks,
* three blocks etc.
*/
std::vector<CBlockAverage> history;
std::vector<CFeeRate> sortedFeeSamples;
std::vector<double> sortedPrioritySamples;
int nBestSeenHeight;
/**
* nBlocksAgo is 0 based, i.e. transactions that confirmed in the highest seen block are
* nBlocksAgo == 0, transactions in the block before that are nBlocksAgo == 1 etc.
*/
void seenTxConfirm(const CFeeRate& feeRate, const CFeeRate& minRelayFee, double dPriority, int nBlocksAgo)
{
// Last entry records "everything else".
int nBlocksTruncated = std::min(nBlocksAgo, (int)history.size() - 1);
assert(nBlocksTruncated >= 0);
// We need to guess why the transaction was included in a block-- either
// because it is high-priority or because it has sufficient fees.
bool sufficientFee = (feeRate > minRelayFee);
bool sufficientPriority = AllowFree(dPriority);
const char* assignedTo = "unassigned";
if (sufficientFee && !sufficientPriority && CBlockAverage::AreSane(feeRate, minRelayFee)) {
history[nBlocksTruncated].RecordFee(feeRate);
assignedTo = "fee";
} else if (sufficientPriority && !sufficientFee && CBlockAverage::AreSane(dPriority)) {
history[nBlocksTruncated].RecordPriority(dPriority);
assignedTo = "priority";
} else {
// Neither or both fee and priority sufficient to get confirmed:
// don't know why they got confirmed.
}
LogPrint("estimatefee", "Seen TX confirm: %s : %s fee/%g priority, took %d blocks\n",
assignedTo, feeRate.ToString(), dPriority, nBlocksAgo);
}
public:
CMinerPolicyEstimator(int nEntries) : nBestSeenHeight(0)
{
history.resize(nEntries);
}
void seenBlock(const std::vector<CTxMemPoolEntry>& entries, int nBlockHeight, const CFeeRate minRelayFee)
{
if (nBlockHeight <= nBestSeenHeight) {
// Ignore side chains and re-orgs; assuming they are random
// they don't affect the estimate.
// And if an attacker can re-org the chain at will, then
// you've got much bigger problems than "attacker can influence
// transaction fees."
return;
}
nBestSeenHeight = nBlockHeight;
// Fill up the history buckets based on how long transactions took
// to confirm.
std::vector<std::vector<const CTxMemPoolEntry*> > entriesByConfirmations;
entriesByConfirmations.resize(history.size());
for (const CTxMemPoolEntry& entry : entries) {
// How many blocks did it take for miners to include this transaction?
int delta = nBlockHeight - entry.GetHeight();
if (delta <= 0) {
// Re-org made us lose height, this should only happen if we happen
// to re-org on a difficulty transition point: very rare!
continue;
}
if ((delta - 1) >= (int)history.size())
delta = history.size(); // Last bucket is catch-all
entriesByConfirmations.at(delta - 1).push_back(&entry);
}
for (size_t i = 0; i < entriesByConfirmations.size(); i++) {
std::vector<const CTxMemPoolEntry*>& e = entriesByConfirmations.at(i);
// Insert at most 10 random entries per bucket, otherwise a single block
// can dominate an estimate:
if (e.size() > 10) {
std::random_shuffle(e.begin(), e.end());
e.resize(10);
}
for (const CTxMemPoolEntry* entry : e) {
// Fees are stored and reported as BTC-per-kb:
CFeeRate feeRate(entry->GetFee(), entry->GetTxSize());
double dPriority = entry->GetPriority(entry->GetHeight()); // Want priority when it went IN
seenTxConfirm(feeRate, minRelayFee, dPriority, i);
}
}
//After new samples are added, we have to clear the sorted lists,
//so they'll be resorted the next time someone asks for an estimate
sortedFeeSamples.clear();
sortedPrioritySamples.clear();
for (size_t i = 0; i < history.size(); i++) {
if (history[i].FeeSamples() + history[i].PrioritySamples() > 0)
LogPrint("estimatefee", "estimates: for confirming within %d blocks based on %d/%d samples, fee=%s, prio=%g\n",
i,
history[i].FeeSamples(), history[i].PrioritySamples(),
estimateFee(i + 1).ToString(), estimatePriority(i + 1));
}
}
/**
* Can return CFeeRate(0) if we don't have any data for that many blocks back. nBlocksToConfirm is 1 based.
*/
CFeeRate estimateFee(int nBlocksToConfirm)
{
nBlocksToConfirm--;
if (nBlocksToConfirm < 0 || nBlocksToConfirm >= (int)history.size())
return CFeeRate(0);
if (sortedFeeSamples.size() == 0) {
for (size_t i = 0; i < history.size(); i++)
history.at(i).GetFeeSamples(sortedFeeSamples);
std::sort(sortedFeeSamples.begin(), sortedFeeSamples.end(),
std::greater<CFeeRate>());
}
if (sortedFeeSamples.size() < 11) {
// Eleven is Gavin's Favorite Number
// ... but we also take a maximum of 10 samples per block so eleven means
// we're getting samples from at least two different blocks
return CFeeRate(0);
}
int nBucketSize = history.at(nBlocksToConfirm).FeeSamples();
// Estimates should not increase as number of confirmations goes up,
// but the estimates are noisy because confirmations happen discretely
// in blocks. To smooth out the estimates, use all samples in the history
// and use the nth highest where n is (number of samples in previous bucket +
// half the samples in nBlocksToConfirm bucket):
size_t nPrevSize = 0;
for (int i = 0; i < nBlocksToConfirm; i++)
nPrevSize += history.at(i).FeeSamples();
size_t index = std::min(nPrevSize + nBucketSize / 2, sortedFeeSamples.size() - 1);
return sortedFeeSamples[index];
}
double estimatePriority(int nBlocksToConfirm)
{
nBlocksToConfirm--;
if (nBlocksToConfirm < 0 || nBlocksToConfirm >= (int)history.size())
return -1;
if (sortedPrioritySamples.size() == 0) {
for (size_t i = 0; i < history.size(); i++)
history.at(i).GetPrioritySamples(sortedPrioritySamples);
std::sort(sortedPrioritySamples.begin(), sortedPrioritySamples.end(),
std::greater<double>());
}
if (sortedPrioritySamples.size() < 11)
return -1.0;
int nBucketSize = history.at(nBlocksToConfirm).PrioritySamples();
// Estimates should not increase as number of confirmations needed goes up,
// but the estimates are noisy because confirmations happen discretely
// in blocks. To smooth out the estimates, use all samples in the history
// and use the nth highest where n is (number of samples in previous buckets +
// half the samples in nBlocksToConfirm bucket).
size_t nPrevSize = 0;
for (int i = 0; i < nBlocksToConfirm; i++)
nPrevSize += history.at(i).PrioritySamples();
size_t index = std::min(nPrevSize + nBucketSize / 2, sortedPrioritySamples.size() - 1);
return sortedPrioritySamples[index];
}
void Write(CAutoFile& fileout) const
{
fileout << nBestSeenHeight;
fileout << history.size();
for (const CBlockAverage& entry : history) {
entry.Write(fileout);
}
}
void Read(CAutoFile& filein, const CFeeRate& minRelayFee)
{
int nFileBestSeenHeight;
filein >> nFileBestSeenHeight;
size_t numEntries;
filein >> numEntries;
if (numEntries <= 0 || numEntries > 10000)
throw std::runtime_error("Corrupt estimates file. Must have between 1 and 10k entries.");
std::vector<CBlockAverage> fileHistory;
for (size_t i = 0; i < numEntries; i++) {
CBlockAverage entry;
entry.Read(filein, minRelayFee);
fileHistory.push_back(entry);
}
// Now that we've processed the entire fee estimate data file and not
// thrown any errors, we can copy it to our history
nBestSeenHeight = nFileBestSeenHeight;
history = fileHistory;
assert(history.size() > 0);
}
};
CTxMemPool::CTxMemPool(const CFeeRate& _minRelayFee) : nTransactionsUpdated(0),
minRelayFee(_minRelayFee)
{
// Sanity checks off by default for performance, because otherwise
// accepting transactions becomes O(N^2) where N is the number
// of transactions in the pool
fSanityCheck = false;
// 25 blocks is a compromise between using a lot of disk/memory and
// trying to give accurate estimates to people who might be willing
// to wait a day or two to save a fraction of a penny in fees.
// Confirmation times for very-low-fee transactions that take more
// than an hour or three to confirm are highly variable.
minerPolicyEstimator = new CMinerPolicyEstimator(25);
}
CTxMemPool::~CTxMemPool()
{
delete minerPolicyEstimator;
}
void CTxMemPool::pruneSpent(const uint256& hashTx, CCoins& coins)
{
LOCK(cs);
std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
// iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
while (it != mapNextTx.end() && it->first.hash == hashTx) {
coins.Spend(it->first.n); // and remove those outputs from coins
it++;
}
}
unsigned int CTxMemPool::GetTransactionsUpdated() const
{
LOCK(cs);
return nTransactionsUpdated;
}
void CTxMemPool::AddTransactionsUpdated(unsigned int n)
{
LOCK(cs);
nTransactionsUpdated += n;
}
bool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry& entry)
{
// Add to memory pool without checking anything.
// Used by main.cpp AcceptToMemoryPool(), which DOES do
// all the appropriate checks.
LOCK(cs);
{
mapTx[hash] = entry;
const CTransaction& tx = mapTx[hash].GetTx();
if(!tx.HasZerocoinSpendInputs()) {
for (unsigned int i = 0; i < tx.vin.size(); i++)
mapNextTx[tx.vin[i].prevout] = CInPoint(&tx, i);
}
nTransactionsUpdated++;
totalTxSize += entry.GetTxSize();
}
return true;
}
void CTxMemPool::remove(const CTransaction& origTx, std::list<CTransaction>& removed, bool fRecursive)
{
// Remove transaction from memory pool
{
LOCK(cs);
std::deque<uint256> txToRemove;
txToRemove.push_back(origTx.GetHash());
if (fRecursive && !mapTx.count(origTx.GetHash())) {
// If recursively removing but origTx isn't in the mempool
// be sure to remove any children that are in the pool. This can
// happen during chain re-orgs if origTx isn't re-accepted into
// the mempool for any reason.
for (unsigned int i = 0; i < origTx.vout.size(); i++) {
std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
if (it == mapNextTx.end())
continue;
txToRemove.push_back(it->second.ptx->GetHash());
}
}
while (!txToRemove.empty()) {
uint256 hash = txToRemove.front();
txToRemove.pop_front();
if (!mapTx.count(hash))
continue;
const CTransaction& tx = mapTx[hash].GetTx();
if (fRecursive) {
for (unsigned int i = 0; i < tx.vout.size(); i++) {
std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i));
if (it == mapNextTx.end())
continue;
txToRemove.push_back(it->second.ptx->GetHash());
}
}
for (const CTxIn& txin : tx.vin)
mapNextTx.erase(txin.prevout);
removed.push_back(tx);
totalTxSize -= mapTx[hash].GetTxSize();
mapTx.erase(hash);
nTransactionsUpdated++;
}
}
}
void CTxMemPool::removeCoinbaseSpends(const CCoinsViewCache* pcoins, unsigned int nMemPoolHeight)
{
// Remove transactions spending a coinbase which are now immature
LOCK(cs);
std::list<CTransaction> transactionsToRemove;
for (std::map<uint256, CTxMemPoolEntry>::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
const CTransaction& tx = it->second.GetTx();
for (const CTxIn& txin : tx.vin) {
std::map<uint256, CTxMemPoolEntry>::const_iterator it2 = mapTx.find(txin.prevout.hash);
if (it2 != mapTx.end())
continue;
const CCoins* coins = pcoins->AccessCoins(txin.prevout.hash);
if (fSanityCheck) assert(coins);
if (!coins || ((coins->IsCoinBase() || coins->IsCoinStake()) && nMemPoolHeight - coins->nHeight < (unsigned)Params().COINBASE_MATURITY())) {
transactionsToRemove.push_back(tx);
break;
}
}
}
for (const CTransaction& tx : transactionsToRemove) {
std::list<CTransaction> removed;
remove(tx, removed, true);
}
}
void CTxMemPool::removeConflicts(const CTransaction& tx, std::list<CTransaction>& removed)
{
// Remove transactions which depend on inputs of tx, recursively
std::list<CTransaction> result;
LOCK(cs);
for (const CTxIn& txin : tx.vin) {
std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
if (it != mapNextTx.end()) {
const CTransaction& txConflict = *it->second.ptx;
if (txConflict != tx) {
remove(txConflict, removed, true);
}
}
}
}
/**
* Called when a block is connected. Removes from mempool and updates the miner fee estimator.
*/
void CTxMemPool::removeForBlock(const std::vector<CTransaction>& vtx, unsigned int nBlockHeight, std::list<CTransaction>& conflicts)
{
LOCK(cs);
std::vector<CTxMemPoolEntry> entries;
for (const CTransaction& tx : vtx) {
uint256 hash = tx.GetHash();
if (mapTx.count(hash))
entries.push_back(mapTx[hash]);
}
minerPolicyEstimator->seenBlock(entries, nBlockHeight, minRelayFee);
for (const CTransaction& tx : vtx) {
std::list<CTransaction> dummy;
remove(tx, dummy, false);
removeConflicts(tx, conflicts);
ClearPrioritisation(tx.GetHash());
}
}
void CTxMemPool::clear()
{
LOCK(cs);
mapTx.clear();
mapNextTx.clear();
totalTxSize = 0;
++nTransactionsUpdated;
}
void CTxMemPool::check(const CCoinsViewCache* pcoins) const
{
if (!fSanityCheck)
return;
LogPrint("mempool", "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
uint64_t checkTotal = 0;
CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(pcoins));
LOCK(cs);
std::list<const CTxMemPoolEntry*> waitingOnDependants;
for (std::map<uint256, CTxMemPoolEntry>::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
unsigned int i = 0;
checkTotal += it->second.GetTxSize();
const CTransaction& tx = it->second.GetTx();
bool fDependsWait = false;
for (const CTxIn& txin : tx.vin) {
// Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
std::map<uint256, CTxMemPoolEntry>::const_iterator it2 = mapTx.find(txin.prevout.hash);
if (it2 != mapTx.end()) {
const CTransaction& tx2 = it2->second.GetTx();
assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
fDependsWait = true;
} else {
const CCoins* coins = pcoins->AccessCoins(txin.prevout.hash);
if(!txin.IsZerocoinSpend() && !txin.IsZerocoinPublicSpend())
assert(coins && coins->IsAvailable(txin.prevout.n));
}
// Check whether its inputs are marked in mapNextTx.
if(!txin.IsZerocoinSpend() && !txin.IsZerocoinPublicSpend()) {
std::map<COutPoint, CInPoint>::const_iterator it3 = mapNextTx.find(txin.prevout);
assert(it3 != mapNextTx.end());
assert(it3->second.ptx == &tx);
assert(it3->second.n == i);
}else{
fDependsWait=false;
}
i++;
}
if (fDependsWait)
waitingOnDependants.push_back(&it->second);
else {
CValidationState state;
CTxUndo undo;
assert(CheckInputs(tx, state, mempoolDuplicate, false, 0, false, NULL));
UpdateCoins(tx, state, mempoolDuplicate, undo, 1000000);
}
}
unsigned int stepsSinceLastRemove = 0;
while (!waitingOnDependants.empty()) {
const CTxMemPoolEntry* entry = waitingOnDependants.front();
waitingOnDependants.pop_front();
CValidationState state;
if (!mempoolDuplicate.HaveInputs(entry->GetTx())) {
waitingOnDependants.push_back(entry);
stepsSinceLastRemove++;
assert(stepsSinceLastRemove < waitingOnDependants.size());
} else {
assert(CheckInputs(entry->GetTx(), state, mempoolDuplicate, false, 0, false, NULL));
CTxUndo undo;
UpdateCoins(entry->GetTx(), state, mempoolDuplicate, undo, 1000000);
stepsSinceLastRemove = 0;
}
}
for (std::map<COutPoint, CInPoint>::const_iterator it = mapNextTx.begin(); it != mapNextTx.end(); it++) {
uint256 hash = it->second.ptx->GetHash();
std::map<uint256, CTxMemPoolEntry>::const_iterator it2 = mapTx.find(hash);
const CTransaction& tx = it2->second.GetTx();
assert(it2 != mapTx.end());
assert(&tx == it->second.ptx);
assert(tx.vin.size() > it->second.n);
assert(it->first == it->second.ptx->vin[it->second.n].prevout);
}
assert(totalTxSize == checkTotal);
}
void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
{
vtxid.clear();
LOCK(cs);
vtxid.reserve(mapTx.size());
for (std::map<uint256, CTxMemPoolEntry>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
vtxid.push_back((*mi).first);
}
void CTxMemPool::getTransactions(std::set<uint256>& setTxid)
{
setTxid.clear();
LOCK(cs);
for (std::map<uint256, CTxMemPoolEntry>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
setTxid.insert((*mi).first);
}
bool CTxMemPool::lookup(uint256 hash, CTransaction& result) const
{
LOCK(cs);
std::map<uint256, CTxMemPoolEntry>::const_iterator i = mapTx.find(hash);
if (i == mapTx.end()) return false;
result = i->second.GetTx();
return true;
}
CFeeRate CTxMemPool::estimateFee(int nBlocks) const
{
LOCK(cs);
return minerPolicyEstimator->estimateFee(nBlocks);
}
double CTxMemPool::estimatePriority(int nBlocks) const
{
LOCK(cs);
return minerPolicyEstimator->estimatePriority(nBlocks);
}
bool CTxMemPool::WriteFeeEstimates(CAutoFile& fileout) const
{
try {
LOCK(cs);
fileout << 120000; // version required to read: 0.12.00 or later
fileout << CLIENT_VERSION; // version that wrote the file
minerPolicyEstimator->Write(fileout);
} catch (const std::exception&) {
LogPrintf("CTxMemPool::WriteFeeEstimates() : unable to write policy estimator data (non-fatal)");
return false;
}
return true;
}
bool CTxMemPool::ReadFeeEstimates(CAutoFile& filein)
{
try {
int nVersionRequired, nVersionThatWrote;
filein >> nVersionRequired >> nVersionThatWrote;
if (nVersionRequired > CLIENT_VERSION)
return error("CTxMemPool::ReadFeeEstimates() : up-version (%d) fee estimate file", nVersionRequired);
LOCK(cs);
minerPolicyEstimator->Read(filein, minRelayFee);
} catch (const std::exception&) {
LogPrintf("CTxMemPool::ReadFeeEstimates() : unable to read policy estimator data (non-fatal)");
return false;
}
return true;
}
void CTxMemPool::PrioritiseTransaction(const uint256 hash, const std::string strHash, double dPriorityDelta, const CAmount& nFeeDelta)
{
{
LOCK(cs);
std::pair<double, CAmount>& deltas = mapDeltas[hash];
deltas.first += dPriorityDelta;
deltas.second += nFeeDelta;
}
LogPrintf("PrioritiseTransaction: %s priority += %f, fee += %d\n", strHash, dPriorityDelta, FormatMoney(nFeeDelta));
}
void CTxMemPool::ApplyDeltas(const uint256 hash, double& dPriorityDelta, CAmount& nFeeDelta)
{
LOCK(cs);
std::map<uint256, std::pair<double, CAmount> >::iterator pos = mapDeltas.find(hash);
if (pos == mapDeltas.end())
return;
const std::pair<double, CAmount>& deltas = pos->second;
dPriorityDelta += deltas.first;
nFeeDelta += deltas.second;
}
void CTxMemPool::ClearPrioritisation(const uint256 hash)
{
LOCK(cs);
mapDeltas.erase(hash);
}
CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) {}
bool CCoinsViewMemPool::GetCoins(const uint256& txid, CCoins& coins) const
{
// If an entry in the mempool exists, always return that one, as it's guaranteed to never
// conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
// transactions. First checking the underlying cache risks returning a pruned entry instead.
CTransaction tx;
if (mempool.lookup(txid, tx)) {
coins = CCoins(tx, MEMPOOL_HEIGHT);
return true;
}
return (base->GetCoins(txid, coins) && !coins.IsPruned());
}
bool CCoinsViewMemPool::HaveCoins(const uint256& txid) const
{
return mempool.exists(txid) || base->HaveCoins(txid);
}
|
// Copyright (c) 2011-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.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <qt/paymentserver.h>
#include <qt/bitcoinunits.h>
#include <qt/guiutil.h>
#include <qt/optionsmodel.h>
#include <chainparams.h>
#include <interfaces/node.h>
#include <policy/policy.h>
#include <key_io.h>
#include <ui_interface.h>
#include <util/system.h>
#include <wallet/wallet.h>
#include <cstdlib>
#include <memory>
#include <openssl/x509_vfy.h>
#include <QApplication>
#include <QByteArray>
#include <QDataStream>
#include <QDateTime>
#include <QDebug>
#include <QFile>
#include <QFileOpenEvent>
#include <QHash>
#include <QList>
#include <QLocalServer>
#include <QLocalSocket>
#include <QNetworkAccessManager>
#include <QNetworkProxy>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QSslCertificate>
#include <QSslConfiguration>
#include <QSslError>
#include <QStringList>
#include <QTextDocument>
#include <QUrlQuery>
const int BITCOIN_IPC_CONNECT_TIMEOUT = 1000; // milliseconds
const QString BITCOIN_IPC_PREFIX("falcon:");
#ifdef ENABLE_BIP70
// BIP70 payment protocol messages
const char* BIP70_MESSAGE_PAYMENTACK = "PaymentACK";
const char* BIP70_MESSAGE_PAYMENTREQUEST = "PaymentRequest";
// BIP71 payment protocol media types
const char* BIP71_MIMETYPE_PAYMENT = "application/bitcoin-payment";
const char* BIP71_MIMETYPE_PAYMENTACK = "application/bitcoin-paymentack";
const char* BIP71_MIMETYPE_PAYMENTREQUEST = "application/bitcoin-paymentrequest";
#endif
//
// Create a name that is unique for:
// testnet / non-testnet
// data directory
//
static QString ipcServerName()
{
QString name("FalconQt");
// Append a simple hash of the datadir
// Note that GetDataDir(true) returns a different path
// for -testnet versus main net
QString ddir(GUIUtil::boostPathToQString(GetDataDir(true)));
name.append(QString::number(qHash(ddir)));
return name;
}
//
// We store payment URIs and requests received before
// the main GUI window is up and ready to ask the user
// to send payment.
static QSet<QString> savedPaymentRequests;
//
// Sending to the server is done synchronously, at startup.
// If the server isn't already running, startup continues,
// and the items in savedPaymentRequest will be handled
// when uiReady() is called.
//
// Warning: ipcSendCommandLine() is called early in init,
// so don't use "Q_EMIT message()", but "QMessageBox::"!
//
void PaymentServer::ipcParseCommandLine(interfaces::Node& node, int argc, char* argv[])
{
for (int i = 1; i < argc; i++)
{
QString arg(argv[i]);
if (arg.startsWith("-"))
continue;
// If the bitcoin: URI contains a payment request, we are not able to detect the
// network as that would require fetching and parsing the payment request.
// That means clicking such an URI which contains a testnet payment request
// will start a mainnet instance and throw a "wrong network" error.
if (arg.startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) // bitcoin: URI
{
if (savedPaymentRequests.contains(arg)) continue;
savedPaymentRequests.insert(arg);
SendCoinsRecipient r;
if (GUIUtil::parseBitcoinURI(arg, &r) && !r.address.isEmpty())
{
auto tempChainParams = CreateChainParams(CBaseChainParams::MAIN);
if (IsValidDestinationString(r.address.toStdString(), *tempChainParams)) {
node.selectParams(CBaseChainParams::MAIN);
} else {
tempChainParams = CreateChainParams(CBaseChainParams::TESTNET);
if (IsValidDestinationString(r.address.toStdString(), *tempChainParams)) {
node.selectParams(CBaseChainParams::TESTNET);
}
}
}
}
#ifdef ENABLE_BIP70
else if (QFile::exists(arg)) // Filename
{
if (savedPaymentRequests.contains(arg)) continue;
savedPaymentRequests.insert(arg);
PaymentRequestPlus request;
if (readPaymentRequestFromFile(arg, request))
{
if (request.getDetails().network() == "main")
{
node.selectParams(CBaseChainParams::MAIN);
}
else if (request.getDetails().network() == "test")
{
node.selectParams(CBaseChainParams::TESTNET);
}
}
}
else
{
// Printing to debug.log is about the best we can do here, the
// GUI hasn't started yet so we can't pop up a message box.
qWarning() << "PaymentServer::ipcSendCommandLine: Payment request file does not exist: " << arg;
}
#endif
}
}
//
// Sending to the server is done synchronously, at startup.
// If the server isn't already running, startup continues,
// and the items in savedPaymentRequest will be handled
// when uiReady() is called.
//
bool PaymentServer::ipcSendCommandLine()
{
bool fResult = false;
for (const QString& r : savedPaymentRequests)
{
QLocalSocket* socket = new QLocalSocket();
socket->connectToServer(ipcServerName(), QIODevice::WriteOnly);
if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT))
{
delete socket;
socket = nullptr;
return false;
}
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << r;
out.device()->seek(0);
socket->write(block);
socket->flush();
socket->waitForBytesWritten(BITCOIN_IPC_CONNECT_TIMEOUT);
socket->disconnectFromServer();
delete socket;
socket = nullptr;
fResult = true;
}
return fResult;
}
PaymentServer::PaymentServer(QObject* parent, bool startLocalServer) :
QObject(parent),
saveURIs(true),
uriServer(nullptr),
optionsModel(nullptr)
#ifdef ENABLE_BIP70
,netManager(nullptr)
#endif
{
#ifdef ENABLE_BIP70
// Verify that the version of the library that we linked against is
// compatible with the version of the headers we compiled against.
GOOGLE_PROTOBUF_VERIFY_VERSION;
#endif
// Install global event filter to catch QFileOpenEvents
// on Mac: sent when you click bitcoin: links
// other OSes: helpful when dealing with payment request files
if (parent)
parent->installEventFilter(this);
QString name = ipcServerName();
// Clean up old socket leftover from a crash:
QLocalServer::removeServer(name);
if (startLocalServer)
{
uriServer = new QLocalServer(this);
if (!uriServer->listen(name)) {
// constructor is called early in init, so don't use "Q_EMIT message()" here
QMessageBox::critical(nullptr, tr("Payment request error"),
tr("Cannot start falcon: click-to-pay handler"));
}
else {
connect(uriServer, &QLocalServer::newConnection, this, &PaymentServer::handleURIConnection);
#ifdef ENABLE_BIP70
connect(this, &PaymentServer::receivedPaymentACK, this, &PaymentServer::handlePaymentACK);
#endif
}
}
}
PaymentServer::~PaymentServer()
{
#ifdef ENABLE_BIP70
google::protobuf::ShutdownProtobufLibrary();
#endif
}
//
// OSX-specific way of handling bitcoin: URIs and PaymentRequest mime types.
// Also used by paymentservertests.cpp and when opening a payment request file
// via "Open URI..." menu entry.
//
bool PaymentServer::eventFilter(QObject *object, QEvent *event)
{
if (event->type() == QEvent::FileOpen) {
QFileOpenEvent *fileEvent = static_cast<QFileOpenEvent*>(event);
if (!fileEvent->file().isEmpty())
handleURIOrFile(fileEvent->file());
else if (!fileEvent->url().isEmpty())
handleURIOrFile(fileEvent->url().toString());
return true;
}
return QObject::eventFilter(object, event);
}
void PaymentServer::uiReady()
{
#ifdef ENABLE_BIP70
initNetManager();
#endif
saveURIs = false;
for (const QString& s : savedPaymentRequests)
{
handleURIOrFile(s);
}
savedPaymentRequests.clear();
}
void PaymentServer::handleURIOrFile(const QString& s)
{
if (saveURIs)
{
savedPaymentRequests.insert(s);
return;
}
if (s.startsWith("falcon://", Qt::CaseInsensitive))
{
Q_EMIT message(tr("URI handling"), tr("'falcon://' is not a valid URI. Use 'falcon:' instead."),
CClientUIInterface::MSG_ERROR);
}
else if (s.startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) // bitcoin: URI
{
QUrlQuery uri((QUrl(s)));
#ifdef ENABLE_BIP70
if (uri.hasQueryItem("r")) // payment request URI
{
Q_EMIT message(tr("URI handling"),
tr("You are using a BIP70 URL which will be unsupported in the future."),
CClientUIInterface::ICON_WARNING);
QByteArray temp;
temp.append(uri.queryItemValue("r"));
QString decoded = QUrl::fromPercentEncoding(temp);
QUrl fetchUrl(decoded, QUrl::StrictMode);
if (fetchUrl.isValid())
{
qDebug() << "PaymentServer::handleURIOrFile: fetchRequest(" << fetchUrl << ")";
fetchRequest(fetchUrl);
}
else
{
qWarning() << "PaymentServer::handleURIOrFile: Invalid URL: " << fetchUrl;
Q_EMIT message(tr("URI handling"),
tr("Payment request fetch URL is invalid: %1").arg(fetchUrl.toString()),
CClientUIInterface::ICON_WARNING);
}
return;
}
else
#endif
// normal URI
{
SendCoinsRecipient recipient;
if (GUIUtil::parseBitcoinURI(s, &recipient))
{
if (!IsValidDestinationString(recipient.address.toStdString())) {
#ifndef ENABLE_BIP70
if (uri.hasQueryItem("r")) { // payment request
Q_EMIT message(tr("URI handling"),
tr("Cannot process payment request because BIP70 support was not compiled in.")+
tr("Due to widespread security flaws in BIP70 it's strongly recommended that any merchant instructions to switch wallets be ignored.")+
tr("If you are receiving this error you should request the merchant provide a BIP21 compatible URI."),
CClientUIInterface::ICON_WARNING);
}
#endif
Q_EMIT message(tr("URI handling"), tr("Invalid payment address %1").arg(recipient.address),
CClientUIInterface::MSG_ERROR);
}
else
Q_EMIT receivedPaymentRequest(recipient);
}
else
Q_EMIT message(tr("URI handling"),
tr("URI cannot be parsed! This can be caused by an invalid Falcon address or malformed URI parameters."),
CClientUIInterface::ICON_WARNING);
return;
}
}
if (QFile::exists(s)) // payment request file
{
#ifdef ENABLE_BIP70
PaymentRequestPlus request;
SendCoinsRecipient recipient;
if (!readPaymentRequestFromFile(s, request))
{
Q_EMIT message(tr("Payment request file handling"),
tr("Payment request file cannot be read! This can be caused by an invalid payment request file."),
CClientUIInterface::ICON_WARNING);
}
else if (processPaymentRequest(request, recipient))
Q_EMIT receivedPaymentRequest(recipient);
return;
#else
Q_EMIT message(tr("Payment request file handling"),
tr("Cannot process payment request because BIP70 support was not compiled in.")+
tr("Due to widespread security flaws in BIP70 it's strongly recommended that any merchant instructions to switch wallets be ignored.")+
tr("If you are receiving this error you should request the merchant provide a BIP21 compatible URI."),
CClientUIInterface::ICON_WARNING);
#endif
}
}
void PaymentServer::handleURIConnection()
{
QLocalSocket *clientConnection = uriServer->nextPendingConnection();
while (clientConnection->bytesAvailable() < (int)sizeof(quint32))
clientConnection->waitForReadyRead();
connect(clientConnection, &QLocalSocket::disconnected, clientConnection, &QLocalSocket::deleteLater);
QDataStream in(clientConnection);
in.setVersion(QDataStream::Qt_4_0);
if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) {
return;
}
QString msg;
in >> msg;
handleURIOrFile(msg);
}
void PaymentServer::setOptionsModel(OptionsModel *_optionsModel)
{
this->optionsModel = _optionsModel;
}
#ifdef ENABLE_BIP70
struct X509StoreDeleter {
void operator()(X509_STORE* b) {
X509_STORE_free(b);
}
};
struct X509Deleter {
void operator()(X509* b) { X509_free(b); }
};
namespace // Anon namespace
{
std::unique_ptr<X509_STORE, X509StoreDeleter> certStore;
}
static void ReportInvalidCertificate(const QSslCertificate& cert)
{
qDebug() << QString("%1: Payment server found an invalid certificate: ").arg(__func__) << cert.serialNumber() << cert.subjectInfo(QSslCertificate::CommonName) << cert.subjectInfo(QSslCertificate::DistinguishedNameQualifier) << cert.subjectInfo(QSslCertificate::OrganizationalUnitName);
}
//
// Load OpenSSL's list of root certificate authorities
//
void PaymentServer::LoadRootCAs(X509_STORE* _store)
{
// Unit tests mostly use this, to pass in fake root CAs:
if (_store)
{
certStore.reset(_store);
return;
}
// Normal execution, use either -rootcertificates or system certs:
certStore.reset(X509_STORE_new());
// Note: use "-system-" default here so that users can pass -rootcertificates=""
// and get 'I don't like X.509 certificates, don't trust anybody' behavior:
QString certFile = QString::fromStdString(gArgs.GetArg("-rootcertificates", "-system-"));
// Empty store
if (certFile.isEmpty()) {
qDebug() << QString("PaymentServer::%1: Payment request authentication via X.509 certificates disabled.").arg(__func__);
return;
}
QList<QSslCertificate> certList;
if (certFile != "-system-") {
qDebug() << QString("PaymentServer::%1: Using \"%2\" as trusted root certificate.").arg(__func__).arg(certFile);
certList = QSslCertificate::fromPath(certFile);
// Use those certificates when fetching payment requests, too:
QSslConfiguration::defaultConfiguration().setCaCertificates(certList);
} else
certList = QSslConfiguration::systemCaCertificates();
int nRootCerts = 0;
const QDateTime currentTime = QDateTime::currentDateTime();
for (const QSslCertificate& cert : certList) {
// Don't log NULL certificates
if (cert.isNull())
continue;
// Not yet active/valid, or expired certificate
if (currentTime < cert.effectiveDate() || currentTime > cert.expiryDate()) {
ReportInvalidCertificate(cert);
continue;
}
// Blacklisted certificate
if (cert.isBlacklisted()) {
ReportInvalidCertificate(cert);
continue;
}
QByteArray certData = cert.toDer();
const unsigned char *data = (const unsigned char *)certData.data();
std::unique_ptr<X509, X509Deleter> x509(d2i_X509(0, &data, certData.size()));
if (x509 && X509_STORE_add_cert(certStore.get(), x509.get()))
{
// Note: X509_STORE increases the reference count to the X509 object,
// we still have to release our reference to it.
++nRootCerts;
}
else
{
ReportInvalidCertificate(cert);
continue;
}
}
qInfo() << "PaymentServer::LoadRootCAs: Loaded " << nRootCerts << " root certificates";
// Project for another day:
// Fetch certificate revocation lists, and add them to certStore.
// Issues to consider:
// performance (start a thread to fetch in background?)
// privacy (fetch through tor/proxy so IP address isn't revealed)
// would it be easier to just use a compiled-in blacklist?
// or use Qt's blacklist?
// "certificate stapling" with server-side caching is more efficient
}
void PaymentServer::initNetManager()
{
if (!optionsModel)
return;
delete netManager;
// netManager is used to fetch paymentrequests given in bitcoin: URIs
netManager = new QNetworkAccessManager(this);
QNetworkProxy proxy;
// Query active SOCKS5 proxy
if (optionsModel->getProxySettings(proxy)) {
netManager->setProxy(proxy);
qDebug() << "PaymentServer::initNetManager: Using SOCKS5 proxy" << proxy.hostName() << ":" << proxy.port();
}
else
qDebug() << "PaymentServer::initNetManager: No active proxy server found.";
connect(netManager, &QNetworkAccessManager::finished, this, &PaymentServer::netRequestFinished);
connect(netManager, &QNetworkAccessManager::sslErrors, this, &PaymentServer::reportSslErrors);
}
//
// Warning: readPaymentRequestFromFile() is used in ipcSendCommandLine()
// so don't use "Q_EMIT message()", but "QMessageBox::"!
//
bool PaymentServer::readPaymentRequestFromFile(const QString& filename, PaymentRequestPlus& request)
{
QFile f(filename);
if (!f.open(QIODevice::ReadOnly)) {
qWarning() << QString("PaymentServer::%1: Failed to open %2").arg(__func__).arg(filename);
return false;
}
// BIP70 DoS protection
if (!verifySize(f.size())) {
return false;
}
QByteArray data = f.readAll();
return request.parse(data);
}
bool PaymentServer::processPaymentRequest(const PaymentRequestPlus& request, SendCoinsRecipient& recipient)
{
if (!optionsModel)
return false;
if (request.IsInitialized()) {
// Payment request network matches client network?
if (!verifyNetwork(optionsModel->node(), request.getDetails())) {
Q_EMIT message(tr("Payment request rejected"), tr("Payment request network doesn't match client network."),
CClientUIInterface::MSG_ERROR);
return false;
}
// Make sure any payment requests involved are still valid.
// This is re-checked just before sending coins in WalletModel::sendCoins().
if (verifyExpired(request.getDetails())) {
Q_EMIT message(tr("Payment request rejected"), tr("Payment request expired."),
CClientUIInterface::MSG_ERROR);
return false;
}
} else {
Q_EMIT message(tr("Payment request error"), tr("Payment request is not initialized."),
CClientUIInterface::MSG_ERROR);
return false;
}
recipient.paymentRequest = request;
recipient.message = GUIUtil::HtmlEscape(request.getDetails().memo());
request.getMerchant(certStore.get(), recipient.authenticatedMerchant);
QList<std::pair<CScript, CAmount> > sendingTos = request.getPayTo();
QStringList addresses;
for (const std::pair<CScript, CAmount>& sendingTo : sendingTos) {
// Extract and check destination addresses
CTxDestination dest;
if (ExtractDestination(sendingTo.first, dest)) {
// Append destination address
addresses.append(QString::fromStdString(EncodeDestination(dest)));
}
else if (!recipient.authenticatedMerchant.isEmpty()) {
// Unauthenticated payment requests to custom bitcoin addresses are not supported
// (there is no good way to tell the user where they are paying in a way they'd
// have a chance of understanding).
Q_EMIT message(tr("Payment request rejected"),
tr("Unverified payment requests to custom payment scripts are unsupported."),
CClientUIInterface::MSG_ERROR);
return false;
}
// Bitcoin amounts are stored as (optional) uint64 in the protobuf messages (see paymentrequest.proto),
// but CAmount is defined as int64_t. Because of that we need to verify that amounts are in a valid range
// and no overflow has happened.
if (!verifyAmount(sendingTo.second)) {
Q_EMIT message(tr("Payment request rejected"), tr("Invalid payment request."), CClientUIInterface::MSG_ERROR);
return false;
}
// Extract and check amounts
CTxOut txOut(sendingTo.second, sendingTo.first);
if (IsDust(txOut, optionsModel->node().getDustRelayFee())) {
Q_EMIT message(tr("Payment request error"), tr("Requested payment amount of %1 is too small (considered dust).")
.arg(BitcoinUnits::formatWithUnit(optionsModel->getDisplayUnit(), sendingTo.second)),
CClientUIInterface::MSG_ERROR);
return false;
}
recipient.amount += sendingTo.second;
// Also verify that the final amount is still in a valid range after adding additional amounts.
if (!verifyAmount(recipient.amount)) {
Q_EMIT message(tr("Payment request rejected"), tr("Invalid payment request."), CClientUIInterface::MSG_ERROR);
return false;
}
}
// Store addresses and format them to fit nicely into the GUI
recipient.address = addresses.join("<br />");
if (!recipient.authenticatedMerchant.isEmpty()) {
qDebug() << "PaymentServer::processPaymentRequest: Secure payment request from " << recipient.authenticatedMerchant;
}
else {
qDebug() << "PaymentServer::processPaymentRequest: Insecure payment request to " << addresses.join(", ");
}
return true;
}
void PaymentServer::fetchRequest(const QUrl& url)
{
QNetworkRequest netRequest;
netRequest.setAttribute(QNetworkRequest::User, BIP70_MESSAGE_PAYMENTREQUEST);
netRequest.setUrl(url);
netRequest.setRawHeader("User-Agent", CLIENT_NAME.c_str());
netRequest.setRawHeader("Accept", BIP71_MIMETYPE_PAYMENTREQUEST);
netManager->get(netRequest);
}
void PaymentServer::fetchPaymentACK(WalletModel* walletModel, const SendCoinsRecipient& recipient, QByteArray transaction)
{
const payments::PaymentDetails& details = recipient.paymentRequest.getDetails();
if (!details.has_payment_url())
return;
QNetworkRequest netRequest;
netRequest.setAttribute(QNetworkRequest::User, BIP70_MESSAGE_PAYMENTACK);
netRequest.setUrl(QString::fromStdString(details.payment_url()));
netRequest.setHeader(QNetworkRequest::ContentTypeHeader, BIP71_MIMETYPE_PAYMENT);
netRequest.setRawHeader("User-Agent", CLIENT_NAME.c_str());
netRequest.setRawHeader("Accept", BIP71_MIMETYPE_PAYMENTACK);
payments::Payment payment;
payment.set_merchant_data(details.merchant_data());
payment.add_transactions(transaction.data(), transaction.size());
// Create a new refund address, or re-use:
CTxDestination dest;
const OutputType change_type = walletModel->wallet().getDefaultChangeType() != OutputType::CHANGE_AUTO ? walletModel->wallet().getDefaultChangeType() : walletModel->wallet().getDefaultAddressType();
if (walletModel->wallet().getNewDestination(change_type, "", dest)) {
// BIP70 requests encode the scriptPubKey directly, so we are not restricted to address
// types supported by the receiver. As a result, we choose the address format we also
// use for change. Despite an actual payment and not change, this is a close match:
// it's the output type we use subject to privacy issues, but not restricted by what
// other software supports.
std::string label = tr("Refund from %1").arg(recipient.authenticatedMerchant).toStdString();
walletModel->wallet().setAddressBook(dest, label, "refund");
CScript s = GetScriptForDestination(dest);
payments::Output* refund_to = payment.add_refund_to();
refund_to->set_script(&s[0], s.size());
} else {
// This should never happen, because sending coins should have
// just unlocked the wallet and refilled the keypool.
qWarning() << "PaymentServer::fetchPaymentACK: Error getting refund key, refund_to not set";
}
int length = payment.ByteSize();
netRequest.setHeader(QNetworkRequest::ContentLengthHeader, length);
QByteArray serData(length, '\0');
if (payment.SerializeToArray(serData.data(), length)) {
netManager->post(netRequest, serData);
}
else {
// This should never happen, either.
qWarning() << "PaymentServer::fetchPaymentACK: Error serializing payment message";
}
}
void PaymentServer::netRequestFinished(QNetworkReply* reply)
{
reply->deleteLater();
// BIP70 DoS protection
if (!verifySize(reply->size())) {
Q_EMIT message(tr("Payment request rejected"),
tr("Payment request %1 is too large (%2 bytes, allowed %3 bytes).")
.arg(reply->request().url().toString())
.arg(reply->size())
.arg(BIP70_MAX_PAYMENTREQUEST_SIZE),
CClientUIInterface::MSG_ERROR);
return;
}
if (reply->error() != QNetworkReply::NoError) {
QString msg = tr("Error communicating with %1: %2")
.arg(reply->request().url().toString())
.arg(reply->errorString());
qWarning() << "PaymentServer::netRequestFinished: " << msg;
Q_EMIT message(tr("Payment request error"), msg, CClientUIInterface::MSG_ERROR);
return;
}
QByteArray data = reply->readAll();
QString requestType = reply->request().attribute(QNetworkRequest::User).toString();
if (requestType == BIP70_MESSAGE_PAYMENTREQUEST)
{
PaymentRequestPlus request;
SendCoinsRecipient recipient;
if (!request.parse(data))
{
qWarning() << "PaymentServer::netRequestFinished: Error parsing payment request";
Q_EMIT message(tr("Payment request error"),
tr("Payment request cannot be parsed!"),
CClientUIInterface::MSG_ERROR);
}
else if (processPaymentRequest(request, recipient))
Q_EMIT receivedPaymentRequest(recipient);
return;
}
else if (requestType == BIP70_MESSAGE_PAYMENTACK)
{
payments::PaymentACK paymentACK;
if (!paymentACK.ParseFromArray(data.data(), data.size()))
{
QString msg = tr("Bad response from server %1")
.arg(reply->request().url().toString());
qWarning() << "PaymentServer::netRequestFinished: " << msg;
Q_EMIT message(tr("Payment request error"), msg, CClientUIInterface::MSG_ERROR);
}
else
{
Q_EMIT receivedPaymentACK(GUIUtil::HtmlEscape(paymentACK.memo()));
}
}
}
void PaymentServer::reportSslErrors(QNetworkReply* reply, const QList<QSslError> &errs)
{
Q_UNUSED(reply);
QString errString;
for (const QSslError& err : errs) {
qWarning() << "PaymentServer::reportSslErrors: " << err;
errString += err.errorString() + "\n";
}
Q_EMIT message(tr("Network request error"), errString, CClientUIInterface::MSG_ERROR);
}
void PaymentServer::handlePaymentACK(const QString& paymentACKMsg)
{
// currently we don't further process or store the paymentACK message
Q_EMIT message(tr("Payment acknowledged"), paymentACKMsg, CClientUIInterface::ICON_INFORMATION | CClientUIInterface::MODAL);
}
bool PaymentServer::verifyNetwork(interfaces::Node& node, const payments::PaymentDetails& requestDetails)
{
bool fVerified = requestDetails.network() == node.getNetwork();
if (!fVerified) {
qWarning() << QString("PaymentServer::%1: Payment request network \"%2\" doesn't match client network \"%3\".")
.arg(__func__)
.arg(QString::fromStdString(requestDetails.network()))
.arg(QString::fromStdString(node.getNetwork()));
}
return fVerified;
}
bool PaymentServer::verifyExpired(const payments::PaymentDetails& requestDetails)
{
bool fVerified = (requestDetails.has_expires() && (int64_t)requestDetails.expires() < GetTime());
if (fVerified) {
const QString requestExpires = QString::fromStdString(FormatISO8601DateTime((int64_t)requestDetails.expires()));
qWarning() << QString("PaymentServer::%1: Payment request expired \"%2\".")
.arg(__func__)
.arg(requestExpires);
}
return fVerified;
}
bool PaymentServer::verifySize(qint64 requestSize)
{
bool fVerified = (requestSize <= BIP70_MAX_PAYMENTREQUEST_SIZE);
if (!fVerified) {
qWarning() << QString("PaymentServer::%1: Payment request too large (%2 bytes, allowed %3 bytes).")
.arg(__func__)
.arg(requestSize)
.arg(BIP70_MAX_PAYMENTREQUEST_SIZE);
}
return fVerified;
}
bool PaymentServer::verifyAmount(const CAmount& requestAmount)
{
bool fVerified = MoneyRange(requestAmount);
if (!fVerified) {
qWarning() << QString("PaymentServer::%1: Payment request amount out of allowed range (%2, allowed 0 - %3).")
.arg(__func__)
.arg(requestAmount)
.arg(MAX_MONEY);
}
return fVerified;
}
X509_STORE* PaymentServer::getCertStore()
{
return certStore.get();
}
#endif
|
/*
* Copyright (C) 2005 - 2013 MaNGOS <http://www.getmangos.com/>
*
* Copyright (C) 2008 - 2013 Trinity <http://www.trinitycore.org/>
*
* Copyright (C) 2010 - 2013 Strawberry-Pr0jcts <http://www.strawberry-pr0jcts.com/>
*
* Copyright (C) 2010 - 2013 ProjectSkyfire <http://www.projectskyfire.org/>
*
* Copyright (C) 2011 - 2013 ArkCORE <http://www.arkania.net/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "gamePCH.h"
#include "DB2Stores.h"
#include "Logging/Log.h"
#include "SharedDefines.h"
#include "SpellMgr.h"
#include "DB2fmt.h"
#include <map>
DB2Storage<ItemEntry> sItemStore(Itemfmt);
typedef std::list<std::string> StoreProblemList1;
uint32 DB2FileCount = 0;
static bool LoadDB2_assert_print (uint32 fsize, uint32 rsize, const std::string& filename)
{
sLog->outError("Size of '%s' setted by format string (%u) not equal size of C++ structure (%u).", filename.c_str(), fsize, rsize);
// ASSERT must fail after function call
return false;
}
struct LocalDB2Data
{
LocalDB2Data (LocaleConstant loc) :
defaultLocale(loc), availableDb2Locales(0xFFFFFFFF)
{
}
LocaleConstant defaultLocale;
// bitmasks for index of fullLocaleNameList
uint32 availableDb2Locales;
};
template<class T>
inline void LoadDB2 (uint32& availableDb2Locales, StoreProblemList1& errlist, DB2Storage<T>& storage, const std::string& db2_path, const std::string& filename)
{
// compatibility format and C++ structure sizes
ASSERT(DB2FileLoader::GetFormatRecordSize(storage.GetFormat()) == sizeof(T) || LoadDB2_assert_print(DB2FileLoader::GetFormatRecordSize(storage.GetFormat()), sizeof(T), filename));
++DB2FileCount;
std::string db2_filename = db2_path + filename;
if (storage.Load(db2_filename.c_str()))
{
//bar.step();
}
else
{
// sort problematic db2 to (1) non compatible and (2) nonexistent
FILE * f = fopen(db2_filename.c_str(), "rb");
if (f)
{
char buf[100];
snprintf(buf, 100, "(exist, but have %d fields instead " SIZEFMTD ") Wrong client version DBC file?", storage.GetFieldCount(), strlen(storage.GetFormat()));
errlist.push_back(db2_filename + buf);
fclose(f);
}
else
errlist.push_back(db2_filename);
}
}
void LoadDB2Stores (const std::string& dataPath)
{
uint32 oldMSTime = getMSTime();
std::string db2Path = dataPath + "dbc/";
StoreProblemList1 bad_db2_files;
uint32 availableDb2Locales = 0xFFFFFFFF;
LoadDB2(availableDb2Locales, bad_db2_files, sItemStore, db2Path, "Item.db2");
// error checks
if (bad_db2_files.size() >= DB2FileCount)
{
sLog->outError("\nIncorrect DataDir value in worldserver.conf or ALL required *.db2 files (%d) not found by path: %sdb2", DB2FileCount, dataPath.c_str());
exit(1);
}
else if (!bad_db2_files.empty())
{
std::string str;
for (std::list<std::string>::iterator i = bad_db2_files.begin(); i != bad_db2_files.end(); ++i)
str += *i + "\n";
sLog->outError("\nSome required *.db2 files (%u from %d) not found or not compatible:\n%s", (uint32) bad_db2_files.size(), DB2FileCount, str.c_str());
exit(1);
}
// Check loaded DBC files proper version
if (!sItemStore.LookupEntry(68815)) // last client known item added in 4.0.6a
{
sLog->outString();
sLog->outError("Please extract correct db2 files from client 4.0.6a 13623.");
exit(1);
}
sLog->outString(">> Initialized %d Db2 data stores in %u ms", DB2FileCount, GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
}
|
// Copyright (c) 2019 The PIVX developers
// Copyright (c) 2020 The Klimatas developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "qt/kts/navmenuwidget.h"
#include "qt/kts/forms/ui_navmenuwidget.h"
#include "qt/kts/ktsgui.h"
#include "qt/kts/qtutils.h"
#include "clientversion.h"
#include "optionsmodel.h"
#include <QScrollBar>
NavMenuWidget::NavMenuWidget(KTSGUI *mainWindow, QWidget *parent) :
PWidget(mainWindow, parent),
ui(new Ui::NavMenuWidget)
{
ui->setupUi(this);
this->setFixedWidth(100);
setCssProperty(ui->navContainer_2, "container-nav");
setCssProperty(ui->imgLogo, "img-nav-logo");
// App version
ui->labelVersion->setText(QString(tr("v%1")).arg(QString::fromStdString(FormatVersionFriendly())));
ui->labelVersion->setProperty("cssClass", "text-title-white");
// Buttons
ui->btnDashboard->setProperty("name", "dash");
ui->btnDashboard->setText("HOME\n");
ui->btnDashboard->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
ui->btnSend->setProperty("name", "send");
ui->btnSend->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
ui->btnSend->setText("SEND\n");
ui->btnAddress->setProperty("name", "address");
ui->btnAddress->setText("CONTACTS\n");
ui->btnAddress->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
//ui->btnPrivacy->setProperty("name", "privacy");
//ui->btnPrivacy->setText("PRIVACY\n");
//ui->btnPrivacy->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
ui->btnMaster->setProperty("name", "master");
ui->btnMaster->setText("MASTER\r\nNODES");
ui->btnMaster->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
ui->btnColdStaking->setProperty("name", "cold-staking");
ui->btnColdStaking->setText("COLD\r\nSTAKING");
ui->btnColdStaking->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
ui->btnSettings->setProperty("name", "settings");
ui->btnSettings->setText("SETTINGS\n");
ui->btnSettings->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
ui->btnReceive->setProperty("name", "receive");
ui->btnReceive->setText("RECEIVE\n");
ui->btnReceive->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
btns = {ui->btnDashboard, ui->btnSend, ui->btnReceive, ui->btnAddress, ui->btnMaster, ui->btnColdStaking, ui->btnSettings, ui->btnColdStaking};
onNavSelected(ui->btnDashboard, true);
ui->scrollAreaNav->setWidgetResizable(true);
QSizePolicy scrollAreaPolicy = ui->scrollAreaNav->sizePolicy();
scrollAreaPolicy.setVerticalStretch(1);
ui->scrollAreaNav->setSizePolicy(scrollAreaPolicy);
QSizePolicy scrollVertPolicy = ui->scrollAreaNavVert->sizePolicy();
scrollVertPolicy.setVerticalStretch(1);
ui->scrollAreaNavVert->setSizePolicy(scrollVertPolicy);
connectActions();
}
void NavMenuWidget::loadWalletModel() {
if (walletModel && walletModel->getOptionsModel()) {
ui->btnColdStaking->setVisible(walletModel->getOptionsModel()->isColdStakingScreenEnabled());
}
}
/**
* Actions
*/
void NavMenuWidget::connectActions() {
connect(ui->btnDashboard,SIGNAL(clicked()),this, SLOT(onDashboardClicked()));
connect(ui->btnSend,SIGNAL(clicked()),this, SLOT(onSendClicked()));
connect(ui->btnAddress,SIGNAL(clicked()),this, SLOT(onAddressClicked()));
//connect(ui->btnPrivacy,SIGNAL(clicked()),this, SLOT(onPrivacyClicked()));
connect(ui->btnMaster,SIGNAL(clicked()),this, SLOT(onMasterNodesClicked()));
connect(ui->btnSettings,SIGNAL(clicked()),this, SLOT(onSettingsClicked()));
connect(ui->btnReceive,SIGNAL(clicked()),this, SLOT(onReceiveClicked()));
connect(ui->btnColdStaking,SIGNAL(clicked()),this, SLOT(onColdStakingClicked()));
ui->btnDashboard->setShortcut(QKeySequence(SHORT_KEY + Qt::Key_1));
ui->btnSend->setShortcut(QKeySequence(SHORT_KEY + Qt::Key_2));
ui->btnReceive->setShortcut(QKeySequence(SHORT_KEY + Qt::Key_3));
ui->btnAddress->setShortcut(QKeySequence(SHORT_KEY + Qt::Key_4));
//ui->btnPrivacy->setShortcut(QKeySequence(SHORT_KEY + Qt::Key_5));
ui->btnMaster->setShortcut(QKeySequence(SHORT_KEY + Qt::Key_6));
ui->btnColdStaking->setShortcut(QKeySequence(SHORT_KEY + Qt::Key_7));
ui->btnSettings->setShortcut(QKeySequence(SHORT_KEY + Qt::Key_8));
}
void NavMenuWidget::onSendClicked(){
window->goToSend();
onNavSelected(ui->btnSend);
}
void NavMenuWidget::onDashboardClicked(){
window->goToDashboard();
onNavSelected(ui->btnDashboard);
}
void NavMenuWidget::onAddressClicked(){
window->goToAddresses();
onNavSelected(ui->btnAddress);
}
//void NavMenuWidget::onPrivacyClicked(){
// window->goToPrivacy();
// onNavSelected(ui->btnPrivacy);
//}
void NavMenuWidget::onMasterNodesClicked(){
window->goToMasterNodes();
onNavSelected(ui->btnMaster);
}
void NavMenuWidget::onColdStakingClicked() {
window->goToColdStaking();
onNavSelected(ui->btnColdStaking);
}
void NavMenuWidget::onSettingsClicked(){
window->goToSettings();
onNavSelected(ui->btnSettings);
}
void NavMenuWidget::onReceiveClicked(){
window->goToReceive();
onNavSelected(ui->btnReceive);
}
void NavMenuWidget::onNavSelected(QWidget* active, bool startup) {
QString start = "btn-nav-";
foreach (QWidget* w, btns) {
QString clazz = start + w->property("name").toString();
if (w == active) {
clazz += "-active";
}
setCssProperty(w, clazz);
}
if (!startup) updateButtonStyles();
}
void NavMenuWidget::selectSettings() {
onSettingsClicked();
}
void NavMenuWidget::onShowHideColdStakingChanged(bool show) {
ui->btnColdStaking->setVisible(show);
if (show)
ui->scrollAreaNav->verticalScrollBar()->setValue(ui->btnColdStaking->y());
}
void NavMenuWidget::showEvent(QShowEvent *event) {
if (!init) {
init = true;
ui->scrollAreaNav->verticalScrollBar()->setValue(ui->btnDashboard->y());
}
}
void NavMenuWidget::updateButtonStyles(){
forceUpdateStyle({
ui->btnDashboard,
ui->btnSend,
ui->btnAddress,
//ui->btnPrivacy,
ui->btnMaster,
ui->btnSettings,
ui->btnReceive,
ui->btnColdStaking
});
}
NavMenuWidget::~NavMenuWidget(){
delete ui;
}
|
//---------------------------------------------------------- -*- Mode: C++ -*-
// $Id$
//
// Created 2010/05/14
// Author: Mike Ovsiannikov
//
// Copyright 2010-2012,2016 Quantcast Corporation. All rights reserved.
//
// This file is part of Kosmos File System (KFS).
//
// 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 "common/BufferInputStream.h"
#include "common/RequestParser.h"
#include "common/Properties.h"
#include <stdint.h>
#include <stdio.h>
#include <unistd.h>
#include <iostream>
using namespace KFS;
class AbstractTest
{
public:
int64_t seq;
AbstractTest()
: seq(-1)
{}
virtual ~AbstractTest()
{}
bool Validate() const { return true; }
virtual std::ostream& Show(
std::ostream& inStream)
{ return inStream; }
bool ValidateRequestHeader(
const char* /* name */,
size_t /* nameLen */,
const char* /* header */,
size_t /* headerLen */,
bool /* hasChecksum */,
uint32_t /* checksum */,
bool /* shortFieldNamesFlag */)
{ return true; }
bool HandleUnknownField(
const char* /* key */, size_t /* keyLen */,
const char* /* val */, size_t /* valLen */)
{ return true; }
template<typename T> static T& ParserDef(
T& inParser)
{
return inParser
.Def("Cseq", &AbstractTest::seq, int64_t(-1))
;
}
};
class AbstractTest1
{
public:
int vers;
AbstractTest1()
: vers(-1)
{}
virtual ~AbstractTest1()
{}
template<typename T> static T& ParserDef(
T& inParser)
{
return inParser
.Def("Client-Protocol-Version", &AbstractTest1::vers, -1)
;
}
};
class Test : public AbstractTest, public AbstractTest1
{
public:
StringBufT<64> host;
StringBufT<256> path;
std::string hostStr;
std::string pathStr;
int64_t fid;
int64_t offset;
int64_t reserve;
bool append;
int maxAppenders;
double doubleTest;
Test()
: AbstractTest(),
host(),
path(),
hostStr(),
pathStr(),
fid(-1),
offset(-1),
reserve(-1),
append(false),
maxAppenders(64),
doubleTest(-1)
{}
// bool Validate() const { return false; }
virtual ~Test()
{}
template<typename T> static T& ParserDef(
T& inParser)
{
return
AbstractTest1::ParserDef(
AbstractTest::ParserDef(
inParser
))
// .Def("Cseq", &Test::seq, int64_t(-1))
// .Def("Client-Protocol-Version", &Test::vers, -1 )
.Def("Client-host", &Test::host )
.Def("Pathname", &Test::path )
.Def("File-handle", &Test::fid, int64_t(-1))
.Def("Chunk-offset", &Test::offset, int64_t(-1))
.Def("Chunk-append", &Test::append, false )
.Def("Space-reserve", &Test::reserve, int64_t(-1))
.Def("Max-appenders", &Test::maxAppenders, 64 )
.Def("Double test", &Test::doubleTest, -1. )
;
}
template<typename T> void Load(
const Properties& props,
const char* name,
T& val,
T def=T())
{ val = props.getValue(name, def); }
void Load(
const Properties& props)
{
Load(props, "Cseq", seq, int64_t(-1));
Load(props, "Client-Protocol-Version", vers, -1 );
Load(props, "Client-host", hostStr );
Load(props, "Pathname", pathStr );
Load(props, "File-handle", fid, int64_t(-1));
Load(props, "Chunk-offset", offset, int64_t(-1));
Load(props, "Chunk-append", append, false );
Load(props, "Space-reserve", reserve, int64_t(-1));
Load(props, "Max-appenders", maxAppenders, 64 );
Load(props, "Double test", doubleTest, -1. );
}
static AbstractTest* Load(
std::istream& is)
{
Test* const res = new Test;
const char separator = ':';
Properties props;
props.loadProperties(is, separator);
res->Load(props);
return res;
}
virtual std::ostream& Show(
std::ostream& inStream)
{
return inStream <<
"Cseq: " << seq << "\r\n"
"Version: " "KFS/1.0" "\r\n"
"Client-Protocol-Version: " << vers << "\r\n"
"Client-host: " << host << hostStr << "\r\n"
"Pathname: " << path << pathStr << "\r\n"
"File-handle: " << fid << "\r\n"
"Chunk-offset: " << offset << "\r\n"
"Chunk-append: " << append << "\r\n"
"Space-reserve: " << reserve << "\r\n"
"Max-appenders: " << maxAppenders << "\r\n"
"Double test: " << doubleTest << "\r\n"
;
}
};
/*
ALLOCATE\r
Cseq: $seq\r
Version: KFS/1.0\r
Client-Protocol-Version: 100\r
Client-host: somehostname\r
Pathname: /sort/job/1/fanout/27/file.27\r
File-handle: $fid\r
Chunk-offset: 0\r
Chunk-append: 1\r
Space-reserve: 0\r
Max-appenders: 640000000\r
*/
/*
To benchmark:
../src/test-scripts/allocatesend.pl 1e6 | ( time src/cc/devtools/requestparser_test q )
*/
typedef RequestHandler<AbstractTest> ReqHandler;
static const ReqHandler& MakeRequestHandler()
{
static ReqHandler sHandler;
return sHandler
.MakeParser<Test>("ALLOCATE")
.MakeParser<Test>("xALLOCATE")
;
}
static const ReqHandler& sReqHandler = MakeRequestHandler();
int
main(int argc, char** argv)
{
if (argc <= 1 || (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) {
return 0;
}
static char buf[1 << 20];
char* ptr = buf;
char* end = buf + sizeof(buf);
BufferInputStream myis;
ssize_t nrd;
const bool quiet = argc > 1 && strchr(argv[1], 'q');
const bool noparse = argc > 1 && strchr(argv[1], 'n');
const bool alloc = argc > 1 && strchr(argv[1], 'a');
const bool useprop = argc > 1 && strchr(argv[1], 'p');
while ((nrd = read(0, ptr, end - ptr)) > 0) {
end = ptr + nrd;
ptr = buf;
if (*ptr == '\n') {
ptr++;
}
char* re = ptr;
while ((re = (char*)memchr(re, '\n', end - re))) {
if (re + 2 >= end) {
break;
}
if (re[-1] != '\r' || re[1] != '\r' || re[2] != '\n') {
re++;
continue;
}
re += 3;
if (! quiet) {
std::cout << "Request:\n";
std::cout.write(ptr, re - ptr);
}
if (! noparse || alloc) {
AbstractTest* const tst = useprop ?
Test::Load(myis.Set(ptr, noparse ? 0 : re - ptr)) :
sReqHandler.Handle(ptr, noparse ? 0 : re - ptr);
if (tst) {
if (! quiet) {
std::cout << "Parsed request:\n";
tst->Show(std::cout);
}
delete tst;
} else {
std::cout << "parse failure\nRequest:\n";
std::cout.write(ptr, re - ptr);
}
}
ptr = re;
}
memmove(buf, ptr, end - ptr);
ptr = buf + (end - ptr);
end = buf + sizeof(buf);
}
return 0;
}
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int i,j,k,n,t,s;
scanf("%d",&s);
printf("\n");
while(s>0){
scanf("%d%d",&n,&t);
printf("\n");
for(k=0;k<t;k++){
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("%d",i);
}
printf("\n");
}
for(i=n-1;i>0;i--)
{
for(j=1;j<=i;j++)
{
printf("%d",i);
}
printf("\n");
}
if(k!=t-1)
printf("\n");
}s--;}
return 0;
}
|
#include <Core/Block.h>
#include <Parsers/ASTExpressionList.h>
#include <Parsers/ASTFunction.h>
#include <Parsers/ASTIdentifier.h>
#include <Parsers/ASTLiteral.h>
#include <Parsers/ASTOrderByElement.h>
#include <Parsers/ASTSelectQuery.h>
#include <Parsers/ASTSubquery.h>
#include <Parsers/ASTWindowDefinition.h>
#include <Parsers/DumpASTNode.h>
#include <DataTypes/DataTypeNullable.h>
#include <Columns/IColumn.h>
#include <Interpreters/ArrayJoinAction.h>
#include <Interpreters/Context.h>
#include <Interpreters/DictionaryReader.h>
#include <Interpreters/evaluateConstantExpression.h>
#include <Interpreters/ExpressionActions.h>
#include <Interpreters/ExpressionAnalyzer.h>
#include <Interpreters/ExternalDictionariesLoader.h>
#include <Interpreters/HashJoin.h>
#include <Interpreters/JoinSwitcher.h>
#include <Interpreters/MergeJoin.h>
#include <Interpreters/Set.h>
#include <Interpreters/TableJoin.h>
#include <Processors/QueryPlan/ExpressionStep.h>
#include <AggregateFunctions/AggregateFunctionFactory.h>
#include <AggregateFunctions/parseAggregateFunctionParameters.h>
#include <Storages/StorageDistributed.h>
#include <Storages/StorageDictionary.h>
#include <Storages/StorageJoin.h>
#include <Dictionaries/DictionaryStructure.h>
#include <Common/typeid_cast.h>
#include <Common/StringUtils/StringUtils.h>
#include "Core/NamesAndTypes.h"
#include <DataTypes/DataTypeFactory.h>
#include <Interpreters/ActionsVisitor.h>
#include <Interpreters/GetAggregatesVisitor.h>
#include <Interpreters/GlobalSubqueriesVisitor.h>
#include <Interpreters/interpretSubquery.h>
#include <Interpreters/join_common.h>
#include <Interpreters/misc.h>
#include <IO/Operators.h>
#include <IO/WriteBufferFromString.h>
#include <Processors/Executors/PullingAsyncPipelineExecutor.h>
#include <Processors/QueryPlan/QueryPlan.h>
#include <Parsers/formatAST.h>
namespace DB
{
using LogAST = DebugASTLog<false>; /// set to true to enable logs
namespace ErrorCodes
{
extern const int BAD_ARGUMENTS;
extern const int ILLEGAL_PREWHERE;
extern const int ILLEGAL_TYPE_OF_ARGUMENT;
extern const int ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER;
extern const int LOGICAL_ERROR;
extern const int NOT_IMPLEMENTED;
extern const int UNKNOWN_IDENTIFIER;
extern const int UNKNOWN_TYPE_OF_AST_NODE;
}
namespace
{
/// Check if there is an ignore function. It's used for disabling constant folding in query
/// predicates because some performance tests use ignore function as a non-optimize guard.
bool allowEarlyConstantFolding(const ActionsDAG & actions, const Settings & settings)
{
if (!settings.enable_early_constant_folding)
return false;
for (const auto & node : actions.getNodes())
{
if (node.type == ActionsDAG::ActionType::FUNCTION && node.function_base)
{
if (!node.function_base->isSuitableForConstantFolding())
return false;
}
}
return true;
}
bool checkPositionalArguments(ASTPtr & argument, const ASTSelectQuery * select_query, ASTSelectQuery::Expression expression)
{
auto columns = select_query->select()->children;
const auto * group_by_expr_with_alias = dynamic_cast<const ASTWithAlias *>(argument.get());
if (group_by_expr_with_alias && !group_by_expr_with_alias->alias.empty())
{
for (const auto & column : columns)
{
const auto * col_with_alias = dynamic_cast<const ASTWithAlias *>(column.get());
if (col_with_alias)
{
const auto & alias = col_with_alias->alias;
if (!alias.empty() && alias == group_by_expr_with_alias->alias)
return false;
}
}
}
/// In case of expression/function (order by 1+2 and 2*x1, greatest(1, 2)) replace
/// positions only if all literals are numbers, otherwise it is not positional.
bool positional = true;
/// Case when GROUP BY element is position.
if (const auto * ast_literal = typeid_cast<const ASTLiteral *>(argument.get()))
{
auto which = ast_literal->value.getType();
if (which == Field::Types::UInt64)
{
auto pos = ast_literal->value.get<UInt64>();
if (pos > 0 && pos <= columns.size())
{
const auto & column = columns[--pos];
if (typeid_cast<const ASTIdentifier *>(column.get()))
{
argument = column->clone();
}
else if (typeid_cast<const ASTFunction *>(column.get()))
{
std::function<void(ASTPtr)> throw_if_aggregate_function = [&](ASTPtr node)
{
if (const auto * function = typeid_cast<const ASTFunction *>(node.get()))
{
auto is_aggregate_function = AggregateFunctionFactory::instance().isAggregateFunctionName(function->name);
if (is_aggregate_function)
{
throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,
"Illegal value (aggregate function) for positional argument in {}",
ASTSelectQuery::expressionToString(expression));
}
else
{
if (function->arguments)
{
for (const auto & arg : function->arguments->children)
throw_if_aggregate_function(arg);
}
}
}
};
if (expression == ASTSelectQuery::Expression::GROUP_BY)
throw_if_aggregate_function(column);
argument = column->clone();
}
else
{
throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,
"Illegal value for positional argument in {}",
ASTSelectQuery::expressionToString(expression));
}
}
else if (pos > columns.size() || !pos)
{
throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,
"Positional argument out of bounds: {} (exprected in range [1, {}]",
pos, columns.size());
}
}
else
positional = false;
}
else if (const auto * ast_function = typeid_cast<const ASTFunction *>(argument.get()))
{
if (ast_function->arguments)
{
for (auto & arg : ast_function->arguments->children)
positional &= checkPositionalArguments(arg, select_query, expression);
}
}
else
positional = false;
return positional;
}
void replaceForPositionalArguments(ASTPtr & argument, const ASTSelectQuery * select_query, ASTSelectQuery::Expression expression)
{
auto argument_with_replacement = argument->clone();
if (checkPositionalArguments(argument_with_replacement, select_query, expression))
argument = argument_with_replacement;
}
}
bool sanitizeBlock(Block & block, bool throw_if_cannot_create_column)
{
for (auto & col : block)
{
if (!col.column)
{
if (isNotCreatable(col.type->getTypeId()))
{
if (throw_if_cannot_create_column)
throw Exception("Cannot create column of type " + col.type->getName(), ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);
return false;
}
col.column = col.type->createColumn();
}
else if (!col.column->empty())
col.column = col.column->cloneEmpty();
}
return true;
}
ExpressionAnalyzerData::~ExpressionAnalyzerData() = default;
ExpressionAnalyzer::ExtractedSettings::ExtractedSettings(const Settings & settings_)
: use_index_for_in_with_subqueries(settings_.use_index_for_in_with_subqueries)
, size_limits_for_set(settings_.max_rows_in_set, settings_.max_bytes_in_set, settings_.set_overflow_mode)
, distributed_group_by_no_merge(settings_.distributed_group_by_no_merge)
{}
ExpressionAnalyzer::~ExpressionAnalyzer() = default;
ExpressionAnalyzer::ExpressionAnalyzer(
const ASTPtr & query_,
const TreeRewriterResultPtr & syntax_analyzer_result_,
ContextPtr context_,
size_t subquery_depth_,
bool do_global,
SubqueriesForSets subqueries_for_sets_,
PreparedSets prepared_sets_)
: WithContext(context_)
, query(query_), settings(getContext()->getSettings())
, subquery_depth(subquery_depth_)
, syntax(syntax_analyzer_result_)
{
/// Cache prepared sets because we might run analysis multiple times
subqueries_for_sets = std::move(subqueries_for_sets_);
prepared_sets = std::move(prepared_sets_);
/// external_tables, subqueries_for_sets for global subqueries.
/// Replaces global subqueries with the generated names of temporary tables that will be sent to remote servers.
initGlobalSubqueriesAndExternalTables(do_global);
auto temp_actions = std::make_shared<ActionsDAG>(sourceColumns());
columns_after_array_join = getColumnsAfterArrayJoin(temp_actions, sourceColumns());
columns_after_join = analyzeJoin(temp_actions, columns_after_array_join);
/// has_aggregation, aggregation_keys, aggregate_descriptions, aggregated_columns.
/// This analysis should be performed after processing global subqueries, because otherwise,
/// if the aggregate function contains a global subquery, then `analyzeAggregation` method will save
/// in `aggregate_descriptions` the information about the parameters of this aggregate function, among which
/// global subquery. Then, when you call `initGlobalSubqueriesAndExternalTables` method, this
/// the global subquery will be replaced with a temporary table, resulting in aggregate_descriptions
/// will contain out-of-date information, which will lead to an error when the query is executed.
analyzeAggregation(temp_actions);
}
NamesAndTypesList ExpressionAnalyzer::getColumnsAfterArrayJoin(ActionsDAGPtr & actions, const NamesAndTypesList & src_columns)
{
const auto * select_query = query->as<ASTSelectQuery>();
if (!select_query)
return {};
auto [array_join_expression_list, is_array_join_left] = select_query->arrayJoinExpressionList();
if (!array_join_expression_list)
return src_columns;
getRootActionsNoMakeSet(array_join_expression_list, true, actions, false);
auto array_join = addMultipleArrayJoinAction(actions, is_array_join_left);
auto sample_columns = actions->getResultColumns();
array_join->prepare(sample_columns);
actions = std::make_shared<ActionsDAG>(sample_columns);
NamesAndTypesList new_columns_after_array_join;
NameSet added_columns;
for (auto & column : actions->getResultColumns())
{
if (syntax->array_join_result_to_source.count(column.name))
{
new_columns_after_array_join.emplace_back(column.name, column.type);
added_columns.emplace(column.name);
}
}
for (const auto & column : src_columns)
if (added_columns.count(column.name) == 0)
new_columns_after_array_join.emplace_back(column.name, column.type);
return new_columns_after_array_join;
}
NamesAndTypesList ExpressionAnalyzer::analyzeJoin(ActionsDAGPtr & actions, const NamesAndTypesList & src_columns)
{
const auto * select_query = query->as<ASTSelectQuery>();
if (!select_query)
return {};
const ASTTablesInSelectQueryElement * join = select_query->join();
if (join)
{
getRootActionsNoMakeSet(analyzedJoin().leftKeysList(), true, actions, false);
auto sample_columns = actions->getNamesAndTypesList();
syntax->analyzed_join->addJoinedColumnsAndCorrectTypes(sample_columns, true);
actions = std::make_shared<ActionsDAG>(sample_columns);
}
NamesAndTypesList result_columns = src_columns;
syntax->analyzed_join->addJoinedColumnsAndCorrectTypes(result_columns,false);
return result_columns;
}
void ExpressionAnalyzer::analyzeAggregation(ActionsDAGPtr & temp_actions)
{
/** Find aggregation keys (aggregation_keys), information about aggregate functions (aggregate_descriptions),
* as well as a set of columns obtained after the aggregation, if any,
* or after all the actions that are usually performed before aggregation (aggregated_columns).
*
* Everything below (compiling temporary ExpressionActions) - only for the purpose of query analysis (type output).
*/
auto * select_query = query->as<ASTSelectQuery>();
makeAggregateDescriptions(temp_actions, aggregate_descriptions);
has_aggregation = !aggregate_descriptions.empty() || (select_query && (select_query->groupBy() || select_query->having()));
if (!has_aggregation)
{
aggregated_columns = temp_actions->getNamesAndTypesList();
return;
}
/// Find out aggregation keys.
if (select_query)
{
if (ASTPtr group_by_ast = select_query->groupBy())
{
NameSet unique_keys;
ASTs & group_asts = group_by_ast->children;
for (ssize_t i = 0; i < ssize_t(group_asts.size()); ++i)
{
ssize_t size = group_asts.size();
if (getContext()->getSettingsRef().enable_positional_arguments)
replaceForPositionalArguments(group_asts[i], select_query, ASTSelectQuery::Expression::GROUP_BY);
getRootActionsNoMakeSet(group_asts[i], true, temp_actions, false);
if (select_query->group_by_with_grouping_sets)
{
ASTs group_elements_ast;
const ASTExpressionList * group_ast_element = group_asts[i]->as<const ASTExpressionList>();
if (!group_ast_element)
throw Exception("Grouping Sets element " + group_asts[i]->getColumnName() + " should be an expression type", ErrorCodes::UNKNOWN_IDENTIFIER);
group_elements_ast = group_ast_element->children;
NamesAndTypesList grouping_set_list;
for (ssize_t j = 0; j < ssize_t(group_elements_ast.size()); ++j)
{
ssize_t group_size = group_elements_ast.size();
const auto & column_name = group_elements_ast[j]->getColumnName();
const auto * node = temp_actions->tryFindInIndex(column_name);
if (!node)
throw Exception("Unknown identifier (in GROUP BY): " + column_name, ErrorCodes::UNKNOWN_IDENTIFIER);
/// Only removes constant keys if it's an initiator or distributed_group_by_no_merge is enabled.
if (getContext()->getClientInfo().distributed_depth == 0 || settings.distributed_group_by_no_merge > 0)
{
/// Constant expressions have non-null column pointer at this stage.
if (node->column && isColumnConst(*node->column))
{
/// But don't remove last key column if no aggregate functions, otherwise aggregation will not work.
if (!aggregate_descriptions.empty() || group_size > 1)
{
if (j + 1 < static_cast<ssize_t>(group_size))
group_elements_ast[j] = std::move(group_elements_ast.back());
group_elements_ast.pop_back();
--j;
continue;
}
}
}
NameAndTypePair key{column_name, node->result_type};
grouping_set_list.push_back(key);
/// Aggregation keys are unique.
if (!unique_keys.count(key.name))
{
unique_keys.insert(key.name);
aggregation_keys.push_back(key);
/// Key is no longer needed, therefore we can save a little by moving it.
aggregated_columns.push_back(std::move(key));
}
}
aggregation_keys_list.push_back(std::move(grouping_set_list));
}
else
{
const auto & column_name = group_asts[i]->getColumnName();
const auto * node = temp_actions->tryFindInIndex(column_name);
if (!node)
throw Exception("Unknown identifier (in GROUP BY): " + column_name, ErrorCodes::UNKNOWN_IDENTIFIER);
/// Only removes constant keys if it's an initiator or distributed_group_by_no_merge is enabled.
if (getContext()->getClientInfo().distributed_depth == 0 || settings.distributed_group_by_no_merge > 0)
{
/// Constant expressions have non-null column pointer at this stage.
if (node->column && isColumnConst(*node->column))
{
select_query->group_by_with_constant_keys = true;
/// But don't remove last key column if no aggregate functions, otherwise aggregation will not work.
if (!aggregate_descriptions.empty() || size > 1)
{
if (i + 1 < static_cast<ssize_t>(size))
group_asts[i] = std::move(group_asts.back());
group_asts.pop_back();
--i;
continue;
}
}
}
NameAndTypePair key{column_name, node->result_type};
/// Aggregation keys are uniqued.
if (!unique_keys.count(key.name))
{
unique_keys.insert(key.name);
aggregation_keys.push_back(key);
/// Key is no longer needed, therefore we can save a little by moving it.
aggregated_columns.push_back(std::move(key));
}
}
}
if (group_asts.empty())
{
select_query->setExpression(ASTSelectQuery::Expression::GROUP_BY, {});
has_aggregation = select_query->having() || !aggregate_descriptions.empty();
}
}
/// Constant expressions are already removed during first 'analyze' run.
/// So for second `analyze` information is taken from select_query.
has_const_aggregation_keys = select_query->group_by_with_constant_keys;
}
else
aggregated_columns = temp_actions->getNamesAndTypesList();
for (const auto & desc : aggregate_descriptions)
aggregated_columns.emplace_back(desc.column_name, desc.function->getReturnType());
}
void ExpressionAnalyzer::initGlobalSubqueriesAndExternalTables(bool do_global)
{
if (do_global)
{
GlobalSubqueriesVisitor::Data subqueries_data(getContext(), subquery_depth, isRemoteStorage(),
external_tables, subqueries_for_sets, has_global_subqueries);
GlobalSubqueriesVisitor(subqueries_data).visit(query);
}
}
void ExpressionAnalyzer::tryMakeSetForIndexFromSubquery(const ASTPtr & subquery_or_table_name, const SelectQueryOptions & query_options)
{
auto set_key = PreparedSetKey::forSubquery(*subquery_or_table_name);
if (prepared_sets.count(set_key))
return; /// Already prepared.
if (auto set_ptr_from_storage_set = isPlainStorageSetInSubquery(subquery_or_table_name))
{
prepared_sets.insert({set_key, set_ptr_from_storage_set});
return;
}
auto interpreter_subquery = interpretSubquery(subquery_or_table_name, getContext(), {}, query_options);
auto io = interpreter_subquery->execute();
PullingAsyncPipelineExecutor executor(io.pipeline);
SetPtr set = std::make_shared<Set>(settings.size_limits_for_set, true, getContext()->getSettingsRef().transform_null_in);
set->setHeader(executor.getHeader().getColumnsWithTypeAndName());
Block block;
while (executor.pull(block))
{
if (block.rows() == 0)
continue;
/// If the limits have been exceeded, give up and let the default subquery processing actions take place.
if (!set->insertFromBlock(block.getColumnsWithTypeAndName()))
return;
}
set->finishInsert();
prepared_sets[set_key] = std::move(set);
}
SetPtr ExpressionAnalyzer::isPlainStorageSetInSubquery(const ASTPtr & subquery_or_table_name)
{
const auto * table = subquery_or_table_name->as<ASTTableIdentifier>();
if (!table)
return nullptr;
auto table_id = getContext()->resolveStorageID(subquery_or_table_name);
const auto storage = DatabaseCatalog::instance().getTable(table_id, getContext());
if (storage->getName() != "Set")
return nullptr;
const auto storage_set = std::dynamic_pointer_cast<StorageSet>(storage);
return storage_set->getSet();
}
/// Performance optimization for IN() if storage supports it.
void SelectQueryExpressionAnalyzer::makeSetsForIndex(const ASTPtr & node)
{
if (!node || !storage() || !storage()->supportsIndexForIn())
return;
for (auto & child : node->children)
{
/// Don't descend into subqueries.
if (child->as<ASTSubquery>())
continue;
/// Don't descend into lambda functions
const auto * func = child->as<ASTFunction>();
if (func && func->name == "lambda")
continue;
makeSetsForIndex(child);
}
const auto * func = node->as<ASTFunction>();
if (func && functionIsInOrGlobalInOperator(func->name))
{
const IAST & args = *func->arguments;
const ASTPtr & left_in_operand = args.children.at(0);
if (storage()->mayBenefitFromIndexForIn(left_in_operand, getContext(), metadata_snapshot))
{
const ASTPtr & arg = args.children.at(1);
if (arg->as<ASTSubquery>() || arg->as<ASTTableIdentifier>())
{
if (settings.use_index_for_in_with_subqueries)
tryMakeSetForIndexFromSubquery(arg, query_options);
}
else
{
auto temp_actions = std::make_shared<ActionsDAG>(columns_after_join);
getRootActions(left_in_operand, true, temp_actions);
if (temp_actions->tryFindInIndex(left_in_operand->getColumnName()))
makeExplicitSet(func, *temp_actions, true, getContext(), settings.size_limits_for_set, prepared_sets);
}
}
}
}
void ExpressionAnalyzer::getRootActions(const ASTPtr & ast, bool no_subqueries, ActionsDAGPtr & actions, bool only_consts)
{
LogAST log;
ActionsVisitor::Data visitor_data(getContext(), settings.size_limits_for_set, subquery_depth,
sourceColumns(), std::move(actions), prepared_sets, subqueries_for_sets,
no_subqueries, false, only_consts, !isRemoteStorage());
ActionsVisitor(visitor_data, log.stream()).visit(ast);
actions = visitor_data.getActions();
}
void ExpressionAnalyzer::getRootActionsNoMakeSet(const ASTPtr & ast, bool no_subqueries, ActionsDAGPtr & actions, bool only_consts)
{
LogAST log;
ActionsVisitor::Data visitor_data(getContext(), settings.size_limits_for_set, subquery_depth,
sourceColumns(), std::move(actions), prepared_sets, subqueries_for_sets,
no_subqueries, true, only_consts, !isRemoteStorage());
ActionsVisitor(visitor_data, log.stream()).visit(ast);
actions = visitor_data.getActions();
}
void ExpressionAnalyzer::getRootActionsForHaving(const ASTPtr & ast, bool no_subqueries, ActionsDAGPtr & actions, bool only_consts)
{
LogAST log;
ActionsVisitor::Data visitor_data(getContext(), settings.size_limits_for_set, subquery_depth,
sourceColumns(), std::move(actions), prepared_sets, subqueries_for_sets,
no_subqueries, false, only_consts, true);
ActionsVisitor(visitor_data, log.stream()).visit(ast);
actions = visitor_data.getActions();
}
void ExpressionAnalyzer::makeAggregateDescriptions(ActionsDAGPtr & actions, AggregateDescriptions & descriptions)
{
for (const ASTFunction * node : aggregates())
{
AggregateDescription aggregate;
if (node->arguments)
getRootActionsNoMakeSet(node->arguments, true, actions);
aggregate.column_name = node->getColumnName();
const ASTs & arguments = node->arguments ? node->arguments->children : ASTs();
aggregate.argument_names.resize(arguments.size());
DataTypes types(arguments.size());
for (size_t i = 0; i < arguments.size(); ++i)
{
const std::string & name = arguments[i]->getColumnName();
const auto * dag_node = actions->tryFindInIndex(name);
if (!dag_node)
{
throw Exception(ErrorCodes::UNKNOWN_IDENTIFIER,
"Unknown identifier '{}' in aggregate function '{}'",
name, node->formatForErrorMessage());
}
types[i] = dag_node->result_type;
aggregate.argument_names[i] = name;
}
AggregateFunctionProperties properties;
aggregate.parameters = (node->parameters) ? getAggregateFunctionParametersArray(node->parameters, "", getContext()) : Array();
aggregate.function = AggregateFunctionFactory::instance().get(node->name, types, aggregate.parameters, properties);
descriptions.push_back(aggregate);
}
}
void makeWindowDescriptionFromAST(const Context & context,
const WindowDescriptions & existing_descriptions,
WindowDescription & desc, const IAST * ast)
{
const auto & definition = ast->as<const ASTWindowDefinition &>();
if (!definition.parent_window_name.empty())
{
auto it = existing_descriptions.find(definition.parent_window_name);
if (it == existing_descriptions.end())
{
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"Window definition '{}' references an unknown window '{}'",
definition.formatForErrorMessage(),
definition.parent_window_name);
}
const auto & parent = it->second;
desc.partition_by = parent.partition_by;
desc.order_by = parent.order_by;
desc.frame = parent.frame;
// If an existing_window_name is specified it must refer to an earlier
// entry in the WINDOW list; the new window copies its partitioning clause
// from that entry, as well as its ordering clause if any. In this case
// the new window cannot specify its own PARTITION BY clause, and it can
// specify ORDER BY only if the copied window does not have one. The new
// window always uses its own frame clause; the copied window must not
// specify a frame clause.
// -- https://www.postgresql.org/docs/current/sql-select.html
if (definition.partition_by)
{
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"Derived window definition '{}' is not allowed to override PARTITION BY",
definition.formatForErrorMessage());
}
if (definition.order_by && !parent.order_by.empty())
{
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"Derived window definition '{}' is not allowed to override a non-empty ORDER BY",
definition.formatForErrorMessage());
}
if (!parent.frame.is_default)
{
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"Parent window '{}' is not allowed to define a frame: while processing derived window definition '{}'",
definition.parent_window_name,
definition.formatForErrorMessage());
}
}
if (definition.partition_by)
{
for (const auto & column_ast : definition.partition_by->children)
{
const auto * with_alias = dynamic_cast<const ASTWithAlias *>(
column_ast.get());
if (!with_alias)
{
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"Expected a column in PARTITION BY in window definition,"
" got '{}'",
column_ast->formatForErrorMessage());
}
desc.partition_by.push_back(SortColumnDescription(
with_alias->getColumnName(), 1 /* direction */,
1 /* nulls_direction */));
}
}
if (definition.order_by)
{
for (const auto & column_ast
: definition.order_by->children)
{
// Parser should have checked that we have a proper element here.
const auto & order_by_element
= column_ast->as<ASTOrderByElement &>();
// Ignore collation for now.
desc.order_by.push_back(
SortColumnDescription(
order_by_element.children.front()->getColumnName(),
order_by_element.direction,
order_by_element.nulls_direction));
}
}
desc.full_sort_description = desc.partition_by;
desc.full_sort_description.insert(desc.full_sort_description.end(),
desc.order_by.begin(), desc.order_by.end());
if (definition.frame_type != WindowFrame::FrameType::Rows
&& definition.frame_type != WindowFrame::FrameType::Range)
{
throw Exception(ErrorCodes::NOT_IMPLEMENTED,
"Window frame '{}' is not implemented (while processing '{}')",
definition.frame_type,
ast->formatForErrorMessage());
}
desc.frame.is_default = definition.frame_is_default;
desc.frame.type = definition.frame_type;
desc.frame.begin_type = definition.frame_begin_type;
desc.frame.begin_preceding = definition.frame_begin_preceding;
desc.frame.end_type = definition.frame_end_type;
desc.frame.end_preceding = definition.frame_end_preceding;
if (definition.frame_end_type == WindowFrame::BoundaryType::Offset)
{
auto [value, _] = evaluateConstantExpression(definition.frame_end_offset,
context.shared_from_this());
desc.frame.end_offset = value;
}
if (definition.frame_begin_type == WindowFrame::BoundaryType::Offset)
{
auto [value, _] = evaluateConstantExpression(definition.frame_begin_offset,
context.shared_from_this());
desc.frame.begin_offset = value;
}
}
void ExpressionAnalyzer::makeWindowDescriptions(ActionsDAGPtr actions)
{
// Window definitions from the WINDOW clause
const auto * select_query = query->as<ASTSelectQuery>();
if (select_query && select_query->window())
{
for (const auto & ptr : select_query->window()->children)
{
const auto & elem = ptr->as<const ASTWindowListElement &>();
WindowDescription desc;
desc.window_name = elem.name;
makeWindowDescriptionFromAST(*getContext(), window_descriptions,
desc, elem.definition.get());
auto [it, inserted] = window_descriptions.insert(
{desc.window_name, desc});
if (!inserted)
{
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"Window '{}' is defined twice in the WINDOW clause",
desc.window_name);
}
}
}
// Window functions
for (const ASTFunction * function_node : syntax->window_function_asts)
{
assert(function_node->is_window_function);
WindowFunctionDescription window_function;
window_function.function_node = function_node;
window_function.column_name
= window_function.function_node->getColumnName();
window_function.function_parameters
= window_function.function_node->parameters
? getAggregateFunctionParametersArray(
window_function.function_node->parameters, "", getContext())
: Array();
// Requiring a constant reference to a shared pointer to non-const AST
// doesn't really look sane, but the visitor does indeed require it.
// Hence we clone the node (not very sane either, I know).
getRootActionsNoMakeSet(window_function.function_node->clone(),
true, actions);
const ASTs & arguments
= window_function.function_node->arguments->children;
window_function.argument_types.resize(arguments.size());
window_function.argument_names.resize(arguments.size());
for (size_t i = 0; i < arguments.size(); ++i)
{
const std::string & name = arguments[i]->getColumnName();
const auto * node = actions->tryFindInIndex(name);
if (!node)
{
throw Exception(ErrorCodes::UNKNOWN_IDENTIFIER,
"Unknown identifier '{}' in window function '{}'",
name, window_function.function_node->formatForErrorMessage());
}
window_function.argument_types[i] = node->result_type;
window_function.argument_names[i] = name;
}
AggregateFunctionProperties properties;
window_function.aggregate_function
= AggregateFunctionFactory::instance().get(
window_function.function_node->name,
window_function.argument_types,
window_function.function_parameters, properties);
// Find the window corresponding to this function. It may be either
// referenced by name and previously defined in WINDOW clause, or it
// may be defined inline.
if (!function_node->window_name.empty())
{
auto it = window_descriptions.find(function_node->window_name);
if (it == std::end(window_descriptions))
{
throw Exception(ErrorCodes::UNKNOWN_IDENTIFIER,
"Window '{}' is not defined (referenced by '{}')",
function_node->window_name,
function_node->formatForErrorMessage());
}
it->second.window_functions.push_back(window_function);
}
else
{
const auto & definition = function_node->window_definition->as<
const ASTWindowDefinition &>();
WindowDescription desc;
desc.window_name = definition.getDefaultWindowName();
makeWindowDescriptionFromAST(*getContext(), window_descriptions,
desc, &definition);
auto [it, inserted] = window_descriptions.insert(
{desc.window_name, desc});
if (!inserted)
{
assert(it->second.full_sort_description
== desc.full_sort_description);
}
it->second.window_functions.push_back(window_function);
}
}
}
const ASTSelectQuery * ExpressionAnalyzer::getSelectQuery() const
{
const auto * select_query = query->as<ASTSelectQuery>();
if (!select_query)
throw Exception("Not a select query", ErrorCodes::LOGICAL_ERROR);
return select_query;
}
const ASTSelectQuery * SelectQueryExpressionAnalyzer::getAggregatingQuery() const
{
if (!has_aggregation)
throw Exception("No aggregation", ErrorCodes::LOGICAL_ERROR);
return getSelectQuery();
}
/// "Big" ARRAY JOIN.
ArrayJoinActionPtr ExpressionAnalyzer::addMultipleArrayJoinAction(ActionsDAGPtr & actions, bool array_join_is_left) const
{
NameSet result_columns;
for (const auto & result_source : syntax->array_join_result_to_source)
{
/// Assign new names to columns, if needed.
if (result_source.first != result_source.second)
{
const auto & node = actions->findInIndex(result_source.second);
actions->getIndex().push_back(&actions->addAlias(node, result_source.first));
}
/// Make ARRAY JOIN (replace arrays with their insides) for the columns in these new names.
result_columns.insert(result_source.first);
}
return std::make_shared<ArrayJoinAction>(result_columns, array_join_is_left, getContext());
}
ArrayJoinActionPtr SelectQueryExpressionAnalyzer::appendArrayJoin(ExpressionActionsChain & chain, ActionsDAGPtr & before_array_join, bool only_types)
{
const auto * select_query = getSelectQuery();
auto [array_join_expression_list, is_array_join_left] = select_query->arrayJoinExpressionList();
if (!array_join_expression_list)
return nullptr;
ExpressionActionsChain::Step & step = chain.lastStep(sourceColumns());
getRootActions(array_join_expression_list, only_types, step.actions());
auto array_join = addMultipleArrayJoinAction(step.actions(), is_array_join_left);
before_array_join = chain.getLastActions();
chain.steps.push_back(std::make_unique<ExpressionActionsChain::ArrayJoinStep>(
array_join, step.getResultColumns()));
chain.addStep();
return array_join;
}
bool SelectQueryExpressionAnalyzer::appendJoinLeftKeys(ExpressionActionsChain & chain, bool only_types)
{
ExpressionActionsChain::Step & step = chain.lastStep(columns_after_array_join);
getRootActions(analyzedJoin().leftKeysList(), only_types, step.actions());
return true;
}
JoinPtr SelectQueryExpressionAnalyzer::appendJoin(ExpressionActionsChain & chain, ActionsDAGPtr & converting_join_columns)
{
const ColumnsWithTypeAndName & left_sample_columns = chain.getLastStep().getResultColumns();
JoinPtr table_join = makeTableJoin(*syntax->ast_join, left_sample_columns, converting_join_columns);
if (converting_join_columns)
{
chain.steps.push_back(std::make_unique<ExpressionActionsChain::ExpressionActionsStep>(converting_join_columns));
chain.addStep();
}
ExpressionActionsChain::Step & step = chain.lastStep(columns_after_array_join);
chain.steps.push_back(std::make_unique<ExpressionActionsChain::JoinStep>(
syntax->analyzed_join, table_join, step.getResultColumns()));
chain.addStep();
return table_join;
}
static ActionsDAGPtr createJoinedBlockActions(ContextPtr context, const TableJoin & analyzed_join)
{
ASTPtr expression_list = analyzed_join.rightKeysList();
auto syntax_result = TreeRewriter(context).analyze(expression_list, analyzed_join.columnsFromJoinedTable());
return ExpressionAnalyzer(expression_list, syntax_result, context).getActionsDAG(true, false);
}
static std::shared_ptr<IJoin> chooseJoinAlgorithm(std::shared_ptr<TableJoin> analyzed_join, const Block & sample_block, ContextPtr context)
{
/// HashJoin with Dictionary optimisation
if (analyzed_join->tryInitDictJoin(sample_block, context))
return std::make_shared<HashJoin>(analyzed_join, sample_block);
bool allow_merge_join = analyzed_join->allowMergeJoin();
if (analyzed_join->forceHashJoin() || (analyzed_join->preferMergeJoin() && !allow_merge_join))
return std::make_shared<HashJoin>(analyzed_join, sample_block);
else if (analyzed_join->forceMergeJoin() || (analyzed_join->preferMergeJoin() && allow_merge_join))
return std::make_shared<MergeJoin>(analyzed_join, sample_block);
return std::make_shared<JoinSwitcher>(analyzed_join, sample_block);
}
static std::unique_ptr<QueryPlan> buildJoinedPlan(
ContextPtr context,
const ASTTablesInSelectQueryElement & join_element,
TableJoin & analyzed_join,
SelectQueryOptions query_options)
{
/// Actions which need to be calculated on joined block.
auto joined_block_actions = createJoinedBlockActions(context, analyzed_join);
Names original_right_columns;
NamesWithAliases required_columns_with_aliases = analyzed_join.getRequiredColumns(
Block(joined_block_actions->getResultColumns()), joined_block_actions->getRequiredColumns().getNames());
for (auto & pr : required_columns_with_aliases)
original_right_columns.push_back(pr.first);
/** For GLOBAL JOINs (in the case, for example, of the push method for executing GLOBAL subqueries), the following occurs
* - in the addExternalStorage function, the JOIN (SELECT ...) subquery is replaced with JOIN _data1,
* in the subquery_for_set object this subquery is exposed as source and the temporary table _data1 as the `table`.
* - this function shows the expression JOIN _data1.
* - JOIN tables will need aliases to correctly resolve USING clause.
*/
auto interpreter = interpretSubquery(
join_element.table_expression, context, original_right_columns, query_options.copy().setWithAllColumns().ignoreAlias(false));
auto joined_plan = std::make_unique<QueryPlan>();
interpreter->buildQueryPlan(*joined_plan);
{
auto sample_block = interpreter->getSampleBlock();
auto rename_dag = std::make_unique<ActionsDAG>(sample_block.getColumnsWithTypeAndName());
for (const auto & name_with_alias : required_columns_with_aliases)
{
if (sample_block.has(name_with_alias.first))
{
auto pos = sample_block.getPositionByName(name_with_alias.first);
const auto & alias = rename_dag->addAlias(*rename_dag->getInputs()[pos], name_with_alias.second);
rename_dag->getIndex()[pos] = &alias;
}
}
auto rename_step = std::make_unique<ExpressionStep>(joined_plan->getCurrentDataStream(), std::move(rename_dag));
rename_step->setStepDescription("Rename joined columns");
joined_plan->addStep(std::move(rename_step));
}
auto joined_actions_step = std::make_unique<ExpressionStep>(joined_plan->getCurrentDataStream(), std::move(joined_block_actions));
joined_actions_step->setStepDescription("Joined actions");
joined_plan->addStep(std::move(joined_actions_step));
return joined_plan;
}
JoinPtr SelectQueryExpressionAnalyzer::makeTableJoin(
const ASTTablesInSelectQueryElement & join_element,
const ColumnsWithTypeAndName & left_columns,
ActionsDAGPtr & left_convert_actions)
{
/// Two JOINs are not supported with the same subquery, but different USINGs.
if (joined_plan)
throw Exception(ErrorCodes::LOGICAL_ERROR, "Table join was already created for query");
ActionsDAGPtr right_convert_actions = nullptr;
const auto & analyzed_join = syntax->analyzed_join;
if (auto storage = analyzed_join->getStorageJoin())
{
std::tie(left_convert_actions, right_convert_actions) = analyzed_join->createConvertingActions(left_columns, {});
return storage->getJoinLocked(analyzed_join, getContext());
}
joined_plan = buildJoinedPlan(getContext(), join_element, *analyzed_join, query_options);
const ColumnsWithTypeAndName & right_columns = joined_plan->getCurrentDataStream().header.getColumnsWithTypeAndName();
std::tie(left_convert_actions, right_convert_actions) = analyzed_join->createConvertingActions(left_columns, right_columns);
if (right_convert_actions)
{
auto converting_step = std::make_unique<ExpressionStep>(joined_plan->getCurrentDataStream(), right_convert_actions);
converting_step->setStepDescription("Convert joined columns");
joined_plan->addStep(std::move(converting_step));
}
JoinPtr join = chooseJoinAlgorithm(analyzed_join, joined_plan->getCurrentDataStream().header, getContext());
/// Do not make subquery for join over dictionary.
if (analyzed_join->getDictionaryReader())
joined_plan.reset();
return join;
}
ActionsDAGPtr SelectQueryExpressionAnalyzer::appendPrewhere(
ExpressionActionsChain & chain, bool only_types, const Names & additional_required_columns)
{
const auto * select_query = getSelectQuery();
if (!select_query->prewhere())
return nullptr;
Names first_action_names;
if (!chain.steps.empty())
first_action_names = chain.steps.front()->getRequiredColumns().getNames();
auto & step = chain.lastStep(sourceColumns());
getRootActions(select_query->prewhere(), only_types, step.actions());
String prewhere_column_name = select_query->prewhere()->getColumnName();
step.addRequiredOutput(prewhere_column_name);
const auto & node = step.actions()->findInIndex(prewhere_column_name);
auto filter_type = node.result_type;
if (!filter_type->canBeUsedInBooleanContext())
throw Exception("Invalid type for filter in PREWHERE: " + filter_type->getName(),
ErrorCodes::ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER);
ActionsDAGPtr prewhere_actions;
{
/// Remove unused source_columns from prewhere actions.
auto tmp_actions_dag = std::make_shared<ActionsDAG>(sourceColumns());
getRootActions(select_query->prewhere(), only_types, tmp_actions_dag);
/// Constants cannot be removed since they can be used in other parts of the query.
/// And if they are not used anywhere, except PREWHERE, they will be removed on the next step.
tmp_actions_dag->removeUnusedActions(
NameSet{prewhere_column_name},
/* allow_remove_inputs= */ true,
/* allow_constant_folding= */ false);
auto required_columns = tmp_actions_dag->getRequiredColumnsNames();
NameSet required_source_columns(required_columns.begin(), required_columns.end());
required_source_columns.insert(first_action_names.begin(), first_action_names.end());
/// Add required columns to required output in order not to remove them after prewhere execution.
/// TODO: add sampling and final execution to common chain.
for (const auto & column : additional_required_columns)
{
if (required_source_columns.count(column))
step.addRequiredOutput(column);
}
auto names = step.actions()->getNames();
NameSet name_set(names.begin(), names.end());
for (const auto & column : sourceColumns())
if (required_source_columns.count(column.name) == 0)
name_set.erase(column.name);
Names required_output(name_set.begin(), name_set.end());
prewhere_actions = chain.getLastActions();
prewhere_actions->removeUnusedActions(required_output);
}
{
/// Add empty action with input = {prewhere actions output} + {unused source columns}
/// Reasons:
/// 1. Remove remove source columns which are used only in prewhere actions during prewhere actions execution.
/// Example: select A prewhere B > 0. B can be removed at prewhere step.
/// 2. Store side columns which were calculated during prewhere actions execution if they are used.
/// Example: select F(A) prewhere F(A) > 0. F(A) can be saved from prewhere step.
/// 3. Check if we can remove filter column at prewhere step. If we can, action will store single REMOVE_COLUMN.
ColumnsWithTypeAndName columns = prewhere_actions->getResultColumns();
auto required_columns = prewhere_actions->getRequiredColumns();
NameSet prewhere_input_names;
NameSet unused_source_columns;
for (const auto & col : required_columns)
prewhere_input_names.insert(col.name);
for (const auto & column : sourceColumns())
{
if (prewhere_input_names.count(column.name) == 0)
{
columns.emplace_back(column.type, column.name);
unused_source_columns.emplace(column.name);
}
}
chain.steps.emplace_back(std::make_unique<ExpressionActionsChain::ExpressionActionsStep>(
std::make_shared<ActionsDAG>(std::move(columns))));
chain.steps.back()->additional_input = std::move(unused_source_columns);
chain.getLastActions();
chain.addStep();
}
return prewhere_actions;
}
bool SelectQueryExpressionAnalyzer::appendWhere(ExpressionActionsChain & chain, bool only_types)
{
const auto * select_query = getSelectQuery();
if (!select_query->where())
return false;
ExpressionActionsChain::Step & step = chain.lastStep(columns_after_join);
getRootActions(select_query->where(), only_types, step.actions());
auto where_column_name = select_query->where()->getColumnName();
step.addRequiredOutput(where_column_name);
const auto & node = step.actions()->findInIndex(where_column_name);
auto filter_type = node.result_type;
if (!filter_type->canBeUsedInBooleanContext())
throw Exception("Invalid type for filter in WHERE: " + filter_type->getName(),
ErrorCodes::ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER);
return true;
}
bool SelectQueryExpressionAnalyzer::appendGroupBy(ExpressionActionsChain & chain, bool only_types, bool optimize_aggregation_in_order,
ManyExpressionActions & group_by_elements_actions)
{
const auto * select_query = getAggregatingQuery();
if (!select_query->groupBy())
return false;
ExpressionActionsChain::Step & step = chain.lastStep(columns_after_join);
ASTs asts = select_query->groupBy()->children;
if (select_query->group_by_with_grouping_sets)
{
for (const auto & ast : asts)
{
for (const auto & ast_element : ast->children)
{
step.addRequiredOutput(ast_element->getColumnName());
getRootActions(ast_element, only_types, step.actions());
}
}
}
else
{
for (const auto & ast : asts)
{
step.addRequiredOutput(ast->getColumnName());
getRootActions(ast, only_types, step.actions());
}
}
if (optimize_aggregation_in_order)
{
for (auto & child : asts)
{
auto actions_dag = std::make_shared<ActionsDAG>(columns_after_join);
getRootActions(child, only_types, actions_dag);
group_by_elements_actions.emplace_back(
std::make_shared<ExpressionActions>(actions_dag, ExpressionActionsSettings::fromContext(getContext(), CompileExpressions::yes)));
}
}
return true;
}
void SelectQueryExpressionAnalyzer::appendAggregateFunctionsArguments(ExpressionActionsChain & chain, bool only_types)
{
const auto * select_query = getAggregatingQuery();
ExpressionActionsChain::Step & step = chain.lastStep(columns_after_join);
for (const auto & desc : aggregate_descriptions)
for (const auto & name : desc.argument_names)
step.addRequiredOutput(name);
/// Collect aggregates removing duplicates by node.getColumnName()
/// It's not clear why we recollect aggregates (for query parts) while we're able to use previously collected ones (for entire query)
/// @note The original recollection logic didn't remove duplicates.
GetAggregatesVisitor::Data data;
GetAggregatesVisitor(data).visit(select_query->select());
if (select_query->having())
GetAggregatesVisitor(data).visit(select_query->having());
if (select_query->orderBy())
GetAggregatesVisitor(data).visit(select_query->orderBy());
/// TODO: data.aggregates -> aggregates()
for (const ASTFunction * node : data.aggregates)
if (node->arguments)
for (auto & argument : node->arguments->children)
getRootActions(argument, only_types, step.actions());
}
void SelectQueryExpressionAnalyzer::appendWindowFunctionsArguments(
ExpressionActionsChain & chain, bool /* only_types */)
{
ExpressionActionsChain::Step & step = chain.lastStep(aggregated_columns);
// (1) Add actions for window functions and the columns they require.
// (2) Mark the columns that are really required. We have to mark them as
// required because we finish the expression chain before processing the
// window functions.
// The required columns are:
// (a) window function arguments,
// (b) the columns from PARTITION BY and ORDER BY.
// (1a) Actions for PARTITION BY and ORDER BY for windows defined in the
// WINDOW clause. The inline window definitions will be processed
// recursively together with (1b) as ASTFunction::window_definition.
if (getSelectQuery()->window())
{
getRootActionsNoMakeSet(getSelectQuery()->window(),
true /* no_subqueries */, step.actions());
}
for (const auto & [_, w] : window_descriptions)
{
for (const auto & f : w.window_functions)
{
// (1b) Actions for function arguments, and also the inline window
// definitions (1a).
// Requiring a constant reference to a shared pointer to non-const AST
// doesn't really look sane, but the visitor does indeed require it.
getRootActionsNoMakeSet(f.function_node->clone(),
true /* no_subqueries */, step.actions());
// (2b) Required function argument columns.
for (const auto & a : f.function_node->arguments->children)
{
step.addRequiredOutput(a->getColumnName());
}
}
// (2a) Required PARTITION BY and ORDER BY columns.
for (const auto & c : w.full_sort_description)
{
step.addRequiredOutput(c.column_name);
}
}
}
bool SelectQueryExpressionAnalyzer::appendHaving(ExpressionActionsChain & chain, bool only_types)
{
const auto * select_query = getAggregatingQuery();
if (!select_query->having())
return false;
ExpressionActionsChain::Step & step = chain.lastStep(aggregated_columns);
getRootActionsForHaving(select_query->having(), only_types, step.actions());
step.addRequiredOutput(select_query->having()->getColumnName());
return true;
}
void SelectQueryExpressionAnalyzer::appendSelect(ExpressionActionsChain & chain, bool only_types)
{
const auto * select_query = getSelectQuery();
ExpressionActionsChain::Step & step = chain.lastStep(aggregated_columns);
getRootActions(select_query->select(), only_types, step.actions());
for (const auto & child : select_query->select()->children)
{
if (const auto * function = typeid_cast<const ASTFunction *>(child.get());
function
&& function->is_window_function)
{
// Skip window function columns here -- they are calculated after
// other SELECT expressions by a special step.
continue;
}
step.addRequiredOutput(child->getColumnName());
}
}
ActionsDAGPtr SelectQueryExpressionAnalyzer::appendOrderBy(ExpressionActionsChain & chain, bool only_types, bool optimize_read_in_order,
ManyExpressionActions & order_by_elements_actions)
{
const auto * select_query = getSelectQuery();
if (!select_query->orderBy())
{
auto actions = chain.getLastActions();
chain.addStep();
return actions;
}
ExpressionActionsChain::Step & step = chain.lastStep(aggregated_columns);
for (auto & child : select_query->orderBy()->children)
{
auto * ast = child->as<ASTOrderByElement>();
if (!ast || ast->children.empty())
throw Exception("Bad ORDER BY expression AST", ErrorCodes::UNKNOWN_TYPE_OF_AST_NODE);
if (getContext()->getSettingsRef().enable_positional_arguments)
replaceForPositionalArguments(ast->children.at(0), select_query, ASTSelectQuery::Expression::ORDER_BY);
}
getRootActions(select_query->orderBy(), only_types, step.actions());
bool with_fill = false;
NameSet order_by_keys;
for (auto & child : select_query->orderBy()->children)
{
auto * ast = child->as<ASTOrderByElement>();
ASTPtr order_expression = ast->children.at(0);
step.addRequiredOutput(order_expression->getColumnName());
if (ast->with_fill)
with_fill = true;
}
if (optimize_read_in_order)
{
for (auto & child : select_query->orderBy()->children)
{
auto actions_dag = std::make_shared<ActionsDAG>(columns_after_join);
getRootActions(child, only_types, actions_dag);
order_by_elements_actions.emplace_back(
std::make_shared<ExpressionActions>(actions_dag, ExpressionActionsSettings::fromContext(getContext(), CompileExpressions::yes)));
}
}
NameSet non_constant_inputs;
if (with_fill)
{
for (const auto & column : step.getResultColumns())
if (!order_by_keys.count(column.name))
non_constant_inputs.insert(column.name);
}
auto actions = chain.getLastActions();
chain.addStep(non_constant_inputs);
return actions;
}
bool SelectQueryExpressionAnalyzer::appendLimitBy(ExpressionActionsChain & chain, bool only_types)
{
const auto * select_query = getSelectQuery();
if (!select_query->limitBy())
return false;
ExpressionActionsChain::Step & step = chain.lastStep(aggregated_columns);
getRootActions(select_query->limitBy(), only_types, step.actions());
NameSet aggregated_names;
for (const auto & column : aggregated_columns)
{
step.addRequiredOutput(column.name);
aggregated_names.insert(column.name);
}
auto & children = select_query->limitBy()->children;
for (auto & child : children)
{
if (getContext()->getSettingsRef().enable_positional_arguments)
replaceForPositionalArguments(child, select_query, ASTSelectQuery::Expression::LIMIT_BY);
auto child_name = child->getColumnName();
if (!aggregated_names.count(child_name))
step.addRequiredOutput(std::move(child_name));
}
return true;
}
ActionsDAGPtr SelectQueryExpressionAnalyzer::appendProjectResult(ExpressionActionsChain & chain) const
{
const auto * select_query = getSelectQuery();
ExpressionActionsChain::Step & step = chain.lastStep(aggregated_columns);
NamesWithAliases result_columns;
ASTs asts = select_query->select()->children;
for (const auto & ast : asts)
{
String result_name = ast->getAliasOrColumnName();
if (required_result_columns.empty() || required_result_columns.count(result_name))
{
std::string source_name = ast->getColumnName();
/*
* For temporary columns created by ExpressionAnalyzer for literals,
* use the correct source column. Using the default display name
* returned by getColumnName is not enough, and we have to use the
* column id set by EA. In principle, this logic applies to all kinds
* of columns, not only literals. Literals are especially problematic
* for two reasons:
* 1) confusing different literal columns leads to weird side
* effects (see 01101_literal_columns_clash);
* 2) the disambiguation mechanism in SyntaxAnalyzer, that, among
* other things, creates unique aliases for columns with same
* names from different tables, is applied before these temporary
* columns are created by ExpressionAnalyzer.
* Similar problems should also manifest for function columns, which
* are likewise created at a later stage by EA.
* In general, we need to have explicit separation between display
* names and identifiers for columns. This code is a workaround for
* a particular subclass of problems, and not a proper solution.
*/
if (const auto * as_literal = ast->as<ASTLiteral>())
{
source_name = as_literal->unique_column_name;
assert(!source_name.empty());
}
result_columns.emplace_back(source_name, result_name);
step.addRequiredOutput(result_columns.back().second);
}
}
auto actions = chain.getLastActions();
actions->project(result_columns);
return actions;
}
void ExpressionAnalyzer::appendExpression(ExpressionActionsChain & chain, const ASTPtr & expr, bool only_types)
{
ExpressionActionsChain::Step & step = chain.lastStep(sourceColumns());
getRootActions(expr, only_types, step.actions());
step.addRequiredOutput(expr->getColumnName());
}
ActionsDAGPtr ExpressionAnalyzer::getActionsDAG(bool add_aliases, bool project_result)
{
auto actions_dag = std::make_shared<ActionsDAG>(aggregated_columns);
NamesWithAliases result_columns;
Names result_names;
ASTs asts;
if (const auto * node = query->as<ASTExpressionList>())
asts = node->children;
else
asts = ASTs(1, query);
for (const auto & ast : asts)
{
std::string name = ast->getColumnName();
std::string alias;
if (add_aliases)
alias = ast->getAliasOrColumnName();
else
alias = name;
result_columns.emplace_back(name, alias);
result_names.push_back(alias);
getRootActions(ast, false, actions_dag);
}
if (add_aliases)
{
if (project_result)
actions_dag->project(result_columns);
else
actions_dag->addAliases(result_columns);
}
if (!(add_aliases && project_result))
{
NameSet name_set(result_names.begin(), result_names.end());
/// We will not delete the original columns.
for (const auto & column_name_type : sourceColumns())
{
if (name_set.count(column_name_type.name) == 0)
{
result_names.push_back(column_name_type.name);
name_set.insert(column_name_type.name);
}
}
actions_dag->removeUnusedActions(name_set);
}
return actions_dag;
}
ExpressionActionsPtr ExpressionAnalyzer::getActions(bool add_aliases, bool project_result, CompileExpressions compile_expressions)
{
return std::make_shared<ExpressionActions>(
getActionsDAG(add_aliases, project_result), ExpressionActionsSettings::fromContext(getContext(), compile_expressions));
}
ExpressionActionsPtr ExpressionAnalyzer::getConstActions(const ColumnsWithTypeAndName & constant_inputs)
{
auto actions = std::make_shared<ActionsDAG>(constant_inputs);
getRootActions(query, true, actions, true);
return std::make_shared<ExpressionActions>(actions, ExpressionActionsSettings::fromContext(getContext()));
}
std::unique_ptr<QueryPlan> SelectQueryExpressionAnalyzer::getJoinedPlan()
{
return std::move(joined_plan);
}
ActionsDAGPtr SelectQueryExpressionAnalyzer::simpleSelectActions()
{
ExpressionActionsChain new_chain(getContext());
appendSelect(new_chain, false);
return new_chain.getLastActions();
}
ExpressionAnalysisResult::ExpressionAnalysisResult(
SelectQueryExpressionAnalyzer & query_analyzer,
const StorageMetadataPtr & metadata_snapshot,
bool first_stage_,
bool second_stage_,
bool only_types,
const FilterDAGInfoPtr & filter_info_,
const Block & source_header)
: first_stage(first_stage_)
, second_stage(second_stage_)
, need_aggregate(query_analyzer.hasAggregation())
, has_window(query_analyzer.hasWindow())
{
/// first_stage: Do I need to perform the first part of the pipeline - running on remote servers during distributed processing.
/// second_stage: Do I need to execute the second part of the pipeline - running on the initiating server during distributed processing.
/** First we compose a chain of actions and remember the necessary steps from it.
* Regardless of from_stage and to_stage, we will compose a complete sequence of actions to perform optimization and
* throw out unnecessary columns based on the entire query. In unnecessary parts of the query, we will not execute subqueries.
*/
const ASTSelectQuery & query = *query_analyzer.getSelectQuery();
auto context = query_analyzer.getContext();
const Settings & settings = context->getSettingsRef();
const ConstStoragePtr & storage = query_analyzer.storage();
ssize_t prewhere_step_num = -1;
ssize_t where_step_num = -1;
ssize_t having_step_num = -1;
auto finalize_chain = [&](ExpressionActionsChain & chain)
{
chain.finalize();
finalize(chain, prewhere_step_num, where_step_num, having_step_num, query);
chain.clear();
};
{
ExpressionActionsChain chain(context);
Names additional_required_columns_after_prewhere;
if (storage && (query.sampleSize() || settings.parallel_replicas_count > 1))
{
Names columns_for_sampling = metadata_snapshot->getColumnsRequiredForSampling();
additional_required_columns_after_prewhere.insert(additional_required_columns_after_prewhere.end(),
columns_for_sampling.begin(), columns_for_sampling.end());
}
if (storage && query.final())
{
Names columns_for_final = metadata_snapshot->getColumnsRequiredForFinal();
additional_required_columns_after_prewhere.insert(additional_required_columns_after_prewhere.end(),
columns_for_final.begin(), columns_for_final.end());
}
if (storage && filter_info_)
{
filter_info = filter_info_;
filter_info->do_remove_column = true;
}
if (auto actions = query_analyzer.appendPrewhere(chain, !first_stage, additional_required_columns_after_prewhere))
{
/// Prewhere is always the first one.
prewhere_step_num = 0;
prewhere_info = std::make_shared<PrewhereInfo>(actions, query.prewhere()->getColumnName());
if (allowEarlyConstantFolding(*prewhere_info->prewhere_actions, settings))
{
Block before_prewhere_sample = source_header;
if (sanitizeBlock(before_prewhere_sample))
{
ExpressionActions(
prewhere_info->prewhere_actions,
ExpressionActionsSettings::fromSettings(context->getSettingsRef())).execute(before_prewhere_sample);
auto & column_elem = before_prewhere_sample.getByName(query.prewhere()->getColumnName());
/// If the filter column is a constant, record it.
if (column_elem.column)
prewhere_constant_filter_description = ConstantFilterDescription(*column_elem.column);
}
}
}
array_join = query_analyzer.appendArrayJoin(chain, before_array_join, only_types || !first_stage);
if (query_analyzer.hasTableJoin())
{
query_analyzer.appendJoinLeftKeys(chain, only_types || !first_stage);
before_join = chain.getLastActions();
join = query_analyzer.appendJoin(chain, converting_join_columns);
chain.addStep();
}
if (query_analyzer.appendWhere(chain, only_types || !first_stage))
{
where_step_num = chain.steps.size() - 1;
before_where = chain.getLastActions();
if (allowEarlyConstantFolding(*before_where, settings))
{
Block before_where_sample;
if (chain.steps.size() > 1)
before_where_sample = Block(chain.steps[chain.steps.size() - 2]->getResultColumns());
else
before_where_sample = source_header;
if (sanitizeBlock(before_where_sample))
{
ExpressionActions(
before_where,
ExpressionActionsSettings::fromSettings(context->getSettingsRef())).execute(before_where_sample);
auto & column_elem = before_where_sample.getByName(query.where()->getColumnName());
/// If the filter column is a constant, record it.
if (column_elem.column)
where_constant_filter_description = ConstantFilterDescription(*column_elem.column);
}
}
chain.addStep();
}
if (need_aggregate)
{
/// TODO correct conditions
optimize_aggregation_in_order =
context->getSettingsRef().optimize_aggregation_in_order
&& storage && query.groupBy();
query_analyzer.appendGroupBy(chain, only_types || !first_stage, optimize_aggregation_in_order, group_by_elements_actions);
query_analyzer.appendAggregateFunctionsArguments(chain, only_types || !first_stage);
before_aggregation = chain.getLastActions();
finalize_chain(chain);
if (query_analyzer.appendHaving(chain, only_types || !second_stage))
{
having_step_num = chain.steps.size() - 1;
before_having = chain.getLastActions();
chain.addStep();
}
}
bool join_allow_read_in_order = true;
if (hasJoin())
{
/// You may find it strange but we support read_in_order for HashJoin and do not support for MergeJoin.
join_has_delayed_stream = query_analyzer.analyzedJoin().needStreamWithNonJoinedRows();
join_allow_read_in_order = typeid_cast<HashJoin *>(join.get()) && !join_has_delayed_stream;
}
optimize_read_in_order =
settings.optimize_read_in_order
&& storage
&& query.orderBy()
&& !query_analyzer.hasAggregation()
&& !query_analyzer.hasWindow()
&& !query.final()
&& join_allow_read_in_order;
/// If there is aggregation, we execute expressions in SELECT and ORDER BY on the initiating server, otherwise on the source servers.
query_analyzer.appendSelect(chain, only_types || (need_aggregate ? !second_stage : !first_stage));
// Window functions are processed in a separate expression chain after
// the main SELECT, similar to what we do for aggregate functions.
if (has_window)
{
query_analyzer.makeWindowDescriptions(chain.getLastActions());
query_analyzer.appendWindowFunctionsArguments(chain, only_types || !first_stage);
// Build a list of output columns of the window step.
// 1) We need the columns that are the output of ExpressionActions.
for (const auto & x : chain.getLastActions()->getNamesAndTypesList())
{
query_analyzer.columns_after_window.push_back(x);
}
// 2) We also have to manually add the output of the window function
// to the list of the output columns of the window step, because the
// window functions are not in the ExpressionActions.
for (const auto & [_, w] : query_analyzer.window_descriptions)
{
for (const auto & f : w.window_functions)
{
query_analyzer.columns_after_window.push_back(
{f.column_name, f.aggregate_function->getReturnType()});
}
}
before_window = chain.getLastActions();
finalize_chain(chain);
auto & step = chain.lastStep(query_analyzer.columns_after_window);
// The output of this expression chain is the result of
// SELECT (before "final projection" i.e. renaming the columns), so
// we have to mark the expressions that are required in the output,
// again. We did it for the previous expression chain ("select w/o
// window functions") earlier, in appendSelect(). But that chain also
// produced the expressions required to calculate window functions.
// They are not needed in the final SELECT result. Knowing the correct
// list of columns is important when we apply SELECT DISTINCT later.
const auto * select_query = query_analyzer.getSelectQuery();
for (const auto & child : select_query->select()->children)
{
step.addRequiredOutput(child->getColumnName());
}
}
selected_columns.clear();
selected_columns.reserve(chain.getLastStep().required_output.size());
for (const auto & it : chain.getLastStep().required_output)
selected_columns.emplace_back(it.first);
has_order_by = query.orderBy() != nullptr;
before_order_by = query_analyzer.appendOrderBy(
chain,
only_types || (need_aggregate ? !second_stage : !first_stage),
optimize_read_in_order,
order_by_elements_actions);
if (query_analyzer.appendLimitBy(chain, only_types || !second_stage))
{
before_limit_by = chain.getLastActions();
chain.addStep();
}
final_projection = query_analyzer.appendProjectResult(chain);
finalize_chain(chain);
}
/// Before executing WHERE and HAVING, remove the extra columns from the block (mostly the aggregation keys).
removeExtraColumns();
checkActions();
}
void ExpressionAnalysisResult::finalize(
const ExpressionActionsChain & chain,
ssize_t & prewhere_step_num,
ssize_t & where_step_num,
ssize_t & having_step_num,
const ASTSelectQuery & query)
{
if (prewhere_step_num >= 0)
{
const ExpressionActionsChain::Step & step = *chain.steps.at(prewhere_step_num);
prewhere_info->prewhere_actions->projectInput(false);
NameSet columns_to_remove;
for (const auto & [name, can_remove] : step.required_output)
{
if (name == prewhere_info->prewhere_column_name)
prewhere_info->remove_prewhere_column = can_remove;
else if (can_remove)
columns_to_remove.insert(name);
}
columns_to_remove_after_prewhere = std::move(columns_to_remove);
prewhere_step_num = -1;
}
if (where_step_num >= 0)
{
where_column_name = query.where()->getColumnName();
remove_where_filter = chain.steps.at(where_step_num)->required_output.find(where_column_name)->second;
where_step_num = -1;
}
if (having_step_num >= 0)
{
having_column_name = query.having()->getColumnName();
remove_having_filter = chain.steps.at(having_step_num)->required_output.find(having_column_name)->second;
having_step_num = -1;
}
}
void ExpressionAnalysisResult::removeExtraColumns() const
{
if (hasWhere())
before_where->projectInput();
if (hasHaving())
before_having->projectInput();
}
void ExpressionAnalysisResult::checkActions() const
{
/// Check that PREWHERE doesn't contain unusual actions. Unusual actions are that can change number of rows.
if (hasPrewhere())
{
auto check_actions = [](const ActionsDAGPtr & actions)
{
if (actions)
for (const auto & node : actions->getNodes())
if (node.type == ActionsDAG::ActionType::ARRAY_JOIN)
throw Exception("PREWHERE cannot contain ARRAY JOIN action", ErrorCodes::ILLEGAL_PREWHERE);
};
check_actions(prewhere_info->prewhere_actions);
check_actions(prewhere_info->alias_actions);
}
}
std::string ExpressionAnalysisResult::dump() const
{
WriteBufferFromOwnString ss;
ss << "need_aggregate " << need_aggregate << "\n";
ss << "has_order_by " << has_order_by << "\n";
ss << "has_window " << has_window << "\n";
if (before_array_join)
{
ss << "before_array_join " << before_array_join->dumpDAG() << "\n";
}
if (array_join)
{
ss << "array_join " << "FIXME doesn't have dump" << "\n";
}
if (before_join)
{
ss << "before_join " << before_join->dumpDAG() << "\n";
}
if (before_where)
{
ss << "before_where " << before_where->dumpDAG() << "\n";
}
if (prewhere_info)
{
ss << "prewhere_info " << prewhere_info->dump() << "\n";
}
if (filter_info)
{
ss << "filter_info " << filter_info->dump() << "\n";
}
if (before_aggregation)
{
ss << "before_aggregation " << before_aggregation->dumpDAG() << "\n";
}
if (before_having)
{
ss << "before_having " << before_having->dumpDAG() << "\n";
}
if (before_window)
{
ss << "before_window " << before_window->dumpDAG() << "\n";
}
if (before_order_by)
{
ss << "before_order_by " << before_order_by->dumpDAG() << "\n";
}
if (before_limit_by)
{
ss << "before_limit_by " << before_limit_by->dumpDAG() << "\n";
}
if (final_projection)
{
ss << "final_projection " << final_projection->dumpDAG() << "\n";
}
if (!selected_columns.empty())
{
ss << "selected_columns ";
for (size_t i = 0; i < selected_columns.size(); i++)
{
if (i > 0)
{
ss << ", ";
}
ss << backQuote(selected_columns[i]);
}
ss << "\n";
}
return ss.str();
}
}
|
#ifndef __ANG_FOUNDATIONS_H__
#error ...
#elif !defined __ANG_FOUNDATIONS_INL__
#define __ANG_FOUNDATIONS_INL__
template<typename T>
inline ang::graphics::point<T> ang::graphics::point<T>::parse(ang::cstr_t cstr)
{
if (cstr.ptr() == null)
return{ 0,0 };
//text::iparser_t parser = text::iparser::get_parser(cstr.encoding());
windex i = 0;
T temp[2] = { 0,0 };
text::parser::seek(cstr, i, " [ "_r);
temp[0] = text::parser::to_value<T>(cstr, i);
text::parserseek(cstr, i, " , "_r);
temp[1] = text::parser::to_value<T>(cstr, i);
//text::parser::seek(cstr, i, " ] "_r);
return{ temp[0], temp[1] };
}
template<typename T>
inline ang::graphics::point<T>::point()
: x(0)
, y(0)
{
}
template<typename T>
inline ang::graphics::point<T>::point(point const& p)
: x(p.x)
, y(p.y)
{
}
template<typename T>
inline ang::graphics::point<T>::point(T x, T y)
: x(x)
, y(y)
{
}
template<typename T>
inline ang::graphics::point<T>& ang::graphics::point<T>::operator = (const ang::graphics::point<T>& p)
{
x = p.x;
y = p.y;
return*this;
}
template<typename T>
inline ang::graphics::point<T>& ang::graphics::point<T>::operator += (const ang::graphics::point<T>& p)
{
x += p.x;
y += p.y;
return *this;
}
template<typename T>
inline ang::graphics::point<T>& ang::graphics::point<T>::operator -= (const ang::graphics::point<T>& p)
{
x -= p.x;
y -= p.y;
return *this;
}
template<typename T>
inline ang::graphics::point<T>& ang::graphics::point<T>::operator *= (T k)
{
x *= k;
y *= k;
return *this;
}
template<typename T>
inline ang::graphics::point<T>& ang::graphics::point<T>::operator /= (T k)
{
x /= k;
y /= k;
return *this;
}
template<typename T>
inline ang::graphics::point3d<T> ang::graphics::point3d<T>::parse(ang::cstr_t cstr)
{
if (cstr.ptr() == null)
return{ 0,0,0 };
//text::iparser_t parser = text::iparser::get_parser(cstr.encoding());
windex i = 0;
T temp[3] = { 0,0,0 };
text::parser::seek(cstr, i, " [ "_r);
temp[0] = text::parser::to_value<T>(cstr, i);
text::parser::seek(cstr, i, " , "_r);
temp[1] = text::parser::to_value<T>(cstr, i);
text::parser::seek(cstr, i, " , "_r);
temp[2] = text::parser::to_value<T>(cstr, i);
//text::parser::seek(cstr, i, " ] "_r);
return{ temp[0], temp[1] ,temp[2] };
}
template<typename T>
inline ang::graphics::point3d<T>::point3d()
: x(0)
, y(0)
, z(0)
{
}
template<typename T>
inline ang::graphics::point3d<T>::point3d(point3d const& p)
: x(p.x)
, y(p.y)
, z(p.z)
{
}
template<typename T>
inline ang::graphics::point3d<T>::point3d(T x, T y, T z)
: x(x)
, y(y)
, z(z)
{
}
template<typename T>
inline ang::graphics::point3d<T>& ang::graphics::point3d<T>::operator = (const ang::graphics::point3d<T>& p)
{
x = p.x;
y = p.y;
z = p.z;
return*this;
}
template<typename T>
inline ang::graphics::point3d<T>& ang::graphics::point3d<T>::operator += (const ang::graphics::point3d<T>& p)
{
x += p.x;
y += p.y;
z += p.z;
return *this;
}
template<typename T>
inline ang::graphics::point3d<T>& ang::graphics::point3d<T>::operator -= (const ang::graphics::point3d<T>& p)
{
x -= p.x;
y -= p.y;
z -= p.z;
return *this;
}
template<typename T>
inline ang::graphics::point3d<T>& ang::graphics::point3d<T>::operator *= (T k)
{
x *= k;
y *= k;
z *= k;
return *this;
}
template<typename T>
inline ang::graphics::point3d<T>& ang::graphics::point3d<T>::operator /= (T k)
{
x /= k;
y /= k;
z /= k;
return *this;
}
template<typename T>
inline ang::graphics::size<T> ang::graphics::size<T>::parse(ang::cstr_t cstr)
{
if (cstr.ptr() == null)
return{ 0,0 };
//text::parser::parse()
//text::iparser_t parser = text::iparser::get_parser(cstr.encoding());
windex i = 0;
T temp[2] = { 0,0 };
text::parser::seek(cstr, i, " [ "_r);
temp[0] = text::parser::to_value<T>(cstr, i);
text::parser::seek(cstr, i, " , "_r);
temp[1] = text::parser::to_value<T>(cstr, i);
return{ temp[0], temp[1] };
}
template<typename T>
inline ang::graphics::size<T>::size()
: width(0)
, height(0)
{
}
template<typename T>
inline ang::graphics::size<T>::size(size<T> const& b)
: width(b.width)
, height(b.height)
{
}
template<typename T>
inline ang::graphics::size<T>::size(T width, T height)
: width(width)
, height(height)
{
}
template<typename T>
inline ang::graphics::size<T>& ang::graphics::size<T>::operator = (const ang::graphics::size<T>& b)
{
width = b.width;
height = b.height;
return*this;
}
template<typename T>
inline ang::graphics::size<T>& ang::graphics::size<T>::operator += (const ang::graphics::size<T>& b)
{
width += b.width;
height += b.height;
return *this;
}
template<typename T>
inline ang::graphics::size<T>& ang::graphics::size<T>::operator -= (const ang::graphics::size<T>& b)
{
width -= b.width;
height -= b.height;
return *this;
}
template<typename T>
inline ang::graphics::size<T>& ang::graphics::size<T>::operator *= (T k)
{
width *= k;
height *= k;
return *this;
}
template<typename T>
inline ang::graphics::size<T>& ang::graphics::size<T>::operator /= (T k)
{
width /= k;
height /= k;
return *this;
}
template<typename T>
inline ang::graphics::size3d<T> ang::graphics::size3d<T>::parse(ang::cstr_t cstr)
{
if (cstr.ptr() == null)
return{ 0,0,0 };
//text::iparser_t parser = text::iparser::get_parser(cstr.encoding());
windex i = 0;
T temp[3] = { 0,0,0 };
text::parser::seek(cstr, i, " [ "_r);
temp[0] = text::parser::to_value<T>(cstr, i);
text::parser::seek(cstr, i, " , "_r);
temp[1] = text::parser::to_value<T>(cstr, i);
text::parser::seek(cstr, i, " , "_r);
temp[2] = text::parser::to_value<T>(cstr, i);
return{ temp[0], temp[1], temp[2] };
}
template<typename T>
inline ang::graphics::size3d<T>::size3d()
: width(0)
, height(0)
, depth(0)
{
}
template<typename T>
inline ang::graphics::size3d<T>::size3d(size3d<T> const& b)
: width(b.width)
, height(b.height)
, depth(b.depth)
{
}
template<typename T>
inline ang::graphics::size3d<T>::size3d(T width, T height, T depth)
: width(width)
, height(height)
, depth(depth)
{
}
template<typename T>
inline ang::graphics::size3d<T>& ang::graphics::size3d<T>::operator = (const ang::graphics::size3d<T>& b)
{
width = b.width;
height = b.height;
depth = b.depth;
return*this;
}
template<typename T>
inline ang::graphics::size3d<T>& ang::graphics::size3d<T>::operator += (const ang::graphics::size3d<T>& b)
{
width += b.width;
height += b.height;
depth += b.depth;
return *this;
}
template<typename T>
inline ang::graphics::size3d<T>& ang::graphics::size3d<T>::operator -= (const ang::graphics::size3d<T>& b)
{
width -= b.width;
height -= b.height;
depth -= b.depth;
return *this;
}
template<typename T>
inline ang::graphics::size3d<T>& ang::graphics::size3d<T>::operator *= (T k)
{
width *= k;
height *= k;
depth *= k;
return *this;
}
template<typename T>
inline ang::graphics::size3d<T>& ang::graphics::size3d<T>::operator /= (T k)
{
width /= k;
height /= k;
depth /= k;
return *this;
}
template<typename T>
inline ang::graphics::rect<T> ang::graphics::rect<T>::parse(ang::cstr_t cstr)
{
if (cstr.ptr() == null)
return{ 0,0,0,0 };
//text::iparser_t parser = text::iparser::get_parser(cstr.encoding());
windex i = 0;
T temp[4] = { 0,0,0,0 };
text::parser::seek(cstr, i, " [ "_r);
temp[0] = text::parser::to_value<T>(cstr, i);
text::parser::seek(cstr, i, " , "_r);
temp[1] = text::parser::to_value<T>(cstr, i);
text::parser::seek(cstr, i, " , "_r);
temp[2] = text::parser::to_value<T>(cstr, i);
text::parser::seek(cstr, i, " , "_r);
temp[3] = text::parser::to_value<T>(cstr, i);
return{ temp[0], temp[1], temp[2], temp[3] };
}
template<typename T>
inline ang::graphics::rect<T>::rect()
: left(0)
, top(0)
, right(0)
, bottom(0)
{
}
template<typename T>
inline ang::graphics::rect<T>::rect(ang::graphics::rect<T> const& rc)
: left(rc.left)
, top(rc.top)
, right(rc.right)
, bottom(rc.bottom)
{
}
template<typename T>
inline ang::graphics::rect<T>::rect(T l, T t, T r, T b)
: left(l)
, top(t)
, right(r < l ? l : r)
, bottom(b < t ? t : b)
{
}
template<typename T>
inline ang::graphics::rect<T>::rect(ang::graphics::point<T> lt, ang::graphics::point<T> rb)
: left(lt.x)
, top(lt.y)
, right(rb.x)
, bottom(rb.y)
{
}
template<typename T>
inline ang::graphics::rect<T>::rect(ang::graphics::point<T> lt, ang::graphics::size<T> sz)
: left(lt.x)
, top(lt.y)
, right(lt.x + sz.width)
, bottom(lt.y + sz.height)
{
}
template<typename T>
inline T ang::graphics::rect<T>::width()const {
return right - left;
}
template<typename T>
inline void ang::graphics::rect<T>::width(T value) {
left = right + forward<T>(value);
}
template<typename T>
inline T ang::graphics::rect<T>::height()const {
return bottom - top;
}
template<typename T>
inline void ang::graphics::rect<T>::height(T value) {
bottom = top + forward<T>(value);
}
template<typename T>
inline ang::graphics::point<T> ang::graphics::rect<T>::left_top()const {
return point<T>(left, top);
}
template<typename T>
inline ang::graphics::point<T> ang::graphics::rect<T>::right_top()const {
return point<T>(right, top);
}
template<typename T>
inline ang::graphics::point<T> ang::graphics::rect<T>::left_bottom()const {
return point<T>(left, bottom);
}
template<typename T>
inline ang::graphics::point<T> ang::graphics::rect<T>::right_bottom()const {
return point<T>(right, bottom);
}
template<typename T>
inline void ang::graphics::rect<T>::move_to(ang::graphics::point<T> p)
{
right = right - left + p.x;
bottom = bottom - top + p.y;
left = p.x;
top = p.y;
}
template<typename T>
inline void ang::graphics::rect<T>::move_to(T x, T y)
{
right = right - left + x;
bottom = bottom - top + y;
left = x;
top = y;
}
template<typename T>
inline void ang::graphics::rect<T>::resize(ang::graphics::size<T> sz)
{
right = left + sz.width;
bottom = top + sz.height;
}
template<typename T>
inline void ang::graphics::rect<T>::resize(T cx, T cy)
{
right = left + cx;
bottom = top + cy;
}
template<typename T>
inline void ang::graphics::rect<T>::deflate(T l, T t, T r, T b)
{
left += l;
top += t;
right -= r;
bottom -= b;
}
template<typename T>
inline void ang::graphics::rect<T>::inflate(T l, T t, T r, T b)
{
left -= l;
top -= t;
right += r;
bottom += b;
}
template<typename T>
inline ang::graphics::rect<T>& ang::graphics::rect<T>::operator = (const ang::graphics::rect<T>& rc)
{
left = rc.left;
top = rc.top;
right = rc.right;
bottom = rc.bottom;
return *this;
}
template<typename T>
inline ang::graphics::rect<T>& ang::graphics::rect<T>::operator += (const ang::graphics::rect<T>& rc)
{
left += rc.left;
top += rc.top;
right += rc.right;
bottom += rc.bottom;
return *this;
}
template<typename T>
inline ang::graphics::rect<T>& ang::graphics::rect<T>::operator -= (const ang::graphics::rect<T>& rc)
{
left -= rc.left;
top -= rc.top;
right -= rc.right;
bottom -= rc.bottom;
return *this;
}
template<typename T>
inline ang::graphics::rect<T>& ang::graphics::rect<T>::operator += (const ang::graphics::point<T>& pt)
{
left += pt.x;
top += pt.y;
right += pt.x;
bottom += pt.y;
return *this;
}
template<typename T>
inline ang::graphics::rect<T>& ang::graphics::rect<T>::operator -= (const ang::graphics::point<T>& pt)
{
left -= pt.x;
top -= pt.y;
right -= pt.x;
bottom -= pt.y;
return *this;
}
template<typename T>
inline ang::graphics::rect<T>& ang::graphics::rect<T>::operator += (const ang::graphics::size<T>& sz)
{
right += sz.width;
bottom += sz.height;
return *this;
}
template<typename T>
inline ang::graphics::rect<T>& ang::graphics::rect<T>::operator -= (const ang::graphics::size<T>& sz)
{
right -= min(sz.width, left);
bottom -= min(sz.height, top) ;
return *this;
}
template<typename T>
inline ang::graphics::rect<T>& ang::graphics::rect<T>::operator *= (T k)
{
left *= k;
top *= k;
right *= k;
bottom *= k;
return *this;
}
template<typename T>
inline ang::graphics::rect<T>& ang::graphics::rect<T>::operator /= (T k)
{
left /= k;
top /= k;
right /= k;
bottom /= k;
return *this;
}
template<typename T>
inline ang::graphics::box<T> ang::graphics::box<T>::parse(ang::cstr_t cstr)
{
if (cstr.ptr() == null)
return{ 0,0,0,0,0,0 };
//text::iparser_t parser = text::iparser::get_parser(cstr.encoding());
windex i = 0;
T temp[6] = { 0,0,0,0,0,0 };
text::parser::seek(cstr, i, " [ "_r);
temp[0] = text::parser::to_value<T>(cstr, i);
text::parser::seek(cstr, i, " , "_r);
temp[1] = text::parser::to_value<T>(cstr, i);
text::parser::seek(cstr, i, " , "_r);
temp[2] = text::parser::to_value<T>(cstr, i);
text::parser::seek(cstr, i, " , "_r);
temp[3] = text::parser::to_value<T>(cstr, i);
text::parser::seek(cstr, i, " , "_r);
temp[4] = text::parser::to_value<T>(cstr, i);
text::parser::seek(cstr, i, " , "_r);
temp[5] = text::parser::to_value<T>(cstr, i);
return{ temp[0], temp[1], temp[2], temp[3], temp[4], temp[5] };
}
template<typename T>
inline ang::graphics::box<T>::box()
: left(0)
, top(0)
, front(0)
, right(0)
, bottom(0)
, back(0)
{
}
template<typename T>
inline ang::graphics::box<T>::box(ang::graphics::box<T> const& bx)
: left(bx.left)
, top(bx.top)
, front(bx.front)
, right(bx.right)
, bottom(bx.bottom)
, back(bx.back)
{
}
template<typename T>
inline ang::graphics::box<T>::box(T l, T t, T f, T r, T b, T bk)
: left(l)
, top(t)
, front(f)
, right(r < l ? l : r)
, bottom(b < t ? t : b)
, back(bk < f ? f : bk)
{
}
template<typename T>
inline ang::graphics::box<T>::box(ang::graphics::point3d<T> ltf, ang::graphics::point3d<T> rbb)
: left(ltf.x)
, top(ltf.y)
, front(ltf.z)
, right(rbb.x)
, bottom(rbb.y)
, back(rbb.z)
{
}
template<typename T>
inline ang::graphics::box<T>::box(ang::graphics::point3d<T> ltf, ang::graphics::size3d<T> sz)
: left(ltf.x)
, top(ltf.y)
, front(ltf.z)
, right(ltf.x + sz.width)
, bottom(ltf.y + sz.height)
, back(ltf.z + sz.depth)
{
}
template<typename T>
inline T ang::graphics::box<T>::width()const {
return right - left;
}
template<typename T>
inline void ang::graphics::box<T>::width(T value) {
right = left + forward<T>(value);
}
template<typename T>
inline T ang::graphics::box<T>::height()const {
return bottom - top;
}
template<typename T>
inline void ang::graphics::box<T>::height(T value) {
bottom = top + forward<T>(value);
}
template<typename T>
inline T ang::graphics::box<T>::depth()const {
return back - front;
}
template<typename T>
inline void ang::graphics::box<T>::depth(T value) {
back = front + forward<T>(value);
}
template<typename T>
inline ang::graphics::point3d<T> ang::graphics::box<T>::left_top_front()const {
return point3d<T>(left, top, front);
}
template<typename T>
inline ang::graphics::point3d<T> ang::graphics::box<T>::left_top_back()const {
return point3d<T>(left, top, back);
}
template<typename T>
inline ang::graphics::point3d<T> ang::graphics::box<T>::right_top_front()const {
return point3d<T>(right, top, front);
}
template<typename T>
inline ang::graphics::point3d<T> ang::graphics::box<T>::right_top_back()const {
return point3d<T>(right, top, back);
}
template<typename T>
inline ang::graphics::point3d<T> ang::graphics::box<T>::left_bottom_front()const {
return point3d<T>(left, bottom, front);
}
template<typename T>
inline ang::graphics::point3d<T> ang::graphics::box<T>::left_bottom_back()const {
return point3d<T>(left, bottom, back);
}
template<typename T>
inline ang::graphics::point3d<T> ang::graphics::box<T>::right_bottom_front()const {
return point3d<T>(right, bottom, front);
}
template<typename T>
inline ang::graphics::point3d<T> ang::graphics::box<T>::right_bottom_back()const {
return point3d<T>(right, bottom, back);
}
template<typename T>
inline void ang::graphics::box<T>::move_to(ang::graphics::point3d<T> p)
{
right = right - left + p.x;
bottom = bottom - top + p.y;
back = back - front + p.z;
left = p.x;
top = p.y;
front = p.z;
}
template<typename T>
inline void ang::graphics::box<T>::move_to(T x, T y, T z)
{
right = right - left + x;
bottom = bottom - top + y;
back = back - front + z;
left = x;
top = y;
front = z;
}
template<typename T>
inline void ang::graphics::box<T>::resize(ang::graphics::size3d<T> sz)
{
right = left + sz.width;
bottom = top + sz.height;
back = front + sz.depth;
}
template<typename T>
inline void ang::graphics::box<T>::resize(T cx, T cy, T cz)
{
right = left + cx;
bottom = top + cy;
back = front + cz;
}
template<typename T>
inline void ang::graphics::box<T>::deflate(T l, T t, T f, T r, T b, T bk)
{
left += l;
top += t;
front += f;
right -= r;
bottom -= b;
back -= bk;
}
template<typename T>
inline void ang::graphics::box<T>::inflate(T l, T t, T f, T r, T b, T bk)
{
left -= l;
top -= t;
front -= f;
right += r;
bottom += b;
back += bk;
}
template<typename T>
inline ang::graphics::box<T>& ang::graphics::box<T>::operator = (const ang::graphics::box<T>& bx)
{
left = bx.left;
top = bx.top;
front = bx.front;
right = bx.right;
bottom = bx.bottom;
back = bx.back;
return *this;
}
template<typename T>
inline ang::graphics::box<T>& ang::graphics::box<T>::operator += (const ang::graphics::box<T>& bx)
{
left += bx.left;
top += bx.top;
front += bx.front;
right += bx.right;
bottom += bx.bottom;
back += bx.back;
return *this;
}
template<typename T>
inline ang::graphics::box<T>& ang::graphics::box<T>::operator -= (const ang::graphics::box<T>& bx)
{
left -= bx.left;
top -= bx.top;
front -= bx.front;
right -= bx.right;
bottom -= bx.bottom;
back -= bx.back;
return *this;
}
template<typename T>
inline ang::graphics::box<T>& ang::graphics::box<T>::operator += (const ang::graphics::point3d<T>& pt)
{
left += pt.x;
top += pt.y;
front += pt.z;
right += pt.x;
bottom += pt.y;
back += pt.z;
return *this;
}
template<typename T>
inline ang::graphics::box<T>& ang::graphics::box<T>::operator -= (const ang::graphics::point3d<T>& pt)
{
left -= pt.x;
top -= pt.y;
front -= pt.z;
right -= pt.x;
bottom -= pt.y;
back -= pt.z;
return *this;
}
template<typename T>
inline ang::graphics::box<T>& ang::graphics::box<T>::operator += (const ang::graphics::size3d<T>& sz)
{
right += sz.width;
bottom += sz.height;
back += sz.depth;
return *this;
}
template<typename T>
inline ang::graphics::box<T>& ang::graphics::box<T>::operator -= (const ang::graphics::size3d<T>& sz)
{
right -= min(sz.width, left);
bottom -= min(sz.height, top);
back -= min(sz.depth, front);
return *this;
}
template<typename T>
inline ang::graphics::box<T>& ang::graphics::box<T>::operator *= (T k)
{
left *= k;
top *= k;
front *= k;
right *= k;
bottom *= k;
back *= k;
return *this;
}
template<typename T>
inline ang::graphics::box<T>& ang::graphics::box<T>::operator /= (T k)
{
left /= k;
top /= k;
front /= k;
right /= k;
bottom /= k;
back /= k;
return *this;
}
template<typename T> inline ang::graphics::point<T> ang::graphics::operator + (const ang::graphics::point<T>& a1, const ang::graphics::point<T>& a2) { return{ a1.x + a2.x, a1.y + a2.y }; }
template<typename T> inline ang::graphics::point<T> ang::graphics::operator - (const ang::graphics::point<T>& a1, const ang::graphics::point<T>& a2) { return{ a1.x - a2.x, a1.y - a2.y }; }
template<typename T> inline ang::graphics::point<T> ang::graphics::operator * (const ang::graphics::point<T>& a1, T k) { return{ a1.x * k, a1.y * k }; }
template<typename T> inline ang::graphics::point<T> ang::graphics::operator * (T k, const ang::graphics::point<T>& a2) { return{ a2.x * k, a2.y * k }; }
template<typename T> inline ang::graphics::point<T> ang::graphics::operator / (const ang::graphics::point<T>& a1, T k) { return{ a1.x / k, a1.y / k }; }
template<typename T> inline ang::graphics::size<T> ang::graphics::operator + (const ang::graphics::size<T>& a1, const ang::graphics::size<T>& a2) { return{ a1.width + a2.width, a1.height + a2.height }; }
template<typename T> inline ang::graphics::size<T> ang::graphics::operator - (const ang::graphics::size<T>& a1, const ang::graphics::size<T>& a2) { return{ a1.width - a2.width, a1.height - a2.height }; }
template<typename T> inline ang::graphics::size<T> ang::graphics::operator * (const ang::graphics::size<T>& a1, T k) { return{ a1.width * k, a1.height * k }; }
template<typename T> inline ang::graphics::size<T> ang::graphics::operator * (T k, const ang::graphics::size<T>& a2) { return{ a2.width * k, a2.height * k }; }
template<typename T> inline ang::graphics::size<T> ang::graphics::operator / (const ang::graphics::size<T>& a1, T k) { return{ a1.width / k, a1.height / k }; }
template<typename T> inline ang::graphics::rect<T> ang::graphics::operator + (const ang::graphics::point<T>& a1, const ang::graphics::size<T>& a2) { return{ a1,a2 }; }
template<typename T> inline ang::graphics::rect<T> ang::graphics::operator + (const ang::graphics::size<T>& a1, const ang::graphics::point<T>& a2) { return{ a2,a1 }; }
template<typename T> inline ang::graphics::rect<T> ang::graphics::operator + (const ang::graphics::rect<T>& a1, const ang::graphics::rect<T>& a2) { return{ a1.left + a2.left, a1.top + a2.top, a1.right + a2.right, a1.bottom + a2.bottom }; }
template<typename T> inline ang::graphics::rect<T> ang::graphics::operator - (const ang::graphics::rect<T>& a1, const ang::graphics::rect<T>& a2) { return{ a1.left - a2.left, a1.top - a2.top, a1.right - a2.right, a1.bottom - a2.bottom }; }
template<typename T> inline ang::graphics::rect<T> ang::graphics::operator + (const ang::graphics::rect<T>& a1, const ang::graphics::point<T>& a2) { return{ a1.left + a2.x, a1.top + a2.y, a1.right + a2.x, a1.bottom + a2.y }; }
template<typename T> inline ang::graphics::rect<T> ang::graphics::operator - (const ang::graphics::rect<T>& a1, const ang::graphics::point<T>& a2) { return{ a1.left - a2.x, a1.top - a2.y, a1.right - a2.x, a1.bottom - a2.y }; }
template<typename T> inline ang::graphics::rect<T> ang::graphics::operator + (const ang::graphics::point<T>& a1, const ang::graphics::rect<T>& a2) { return{ a2.left + a1.x, a2.top + a1.y, a2.right + a1.x, a2.bottom + a1.y }; }
template<typename T> inline ang::graphics::rect<T> ang::graphics::operator + (const ang::graphics::rect<T>& a1, const ang::graphics::size<T>& a2) { return{ a1.left, a1.top, a1.right + a2.width, a1.bottom + a2.height }; }
template<typename T> inline ang::graphics::rect<T> ang::graphics::operator - (const ang::graphics::rect<T>& a1, const ang::graphics::size<T>& a2) { return{ a1.left, a1.top, a1.right - a2.width, a1.bottom - a2.height }; }
template<typename T> inline ang::graphics::rect<T> ang::graphics::operator + (const ang::graphics::size<T>& a1, const ang::graphics::rect<T>& a2) { return{ a2.left, a2.top, a2.right + a1.width, a2.bottom + a1.height }; }
template<typename T> inline ang::graphics::rect<T> ang::graphics::operator * (const ang::graphics::rect<T>& a1, T k) { return{ a1.left * k, a1.top * k, a1.right * k, a1.bottom * k }; }
template<typename T> inline ang::graphics::rect<T> ang::graphics::operator * (T k, const ang::graphics::rect<T>& a2) { return{ a2.left * k, a2.top * k, a2.right * k, a2.bottom * k }; }
template<typename T> inline ang::graphics::rect<T> ang::graphics::operator / (const ang::graphics::rect<T>& a1, T k) { return{ a1.left / k, a1.top / k, a1.right / k, a1.bottom / k }; }
template<typename T> inline ang::graphics::point3d<T> ang::graphics::operator + (const ang::graphics::point3d<T>& a1, const ang::graphics::point3d<T>& a2) { return{ a1.x + a2.x, a1.y + a2.y, a1.z + a2.z }; }
template<typename T> inline ang::graphics::point3d<T> ang::graphics::operator - (const ang::graphics::point3d<T>& a1, const ang::graphics::point3d<T>& a2) { return{ a1.x - a2.x, a1.y - a2.y, a1.z - a2.z }; }
template<typename T> inline ang::graphics::point3d<T> ang::graphics::operator * (const ang::graphics::point3d<T>& a1, T k) { return{ a1.x * k, a1.y * k, a1.z * k }; }
template<typename T> inline ang::graphics::point3d<T> ang::graphics::operator * (T k, const ang::graphics::point3d<T>& a2) { return{ a2.x * k, a2.y * k, a2.z * k }; }
template<typename T> inline ang::graphics::point3d<T> ang::graphics::operator / (const ang::graphics::point3d<T>& a1, T k) { return{ a1.x / k, a1.y / k, a1.z / k }; }
template<typename T> inline ang::graphics::size3d<T> ang::graphics::operator + (const ang::graphics::size3d<T>& a1, const ang::graphics::size3d<T>& a2) { return{ a1.width + a2.width, a1.height + a2.height, a1.depth + a2.depth }; }
template<typename T> inline ang::graphics::size3d<T> ang::graphics::operator - (const ang::graphics::size3d<T>& a1, const ang::graphics::size3d<T>& a2) { return{ a1.width - a2.width, a1.height - a2.height, a1.depth - a2.depth }; }
template<typename T> inline ang::graphics::size3d<T> ang::graphics::operator * (const ang::graphics::size3d<T>& a1, T k) { return{ a1.width * k, a1.height * k, a1.depth * k }; }
template<typename T> inline ang::graphics::size3d<T> ang::graphics::operator * (T k, const ang::graphics::size3d<T>& a2) { return{ a2.width * k, a2.height * k, a2.depth * k }; }
template<typename T> inline ang::graphics::size3d<T> ang::graphics::operator / (const ang::graphics::size3d<T>& a1, T k) { return{ a1.width / k, a1.height / k, a1.depth / k }; }
template<typename T> inline ang::graphics::box<T> ang::graphics::operator + (const ang::graphics::point3d<T>& a1, const ang::graphics::size3d<T>& a2) { return{ a1,a2 }; }
template<typename T> inline ang::graphics::box<T> ang::graphics::operator + (const ang::graphics::size3d<T>& a1, const ang::graphics::point3d<T>& a2) { return{ a2,a1 }; }
template<typename T> inline ang::graphics::box<T> ang::graphics::operator + (const ang::graphics::box<T>& a1, const ang::graphics::box<T>& a2) { return{ a1.left + a2.left, a1.top + a2.top, a1.front + a2.front, a1.right + a2.right, a1.bottom + a2.bottom, a1.back + a2.back }; }
template<typename T> inline ang::graphics::box<T> ang::graphics::operator - (const ang::graphics::box<T>& a1, const ang::graphics::box<T>& a2) { return{ a1.left - a2.left, a1.top - a2.top, a1.front - a2.front, a1.right - a2.right, a1.bottom - a2.bottom, a1.back - a2.back }; }
template<typename T> inline ang::graphics::box<T> ang::graphics::operator + (const ang::graphics::box<T>& a1, const ang::graphics::point3d<T>& a2) { return{ a1.left + a2.x, a1.top + a2.y, a1.front + a2.z, a1.right + a2.x, a1.bottom + a2.y, a1.back + a2.z }; }
template<typename T> inline ang::graphics::box<T> ang::graphics::operator - (const ang::graphics::box<T>& a1, const ang::graphics::point3d<T>& a2) { return{ a1.left - a2.x, a1.top - a2.y, a1.front - a2.z, a1.right - a2.x, a1.bottom - a2.y, a1.back - a2.z }; }
template<typename T> inline ang::graphics::box<T> ang::graphics::operator + (const ang::graphics::point3d<T>& a1, const ang::graphics::box<T>& a2) { return{ a2.left + a1.x, a2.top + a1.y, a2.front + a1.z, a2.right + a1.x, a2.bottom + a1.y, a2.back + a1.z }; }
template<typename T> inline ang::graphics::box<T> ang::graphics::operator + (const ang::graphics::box<T>& a1, const ang::graphics::size3d<T>& a2) { return{ a1.left, a1.top, a1.front, a1.right + a2.width, a1.bottom + a2.height, a1.back + a2.depth }; }
template<typename T> inline ang::graphics::box<T> ang::graphics::operator - (const ang::graphics::box<T>& a1, const ang::graphics::size3d<T>& a2) { return{ a1.left, a1.top, a1.front, a1.right - min(a2.width, a1.left), a1.bottom - min(a2.height,a1.top), a1.back - min(a2.depth, a1.front) }; }
template<typename T> inline ang::graphics::box<T> ang::graphics::operator + (const ang::graphics::size3d<T>& a1, const ang::graphics::box<T>& a2) { return{ a2.left, a2.top, a2.front, a2.right + a1.width, a2.bottom + a1.height, a2.back + a1.depth }; }
template<typename T> inline ang::graphics::box<T> ang::graphics::operator * (const ang::graphics::box<T>& a1, T k) { return{ a1.left * k, a1.top * k, a1.front * k, a1.right * k, a1.bottom * k, a1.back * k }; }
template<typename T> inline ang::graphics::box<T> ang::graphics::operator * (T k, const ang::graphics::box<T>& a2) { return{ a2.left * k, a2.top * k, a2.front * k, a2.right * k, a2.bottom * k, a2.back * k }; }
template<typename T> inline ang::graphics::box<T> ang::graphics::operator / (const ang::graphics::box<T>& a1, T k) { return{ a1.left / k, a1.top / k, a1.front / k, a1.right / k, a1.bottom / k, a1.back / k }; }
#endif//__ANG_FOUNDATIONS_INL__
|
/*
* 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.
*/
/* Example usage:
./AtmosphericCorrectionSequencement Input/Romania_Extract.tif \
Output/AtmosphericCorrectionSequencement.tif \
Input/atmosphericCorrectionSequencement_alpha_beta.txt \
Input/atmosphericCorrectionSequencement_solar_illumination.txt \
Input/atmosphericCorrectionSequencement_wavelength_spectral_bands_spot4_1.txt \
27.3 \
4 \
12 \
152.7 \
2.5 \
-77.0 \
1013. \
2.48134 \
0.34400 \
1 \
0.199854 \
2 \
0.020
*/
// \index{otb::VegetationIndex}
// \index{otb::VegetationIndex!header}
//
//
// The following example illustrates the application of atmospheric corrections to
// an optical multispectral image similar to Pleiades.
// These corrections are made in four steps :
// \begin{itemize}
// \item digital number to radiance correction;
// \item radiance to refletance image conversion;
// \item atmospheric correction for TOA (top of atmosphere) to TOC (top of canopy)
// reflectance estimation;
// \item correction of the adjacency effects taking into account the neighborhood contribution.
// \end{itemize}
//
// The manipulation of each class used for the different steps and the
// link with the 6S radiometry library will be explained. In particular,
// the API modifications that have been made in version 4.2 will be
// detailed. There was several reasons behind these modifications :
// \begin{itemize}
// \item fix design issues in the framework that were causing trouble
// when setting the atmospheric parameters
// \item allow the computation of the radiative terms by other libraries
// than 6S (such as SMAC method).
// \item allow the users of the OpticalCalibration application to set
// and override each correction parameter.
// \end{itemize}
//
// Let's look at the minimal code required to use this
// algorithm. First, the following header defining the
// \doxygen{otb}{AtmosphericCorrectionSequencement} class must be
// included. For the numerical to radiance image, radiance to
// refletance image, and reflectance to atmospheric correction image
// corrections and the neighborhood correction, four header files are
// required.
#include "otbImageToRadianceImageFilter.h"
#include "otbRadianceToReflectanceImageFilter.h"
#include "otbReflectanceToSurfaceReflectanceImageFilter.h"
#include "otbSurfaceAdjacencyEffectCorrectionSchemeFilter.h"
// In version 4.2, the class \code{SurfaceAdjacencyEffect6SCorrectionSchemeFilter}
// has been renamed into \doxygen{otb}{SurfaceAdjacencyEffectCorrectionSchemeFilter},
// but it still does the same thing.
//
// This chain uses the 6S radiative
// transfer code to compute radiative terms (for instance upward and
// downward transmittance). The inputs needed are separated into
// two categories :
// \begin{itemize}
// \item The atmospheric correction parameters : physical parameters of the
// atmosphere when the image was taken (for instance : atmospheric pressure,
// water vapour amount, aerosol data, ...). They are stored in the class
// \footnote{Before version 4.2, this class was storing all correction
// parameters} \doxygen{otb}{AtmosphericCorrectionParameters}.
// \item The acquisition correction parameters : sensor related information
// about the way the image was taken, usually available with the image
// metadata (for instance : solar angles, spectral
// sensitivity, ...). They are stored in the class
// \doxygen{otb}{ImageMetadataCorrectionParameters}.
// \end{itemize}
//
// The class \doxygen{otb}{RadiometryCorrectionParametersToAtmisphericRadiativeTerms}
// computes the radiative terms using these two types of parameters. It
// contains a single static method that calls the 6S library. The header
// also includes the classes to manipulate correction parameters and radiative
// terms.
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include <string>
int main(int argc, char* argv[])
{
if (argc != 19)
{
std::cerr << "Missing Parameters " << std::endl;
std::cerr << "Usage: " << argv[0] << std::endl;
std::cerr << " inputImage outputImage atmosphericCorrectionSequencement_alpha_beta.txt atmosphericCorrectionSequencement_solar_illumination.txt "
"atmosphericCorrectionSequencement_wavelength_spectral_bands_spot4_1.txt SolarZenithalAngle day month SolarAzimuthalAngle "
"ViewingZenithalAngle ViewingAzimuthalAngle AtmosphericPresure WaterVaporAmount OzoneAmount AerosolModel AerosolOpticalThickness "
"WindowRadiusForAdjacencyCorrection PixelSpacing"
<< std::endl;
std::cerr << std::endl;
return 1;
}
// Image types are now defined using pixel types and
// dimension. The input image is defined as an \doxygen{otb}{VectorImage},
// the output image is a \doxygen{otb}{VectorImage}. To simplify, input and
// output image types are the same one.
const unsigned int Dimension = 2;
using PixelType = double;
using ImageType = otb::VectorImage<PixelType, Dimension>;
// We instantiate reader and writer types
using ReaderType = otb::ImageFileReader<ImageType>;
using WriterType = otb::ImageFileWriter<ImageType>;
ReaderType::Pointer reader = ReaderType::New();
// The \code{GenerateOutputInformation()} reader method is called
// to know the number of component per pixel of the image. It is
// recommended to
// place \code{GenerateOutputInformation} calls in a \code{try/catch} block in case
// errors occur and exceptions are thrown.
reader->SetFileName(argv[1]);
try
{
reader->GenerateOutputInformation();
}
catch (itk::ExceptionObject& excep)
{
std::cerr << "Exception caught !" << std::endl;
std::cerr << excep << std::endl;
}
catch (...)
{
std::cout << "Unknown exception !" << std::endl;
return EXIT_FAILURE;
}
unsigned int nbOfComponent = reader->GetOutput()->GetNumberOfComponentsPerPixel();
//-------------------------------
// The \doxygen{otb}{ImageToRadianceImageFilter}
// type is defined and instancied. This class uses a functor applied
// to each component of each pixel ($\mathbf{X^{k}}$) whose formula is:
//
// \begin{equation}
// \mathbf{L_{TOA}^{k}} = \frac{ X^{k} } { \alpha_{k} } + \beta_{k}.
// \end{equation}
//
// Where :
// \begin{itemize}
// \item $\mathbf{L_{TOA}^{k}}$ is the incident radiance (in
// $W.m^{-2}.sr^{-1}.\mu m^{-1}$);
// \item $\mathbf{X^{k}}$ is the measured digital number (ie. the input image pixel component);
// \item $\alpha_{k}$ is the absolute calibration gain for the channel k;
// \item $\beta_{k}$ is the absolute calibration bias for the channel k.
// \end{itemize}
using ImageToRadianceImageFilterType = otb::ImageToRadianceImageFilter<ImageType, ImageType>;
ImageToRadianceImageFilterType::Pointer filterImageToRadiance = ImageToRadianceImageFilterType::New();
using VectorType = ImageToRadianceImageFilterType::VectorType;
VectorType alpha(nbOfComponent);
VectorType beta(nbOfComponent);
alpha.Fill(0);
beta.Fill(0);
std::ifstream fin;
fin.open(argv[3]);
double dalpha(0.), dbeta(0.);
for (unsigned int i = 0; i < nbOfComponent; ++i)
{
fin >> dalpha;
fin >> dbeta;
alpha[i] = dalpha;
beta[i] = dbeta;
}
fin.close();
// Here, $\alpha$ and $\beta$ are read from an ASCII file given in input,
// stored in a vector and passed to the class.
filterImageToRadiance->SetAlpha(alpha);
filterImageToRadiance->SetBeta(beta);
//-------------------------------
// The \doxygen{otb}{RadianceToReflectanceImageFilter}
// type is defined and instancied.
// This class used a functor applied to each component of each pixel
// of the radiance filter output ($\mathbf{L_{TOA}^{k}}$):
//
// \begin{equation}
// \rho_{TOA}^{k} = \frac{ \pi.\mathbf{L_{TOA}^{k}} } { E_{S}^{k}.cos(\theta_{S}).d/d_{0} }.
// \end{equation}
//
// Where :
// \begin{itemize}
// \item $\mathbf{\rho_{TOA}^{k}}$ is the reflectance measured by the sensor;
// \item $\theta_{S}$ is the zenithal solar angle in degrees;
// \item $E_{S}^{k}$ is the solar illumination out of the atmosphere measured at a distance
// $d_{0}$ from the Earth;
// \item $d/d_{0}$ is the ratio between the Earth-Sun distance at
// the acquisition date and the mean Earth-Sun distance. The ratio can be directly
// given to the class or computed using a 6S routine. TODO
// In the last case (that is the one of this example), the user has to precise
// the month and the day of the acquisition.
// \end{itemize}
using RadianceToReflectanceImageFilterType = otb::RadianceToReflectanceImageFilter<ImageType, ImageType>;
RadianceToReflectanceImageFilterType::Pointer filterRadianceToReflectance = RadianceToReflectanceImageFilterType::New();
using VectorType = RadianceToReflectanceImageFilterType::VectorType;
VectorType solarIllumination(nbOfComponent);
solarIllumination.Fill(0);
fin.open(argv[4]);
double dsolarIllumination(0.);
for (unsigned int i = 0; i < nbOfComponent; ++i)
{
fin >> dsolarIllumination;
solarIllumination[i] = dsolarIllumination;
}
fin.close();
// The solar illumination is read from a ASCII file given in input,
// stored in a vector
// and given to the class.
// Day, month and zenital solar angle are inputs and can be directly given to the class.
filterRadianceToReflectance->SetZenithalSolarAngle(static_cast<double>(atof(argv[6])));
filterRadianceToReflectance->SetDay(atoi(argv[7]));
filterRadianceToReflectance->SetMonth(atoi(argv[8]));
filterRadianceToReflectance->SetSolarIllumination(solarIllumination);
//-------------------------------
// At this step of the chain, radiative information are nedeed to compute
// the contribution of the atmosphere (such as atmosphere transmittance
// and reflectance). Those information will be computed from different
// correction parameters stored in \doxygen{otb}{AtmosphericCorrectionParameters}
// and \doxygen{otb}{ImageMetadataCorrectionParameters} instances.
// These {\em containers} will be given to the static function \texttt{Compute}
// from \doxygen{otb}{RadiometryCorrectionParametersToAtmosphericRadiativeTerms}
// class, which will call a 6S routine that will compute the needed
// radiometric information and store them in a
// \doxygen{otb}{AtmosphericRadiativeTerms} class instance.
// For this,
// \doxygen{otb}{RadiometryCorrectionParametersToAtmosphericRadiativeTerms},
// \doxygen{otb}{AtmosphericCorrectionParameters},
// \doxygen{otb}{ImageMetadataCorrectionParameters} and
// \doxygen{otb}{AtmosphericRadiativeTerms}
// types are defined and instancied.
using RadiometryCorrectionParametersToRadiativeTermsType = otb::RadiometryCorrectionParametersToAtmosphericRadiativeTerms;
using AtmosphericCorrectionParametersType = otb::AtmosphericCorrectionParameters;
using AcquisitionCorrectionParametersType = otb::ImageMetadataCorrectionParameters;
using AtmosphericRadiativeTermsType = otb::AtmosphericRadiativeTerms;
using AerosolModelType = AtmosphericCorrectionParametersType::AerosolModelType;
using FilterFunctionValuesType = otb::FilterFunctionValues;
using ValuesVectorType = FilterFunctionValuesType::ValuesVectorType;
AtmosphericCorrectionParametersType::Pointer dataAtmosphericCorrectionParameters = AtmosphericCorrectionParametersType::New();
AcquisitionCorrectionParametersType::Pointer dataAcquisitionCorrectionParameters = AcquisitionCorrectionParametersType::New();
AtmosphericRadiativeTermsType::Pointer dataAtmosphericRadiativeTerms = AtmosphericRadiativeTermsType::New();
float minSpectralValue(0.);
float maxSpectralValue(0.);
float userStep(0.);
float value(0.);
unsigned int nbBands(0);
unsigned int nbValuesPerBand(0);
std::string sString;
ValuesVectorType vector;
fin.open(argv[5]);
fin >> nbBands;
for (unsigned int i = 0; i < nbBands; ++i)
{
vector.clear();
fin >> sString;
fin >> minSpectralValue;
fin >> maxSpectralValue;
fin >> userStep;
fin >> nbValuesPerBand;
for (unsigned int j = 0; j < nbValuesPerBand; ++j)
{
fin >> value;
vector.push_back(value);
}
FilterFunctionValuesType::Pointer functionValues = FilterFunctionValuesType::New();
functionValues->SetFilterFunctionValues(vector);
functionValues->SetMinSpectralValue(minSpectralValue);
functionValues->SetMaxSpectralValue(maxSpectralValue);
functionValues->SetUserStep(userStep);
dataAcquisitionCorrectionParameters->SetWavelengthSpectralBandWithIndex(i, functionValues);
}
fin.close();
// The \doxygen{otb}{ImageMetadataCorrectionParameters} class stores
// several parameters that are generally present in the image metadata :
// \begin{itemize}
// \item The zenithal and azimutal solar angles that describe the solar incidence
// configuration (in degrees);
// \item The zenithal and azimuthal viewing angles that describe the viewing
// direction (in degrees);
// \item The month and the day of the acquisition;
// \item The filter function that is the values of the filter function for one
// spectral band, from $\lambda_{inf}$ to $\lambda_{sup}$ by step of 2.5 nm.
// One filter function by channel is required.
// This last parameter are read in text files, the other one are directly given to the class.
// \end{itemize}
//
// When this container is not set in the ReflectanceToSurfaceReflectance
// filter, it is automatically filled using the image metadata. The
// following lines show that it is also possible to set the values manually.
// Set parameters
dataAcquisitionCorrectionParameters->SetSolarZenithalAngle(static_cast<double>(atof(argv[6])));
dataAcquisitionCorrectionParameters->SetSolarAzimutalAngle(static_cast<double>(atof(argv[9])));
dataAcquisitionCorrectionParameters->SetViewingZenithalAngle(static_cast<double>(atof(argv[10])));
dataAcquisitionCorrectionParameters->SetViewingAzimutalAngle(static_cast<double>(atof(argv[11])));
dataAcquisitionCorrectionParameters->SetMonth(atoi(argv[8]));
dataAcquisitionCorrectionParameters->SetDay(atoi(argv[7]));
// The \doxygen{otb}{AtmosphericCorrectionParameters} class stores
// physical parameters of the atmosphere that are not impacted
// by the viewing angles of the image :
// \begin{itemize}
// \item The atmospheric pressure;
// \item The water vapor amount, that is, the total water vapor content over vertical
// atmospheric column;
// \item The ozone amount that is the Stratospheric ozone layer content;
// \item The aerosol model that is the kind of particles (no aerosol, continental,
// maritime, urban, desertic);
// \item The aerosol optical thickness at 550 nm that is the is the Radiative impact
// of aerosol for the reference wavelength 550 nm;
// \end{itemize}
dataAtmosphericCorrectionParameters->SetAtmosphericPressure(static_cast<double>(atof(argv[12])));
dataAtmosphericCorrectionParameters->SetWaterVaporAmount(static_cast<double>(atof(argv[13])));
dataAtmosphericCorrectionParameters->SetOzoneAmount(static_cast<double>(atof(argv[14])));
AerosolModelType aerosolModel = static_cast<AerosolModelType>(::atoi(argv[15]));
dataAtmosphericCorrectionParameters->SetAerosolModel(aerosolModel);
dataAtmosphericCorrectionParameters->SetAerosolOptical(static_cast<double>(atof(argv[16])));
// Once those parameters are loaded, they are used by the 6S library
// to compute the needed radiometric information. The
// RadiometryCorrectionParametersToAtmosphericRadiativeTerms class
// provides a static function to perform this step\footnote{Before version
// 4.2, it was done with the filter
// AtmosphericCorrectionParametersTo6SAtmosphericRadiativeTerms}.
AtmosphericRadiativeTermsType::Pointer atmosphericRadiativeTerms =
RadiometryCorrectionParametersToRadiativeTermsType::Compute(dataAtmosphericCorrectionParameters, dataAcquisitionCorrectionParameters);
// The output is stored inside an instance of the
// \doxygen{otb}{AtmosphericRadiativeTerms} class.
// This class contains (for each channel of the image)
// \begin{itemize}
// \item The Intrinsic atmospheric reflectance that takes into account for the molecular scattering
// and the aerosol scattering attenuated by water vapor absorption;
// \item The spherical albedo of the atmosphere;
// \item The total gaseous transmission (for all species);
// \item The total transmittance of the atmosphere from sun to ground (downward transmittance)
// and from ground to space sensor (upward transmittance).
// \end{itemize}
//-------------------------------
// Atmospheric corrections can now start.
// First, an instance of \doxygen{otb}{ReflectanceToSurfaceReflectanceImageFilter} is created.
using ReflectanceToSurfaceReflectanceImageFilterType = otb::ReflectanceToSurfaceReflectanceImageFilter<ImageType, ImageType>;
ReflectanceToSurfaceReflectanceImageFilterType::Pointer filterReflectanceToSurfaceReflectanceImageFilter =
ReflectanceToSurfaceReflectanceImageFilterType::New();
// The aim of the atmospheric correction is to invert the surface reflectance
// (for each pixel of the input image) from the TOA reflectance and from simulations
// of the atmospheric radiative functions corresponding to the geometrical conditions
// of the observation and to the atmospheric components.
// The process required to be applied on each pixel of the image, band by band with
// the following formula:
//
// \begin{equation}
// \rho_{S}^{unif} = \frac{ \mathbf{A} }{ 1 + Sx\mathbf{A} }
// \end{equation}
// Where,
// \begin{equation}
// \mathbf{A} = \frac{ \rho_{TOA} - \rho_{atm} }{ T(\mu_{S}).T(\mu_{V}).t_{g}^{all gas} }
// \end{equation}
//
// With :
// \begin{itemize}
// \item $\rho_{TOA}$ is the reflectance at the top of the atmosphere;
// \item $\rho_{S}^{unif}$ is the ground reflectance under assumption
// of a lambertian surface and an uniform environment;
// \item $\rho_{atm}$ is the intrinsic atmospheric reflectance;
// \item $t_{g}^{all gas}$ is the spherical albedo of the atmosphere;
// \item $T(\mu_{S})$ is the downward transmittance;
// \item $T(\mu_{V})$ is the upward transmittance.
// \end{itemize}
// All those parameters are contained in the AtmosphericRadiativeTerms
// container.
filterReflectanceToSurfaceReflectanceImageFilter->SetAtmosphericRadiativeTerms(atmosphericRadiativeTerms);
//-------------------------------
// Next (and last step) is the neighborhood correction.
// For this, the SurfaceAdjacencyEffectCorrectionSchemeFilter class is used.
// The previous surface reflectance inversion is performed under the assumption of a
// homogeneous ground environment. The following step allows correcting the adjacency
// effect on the radiometry of pixels. The method is based on the decomposition of
// the observed signal as the summation of the own contribution of the target pixel and
// of the contributions of neighbored pixels moderated by their distance to the target pixel.
// A simplified relation may be :
// \begin{equation}
// \rho{S} = \frac{ \rho_{S}^{unif}.T(\mu_{V}) - <\rho{S}>.t_{d}(\mu_{V}) }{ exp(-\delta/\mu_{V}) }
// \end{equation}
// With :
// \begin{itemize}
// \item $\rho_{S}^{unif}$ is the ground reflectance under assumption of an homogeneous environment;
// \item $T(\mu_{V})$ is the upward transmittance;
// \item $t_{d}(\mu_{S})$ is the upward diffus transmittance;
// \item $exp(-\delta/\mu_{V})$ is the upward direct transmittance;
// \item $\rho_{S}$ is the environment contribution to the pixel target reflectance in the total
// observed signal.
// \begin{equation}
// \rho{S} = \sum{j}\sum{i}f(r(i, j))\times \rho_{S}^{unif}(i, j)
// \end{equation}
// where,
// \begin{itemize}
// \item r(i, j) is the distance between the pixel(i, j) and the central pixel of the window in $km$;
// \item f(r) is the global environment function.
// \begin{equation}
// f(r) = \frac{t_{d}^{R}(\mu_{V}).f_{R}(r)+t_{d}^{A}(\mu_{V}).f_{A}(r)}{ t_{d}(\mu_{V}) }
// \end{equation}
// \end{itemize}
// \end{itemize}
// The neighborhood consideration window size is given by the window radius.
//
// An instance of \doxygen{otb}{SurfaceAdjacencyEffectCorrectionSchemeFilter}
// is created. This class has an interface quite similar to
// \doxygen{otb}{ReflectanceToSurfaceReflectance}. They both need radiative terms
// (\doxygen{otb}{AtmosphericRadiativeTerms}), so it is possible to compute
// them outside the filter and set them directly in the filter. The other
// solution is to give as input the two parameters containers ("atmospheric"
// and "acquisition" parameters), then the filter will compute the radiative
// terms internally. If the "acquisition" correction parameters are not
// present, the filter will try to get them from the image metadata.
using SurfaceAdjacencyEffectCorrectionSchemeFilterType = otb::SurfaceAdjacencyEffectCorrectionSchemeFilter<ImageType, ImageType>;
SurfaceAdjacencyEffectCorrectionSchemeFilterType::Pointer filterSurfaceAdjacencyEffectCorrectionSchemeFilter =
SurfaceAdjacencyEffectCorrectionSchemeFilterType::New();
// Four inputs are needed to compute the neighborhood contribution:
// \begin{itemize}
// \item The radiative terms (stored in the AtmosphericRadiativeTerms container);
// \item The zenithal viewing angle;
// \item The neighborhood window radius;
// \item The pixel spacing in kilometers.
// \end{itemize}
filterSurfaceAdjacencyEffectCorrectionSchemeFilter->SetAtmosphericRadiativeTerms(atmosphericRadiativeTerms);
filterSurfaceAdjacencyEffectCorrectionSchemeFilter->SetZenithalViewingAngle(dataAcquisitionCorrectionParameters->GetViewingZenithalAngle());
filterSurfaceAdjacencyEffectCorrectionSchemeFilter->SetWindowRadius(atoi(argv[17]));
filterSurfaceAdjacencyEffectCorrectionSchemeFilter->SetPixelSpacingInKilometers(static_cast<double>(atof(argv[18])));
//-------------------------------
WriterType::Pointer writer = WriterType::New();
// At this step, each filter of the chain is instancied and every one has its
// input parameters set. A name can be given to the output image, each filter
// can be linked to the next one and create the final processing chain.
writer->SetFileName(argv[2]);
filterImageToRadiance->SetInput(reader->GetOutput());
filterRadianceToReflectance->SetInput(filterImageToRadiance->GetOutput());
filterReflectanceToSurfaceReflectanceImageFilter->SetInput(filterRadianceToReflectance->GetOutput());
filterSurfaceAdjacencyEffectCorrectionSchemeFilter->SetInput(filterReflectanceToSurfaceReflectanceImageFilter->GetOutput());
writer->SetInput(filterSurfaceAdjacencyEffectCorrectionSchemeFilter->GetOutput());
// The invocation of the \code{Update()} method on the writer triggers the
// execution of the pipeline. It is recommended to place this call in a
// \code{try/catch} block in case errors occur and exceptions are thrown.
try
{
writer->Update();
}
catch (itk::ExceptionObject& excep)
{
std::cerr << "Exception caught !" << std::endl;
std::cerr << excep << std::endl;
}
catch (...)
{
std::cout << "Unknown exception !" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2017-2017 The BitenX Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparams.h"
#include "validation.h"
#include "messagesigner.h"
#include "net_processing.h"
#include "spork.h"
#include <boost/lexical_cast.hpp>
class CSporkMessage;
class CSporkManager;
CSporkManager sporkManager;
std::map<uint256, CSporkMessage> mapSporks;
void CSporkManager::ProcessSpork(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
if(fLiteMode) return; // disable all BitenX specific functionality
if (strCommand == NetMsgType::SPORK) {
CSporkMessage spork;
vRecv >> spork;
uint256 hash = spork.GetHash();
std::string strLogMsg;
{
LOCK(cs_main);
pfrom->setAskFor.erase(hash);
if(!chainActive.Tip()) return;
strLogMsg = strprintf("SPORK -- hash: %s id: %d value: %10d bestHeight: %d peer=%d", hash.ToString(), spork.nSporkID, spork.nValue, chainActive.Height(), pfrom->id);
}
if(mapSporksActive.count(spork.nSporkID)) {
if (mapSporksActive[spork.nSporkID].nTimeSigned >= spork.nTimeSigned) {
LogPrint("spork", "%s seen\n", strLogMsg);
return;
} else {
LogPrintf("%s updated\n", strLogMsg);
}
} else {
LogPrintf("%s new\n", strLogMsg);
}
if(!spork.CheckSignature()) {
LogPrintf("CSporkManager::ProcessSpork -- invalid signature\n");
Misbehaving(pfrom->GetId(), 100);
return;
}
mapSporks[hash] = spork;
mapSporksActive[spork.nSporkID] = spork;
spork.Relay();
//does a task if needed
ExecuteSpork(spork.nSporkID, spork.nValue);
} else if (strCommand == NetMsgType::GETSPORKS) {
std::map<int, CSporkMessage>::iterator it = mapSporksActive.begin();
while(it != mapSporksActive.end()) {
g_connman->PushMessage(pfrom, NetMsgType::SPORK, it->second);
it++;
}
}
}
void CSporkManager::ExecuteSpork(int nSporkID, int nValue)
{
//correct fork via spork technology
if(nSporkID == SPORK_12_RECONSIDER_BLOCKS && nValue > 0) {
// allow to reprocess 24h of blocks max, which should be enough to resolve any issues
int64_t nMaxBlocks = 576;
// this potentially can be a heavy operation, so only allow this to be executed once per 10 minutes
int64_t nTimeout = 10 * 60;
static int64_t nTimeExecuted = 0; // i.e. it was never executed before
if(GetTime() - nTimeExecuted < nTimeout) {
LogPrint("spork", "CSporkManager::ExecuteSpork -- ERROR: Trying to reconsider blocks, too soon - %d/%d\n", GetTime() - nTimeExecuted, nTimeout);
return;
}
if(nValue > nMaxBlocks) {
LogPrintf("CSporkManager::ExecuteSpork -- ERROR: Trying to reconsider too many blocks %d/%d\n", nValue, nMaxBlocks);
return;
}
LogPrintf("CSporkManager::ExecuteSpork -- Reconsider Last %d Blocks\n", nValue);
ReprocessBlocks(nValue);
nTimeExecuted = GetTime();
}
}
bool CSporkManager::UpdateSpork(int nSporkID, int64_t nValue)
{
CSporkMessage spork = CSporkMessage(nSporkID, nValue, GetTime());
if(spork.Sign(strMasterPrivKey)) {
spork.Relay();
mapSporks[spork.GetHash()] = spork;
mapSporksActive[nSporkID] = spork;
return true;
}
return false;
}
// grab the spork, otherwise say it's off
bool CSporkManager::IsSporkActive(int nSporkID)
{
int64_t r = -1;
if(mapSporksActive.count(nSporkID)){
r = mapSporksActive[nSporkID].nValue;
} else {
switch (nSporkID) {
case SPORK_2_INSTAPAY_ENABLED: r = SPORK_2_INSTAPAY_ENABLED_DEFAULT; break;
case SPORK_3_INSTAPAY_BLOCK_FILTERING: r = SPORK_3_INSTAPAY_BLOCK_FILTERING_DEFAULT; break;
case SPORK_5_INSTAPAY_MAX_VALUE: r = SPORK_5_INSTAPAY_MAX_VALUE_DEFAULT; break;
case SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT: r = SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT_DEFAULT; break;
case SPORK_9_SUPERBLOCKS_ENABLED: r = SPORK_9_SUPERBLOCKS_ENABLED_DEFAULT; break;
case SPORK_10_MASTERNODE_PAY_UPDATED_NODES: r = SPORK_10_MASTERNODE_PAY_UPDATED_NODES_DEFAULT; break;
case SPORK_12_RECONSIDER_BLOCKS: r = SPORK_12_RECONSIDER_BLOCKS_DEFAULT; break;
case SPORK_13_OLD_SUPERBLOCK_FLAG: r = SPORK_13_OLD_SUPERBLOCK_FLAG_DEFAULT; break;
case SPORK_14_REQUIRE_SENTINEL_FLAG: r = SPORK_14_REQUIRE_SENTINEL_FLAG_DEFAULT; break;
default:
LogPrint("spork", "CSporkManager::IsSporkActive -- Unknown Spork ID %d\n", nSporkID);
r = 4070908800ULL; // 2099-1-1 i.e. off by default
break;
}
}
return r < GetTime();
}
// grab the value of the spork on the network, or the default
int64_t CSporkManager::GetSporkValue(int nSporkID)
{
if (mapSporksActive.count(nSporkID))
return mapSporksActive[nSporkID].nValue;
switch (nSporkID) {
case SPORK_2_INSTAPAY_ENABLED: return SPORK_2_INSTAPAY_ENABLED_DEFAULT;
case SPORK_3_INSTAPAY_BLOCK_FILTERING: return SPORK_3_INSTAPAY_BLOCK_FILTERING_DEFAULT;
case SPORK_5_INSTAPAY_MAX_VALUE: return SPORK_5_INSTAPAY_MAX_VALUE_DEFAULT;
case SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT: return SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT_DEFAULT;
case SPORK_9_SUPERBLOCKS_ENABLED: return SPORK_9_SUPERBLOCKS_ENABLED_DEFAULT;
case SPORK_10_MASTERNODE_PAY_UPDATED_NODES: return SPORK_10_MASTERNODE_PAY_UPDATED_NODES_DEFAULT;
case SPORK_12_RECONSIDER_BLOCKS: return SPORK_12_RECONSIDER_BLOCKS_DEFAULT;
case SPORK_13_OLD_SUPERBLOCK_FLAG: return SPORK_13_OLD_SUPERBLOCK_FLAG_DEFAULT;
case SPORK_14_REQUIRE_SENTINEL_FLAG: return SPORK_14_REQUIRE_SENTINEL_FLAG_DEFAULT;
default:
LogPrint("spork", "CSporkManager::GetSporkValue -- Unknown Spork ID %d\n", nSporkID);
return -1;
}
}
int CSporkManager::GetSporkIDByName(std::string strName)
{
if (strName == "SPORK_2_INSTAPAY_ENABLED") return SPORK_2_INSTAPAY_ENABLED;
if (strName == "SPORK_3_INSTAPAY_BLOCK_FILTERING") return SPORK_3_INSTAPAY_BLOCK_FILTERING;
if (strName == "SPORK_5_INSTAPAY_MAX_VALUE") return SPORK_5_INSTAPAY_MAX_VALUE;
if (strName == "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT") return SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT;
if (strName == "SPORK_9_SUPERBLOCKS_ENABLED") return SPORK_9_SUPERBLOCKS_ENABLED;
if (strName == "SPORK_10_MASTERNODE_PAY_UPDATED_NODES") return SPORK_10_MASTERNODE_PAY_UPDATED_NODES;
if (strName == "SPORK_12_RECONSIDER_BLOCKS") return SPORK_12_RECONSIDER_BLOCKS;
if (strName == "SPORK_13_OLD_SUPERBLOCK_FLAG") return SPORK_13_OLD_SUPERBLOCK_FLAG;
if (strName == "SPORK_14_REQUIRE_SENTINEL_FLAG") return SPORK_14_REQUIRE_SENTINEL_FLAG;
LogPrint("spork", "CSporkManager::GetSporkIDByName -- Unknown Spork name '%s'\n", strName);
return -1;
}
std::string CSporkManager::GetSporkNameByID(int nSporkID)
{
switch (nSporkID) {
case SPORK_2_INSTAPAY_ENABLED: return "SPORK_2_INSTAPAY_ENABLED";
case SPORK_3_INSTAPAY_BLOCK_FILTERING: return "SPORK_3_INSTAPAY_BLOCK_FILTERING";
case SPORK_5_INSTAPAY_MAX_VALUE: return "SPORK_5_INSTAPAY_MAX_VALUE";
case SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT: return "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT";
case SPORK_9_SUPERBLOCKS_ENABLED: return "SPORK_9_SUPERBLOCKS_ENABLED";
case SPORK_10_MASTERNODE_PAY_UPDATED_NODES: return "SPORK_10_MASTERNODE_PAY_UPDATED_NODES";
case SPORK_12_RECONSIDER_BLOCKS: return "SPORK_12_RECONSIDER_BLOCKS";
case SPORK_13_OLD_SUPERBLOCK_FLAG: return "SPORK_13_OLD_SUPERBLOCK_FLAG";
case SPORK_14_REQUIRE_SENTINEL_FLAG: return "SPORK_14_REQUIRE_SENTINEL_FLAG";
default:
LogPrint("spork", "CSporkManager::GetSporkNameByID -- Unknown Spork ID %d\n", nSporkID);
return "Unknown";
}
}
bool CSporkManager::SetPrivKey(std::string strPrivKey)
{
CSporkMessage spork;
spork.Sign(strPrivKey);
if(spork.CheckSignature()){
// Test signing successful, proceed
LogPrintf("CSporkManager::SetPrivKey -- Successfully initialized as spork signer\n");
strMasterPrivKey = strPrivKey;
return true;
} else {
return false;
}
}
bool CSporkMessage::Sign(std::string strSignKey)
{
CKey key;
CPubKey pubkey;
std::string strError = "";
std::string strMessage = boost::lexical_cast<std::string>(nSporkID) + boost::lexical_cast<std::string>(nValue) + boost::lexical_cast<std::string>(nTimeSigned);
if(!CMessageSigner::GetKeysFromSecret(strSignKey, key, pubkey)) {
LogPrintf("CSporkMessage::Sign -- GetKeysFromSecret() failed, invalid spork key %s\n", strSignKey);
return false;
}
if(!CMessageSigner::SignMessage(strMessage, vchSig, key)) {
LogPrintf("CSporkMessage::Sign -- SignMessage() failed\n");
return false;
}
if(!CMessageSigner::VerifyMessage(pubkey, vchSig, strMessage, strError)) {
LogPrintf("CSporkMessage::Sign -- VerifyMessage() failed, error: %s\n", strError);
return false;
}
return true;
}
bool CSporkMessage::CheckSignature()
{
//note: need to investigate why this is failing
std::string strError = "";
std::string strMessage = boost::lexical_cast<std::string>(nSporkID) + boost::lexical_cast<std::string>(nValue) + boost::lexical_cast<std::string>(nTimeSigned);
CPubKey pubkey(ParseHex(Params().SporkPubKey()));
if(!CMessageSigner::VerifyMessage(pubkey, vchSig, strMessage, strError)) {
LogPrintf("CSporkMessage::CheckSignature -- VerifyMessage() failed, error: %s\n", strError);
return false;
}
return true;
}
void CSporkMessage::Relay()
{
CInv inv(MSG_SPORK, GetHash());
g_connman->RelayInv(inv);
}
|
#include "GamePCH.h"
#include "GameObjects/GameObject.h"
#include "UIObject.h"
#include "GameObjects/UI/ScoreNumber.h"
#include "GameObjects/UI/PokeBall.h"
#include "GameplayHelpers/TileMap.h"
#include "GameplayHelpers/TileMapExtras.h"
#include "Mesh/Mesh.h"
#include "Game/Game.h"
#include "GameObjects/Trainer.h"
UIObject::UIObject(ResourceManager * aResourceManager, TileMap* aTileMap, GameCore * myGame, Mesh * myMesh, GLuint aTexture) : GameObject(myGame, myMesh, aTexture)
{
m_PokeBall = new PokeBall(aResourceManager, aTileMap, myGame, myMesh, aTexture);
m_ScoreNumber = new ScoreNumber(aResourceManager, aTileMap, myGame, myMesh, aTexture);
m_PokeBall->SetPosition(vec2(m_Position.x - 14.0f, m_Position.y + 12.5f));
m_ScoreNumber->SetPosition(vec2(m_Position.x - 12.5f, m_Position.y + 12.5f));
}
UIObject::~UIObject()
{
delete m_PokeBall;
delete m_ScoreNumber;
}
void UIObject::Update(float deltatime)
{
}
void UIObject::Draw(vec2 camPos, vec2 camProjection)
{
m_PokeBall->Draw(camPos, camProjection);
m_ScoreNumber->Draw(camPos, camProjection);
}
void UIObject::SetScore(int aScore)
{
m_ScoreNumber->SetScore(aScore);
}
|
#include "EventFilter/L1TRawToDigi/interface/OmtfRpcPacker.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/ESTransientHandle.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "CondFormats/RPCObjects/interface/RPCReadOutMapping.h"
#include "EventFilter/RPCRawToDigi/interface/RPCRecordFormatter.h"
#include "EventFilter/RPCRawToDigi/interface/RPCPackingModule.h"
#include "EventFilter/RPCRawToDigi/interface/DebugDigisPrintout.h"
#include "CondFormats/RPCObjects/interface/RPCEMap.h"
#include "CondFormats/DataRecord/interface/RPCEMapRcd.h"
#include "EventFilter/L1TRawToDigi/interface/OmtfRpcDataWord64.h"
namespace omtf {
void RpcPacker::initCabling(const edm::EventSetup& es) {
edm::ESTransientHandle<RPCEMap> readoutMapping;
es.get<RPCEMapRcd>().get(readoutMapping);
thePactCabling.reset(readoutMapping->convert());
LogDebug("OmtfPacker") << " Has PACT readout map, VERSION: " << thePactCabling->version() << std::endl;
}
void RpcPacker::init(const edm::EventSetup& es) {
initCabling(es);
RpcLinkMap omtfLink2Ele;
omtfLink2Ele.init(es);
thePact2Omtf = translatePact2Omtf(omtfLink2Ele, thePactCabling.get());
}
void RpcPacker::init(const edm::EventSetup& es, const std::string& connectionFile) {
initCabling(es);
RpcLinkMap omtfLink2Ele;
omtfLink2Ele.init(connectionFile);
thePact2Omtf = translatePact2Omtf(omtfLink2Ele, thePactCabling.get());
}
void RpcPacker::pack(const RPCDigiCollection* digis, FedAmcRawsMap& raws) {
LogTrace("") << " HERE HERE !!! RPC PACKER" << rpcrawtodigi::DebugDigisPrintout()(digis);
for (int dcc = 790; dcc <= 792; dcc++) {
RPCRecordFormatter formatter(dcc, thePactCabling.get());
const std::vector<rpcrawtodigi::EventRecords>& merged =
RPCPackingModule::eventRecords(dcc, 200, digis, formatter);
LogTrace("") << " SIZE OF MERGED, for DCC=" << dcc << " is: " << merged.size() << std::endl;
for (const auto& rpcEvent : merged) {
RpcDataWord64 data;
data.bxNum_ = rpcEvent.dataToTriggerDelay();
data.frame1_ = rpcEvent.recordCD().data();
LinkBoardElectronicIndex rpcEle = {
dcc, rpcEvent.recordSLD().rmb(), rpcEvent.recordSLD().tbLinkInputNumber(), rpcEvent.recordCD().lbInLink()};
auto it = thePact2Omtf.find(rpcEle);
if (it != thePact2Omtf.end()) {
const EleIndex& omtfEle1 = it->second.first;
const EleIndex& omtfEle2 = it->second.second;
if (omtfEle1.fed()) {
data.linkNum_ = omtfEle1.link();
raws[std::make_pair(omtfEle1.fed(), omtfEle1.amc() * 2 - 1)].push_back(data.rawData);
}
if (omtfEle2.fed()) {
data.linkNum_ = omtfEle2.link();
raws[std::make_pair(omtfEle2.fed(), omtfEle2.amc() * 2 - 1)].push_back(data.rawData);
}
}
}
}
}
}; // namespace omtf
|
/*
* ======================================================================
* Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
* Licensed under the MIT License.
* See LICENSE.md in the project root for license information.
* ======================================================================
*/
#include "StorageAccessWindows.h"
#include <strsafe.h>
#include <CryptoAPI/RMSCryptoExceptions.h>
#include <Platform/Logger/Logger.h>
using namespace rmscrypto::exceptions;
using namespace rmscrypto::platform::logger;
using namespace std;
static const string TableName = "MSIPCKeyStorage";
static const string KeyWrapperColumn = "csKeyWrapper";
static const string KeyColumn = "csKey";
/**
* Helper Functions
*/
string GetLastWin32ErrorAsString()
{
unsigned long errorMessageID = ::GetLastError();
if(errorMessageID == 0)
return string();
char* messageBuffer = nullptr;
size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (char*)&messageBuffer, 0, NULL);
string message(messageBuffer, size);
LocalFree(messageBuffer);
return message;
}
/**
* StorageAccessWindows Singleton implementation.
* If the class has already been created, the static variable will not be created again.
* Starting MSVC 2015 (which supports Magic Statics), this implementation is also thread-safe.
*/
StorageAccessWindows& StorageAccessWindows::Instance()
{
static StorageAccessWindows mInstance;
return mInstance;
}
StorageAccessWindows::StorageAccessWindows()
{
const wstring directory = CreateLocalStorage();
const wstring dbName = directory + L"\\DefaultMSIPCKeyStorage.db";
sqlite3* mDbTemp;
int rc = sqlite3_open16(dbName.c_str(), &mDbTemp);
mDb.reset(mDbTemp, sqlite3_close);
ErrorHandler(rc, "CreateTable");
string sqlCreateTable = CreateTableQuery(TableName);
rc = sqlite3_exec(mDb.get(), sqlCreateTable.c_str(), NULL, NULL, NULL);
ErrorHandler(rc, "CreateTable");
}
wstring StorageAccessWindows::CreateLocalStorage()
{
/**
* Fetch environment variable %localappdata%.
* Check if db folder exists.
* If not, create and encrypt.
*/
const wstring lpName (L"localappdata");
const wstring aipDir (L"\\Microsoft\\RMSLocalStorage");
unsigned long bufferSize = GetEnvironmentVariableW(lpName.c_str(), NULL, 0);
if (bufferSize == 0)
{
throw RMSCryptoIOKeyException(GetLastWin32ErrorAsString().c_str());
}
wstring lpBuffer (bufferSize, L'\0');
if (!GetEnvironmentVariableW(lpName.c_str(), &lpBuffer[0], lpBuffer.length()))
{
throw RMSCryptoIOKeyException(GetLastWin32ErrorAsString().c_str());
}
/**
* Resizing the buffer to exclude the terminating null character.
* Read https://msdn.microsoft.com/en-us/magazine/mt238407.aspx for
* best practices of using STL strings at Win32 API boundaries.
*/
lpBuffer.resize(bufferSize-1);
wstring directory = lpBuffer + aipDir;
if (!CreateDirectory(directory.c_str(), NULL))
{
unsigned long lastError = GetLastError();
/**
* Other than the first time this code runs, the directory creation will always return
* ERROR_ALREADY_EXISTS and hence that is not a fatal error.
*/
if (lastError != ERROR_ALREADY_EXISTS)
{
throw RMSCryptoIOKeyException(GetLastWin32ErrorAsString().c_str());
}
}
else
{
if (!EncryptFile(directory.c_str()))
{
Logger::Warning("EncryptFile failed with " + GetLastWin32ErrorAsString());
}
}
return directory;
}
void StorageAccessWindows::StoreKey(const string& csKeyWrapper,const string& csKey)
{
string sqlInsert = StoreQuery(csKeyWrapper, csKey, TableName);
int rc = sqlite3_exec(mDb.get(), sqlInsert.c_str(), NULL, NULL, NULL);
ErrorHandler(rc, "Store");
}
shared_ptr<string> StorageAccessWindows::LookupKey(const string& csKeyWrapper)
{
string sqlLookup = LookupQuery(csKeyWrapper, TableName);
char** results = NULL;
int rows, columns;
int rc = sqlite3_get_table(mDb.get(), sqlLookup.c_str(), &results, &rows, &columns, NULL);
ErrorHandler(rc, "Lookup");
shared_ptr<string> result;
if (rows >= 1 && columns >= 1)
{
result.reset(new string(results[1]));
sqlite3_free_table(results);
}
return result;
}
void StorageAccessWindows::RemoveKey(const string& csKeyWrapper)
{
string sqlDelete = RemoveQuery(csKeyWrapper, TableName);
int rc = sqlite3_exec(mDb.get(), sqlDelete.c_str(), NULL, NULL, NULL);
ErrorHandler(rc, "Remove");
}
string StorageAccessWindows::CreateTableQuery(const string& TableName)
{
return "CREATE TABLE IF NOT EXISTS " + TableName + " (" + KeyWrapperColumn +
" STRING PRIMARY KEY, " + KeyColumn + " STRING);";
}
string StorageAccessWindows::StoreQuery(
const string& keyWrapper,
const string& key,
const string& TableName)
{
return "INSERT OR REPLACE INTO " + TableName + " VALUES('"+ keyWrapper +"','" + key + "');";
}
string StorageAccessWindows::LookupQuery(const string& keyWrapper, const string& TableName)
{
return "SELECT " + KeyColumn + " FROM " + TableName + " WHERE " + KeyWrapperColumn + "='" + keyWrapper + "';";
}
string StorageAccessWindows::RemoveQuery(const string& keyWrapper, const string& TableName)
{
return "DELETE FROM " + TableName + " WHERE " + KeyWrapperColumn + "='" + keyWrapper + "';";
}
void StorageAccessWindows::ErrorHandler(int returnCode, const string& errorOp)
{
if (returnCode)
{
Logger::Error("StorageAccessWindows failure in " + errorOp + ", sqlite3 failure " + sqlite3_errmsg(mDb.get()));
throw RMSCryptoIOKeyException("StorageAccessWindows failure in operation " + errorOp);
}
}
|
#include "tradingdialog.h"
#include "ui_tradingdialog.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include <qmessagebox.h>
#include <qtimer.h>
#include <rpcserver.h>
#include <QClipboard>
#include <QDebug>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>
#include <QUrlQuery>
#include <QVariant>
#include <QJsonValue>
#include <QJsonDocument>
#include <QJsonObject>
#include <QVariantMap>
#include <QJsonArray>
#include <QTime>
#include <openssl/hmac.h>
#include <stdlib.h>
using namespace std;
tradingDialog::tradingDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::tradingDialog),
model(0)
{
ui->setupUi(this);
timerid = 0;
qDebug() << "Expected this";
ui->BtcAvailableLabel->setTextFormat(Qt::RichText);
ui->TXAvailableLabel->setTextFormat(Qt::RichText);
ui->BuyCostLabel->setTextFormat(Qt::RichText);
ui->SellCostLabel->setTextFormat(Qt::RichText);
ui->FuExchangeBTCLabel->setTextFormat(Qt::RichText);
ui->FuExchangeTXLabel->setTextFormat(Qt::RichText);
ui->CSDumpLabel->setTextFormat(Qt::RichText);
ui->CSTotalLabel->setTextFormat(Qt::RichText);
ui->CSReceiveLabel->setTextFormat(Qt::RichText);
//Set tabs to inactive
ui->TradingTabWidget->setTabEnabled(0,false);
ui->TradingTabWidget->setTabEnabled(1,false);
ui->TradingTabWidget->setTabEnabled(3,false);
ui->TradingTabWidget->setTabEnabled(4,false);
ui->TradingTabWidget->setTabEnabled(5,false);
// Listen for keypress
connect(ui->PasswordInput, SIGNAL(returnPressed()),ui->LoadKeys,SIGNAL(clicked()));
/*OrderBook Table Init*/
CreateOrderBookTables(*ui->BidsTable,QStringList() << "SUM(BTC)" << "TOTAL(BTC)" << "NEAR(SIZE)" << "BID(BTC)");
CreateOrderBookTables(*ui->AsksTable,QStringList() << "ASK(BTC)" << "NEAR(SIZE)" << "TOTAL(BTC)" << "SUM(BTC)");
/*OrderBook Table Init*/
/*Market History Table Init*/
ui->MarketHistoryTable->setColumnCount(5);
ui->MarketHistoryTable->verticalHeader()->setVisible(false);
ui->MarketHistoryTable->setHorizontalHeaderLabels(QStringList()<<"DATE"<<"BUY/SELL"<<"BID/ASK"<<"TOTAL UNITS(NEAR)"<<"TOTAL COST(BTC");
ui->MarketHistoryTable->setRowCount(0);
int Cellwidth = ui->MarketHistoryTable->width() / 5;
ui->MarketHistoryTable->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
ui->MarketHistoryTable->horizontalHeader()->resizeSection(1,Cellwidth);
ui->MarketHistoryTable->horizontalHeader()->resizeSection(2,Cellwidth);
ui->MarketHistoryTable->horizontalHeader()->resizeSection(3,Cellwidth);
ui->MarketHistoryTable->horizontalHeader()->resizeSection(4,Cellwidth);
ui->MarketHistoryTable->horizontalHeader()->resizeSection(5,Cellwidth);
ui->MarketHistoryTable->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
ui->MarketHistoryTable->horizontalHeader()->setStyleSheet("QHeaderView::section, QHeaderView::section * {font-weight :bold;}");
/*Market History Table Init*/
/*Account History Table Init*/
ui->TradeHistoryTable->setColumnCount(9);
ui->TradeHistoryTable->verticalHeader()->setVisible(false);
ui->TradeHistoryTable->setHorizontalHeaderLabels(QStringList() << "Date Time" << "Exchange" << "OrderType" << "Limit" << "QTY" << "QTY_Rem" << "Price" << "PricePerUnit" << "Closed");
ui->TradeHistoryTable->setRowCount(0);
Cellwidth = ui->TradeHistoryTable->width() / 9;
ui->TradeHistoryTable->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(1,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(2,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(3,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(4,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(5,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(6,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(7,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(8,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->resizeSection(9,Cellwidth);
ui->TradeHistoryTable->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
ui->TradeHistoryTable->horizontalHeader()->setStyleSheet("QHeaderView::section, QHeaderView::section * {font-weight :bold;}");
/*Account History Table Init*/
/*Open Orders Table*/
ui->OpenOrdersTable->setColumnCount(10);
ui->OpenOrdersTable->verticalHeader()->setVisible(false);
ui->OpenOrdersTable->setHorizontalHeaderLabels(QStringList() << "OrderId" << "Date Time" << "Exchange" << "OrderType" << "Limit" << "QTY" << "QTY_Rem" << "Price" << "PricePerUnit" << "Cancel Order");
ui->OpenOrdersTable->setRowCount(0);
Cellwidth = ui->TradeHistoryTable->width() / 9;
ui->OpenOrdersTable->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
ui->OpenOrdersTable->horizontalHeader()->resizeSection(2,Cellwidth);
ui->OpenOrdersTable->horizontalHeader()->resizeSection(3,Cellwidth);
ui->OpenOrdersTable->horizontalHeader()->resizeSection(4,Cellwidth);
ui->OpenOrdersTable->horizontalHeader()->resizeSection(5,Cellwidth);
ui->OpenOrdersTable->horizontalHeader()->resizeSection(6,Cellwidth);
ui->OpenOrdersTable->horizontalHeader()->resizeSection(7,Cellwidth);
ui->OpenOrdersTable->horizontalHeader()->resizeSection(8,Cellwidth);
ui->OpenOrdersTable->horizontalHeader()->resizeSection(9,Cellwidth);
ui->OpenOrdersTable->setColumnHidden(0,true);
ui->OpenOrdersTable->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
ui->OpenOrdersTable->horizontalHeader()->setStyleSheet("QHeaderView::section, QHeaderView::section * {font-weight :bold;}");
connect (ui->OpenOrdersTable, SIGNAL(cellClicked(int,int)), this, SLOT(CancelOrderSlot(int, int)));
/*Open Orders Table*/
}
void tradingDialog::InitTrading()
{ //todo - add internet connection/socket error checking.
//Get default exchange info for the qlabels
UpdaterFunction();
qDebug() << "Updater called";
if(this->timerid == 0)
{
//Timer is not set,lets create one.
this->timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(UpdaterFunction()));
this->timer->start(5000);
this->timerid = this->timer->timerId();
}
}
void tradingDialog::UpdaterFunction(){
//TXst get the main exchange info in order to populate qLabels in maindialog. then get data
//required for the current tab.
int Retval = SetExchangeInfoTextLabels();
if (Retval == 0){
ActionsOnSwitch(-1);
}
}
QString tradingDialog::GetMarketSummary(){
QString Response = sendRequest("https://future-exchange.com/api/v1.1/public/GetMarketSummary?market=btc-NEAR");
return Response;
}
QString tradingDialog::GetOrderBook(){
QString Response = sendRequest("https://future-exchange.com/api/v1.1/public/getorderbook?market=BTC-NEAR&type=both&depth=50");
return Response;
}
QString tradingDialog::GetMarketHistory(){
QString Response = sendRequest("https://future-exchange.com/api/v1.1/public/getmarkethistory?market=BTC-NEAR&count=100");
return Response;
}
QString tradingDialog::CancelOrder(QString OrderId){
QString URL = "https://future-exchange.com/api/v1.1/market/cancel?apikey=";
URL += this->ApiKey;
URL += "&nonce=12345434&uuid=";
URL += OrderId;
QString Response = sendRequest(URL);
return Response;
}
QString tradingDialog::BuyTX(QString OrderType, double Quantity, double Rate){
QString str = "";
QString URL = "https://future-exchange.com/api/v1.1/market/";
URL += OrderType;
URL += "?apikey=";
URL += this->ApiKey;
URL += "&nonce=12345434&market=BTC-NEAR&quantity=";
URL += str.number(Quantity,'i',8);
URL += "&rate=";
URL += str.number(Rate,'i',8);
QString Response = sendRequest(URL);
return Response;
}
QString tradingDialog::SellTX(QString OrderType, double Quantity, double Rate){
QString str = "";
QString URL = "https://future-exchange.com/api/v1.1/market/";
URL += OrderType;
URL += "?apikey=";
URL += this->ApiKey;
URL += "&nonce=12345434&market=BTC-NEAR&quantity=";
URL += str.number(Quantity,'i',8);
URL += "&rate=";
URL += str.number(Rate,'i',8);
QString Response = sendRequest(URL);
return Response;
}
QString tradingDialog::Withdraw(double Amount, QString Address, QString Coin){
QString str = "";
QString URL = "https://future-exchange.com/api/v1.1/account/withdraw?apikey=";
URL += this->ApiKey;
URL += "¤cy=";
URL += Coin;
URL += "&quantity=";
URL += str.number(Amount,'i',8);
URL += "&address=";
URL += Address;
URL += "&nonce=12345434";
QString Response = sendRequest(URL);
return Response;
}
QString tradingDialog::GetOpenOrders(){
QString URL = "https://future-exchange.com/api/v1.1/market/getopenorders?apikey=";
URL += this->ApiKey;
URL += "&nonce=12345434&market=BTC-NEAR";
QString Response = sendRequest(URL);
return Response;
}
QString tradingDialog::GetBalance(QString Currency){
QString URL = "https://future-exchange.com/api/v1.1/account/getbalance?apikey=";
URL += this->ApiKey;
URL += "&nonce=12345434¤cy=";
URL += Currency;
QString Response = sendRequest(URL);
return Response;
}
QString tradingDialog::GetDepositAddress(){
QString URL = "https://future-exchange.com/api/v1.1/account/getdepositaddress?apikey=";
URL += this->ApiKey;
URL += "&nonce=12345434¤cy=NEAR";
QString Response = sendRequest(URL);
return Response;
}
QString tradingDialog::GetAccountHistory(){
QString URL = "https://future-exchange.com/api/v1.1/account/getorderhistory?apikey=";
URL += this->ApiKey;
URL += "&nonce=12345434&market=BTC-NEAR&count=10";
QString Response = sendRequest(URL);
return Response;
}
int tradingDialog::SetExchangeInfoTextLabels(){
//Get the current exchange information + information for the current open tab if required.
QString str = "";
QString Response = GetMarketSummary();
//Set the labels, parse the json result to get values.
QJsonObject obj = GetResultObjectFromJSONArray(Response);
//set labels to richtext to use css.
ui->Bid->setTextFormat(Qt::RichText);
ui->Ask->setTextFormat(Qt::RichText);
ui->volumet->setTextFormat(Qt::RichText);
ui->volumebtc->setTextFormat(Qt::RichText);
ui->Ask->setText("<b>Ask:</b> <span style='font-weight:bold; font-size:12px; color:Red'>" + str.number(obj["Ask"].toDouble(),'i',8) + "</span> BTC");
ui->Bid->setText("<b>Bid:</b> <span style='font-weight:bold; font-size:12px; color:Green;'>" + str.number(obj["Bid"].toDouble(),'i',8) + "</span> BTC");
ui->volumet->setText("<b>NEAR Volume:</b> <span style='font-weight:bold; font-size:12px; color:blue;'>" + str.number(obj["Volume"].toDouble(),'i',8) + "</span> NEAR");
ui->volumebtc->setText("<b>BTC Volume:</b> <span style='font-weight:bold; font-size:12px; color:blue;'>" + str.number(obj["BaseVolume"].toDouble(),'i',8) + "</span> BTC");
obj.empty();
return 0;
}
void tradingDialog::CreateOrderBookTables(QTableWidget& Table,QStringList TableHeader){
Table.setColumnCount(4);
Table.verticalHeader()->setVisible(false);
Table.setHorizontalHeaderLabels(TableHeader);
int Cellwidth = Table.width() / 4;
Table.horizontalHeader()->resizeSection(1,Cellwidth); // column 1, width 50
Table.horizontalHeader()->resizeSection(2,Cellwidth);
Table.horizontalHeader()->resizeSection(3,Cellwidth);
Table.horizontalHeader()->resizeSection(4,Cellwidth);
Table.setRowCount(0);
Table.horizontalHeader()->setResizeMode(QHeaderView::Stretch);
Table.horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
Table.horizontalHeader()->setStyleSheet("QHeaderView::section, QHeaderView::section * { font-weight :bold;}");
}
void tradingDialog::DisplayBalance(QLabel &BalanceLabel,QLabel &Available, QLabel &Pending, QString Currency,QString Response){
QString str;
BalanceLabel.setTextFormat(Qt::RichText);
Available.setTextFormat(Qt::RichText);
Pending.setTextFormat(Qt::RichText);
//Set the labels, parse the json result to get values.
QJsonObject ResultObject = GetResultObjectFromJSONObject(Response);
BalanceLabel.setText("<span style='font-weight:bold; font-size:11px; color:green'>" + str.number( ResultObject["Balance"].toDouble(),'i',8) + "</span> " + Currency);
Available.setText("<span style='font-weight:bold; font-size:11px; color:green'>" + str.number( ResultObject["Available"].toDouble(),'i',8) + "</span> " +Currency);
Pending.setText("<span style='font-weight:bold; font-size:11px; color:green'>" + str.number( ResultObject["Pending"].toDouble(),'i',8) + "</span> " +Currency);
}
void tradingDialog::DisplayBalance(QLabel &BalanceLabel, QString Response){
QString str;
//Set the labels, parse the json result to get values.
QJsonObject ResultObject = GetResultObjectFromJSONObject(Response);
BalanceLabel.setText("<span style='font-weight:bold; font-size:12px; color:green'>" + str.number(ResultObject["Available"].toDouble(),'i',8) + "</span>");
}
void tradingDialog::DisplayBalance(QLabel &BalanceLabel, QLabel &BalanceLabel2, QString Response, QString Response2){
QString str;
QString str2;
//Set the labels, parse the json result to get values.
QJsonObject ResultObject = GetResultObjectFromJSONObject(Response);
QJsonObject ResultObject2 = GetResultObjectFromJSONObject(Response2);
BalanceLabel.setText("<span style='font-weight:bold; font-size:12px; color:green'>" + str.number(ResultObject["Available"].toDouble(),'i',8) + "</span>");
BalanceLabel2.setText("<span style='font-weight:bold; font-size:12px; color:green'>" + str2.number(ResultObject2["Available"].toDouble(),'i',8) + "</span>");
}
void tradingDialog::ParseAndPopulateOpenOrdersTable(QString Response){
int itteration = 0, RowCount = 0;
QJsonArray jsonArray = GetResultArrayFromJSONObject(Response);
QJsonObject obj;
ui->OpenOrdersTable->setRowCount(0);
foreach (const QJsonValue & value, jsonArray)
{
QString str = "";
obj = value.toObject();
RowCount = ui->OpenOrdersTable->rowCount();
ui->OpenOrdersTable->insertRow(RowCount);
ui->OpenOrdersTable->setItem(itteration, 0, new QTableWidgetItem(obj["OrderUuid"].toString()));
ui->OpenOrdersTable->setItem(itteration, 1, new QTableWidgetItem(FuExchangeTimeStampToReadable(obj["Opened"].toString())));
ui->OpenOrdersTable->setItem(itteration, 2, new QTableWidgetItem(obj["Exchange"].toString()));
ui->OpenOrdersTable->setItem(itteration, 3, new QTableWidgetItem(obj["OrderType"].toString()));
ui->OpenOrdersTable->setItem(itteration, 4, new QTableWidgetItem(str.number(obj["Limit"].toDouble(),'i',8)));
ui->OpenOrdersTable->setItem(itteration, 5, new QTableWidgetItem(str.number(obj["Quantity"].toDouble(),'i',8)));
ui->OpenOrdersTable->setItem(itteration, 6, new QTableWidgetItem(str.number(obj["QuantityRemaining"].toDouble(),'i',8)));
ui->OpenOrdersTable->setItem(itteration, 7, new QTableWidgetItem(str.number(obj["Price"].toDouble(),'i',8)));
ui->OpenOrdersTable->setItem(itteration, 8, new QTableWidgetItem(str.number(obj["PricePerUnit"].toDouble(),'i',8)));
ui->OpenOrdersTable->setItem(itteration, 9, new QTableWidgetItem(tr("Cancel Order")));
//Handle the cancel link in open orders table
QTableWidgetItem* CancelCell;
CancelCell= ui->OpenOrdersTable->item(itteration, 9); //Set the wtablewidget item to the cancel cell item.
CancelCell->setForeground(QColor::fromRgb(255,0,0)); //make this item red.
CancelCell->setTextAlignment(Qt::AlignCenter);
itteration++;
}
obj.empty();
}
void tradingDialog::CancelOrderSlot(int row, int col){
QString OrderId = ui->OpenOrdersTable->model()->data(ui->OpenOrdersTable->model()->index(row,0)).toString();
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this,"Cancel Order","Are you sure you want to cancel the order?",QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes) {
QString Response = CancelOrder(OrderId);
QJsonDocument jsonResponse = QJsonDocument::fromJson(Response.toUtf8());
QJsonObject ResponseObject = jsonResponse.object();
if (ResponseObject["success"].toBool() == false){
QMessageBox::information(this,"Failed To Cancel Order",ResponseObject["message"].toString());
}else if (ResponseObject["success"].toBool() == true){
ui->OpenOrdersTable->model()->removeRow(row);
QMessageBox::information(this,"Success","You're order was cancelled.");
}
} else {
qDebug() << "Do Nothing";
}
}
void tradingDialog::ParseAndPopulateAccountHistoryTable(QString Response){
int itteration = 0, RowCount = 0;
QJsonArray jsonArray = GetResultArrayFromJSONObject(Response);
QJsonObject obj;
ui->TradeHistoryTable->setRowCount(0);
foreach (const QJsonValue & value, jsonArray)
{
QString str = "";
obj = value.toObject();
RowCount = ui->TradeHistoryTable->rowCount();
ui->TradeHistoryTable->insertRow(RowCount);
ui->TradeHistoryTable->setItem(itteration, 0, new QTableWidgetItem(FuExchangeTimeStampToReadable(obj["TimeStamp"].toString())));
ui->TradeHistoryTable->setItem(itteration, 1, new QTableWidgetItem(obj["Exchange"].toString()));
ui->TradeHistoryTable->setItem(itteration, 2, new QTableWidgetItem(obj["OrderType"].toString()));
ui->TradeHistoryTable->setItem(itteration, 3, new QTableWidgetItem(str.number(obj["Limit"].toDouble(),'i',8)));
ui->TradeHistoryTable->setItem(itteration, 4, new QTableWidgetItem(str.number(obj["Quantity"].toDouble(),'i',8)));
ui->TradeHistoryTable->setItem(itteration, 5, new QTableWidgetItem(str.number(obj["QuantityRemaining"].toDouble(),'i',8)));
ui->TradeHistoryTable->setItem(itteration, 6, new QTableWidgetItem(str.number(obj["Price"].toDouble(),'i',8)));
ui->TradeHistoryTable->setItem(itteration, 7, new QTableWidgetItem(str.number(obj["PricePerUnit"].toDouble(),'i',8)));
ui->TradeHistoryTable->setItem(itteration, 8, new QTableWidgetItem(obj["Closed"].toString()));
itteration++;
}
obj.empty();
}
void tradingDialog::ParseAndPopulateOrderBookTables(QString OrderBook){
QString str;
QJsonObject obj;
QJsonObject ResultObject = GetResultObjectFromJSONObject(OrderBook);
int BuyItteration = 0,SellItteration = 0, BidRows = 0, AskRows = 0;
QJsonArray BuyArray = ResultObject.value("buy").toArray(); //get buy/sell object from result object
QJsonArray SellArray = ResultObject.value("sell").toArray(); //get buy/sell object from result object
double TXSupply = 0;
double TXDemand = 0;
double BtcSupply = 0;
double BtcDemand = 0;
ui->AsksTable->setRowCount(0);
foreach (const QJsonValue & value, SellArray)
{
obj = value.toObject();
double x = obj["Rate"].toDouble(); //would like to use int64 here
double y = obj["Quantity"].toDouble();
double a = (x * y);
TXSupply += y;
BtcSupply += a;
AskRows = ui->AsksTable->rowCount();
ui->AsksTable->insertRow(AskRows);
ui->AsksTable->setItem(SellItteration, 0, new QTableWidgetItem(str.number(x,'i',8)));
ui->AsksTable->setItem(SellItteration, 1, new QTableWidgetItem(str.number(y,'i',8)));
ui->AsksTable->setItem(SellItteration, 2, new QTableWidgetItem(str.number(a,'i',8)));
ui->AsksTable->setItem(SellItteration, 3, new QTableWidgetItem(str.number(BtcSupply,'i',8)));
SellItteration++;
}
ui->BidsTable->setRowCount(0);
foreach (const QJsonValue & value, BuyArray)
{
obj = value.toObject();
double x = obj["Rate"].toDouble(); //would like to use int64 here
double y = obj["Quantity"].toDouble();
double a = (x * y);
TXDemand += y;
BtcDemand += a;
BidRows = ui->BidsTable->rowCount();
ui->BidsTable->insertRow(BidRows);
ui->BidsTable->setItem(BuyItteration, 0, new QTableWidgetItem(str.number(BtcDemand,'i',8)));
ui->BidsTable->setItem(BuyItteration, 1, new QTableWidgetItem(str.number(a,'i',8)));
ui->BidsTable->setItem(BuyItteration, 2, new QTableWidgetItem(str.number(y,'i',8)));
ui->BidsTable->setItem(BuyItteration, 3, new QTableWidgetItem(str.number(x,'i',8)));
BuyItteration++;
}
ui->TXSupply->setText("<b>Supply:</b> <span style='font-weight:bold; font-size:12px; color:blue'>" + str.number(TXSupply,'i',8) + "</span><b> NEAR</b>");
ui->BtcSupply->setText("<span style='font-weight:bold; font-size:12px; color:blue'>" + str.number(BtcSupply,'i',8) + "</span><b> BTC</b>");
ui->AsksCount->setText("<b>Ask's :</b> <span style='font-weight:bold; font-size:12px; color:blue'>" + str.number(ui->AsksTable->rowCount()) + "</span>");
ui->TXDemand->setText("<b>Demand:</b> <span style='font-weight:bold; font-size:12px; color:blue'>" + str.number(TXDemand,'i',8) + "</span><b> NEAR</b>");
ui->BtcDemand->setText("<span style='font-weight:bold; font-size:12px; color:blue'>" + str.number(BtcDemand,'i',8) + "</span><b> BTC</b>");
ui->BidsCount->setText("<b>Bid's :</b> <span style='font-weight:bold; font-size:12px; color:blue'>" + str.number(ui->BidsTable->rowCount()) + "</span>");
obj.empty();
}
void tradingDialog::ParseAndPopulateMarketHistoryTable(QString Response){
int itteration = 0, RowCount = 0;
QJsonArray jsonArray = GetResultArrayFromJSONObject(Response);
QJsonObject obj;
ui->MarketHistoryTable->setRowCount(0);
foreach (const QJsonValue & value, jsonArray)
{
QString str = "";
obj = value.toObject();
RowCount = ui->MarketHistoryTable->rowCount();
ui->MarketHistoryTable->insertRow(RowCount);
ui->MarketHistoryTable->setItem(itteration, 0, new QTableWidgetItem(FuExchangeTimeStampToReadable(obj["TimeStamp"].toString())));
ui->MarketHistoryTable->setItem(itteration, 1, new QTableWidgetItem(obj["OrderType"].toString()));
ui->MarketHistoryTable->setItem(itteration, 2, new QTableWidgetItem(str.number(obj["Price"].toDouble(),'i',8)));
ui->MarketHistoryTable->setItem(itteration, 3, new QTableWidgetItem(str.number(obj["Quantity"].toDouble(),'i',8)));
ui->MarketHistoryTable->setItem(itteration, 4, new QTableWidgetItem(str.number(obj["Total"].toDouble(),'i',8)));
ui->MarketHistoryTable->item(itteration,1)->setBackgroundColor((obj["OrderType"] == QStringLiteral("BUY")) ? (QColor (150, 191, 70,255)) : ( QColor (201, 119, 153,255)));
itteration++;
}
obj.empty();
}
void tradingDialog::ActionsOnSwitch(int index = -1){
QString Response = "";
QString Response2 = "";
QString Response3 = "";
if(index == -1){
index = ui->TradingTabWidget->currentIndex();
}
switch (index){
case 0: //buy tab is active
Response = GetBalance("BTC");
Response2 = GetBalance("NEAR");
Response3 = GetOrderBook();
if((Response.size() > 0 && Response != "Error") && (Response2.size() > 0 && Response2 != "Error")){
DisplayBalance(*ui->BtcAvailableLabel, *ui->TXAvailableLabel, Response, Response2);
}
if ((Response3.size() > 0 && Response3 != "Error")) {
ParseAndPopulateOrderBookTables(Response3);
}
break;
case 1: //Cross send tab active
Response = GetBalance("NEAR");
Response2 = GetBalance("BTC");
if((Response.size() > 0 && Response != "Error") && (Response2.size() > 0 && Response2 != "Error")){
DisplayBalance(*ui->FuExchangeTXLabel, *ui->FuExchangeBTCLabel, Response, Response2);
}
break;
case 2://market history tab
Response = GetMarketHistory();
if(Response.size() > 0 && Response != "Error"){
ParseAndPopulateMarketHistoryTable(Response);
}
break;
case 3: //open orders tab
Response = GetOpenOrders();
if(Response.size() > 0 && Response != "Error"){
ParseAndPopulateOpenOrdersTable(Response);
}
break;
case 4://account history tab
Response = GetAccountHistory();
if(Response.size() > 0 && Response != "Error"){
ParseAndPopulateAccountHistoryTable(Response);
}
break;
case 5://show balance tab
Response = GetBalance("BTC");
if(Response.size() > 0 && Response != "Error"){
DisplayBalance(*ui->BitcoinBalanceLabel,*ui->BitcoinAvailableLabel,*ui->BitcoinPendingLabel, QString::fromUtf8("BTC"),Response);
}
Response = GetBalance("NEAR");
if(Response.size() > 0 && Response != "Error"){
DisplayBalance(*ui->TXBalanceLabel,*ui->TXAvailableLabel_2,*ui->TXPendingLabel, QString::fromUtf8("NEAR"),Response);
}
break;
case 6:
break;
}
}
void tradingDialog::on_TradingTabWidget_tabBarClicked(int index)
{
//tab was clicked, interrupt the timer and restart after action completed.
this->timer->stop();
ActionsOnSwitch(index);
this->timer->start();
}
QString tradingDialog::sendRequest(QString url){
QString Response = "";
QString Secret = this->SecretKey;
// create custom temporary event loop on stack
QEventLoop eventLoop;
// "quit()" the event-loop, when the network request "finished()"
QNetworkAccessManager mgr;
QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
// the HTTP request
QNetworkRequest req = QNetworkRequest(QUrl(url));
req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
//make this conditional,depending if we are using private api call
req.setRawHeader("apisign",HMAC_SHA512_SIGNER(url,Secret).toStdString().c_str()); //set header for future-exchange
QNetworkReply *reply = mgr.get(req);
eventLoop.exec(); // blocks stack until "finished()" has been called
if (reply->error() == QNetworkReply::NoError) {
//success
Response = reply->readAll();
delete reply;
}
else{
//failure
qDebug() << "Failure" <<reply->errorString();
Response = "Error";
//QMessageBox::information(this,"Error",reply->errorString());
delete reply;
}
return Response;
}
QString tradingDialog::FuExchangeTimeStampToReadable(QString DateTime){
//Seperate Time and date.
int TPos = DateTime.indexOf("T");
int sPos = DateTime.indexOf(".");
QDateTime Date = QDateTime::fromString(DateTime.left(TPos),"yyyy-MM-dd"); //format to convert from
DateTime.remove(sPos,sizeof(DateTime));
DateTime.remove(0,TPos+1);
QDateTime Time = QDateTime::fromString(DateTime.right(TPos),"hh:mm:ss");
//Reconstruct time and date in our own format, one that QDateTime will recognise.
QString DisplayDate = Date.toString("dd/MM/yyyy") + " " + Time.toString("hh:mm:ss A"); //formats to convert to
return DisplayDate;
}
void tradingDialog::CalculateBuyCostLabel(){
double price = ui->BuyBidPriceEdit->text().toDouble();
double Quantity = ui->UnitsInput->text().toDouble();
double cost = ((price * Quantity) + ((price * Quantity / 100) * 0.25));
QString Str = "";
ui->BuyCostLabel->setText("<span style='font-weight:bold; font-size:12px; color:red'>" + Str.number(cost,'i',8) + "</span>");
}
void tradingDialog::CalculateSellCostLabel(){
double price = ui->SellBidPriceEdit->text().toDouble();
double Quantity = ui->UnitsInputTX->text().toDouble();
double cost = ((price * Quantity) - ((price * Quantity / 100) * 0.25));
QString Str = "";
ui->SellCostLabel->setText("<span style='font-weight:bold; font-size:12px; color:green'>" + Str.number(cost,'i',8) + "</span>");
}
void tradingDialog::CalculateCSReceiveLabel(){
//calculate amount of currency than can be transferred to bitcoin
QString balance = GetBalance("NEAR");
QString buyorders = GetOrderBook();
QJsonObject BuyObject = GetResultObjectFromJSONObject(buyorders);
QJsonObject BalanceObject = GetResultObjectFromJSONObject(balance);
QJsonObject obj;
double AvailableTX = BalanceObject["Available"].toDouble();
double Quantity = ui->CSUnitsInput->text().toDouble();
double Received = 0;
double Qty = 0;
double Price = 0;
QJsonArray BuyArray = BuyObject.value("buy").toArray(); //get buy/sell object from result object
// For each buy order
foreach (const QJsonValue & value, BuyArray)
{
obj = value.toObject();
double x = obj["Rate"].toDouble(); //would like to use int64 here
double y = obj["Quantity"].toDouble();
// If
if ( ((Quantity / x) - y) > 0 )
{
Price = x;
Received += ((Price * y) - ((Price * y / 100) * 0.25));
Qty += y;
Quantity -= ((Price * y) - ((Price * y / 100) * 0.25));
} else {
Price = x;
Received += ((Price * (Quantity / x)) - ((Price * (Quantity / x) / 100) * 0.25));
Qty += (Quantity / x);
Quantity -= 0;
break;
}
}
QString ReceiveStr = "";
QString DumpStr = "";
QString TotalStr = "";
if ( Qty < AvailableTX )
{
ui->CSReceiveLabel->setText("<span style='font-weight:bold; font-size:12px; color:green'>" + ReceiveStr.number((ui->CSUnitsInput->text().toDouble() - 0.0002),'i',8) + "</span>");
ui->CSDumpLabel->setText("<span style='font-weight:bold; font-size:12px; color:red'>" + DumpStr.number(Price,'i',8) + "</span>");
ui->CSTotalLabel->setText("<span style='font-weight:bold; font-size:12px; color:red'>" + TotalStr.number(Qty,'i',8) + "</span>");
} else {
ReceiveStr = "N/A";
TotalStr = "N/A";
DumpStr = "N/A";
ui->CSReceiveLabel->setText("<span style='font-weight:bold; font-size:12px; color:red'>" + ReceiveStr + "</span>");
ui->CSDumpLabel->setText("<span style='font-weight:bold; font-size:12px; color:red'>" + DumpStr + "</span>");
ui->CSTotalLabel->setText("<span style='font-weight:bold; font-size:12px; color:red'>" + TotalStr + "</span>");
}
}
void tradingDialog::on_UpdateKeys_clicked(bool Save, bool Load)
{
this->ApiKey = ui->ApiKeyInput->text();
this->SecretKey = ui->SecretKeyInput->text();
QJsonDocument jsonResponse = QJsonDocument::fromJson(GetAccountHistory().toUtf8()); //get json from str.
QJsonObject ResponseObject = jsonResponse.object(); //get json obj
if ( ResponseObject.value("success").toBool() == false){
QMessageBox::information(this,"API Configuration Failed","Api configuration was unsuccesful.");
}else if ( ResponseObject.value("success").toBool() == true && Load){
QMessageBox::information(this,"API Configuration Complete","Your API keys have been loaded and the connection has been successfully configured and tested.");
ui->ApiKeyInput->setEchoMode(QLineEdit::Password);
ui->SecretKeyInput->setEchoMode(QLineEdit::Password);
ui->PasswordInput->setText("");
ui->TradingTabWidget->setTabEnabled(0,true);
ui->TradingTabWidget->setTabEnabled(1,true);
ui->TradingTabWidget->setTabEnabled(3,true);
ui->TradingTabWidget->setTabEnabled(4,true);
ui->TradingTabWidget->setTabEnabled(5,true);
}else if ( ResponseObject.value("success").toBool() == true && Save){
QMessageBox::information(this,"API Configuration Complete","Your API keys have been saved and the connection has been successfully configured and tested.");
ui->ApiKeyInput->setEchoMode(QLineEdit::Password);
ui->SecretKeyInput->setEchoMode(QLineEdit::Password);
ui->PasswordInput->setText("");
ui->TradingTabWidget->setTabEnabled(0,true);
ui->TradingTabWidget->setTabEnabled(1,true);
ui->TradingTabWidget->setTabEnabled(3,true);
ui->TradingTabWidget->setTabEnabled(4,true);
ui->TradingTabWidget->setTabEnabled(5,true);
}else{
QMessageBox::information(this,"API Configuration Complete","Api connection has been successfully configured and tested.");
ui->ApiKeyInput->setEchoMode(QLineEdit::Password);
ui->SecretKeyInput->setEchoMode(QLineEdit::Password);
ui->PasswordInput->setText("");
ui->TradingTabWidget->setTabEnabled(0,true);
ui->TradingTabWidget->setTabEnabled(1,true);
ui->TradingTabWidget->setTabEnabled(3,true);
ui->TradingTabWidget->setTabEnabled(4,true);
ui->TradingTabWidget->setTabEnabled(5,true);
}
}
string tradingDialog::encryptDecrypt(string toEncrypt, string password) {
char * key = new char [password.size()+1];
std::strcpy (key, password.c_str());
key[password.size()] = '\0'; // don't forget the terminating 0
string output = toEncrypt;
for (unsigned int i = 0; i < toEncrypt.size(); i++)
output[i] = toEncrypt[i] ^ key[i % (sizeof(key) / sizeof(char))];
return output;
}
void tradingDialog::on_SaveKeys_clicked()
{
bool fSuccess = true;
boost::filesystem::path pathConfigFile = GetDataDir() / "APIcache.txt";
boost::filesystem::ofstream stream (pathConfigFile.string(), ios::out | ios::trunc);
// Qstring to string
string password = ui->PasswordInput->text().toUtf8().constData();
if (password.length() <= 6){
QMessageBox::information(this,"Error !","Your password is too short !");
fSuccess = false;
stream.close();
}
// qstrings to utf8, add to byteArray and convert to const char for stream
string Secret = ui->SecretKeyInput->text().toUtf8().constData();
string Key = ui->ApiKeyInput->text().toUtf8().constData();
string ESecret = "";
string EKey = "";
if (stream.is_open() && fSuccess)
{
ESecret = encryptDecrypt(Secret, password);
EKey = encryptDecrypt(Key, password);
stream << ESecret << '\n';
stream << EKey;
stream.close();
}
if (fSuccess) {
bool Save = true;
on_UpdateKeys_clicked(Save);
}
}
void tradingDialog::on_LoadKeys_clicked()
{
bool fSuccess = true;
boost::filesystem::path pathConfigFile = GetDataDir() / "APIcache.txt";
boost::filesystem::ifstream stream (pathConfigFile.string());
// Qstring to string
string password = ui->PasswordInput->text().toUtf8().constData();
if (password.length() <= 6){
QMessageBox::information(this,"Error !","Your password is too short !");
fSuccess = false;
stream.close();
}
QString DSecret = "";
QString DKey = "";
if (stream.is_open() && fSuccess)
{
int i =0;
for ( std::string line; std::getline(stream,line); )
{
if (i == 0 ){
DSecret = QString::fromUtf8(encryptDecrypt(line, password).c_str());
ui->SecretKeyInput->setText(DSecret);
} else if (i == 1){
DKey = QString::fromUtf8(encryptDecrypt(line, password).c_str());
ui->ApiKeyInput->setText(DKey);
}
i++;
}
stream.close();
}
if (fSuccess) {
bool Save = false;
bool Load = true;
on_UpdateKeys_clicked(Save, Load);
}
}
void tradingDialog::on_GenDepositBTN_clicked()
{
QString response = GetDepositAddress();
QJsonObject ResultObject = GetResultObjectFromJSONObject(response);
ui->DepositAddressLabel->setText(ResultObject["Address"].toString());
}
void tradingDialog::on_Sell_Max_Amount_clicked()
{
//calculate amount of BTC that can be gained from sellingNEARavailable balance
QString responseA = GetBalance("NEAR");
QString str;
QJsonObject ResultObject = GetResultObjectFromJSONObject(responseA);
double AvailableTX = ResultObject["Available"].toDouble();
ui->UnitsInputTX->setText(str.number(AvailableTX,'i',8));
}
void tradingDialog::on_Buy_Max_Amount_clicked()
{
//calculate amount of currency than can be brought with the BTC balance available
QString responseA = GetBalance("BTC");
QString responseB = GetMarketSummary();
QString str;
QJsonObject ResultObject = GetResultObjectFromJSONObject(responseA);
QJsonObject ResultObj = GetResultObjectFromJSONArray(responseB);
//Get the Bid ask or last value from combo
QString value = ui->BuyBidcomboBox->currentText();
double AvailableBTC = ResultObject["Available"].toDouble();
double CurrentASK = ResultObj[value].toDouble();
double Result = (AvailableBTC / CurrentASK);
double percentofnumber = (Result * 0.0025);
Result = Result - percentofnumber;
ui->UnitsInput->setText(str.number(Result,'i',8));
}
void tradingDialog::on_CS_Max_Amount_clicked()
{
double Quantity = ui->FuExchangeTXLabel->text().toDouble();
double Received = 0;
double Qty = 0;
double Price = 0;
QString buyorders = GetOrderBook();
QJsonObject BuyObject = GetResultObjectFromJSONObject(buyorders);
QJsonObject obj;
QString str;
QJsonArray BuyArray = BuyObject.value("buy").toArray(); //get buy/sell object from result object
// For each buy order
foreach (const QJsonValue & value, BuyArray)
{
obj = value.toObject();
double x = obj["Rate"].toDouble(); //would like to use int64 here
double y = obj["Quantity"].toDouble();
// If
if ( (Quantity - y) > 0 )
{
Price = x;
Received += ((Price * y) - ((Price * y / 100) * 0.25));
Qty += y;
Quantity -= y;
} else {
Price = x;
Received += ((Price * Quantity) - ((Price * Quantity / 100) * 0.25));
Qty += Quantity;
if ((Quantity * x) < 0.00055){
Quantity = (0.00055 / x);
}
break;
}
}
ui->CSUnitsInput->setText(str.number(Received,'i',8));
}
void tradingDialog::on_Withdraw_Max_Amount_clicked()
{
//calculate amount of currency than can be brought with the BTC balance available
QString responseA = GetBalance("NEAR");
QString str;
QJsonObject ResultObject = GetResultObjectFromJSONObject(responseA);
double AvailableTX = ResultObject["Available"].toDouble();
ui->WithdrawUnitsInput->setText(str.number(AvailableTX,'i',8));
}
QJsonObject tradingDialog::GetResultObjectFromJSONObject(QString response){
QJsonDocument jsonResponse = QJsonDocument::fromJson(response.toUtf8()); //get json from str.
QJsonObject ResponseObject = jsonResponse.object(); //get json obj
QJsonObject ResultObject = ResponseObject.value(QString("result")).toObject(); //get result object
return ResultObject;
}
QJsonObject tradingDialog::GetResultObjectFromJSONArray(QString response){
QJsonDocument jsonResponsea = QJsonDocument::fromJson(response.toUtf8());
QJsonObject jsonObjecta = jsonResponsea.object();
QJsonArray jsonArraya = jsonObjecta["result"].toArray();
QJsonObject obj;
foreach (const QJsonValue & value, jsonArraya)
{
obj = value.toObject();
}
return obj;
}
QJsonArray tradingDialog::GetResultArrayFromJSONObject(QString response){
QJsonDocument jsonResponse = QJsonDocument::fromJson(response.toUtf8());
QJsonObject jsonObject = jsonResponse.object();
QJsonArray jsonArray = jsonObject["result"].toArray();
return jsonArray;
}
QString tradingDialog::HMAC_SHA512_SIGNER(QString UrlToSign, QString Secret){
QString retval = "";
QByteArray byteArray = UrlToSign.toUtf8();
const char* URL = byteArray.constData();
QByteArray byteArrayB = Secret.toUtf8();
const char* Secretkey = byteArrayB.constData();
const EVP_MD *md = EVP_sha512();
unsigned char* digest = NULL;
// Using sha512 hash engine here.
digest = HMAC(md, Secretkey, strlen( Secretkey), (unsigned char*) URL, strlen( URL), NULL, NULL);
// Be careful of the length of string with the choosen hash engine. SHA1 produces a 20-byte hash value which rendered as 40 characters.
// Change the length accordingly with your choosen hash engine
char mdString[129] = { 0 };
for(int i = 0; i < 64; i++){
sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);
}
retval = mdString;
//qDebug() << "HMAC digest:"<< retval;
return retval;
}
void tradingDialog::on_SellBidcomboBox_currentIndexChanged(const QString &arg1)
{
QString response = GetMarketSummary();
QJsonObject ResultObject = GetResultObjectFromJSONArray(response);
QString Str;
//Get the Bid ask or last value from combo
ui->SellBidPriceEdit->setText(Str.number(ResultObject[arg1].toDouble(),'i',8));
CalculateSellCostLabel(); //update cost
}
void tradingDialog::on_BuyBidcomboBox_currentIndexChanged(const QString &arg1)
{
QString response = GetMarketSummary();
QJsonObject ResultObject = GetResultObjectFromJSONArray(response);
QString Str;
//Get the Bid ask or last value from combo
ui->BuyBidPriceEdit->setText(Str.number(ResultObject[arg1].toDouble(),'i',8));
CalculateBuyCostLabel(); //update cost
}
void tradingDialog::on_BuyTX_clicked()
{
double Rate;
double Quantity;
Rate = ui->BuyBidPriceEdit->text().toDouble();
Quantity = ui->UnitsInput->text().toDouble();
QString OrderType = "Limit";
QString Order;
if(OrderType == "Limit"){Order = "buylimit";}else if (OrderType == "Market"){ Order = "buymarket";}
QString Msg = "Are you sure you want to buy ";
Msg += ui->UnitsInput->text();
Msg += "NEAR @ ";
Msg += ui->BuyBidPriceEdit->text();
Msg += " BTC Each";
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this,"Buy Order",Msg,QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes) {
QString Response = BuyTX(Order,Quantity,Rate);
QJsonDocument jsonResponse = QJsonDocument::fromJson(Response.toUtf8()); //get json from str.
QJsonObject ResponseObject = jsonResponse.object(); //get json obj
if (ResponseObject["success"].toBool() == false){
QMessageBox::information(this,"Buy Order Failed",ResponseObject["message"].toString());
}else if (ResponseObject["success"].toBool() == true){
QMessageBox::information(this,"Buy Order Initiated","You Placed an order");
}
}else{
//do nothing
}
}
void tradingDialog::on_SellTXBTN_clicked()
{
double Rate;
double Quantity;
Rate = ui->SellBidPriceEdit->text().toDouble();
Quantity = ui->UnitsInputTX->text().toDouble();
QString OrderType = "Limit";
QString Order;
if(OrderType == "Limit"){Order = "selllimit";}else if (OrderType == "Market"){ Order = "sellmarket";}
QString Msg = "Are you sure you want to Sell ";
Msg += ui->UnitsInputTX->text();
Msg += "NEAR@ ";
Msg += ui->SellBidPriceEdit->text();
Msg += " BTC Each";
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this,"Sell Order",Msg,QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes) {
QString Response = SellTX(Order,Quantity,Rate);
QJsonDocument jsonResponse = QJsonDocument::fromJson(Response.toUtf8()); //get json from str.
QJsonObject ResponseObject = jsonResponse.object(); //get json obj
if (ResponseObject["success"].toBool() == false){
QMessageBox::information(this,"Sell Order Failed",ResponseObject["message"].toString());
}else if (ResponseObject["success"].toBool() == true){
QMessageBox::information(this,"Sell Order Initiated","You Placed an order");
}
}else{
//do nothing
}
}
void tradingDialog::on_CSUnitsBtn_clicked()
{
double Quantity = ui->CSUnitsInput->text().toDouble();
double Rate = ui->CSDumpLabel->text().toDouble();
double Received = 0;
double Qty = 0;
double Price = 0;
double Add = 0;
QString buyorders = GetOrderBook();
QJsonObject BuyObject = GetResultObjectFromJSONObject(buyorders);
QJsonObject obj;
QString Astr;
QString Qstr;
QString Rstr;
QString Coin = "BTC";
QString Msg = "Are you sure you want to Send ";
Msg += Qstr.number((Quantity - 0.0002),'i',8);
Msg += " BTC to ";
Msg += ui->CSUnitsAddress->text();
Msg += ", DUMPING your coins at ";
Msg += Rstr.number(Rate,'i',8);
Msg += " satoshis ?";
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this,"Cross-Send",Msg,QMessageBox::Yes|QMessageBox::No);
if(reply != QMessageBox::Yes)
{
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock());
if(!ctx.isValid())
{
// Unlock wallet was cancelled
return;
}
QString Order = "selllimit";
QJsonArray BuyArray = BuyObject.value("buy").toArray(); //get buy/sell object from result object
// For each buy order
foreach (const QJsonValue & value, BuyArray)
{
obj = value.toObject();
double x = obj["Rate"].toDouble(); //would like to use int64 here
double y = obj["Quantity"].toDouble();
// If
if ( ((Quantity / x) - y) > 0 )
{
Price = x;
Received += ((Price * y) - ((Price * y / 100) * 0.25));
Qty += y;
Quantity -= ((Price * y) - ((Price * y / 100) * 0.25));
QString SellResponse = SellTX(Order,y,x);
QJsonDocument SelljsonResponse = QJsonDocument::fromJson(SellResponse.toUtf8()); //get json from str.
QJsonObject SellResponseObject = SelljsonResponse.object(); //get json obj
if (SellResponseObject["success"].toBool() == false){
if (SellResponseObject["message"].toString() == "DUST_TRADE_DISALLOWED_MIN_VALUE_50K_SAT"){
Add += y;
continue;
}
QMessageBox::information(this,"sFailed",SellResponse);
break;
}
MilliSleep(100);
} else {
Price = x;
Received += ((Price * (Quantity / x)) - ((Price * (Quantity / x) / 100) * 0.25));
Qty += (Quantity / x);
if (Add > 0)
Quantity += (Add * x);
if (Quantity < 0.00051){
Quantity = 0.00051;
}
QString SellResponse = SellTX(Order,(Quantity / x),x);
QJsonDocument SelljsonResponse = QJsonDocument::fromJson(SellResponse.toUtf8()); //get json from str.
QJsonObject SellResponseObject = SelljsonResponse.object(); //get json obj
if (SellResponseObject["success"].toBool() == false){
QMessageBox::information(this,"sFailed",SellResponse);
} else if (SellResponseObject["success"].toBool() == true){
MilliSleep(5000);
QString Response = Withdraw(ui->CSUnitsInput->text().toDouble(),ui->CSUnitsAddress->text(),Coin);
QJsonDocument jsonResponse = QJsonDocument::fromJson(Response.toUtf8()); //get json from str.
QJsonObject ResponseObject = jsonResponse.object(); //get json obj
if (ResponseObject["success"].toBool() == false){
MilliSleep(5000);
QString Response = Withdraw(ui->CSUnitsInput->text().toDouble(),ui->CSUnitsAddress->text(),Coin);
QJsonDocument jsonResponse = QJsonDocument::fromJson(Response.toUtf8()); //get json from str.
QJsonObject ResponseObject = jsonResponse.object();
if (ResponseObject["success"].toBool() == false){
QMessageBox::information(this,"Failed",ResponseObject["message"].toString());
} else if (ResponseObject["success"].toBool() == true){
QMessageBox::information(this,"Success","<center>Cross-Send Successful</center>\n Sold "+Astr.number(Qty,'i',4)+"NEARfor "+Qstr.number((ui->CSUnitsInput->text().toDouble()-0.0002),'i',8)+" BTC");
}
} else if (ResponseObject["success"].toBool() == true){
QMessageBox::information(this,"Success","<center>Cross-Send Successful</center>\n Sold "+Astr.number(Qty,'i',4)+"NEARfor "+Qstr.number((ui->CSUnitsInput->text().toDouble()-0.0002),'i',8)+" BTC");
}
}
break;
}
}
}
void tradingDialog::on_WithdrawUnitsBtn_clicked()
{
double Quantity = ui->WithdrawUnitsInput->text().toDouble();
QString Qstr;
QString Coin = "NEAR";
QString Msg = "Are you sure you want to Withdraw ";
Msg += Qstr.number((Quantity - 0.02),'i',8);
Msg += "NEARto ";
Msg += ui->WithdrawAddress->text();
Msg += " ?";
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this,"Withdraw",Msg,QMessageBox::Yes|QMessageBox::No);
if(reply != QMessageBox::Yes)
{
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock());
if(!ctx.isValid())
{
// Unlock wallet was cancelled
return;
}
QString Response = Withdraw(Quantity, ui->WithdrawAddress->text(), Coin);
QJsonDocument jsonResponse = QJsonDocument::fromJson(Response.toUtf8()); //get json from str.
QJsonObject ResponseObject = jsonResponse.object(); //get json obj
if (ResponseObject["success"].toBool() == false){
QMessageBox::information(this,"Failed",ResponseObject["message"].toString());
}else if (ResponseObject["success"].toBool() == true){
QMessageBox::information(this,"Success","Withdrawal Successful !");
}
}
void tradingDialog::on_UnitsInputTX_textChanged(const QString &arg1)
{
CalculateSellCostLabel(); //update cost
}
void tradingDialog::on_UnitsInput_textChanged(const QString &arg1)
{
CalculateBuyCostLabel(); //update cost
}
void tradingDialog::on_BuyBidPriceEdit_textChanged(const QString &arg1)
{
CalculateBuyCostLabel(); //update cost
}
void tradingDialog::on_SellBidPriceEdit_textChanged(const QString &arg1)
{
CalculateSellCostLabel();
}
void tradingDialog::on_CSUnitsInput_textChanged(const QString &arg1)
{
CalculateCSReceiveLabel(); //update cost
}
void tradingDialog::on_CSPasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->CSUnitsAddress->setText(QApplication::clipboard()->text());
}
void tradingDialog::on_WithdrawPasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->WithdrawAddress->setText(QApplication::clipboard()->text());
}
void tradingDialog::on_SecretPasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->SecretKeyInput->setText(QApplication::clipboard()->text());
}
void tradingDialog::on_KeyPasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->ApiKeyInput->setText(QApplication::clipboard()->text());
}
void setClipboard(const QString& str)
{
QApplication::clipboard()->setText(str, QClipboard::Clipboard);
QApplication::clipboard()->setText(str, QClipboard::Selection);
}
void tradingDialog::on_DepositCopyButton_clicked()
{
setClipboard(ui->DepositAddressLabel->text());
}
void tradingDialog::setModel(WalletModel *model)
{
this->model = model;
}
tradingDialog::~tradingDialog()
{
delete ui;
}
|
#include "listado_vertical.h"
|
// Copyright (c) 2018-2020 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(PHYLANX_IR_NODE_SLICE_NODE_DATA_3d_SEP_18_2018_0125PM)
#define PHYLANX_IR_NODE_SLICE_NODE_DATA_3d_SEP_18_2018_0125PM
#include <phylanx/config.hpp>
#include <phylanx/execution_tree/primitives/base_primitive.hpp>
#include <phylanx/execution_tree/primitives/detail/slice_assign.hpp>
#include <phylanx/execution_tree/primitives/detail/slice_identity.hpp>
#include <phylanx/execution_tree/primitives/node_data_helpers.hpp>
#include <phylanx/ir/node_data.hpp>
#include <phylanx/ir/ranges.hpp>
#include <phylanx/util/slicing_helpers.hpp>
#include <hpx/assert.hpp>
#include <hpx/errors/throw_exception.hpp>
#include <cstddef>
#include <cstdint>
#include <string>
#include <utility>
#include <blaze/Math.h>
#include <blaze/math/Elements.h>
// Slicing functionality for 3d data
namespace phylanx { namespace execution_tree
{
///////////////////////////////////////////////////////////////////////////
// return a slice from a 3d ir::node_data
template <typename T, typename Data, typename F>
ir::node_data<T> slice3d_basic_basic_basic(Data&& t,
ir::slicing_indices const& pages, ir::slicing_indices const& rows,
ir::slicing_indices const& columns, F const& f,
std::string const& name, std::string const& codename,
eval_context ctx)
{
std::size_t numpages = t.pages();
if (pages.start() >= std::int64_t(numpages) ||
pages.span() > std::int64_t(numpages))
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"phylanx::execution_tree::slice3d_basic_basic_basic",
util::generate_error_message(
"cannot extract the requested tensor element(s)",
name, codename, ctx.back_trace()));
}
std::int64_t page_start = pages.start();
std::int64_t page_stop = pages.stop();
std::int64_t page_step = pages.step();
if (page_step == 0 && !pages.single_value())
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"phylanx::execution_tree::slice3d_basic_basic_basic",
util::generate_error_message("page-step can not be zero", name,
codename, ctx.back_trace()));
}
std::size_t numrows = t.rows();
if (rows.start() >= std::int64_t(numrows) ||
rows.span() > std::int64_t(numrows))
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"phylanx::execution_tree::slice3d_basic_basic_basic",
util::generate_error_message(
"cannot extract the requested tensor element(s)",
name, codename, ctx.back_trace()));
}
std::int64_t row_start = rows.start();
std::int64_t row_stop = rows.stop();
std::int64_t row_step = rows.step();
if (row_step == 0 && !rows.single_value())
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"phylanx::execution_tree::slice3d_basic_basic_basic",
util::generate_error_message("row-step can not be zero", name,
codename, ctx.back_trace()));
}
std::size_t numcols = t.columns();
if (columns.start() >= std::int64_t(numcols) ||
columns.span() > std::int64_t(numcols))
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"phylanx::execution_tree::slice3d_basic_basic_basic",
util::generate_error_message(
"cannot extract the requested tensor element(s)",
name, codename, ctx.back_trace()));
}
std::int64_t col_start = columns.start();
std::int64_t col_stop = columns.stop();
std::int64_t col_step = columns.step();
if (col_step == 0 && !columns.single_value())
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"phylanx::execution_tree::slice3d_basic_basic_basic",
util::generate_error_message("column-step can not be zero",
name, codename, ctx.back_trace()));
}
// handle special cases
if (pages.single_value())
{
auto pageslice = blaze::pageslice(t, page_start);
if (rows.single_value())
{
auto row = blaze::row(pageslice, row_start);
// handle single value slicing result
if (columns.single_value())
{
return f.scalar(t, row[col_start]);
}
// extract a consecutive sub-vector (sub-row)
if (col_step == 1)
{
HPX_ASSERT(col_stop > col_start);
auto sv =
blaze::subvector(row, col_start, col_stop - col_start);
return f.trans_vector(t, std::move(sv));
}
// general case, pick arbitrary elements from selected row
auto indices = util::slicing_helpers::create_list_slice(
col_start, col_stop, col_step);
auto sv = blaze::elements(row, indices);
return f.trans_vector(t, std::move(sv));
}
else if (columns.single_value())
{
// handle single column case
auto col = blaze::column(pageslice, col_start);
// extract a consecutive sub-vector (sub-column)
if (row_step == 1)
{
HPX_ASSERT(row_stop > row_start);
auto sv =
blaze::subvector(col, row_start, row_stop - row_start);
return f.vector(t, std::move(sv));
}
// general case, pick arbitrary elements from selected column
auto indices = util::slicing_helpers::create_list_slice(
row_start, row_stop, row_step);
auto sv = blaze::elements(col, indices);
return f.vector(t, std::move(sv));
}
}
else if (rows.single_value())
{
auto rowslice = blaze::rowslice(t, row_start);
if (columns.single_value())
{
// the row of a rowslice is a vector along the pages of the tensor
auto row = blaze::row(rowslice, col_start);
// extract a consecutive sub-vector (sub-'column')
if (page_step == 1)
{
HPX_ASSERT(page_stop > page_start);
auto sv = blaze::subvector(
row, page_start, page_stop - page_start);
return f.vector(t, std::move(sv));
}
// general case, pick arbitrary elements from selected 'column'
auto indices = util::slicing_helpers::create_list_slice(
page_start, page_stop, page_step);
auto sv = blaze::elements(row, indices);
return f.vector(t, std::move(sv));
}
// general case, pick arbitrary elements from matrix (rowslice)
auto row_indices = util::slicing_helpers::create_list_slice(
page_start, page_stop, page_step);
auto sm = blaze::columns(rowslice, row_indices);
auto column_indices = util::slicing_helpers::create_list_slice(
col_start, col_stop, col_step);
auto result = blaze::rows(sm, column_indices);
return f.matrix(t, std::move(result));
}
else if (columns.single_value())
{
auto columnslice = blaze::columnslice(t, col_start);
// general case, pick arbitrary elements from matrix (columnslice)
auto row_indices = util::slicing_helpers::create_list_slice(
page_start, page_stop, page_step);
auto sm = blaze::rows(columnslice, row_indices);
auto column_indices = util::slicing_helpers::create_list_slice(
row_start, row_stop, row_step);
auto result = blaze::columns(sm, column_indices);
return f.matrix(t, std::move(result));
}
// extract various sub-tensors of the given tensor
if (page_step == 1)
{
HPX_ASSERT(page_stop > page_start);
if (col_step == 1)
{
HPX_ASSERT(col_stop > col_start);
if (row_step == 1)
{
HPX_ASSERT(row_stop > row_start);
auto result = blaze::subtensor(t, page_start, row_start,
col_start, page_stop - page_start, row_stop - row_start,
col_stop - col_start);
return f.tensor(t, std::move(result));
}
// row_step != 1: fall through as not-implemented
}
else if (row_step == 1)
{
// column_step != 1: fall through as not-implemented
}
}
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"phylanx::execution_tree::slice3d_basic_basic_basic",
util::generate_error_message(
"unsupported indexing type", name, codename, ctx.back_trace()));
}
///////////////////////////////////////////////////////////////////////////
template <typename T, typename Data, typename F>
ir::node_data<T> slice3d_integer_integer_integer(Data&& t,
ir::node_data<std::int64_t> && pages,
ir::node_data<std::int64_t> && rows,
ir::node_data<std::int64_t> && columns, F const& f,
std::string const& name, std::string const& codename,
eval_context ctx)
{
std::size_t numpages = t.pages();
std::size_t pages_index_size = pages.size();
for (std::size_t i = 0; i != pages_index_size; ++i)
{
pages[i] =
detail::check_index(pages[i], numpages, name, codename, ctx);
}
std::size_t numrows = t.rows();
std::size_t rows_index_size = rows.size();
for (std::size_t i = 0; i != rows_index_size; ++i)
{
rows[i] =
detail::check_index(rows[i], numrows, name, codename, ctx);
}
std::size_t numcols = t.columns();
std::size_t columns_index_size = columns.size();
for (std::size_t i = 0; i != columns_index_size; ++i)
{
columns[i] =
detail::check_index(columns[i], numcols, name, codename, ctx);
}
// broadcast all index arrays, use result to index elements in tensor
std::size_t largest_dimensionality =
extract_largest_dimension(name, codename, pages, rows);
if (largest_dimensionality > 1)
{
HPX_THROW_EXCEPTION(hpx::not_implemented,
"phylanx::execution_tree::slice3d_integer_integer_integer",
util::generate_error_message(
"this operation is not supported (yet)", name, codename,
ctx.back_trace()));
}
if (largest_dimensionality == 0)
{
return f.scalar(t, t(pages[0], rows[0], columns[0]));
}
auto sizes = extract_largest_dimensions(name, codename, pages, rows);
auto page_indices =
extract_value_vector<T>(std::move(pages), sizes[0], name, codename);
auto row_indices =
extract_value_vector<T>(std::move(rows), sizes[0], name, codename);
auto column_indices =
extract_value_vector<T>(std::move(columns), sizes[0], name, codename);
typename ir::node_data<T>::storage1d_type result(page_indices.size());
for (std::size_t i = 0; i != page_indices.size(); ++i)
{
result[i] = t(page_indices[i], row_indices[i], column_indices[i]);
}
return f.vector(t, std::move(result));
}
///////////////////////////////////////////////////////////////////////////
template <typename T, typename Data, typename F>
ir::node_data<T> slice3d_integer_integer(Data&& t,
ir::node_data<std::int64_t> && pages,
ir::node_data<std::int64_t> && rows, F const& f,
std::string const& name, std::string const& codename,
eval_context ctx)
{
std::size_t numpages = t.pages();
std::size_t pages_index_size = pages.size();
for (std::size_t i = 0; i != pages_index_size; ++i)
{
pages[i] =
detail::check_index(pages[i], numpages, name, codename, ctx);
}
std::size_t numrows = t.rows();
std::size_t rows_index_size = rows.size();
for (std::size_t i = 0; i != rows_index_size; ++i)
{
rows[i] =
detail::check_index(rows[i], numrows, name, codename, ctx);
}
// broadcast both index arrays, use result to index elements in matrix
std::size_t largest_dimensionality =
extract_largest_dimension(name, codename, pages, rows);
if (largest_dimensionality > 1)
{
HPX_THROW_EXCEPTION(hpx::not_implemented,
"phylanx::execution_tree::slice3d_integer_integer",
util::generate_error_message(
"this operation is not supported (yet)", name, codename,
ctx.back_trace()));
}
if (largest_dimensionality == 0)
{
auto row = blaze::row(blaze::pageslice(t, pages[0]), rows[0]);
return f.vector(t, row);
}
auto sizes = extract_largest_dimensions(name, codename, pages, rows);
auto page_indices =
extract_value_vector<T>(std::move(pages), sizes[0], name, codename);
auto row_indices =
extract_value_vector<T>(std::move(rows), sizes[0], name, codename);
typename ir::node_data<T>::storage2d_type result(
page_indices.size(), t.columns());
for (std::size_t i = 0; i != page_indices.size(); ++i)
{
blaze::row(result, i) = blaze::row(
blaze::pageslice(t, page_indices[i]), row_indices[i]);
}
return f.matrix(t, std::move(result));
}
///////////////////////////////////////////////////////////////////////////
template <typename T, typename Data, typename F>
ir::node_data<T> slice3d_integer_0d(Data&& t,
ir::node_data<std::int64_t> && pages, F const& f,
std::string const& name, std::string const& codename,
eval_context ctx)
{
// handle single value page-slicing result
auto pageslice = blaze::pageslice(
t, detail::check_index(pages[0], t.pages(), name, codename, ctx));
return f.matrix(t, std::move(pageslice));
}
template <typename T, typename Data, typename F>
ir::node_data<T> slice3d_integer_1d(Data&& t,
ir::node_data<std::int64_t> && pages, F const& f,
std::string const& name, std::string const& codename,
eval_context ctx)
{
std::size_t numpages = t.pages();
std::size_t pages_index_size = pages.size();
typename ir::node_data<T>::storage3d_type result(
pages_index_size, t.rows(), t.columns());
for (std::size_t i = 0; i != pages_index_size; ++i)
{
blaze::pageslice(result, i) = blaze::pageslice(t,
detail::check_index(pages[i], numpages, name, codename, ctx));
}
return f.tensor(t, std::move(result));
}
template <typename T, typename Data, typename F>
ir::node_data<T> slice3d_integer(Data&& t,
ir::node_data<std::int64_t> && pages, F const& f,
std::string const& name, std::string const& codename,
eval_context ctx)
{
switch (pages.num_dimensions())
{
case 0:
return slice3d_integer_0d<T>(std::forward<Data>(t),
std::move(pages), f, name, codename, ctx);
case 1:
return slice3d_integer_1d<T>(std::forward<Data>(t),
std::move(pages), f, name, codename, ctx);
default:
break;
}
HPX_THROW_EXCEPTION(hpx::not_implemented,
"phylanx::execution_tree::slice3d_integer",
util::generate_error_message(
"this operation is not supported (yet)", name, codename,
ctx.back_trace()));
}
///////////////////////////////////////////////////////////////////////////
template <typename T, typename Data, typename F>
ir::node_data<T> slice3d_boolean_boolean_boolean(Data&& t,
ir::node_data<std::uint8_t> && pages,
ir::node_data<std::uint8_t> && rows,
ir::node_data<std::uint8_t> && columns, F const& f,
std::string const& name, std::string const& codename,
eval_context ctx)
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"phylanx::execution_tree::slice3d_boolean_boolean_boolean",
util::generate_error_message(
"unsupported indexing type", name, codename, ctx.back_trace()));
}
// auto t = data.tensor();
// ir::slicing_indices rows{0ll, std::int64_t(t.rows()), 1ll};
// ir::slicing_indices columns{0ll, std::int64_t(t.columns()), 1ll};
// return slice3d_basic_basic_basic<T>(t,
// util::slicing_helpers::extract_slicing(
// indices, t.pages(), name, codename, ctx),
// rows, columns, detail::slice_identity<T>{}, name, codename);
///////////////////////////////////////////////////////////////////////////
// This is the main entry point for 3d slicing
template <typename T, typename Data, typename F>
ir::node_data<T> slice3d(Data&& t, primitive_argument_type const& pages,
primitive_argument_type const& rows,
primitive_argument_type const& columns, F const& f,
std::string const& name, std::string const& codename,
eval_context ctx)
{
if (is_list_operand_strict(rows) && is_list_operand_strict(columns) &&
is_list_operand_strict(pages))
{
auto column_type =
detail::extract_slicing_index_type(rows, name, codename);
auto row_type =
detail::extract_slicing_index_type(columns, name, codename);
auto page_type =
detail::extract_slicing_index_type(pages, name, codename);
if (column_type == detail::slicing_index_basic &&
row_type == detail::slicing_index_basic &&
page_type == detail::slicing_index_basic)
{
auto page_indices = util::slicing_helpers::extract_slicing(
pages, t.pages(), name, codename, ctx);
auto row_indices = util::slicing_helpers::extract_slicing(
rows, t.rows(), name, codename, ctx);
auto col_indices = util::slicing_helpers::extract_slicing(
columns, t.columns(), name, codename, ctx);
return slice3d_basic_basic_basic<T>(std::forward<Data>(t),
page_indices, row_indices, col_indices, f, name, codename,
ctx);
}
else if (column_type == detail::slicing_index_advanced_integer &&
row_type == detail::slicing_index_advanced_integer &&
page_type == detail::slicing_index_advanced_integer)
{
auto page_indices = extract_integer_value_strict(
detail::extract_advanced_integer_index(
pages, name, codename),
name, codename);
auto row_indices = extract_integer_value_strict(
detail::extract_advanced_integer_index(
rows, name, codename),
name, codename);
auto col_indices = extract_integer_value_strict(
detail::extract_advanced_integer_index(
columns, name, codename),
name, codename);
return slice3d_integer_integer_integer<T>(std::forward<Data>(t),
std::move(page_indices), std::move(row_indices),
std::move(col_indices), f, name, codename, ctx);
}
else if (column_type == detail::slicing_index_advanced_boolean &&
row_type == detail::slicing_index_advanced_boolean &&
page_type == detail::slicing_index_advanced_boolean)
{
auto page_indices = extract_boolean_value_strict(
detail::extract_advanced_boolean_index(
pages, name, codename),
name, codename);
auto row_indices = extract_boolean_value_strict(
detail::extract_advanced_boolean_index(
rows, name, codename),
name, codename);
auto col_indices = extract_boolean_value_strict(
detail::extract_advanced_boolean_index(
columns, name, codename),
name, codename);
return slice3d_boolean_boolean_boolean<T>(std::forward<Data>(t),
std::move(page_indices), std::move(row_indices),
std::move(col_indices), f, name, codename, ctx);
}
}
else if (is_boolean_operand_strict(rows) &&
is_boolean_operand_strict(columns) &&
is_boolean_operand_strict(pages))
{
return slice3d_boolean_boolean_boolean<T>(std::forward<Data>(t),
extract_boolean_value_strict(pages, name, codename),
extract_boolean_value_strict(rows, name, codename),
extract_boolean_value_strict(columns, name, codename), f, name,
codename, ctx);
}
else if (is_integer_operand(pages))
{
if (is_integer_operand(rows))
{
if (is_integer_operand(columns))
{
// 'normal' advanced integer indexing
return slice3d_integer_integer_integer<T>(
std::forward<Data>(t),
extract_integer_value(pages, name, codename),
extract_integer_value(rows, name, codename),
extract_integer_value(columns, name, codename), f, name,
codename, ctx);
}
else if (!valid(columns))
{
// advanced integer indexing with valid page and column
// index
HPX_ASSERT(!is_explicit_nil(columns));
return slice3d_integer_integer<T>(std::forward<Data>(t),
extract_integer_value(pages, name, codename),
extract_integer_value(rows, name, codename), f, name,
codename, ctx);
}
}
else if (!valid(rows) && !valid(columns))
{
// advanced integer indexing with valid page index
HPX_ASSERT(!is_explicit_nil(rows) && !is_explicit_nil(columns));
return slice3d_integer<T>(std::forward<Data>(t),
extract_integer_value(pages, name, codename), f, name,
codename, ctx);
}
}
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"phylanx::execution_tree::slice3d",
util::generate_error_message(
"unsupported indexing type", name, codename, ctx.back_trace()));
}
///////////////////////////////////////////////////////////////////////////
// Slice 3D data with three (page, row, and column) indices
template <typename T>
ir::node_data<T> slice3d_extract3d(ir::node_data<T> const& data,
execution_tree::primitive_argument_type const& pages,
execution_tree::primitive_argument_type const& rows,
execution_tree::primitive_argument_type const& columns,
std::string const& name, std::string const& codename,
eval_context ctx)
{
return slice3d<T>(data.tensor(), pages, rows, columns,
detail::slice_identity<T>{}, name, codename, ctx);
}
///////////////////////////////////////////////////////////////////////////
// Slice 3D data with two (page and row) indices, extracts full rows
template <typename T>
ir::node_data<T> slice2d_extract3d(ir::node_data<T> const& data,
execution_tree::primitive_argument_type const& rows,
execution_tree::primitive_argument_type const& columns,
std::string const& name, std::string const& codename,
eval_context ctx)
{
return slice3d<T>(data.tensor(), rows, columns,
primitive_argument_type{}, detail::slice_identity<T>{}, name,
codename, ctx);
}
///////////////////////////////////////////////////////////////////////////
// Slice 3D data with one (page) index, extracts full matrices
template <typename T>
ir::node_data<T> slice1d_extract3d(ir::node_data<T> const& data,
execution_tree::primitive_argument_type const& indices,
std::string const& name, std::string const& codename,
eval_context ctx)
{
return slice3d<T>(data.tensor(), indices, primitive_argument_type{},
primitive_argument_type{}, detail::slice_identity<T>{}, name,
codename, ctx);
}
///////////////////////////////////////////////////////////////////////////
// Slice 3D data with one (page) index, extracts full matrices
template <typename T>
ir::node_data<T> slice1d_assign3d(ir::node_data<T>&& data,
execution_tree::primitive_argument_type const& indices,
ir::node_data<T>&& value, std::string const& name,
std::string const& codename, eval_context ctx)
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"phylanx::execution_tree::slice1d_assign3d",
util::generate_error_message(
"unsupported indexing type", name, codename, ctx.back_trace()));
}
///////////////////////////////////////////////////////////////////////////
// Slice 3d data with two indices
template <typename T>
ir::node_data<T> slice2d_assign3d(ir::node_data<T>&& data,
execution_tree::primitive_argument_type const& rows,
execution_tree::primitive_argument_type const& columns,
ir::node_data<T>&& value, std::string const& name,
std::string const& codename, eval_context ctx)
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"phylanx::execution_tree::slice2d_assign3d",
util::generate_error_message(
"unsupported indexing type", name, codename, ctx.back_trace()));
}
///////////////////////////////////////////////////////////////////////////
// Slice 3d data with three indices
template <typename T>
ir::node_data<T> slice3d_assign3d(ir::node_data<T>&& data,
execution_tree::primitive_argument_type const& pages,
execution_tree::primitive_argument_type const& rows,
execution_tree::primitive_argument_type const& columns,
ir::node_data<T>&& value, std::string const& name,
std::string const& codename, eval_context ctx)
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"phylanx::execution_tree::slice3d",
util::generate_error_message(
"unsupported indexing type", name, codename, ctx.back_trace()));
}
}}
#endif
|
#include <iostream>
using namespace std;
int main() {
int a, b, c;
cin >> a >> b >> c;
int x1 = a + b, x2 = a * b, y1 = b + c, y2 = b * c;
int r = 0, s = 0;
s = x1 + c;
if (s > r) r = s;
s = x1 * c;
if (s > r) r = s;
s = x2 + c;
if (s > r) r = s;
s = x2 * c;
if (s > r) r = s;
s = a + y1;
if (s > r) r = s;
s = a * y1;
if (s > r) r = s;
s = a + y2;
if (s > r) r = s;
s = a * y2;
if (s > r) r = s;
cout << r << endl;
}
|
#include <front/ForwardRenderingPath.h>
#include <core/BasicRenderPass.h>
#include <core/Renderer.h>
#include <core/Shader.h>
#include <front/Camera.h>
#include <front/Camera.h>
namespace blitz::front
{
const auto viewPortSizeUniformName = hashString("_bViewPortSize");
const auto viewMatrixUniformName = hashString("_bView");
const auto projectionMatrixUniformName = hashString("_bProjection");
ForwardRenderingPath::ForwardRenderingPath(Renderer* renderer) : RenderingPath(renderer) {}
void ForwardRenderingPath::render(RenderList* renderList)
{
const Camera* camera = renderList->camera;
const ViewPort* viewPort = renderList->viewPort;
Vector2i viewPortSize = { viewPort->width - viewPort->x, viewPort->height - viewPort->y };
Matrix4f viewMatrix = camera->calculateViewMatrix();
// TODO this changes only when viewPort changes, we should use this fact
auto projectionMatrix = calculateProjectionMatrix(viewPort, camera->getProjection(), camera->getFieldOfView());
Array<UniformState> renderPassWideUniform(3);
renderPassWideUniform.add({ DataType::VECTOR2I, viewPortSizeUniformName, &viewPortSize });
renderPassWideUniform.add({ DataType::MATRIX4F, viewMatrixUniformName, &viewMatrix });
renderPassWideUniform.add({ DataType::MATRIX4F, projectionMatrixUniformName, &projectionMatrix });
RenderState renderState{
viewPort, camera->getProjection(), true, false, true, renderList->framebuffer, &renderPassWideUniform
};
BasicRenderPass forwardRenderPass{ &renderState, renderList->geometry };
forwardRenderPass.prepare();
backend->issue(&forwardRenderPass);
backend->render();
}
} // namespace blitz::front
|
/*
*
* Copyright (C) 1994-2010, OFFIS e.V.
* All rights reserved. See COPYRIGHT file for details.
*
* This software and supporting documentation were developed by
*
* OFFIS e.V.
* R&D Division Health
* Escherweg 2
* D-26121 Oldenburg, Germany
*
*
* Module: dcmnet
*
* Author: Andrew Hewett
*
* Purpose: Storage Service Class Provider (C-STORE operation)
*
* Last Update: $Author: joergr $
* Update Date: $Date: 2010-11-04 10:22:50 $
* CVS/RCS Revision: $Revision: 1.137 $
* Status: $State: Exp $
*
* CVS/RCS Log at end of file
*
*/
#include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */
#define INCLUDE_CSTDLIB
#define INCLUDE_CSTRING
#define INCLUDE_CSTDARG
#define INCLUDE_CCTYPE
#define INCLUDE_CSIGNAL
#include "dcmtk/ofstd/ofstdinc.h"
BEGIN_EXTERN_C
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h> /* needed on Solaris for O_RDONLY */
#endif
#ifdef HAVE_SIGNAL_H
// On Solaris with Sun Workshop 11, <signal.h> declares signal() but <csignal> does not
#include <signal.h>
#endif
END_EXTERN_C
#ifdef HAVE_GUSI_H
#include <GUSI.h>
#endif
#ifdef HAVE_WINDOWS_H
#include <direct.h> /* for _mkdir() */
#endif
#include "dcmtk/ofstd/ofstd.h"
#include "dcmtk/ofstd/ofconapp.h"
#include "dcmtk/ofstd/ofdatime.h"
#include "dcmtk/dcmnet/dicom.h" /* for DICOM_APPLICATION_ACCEPTOR */
#include "dcmtk/dcmnet/dimse.h"
#include "dcmtk/dcmnet/diutil.h"
#include "dcmtk/dcmnet/dcasccfg.h" /* for class DcmAssociationConfiguration */
#include "dcmtk/dcmnet/dcasccff.h" /* for class DcmAssociationConfigurationFile */
#include "dcmtk/dcmdata/dcfilefo.h"
#include "dcmtk/dcmdata/dcuid.h"
#include "dcmtk/dcmdata/dcdict.h"
#include "dcmtk/dcmdata/cmdlnarg.h"
#include "dcmtk/dcmdata/dcmetinf.h"
#include "dcmtk/dcmdata/dcuid.h" /* for dcmtk version name */
#include "dcmtk/dcmdata/dcdeftag.h"
#include "dcmtk/dcmdata/dcostrmz.h" /* for dcmZlibCompressionLevel */
#ifdef WITH_OPENSSL
#include "dcmtk/dcmtls/tlstrans.h"
#include "dcmtk/dcmtls/tlslayer.h"
#endif
#ifdef WITH_ZLIB
#include <zlib.h> /* for zlibVersion() */
#endif
#if defined(HAVE_MKTEMP) && !defined(HAVE_PROTOTYPE_MKTEMP)
extern "C" {
char * mktemp(char *);
}
#endif
// Solaris 2.5.1 has mkstemp() in libc.a but no prototype
#if defined(HAVE_MKSTEMP) && !defined(HAVE_PROTOTYPE_MKSTEMP)
extern "C" {
int mkstemp(char *);
}
#endif
#ifdef PRIVATE_STORESCP_DECLARATIONS
PRIVATE_STORESCP_DECLARATIONS
#else
#define OFFIS_CONSOLE_APPLICATION "storescp"
#endif
static OFLogger storescpLogger = OFLog::getLogger("dcmtk.apps." OFFIS_CONSOLE_APPLICATION);
static char rcsid[] = "$dcmtk: " OFFIS_CONSOLE_APPLICATION " v" OFFIS_DCMTK_VERSION " " OFFIS_DCMTK_RELEASEDATE " $";
#define APPLICATIONTITLE "STORESCP" /* our application entity title */
#define PATH_PLACEHOLDER "#p"
#define FILENAME_PLACEHOLDER "#f"
#define CALLING_AETITLE_PLACEHOLDER "#a"
#define CALLED_AETITLE_PLACEHOLDER "#c"
#define CALLING_PRESENTATION_ADDRESS_PLACEHOLDER "#r"
static OFCondition processCommands(T_ASC_Association *assoc);
static OFCondition acceptAssociation(T_ASC_Network *net, DcmAssociationConfiguration& asccfg);
static OFCondition echoSCP(T_ASC_Association * assoc, T_DIMSE_Message * msg, T_ASC_PresentationContextID presID);
static OFCondition storeSCP(T_ASC_Association * assoc, T_DIMSE_Message * msg, T_ASC_PresentationContextID presID);
static void executeOnReception();
static void executeEndOfStudyEvents();
static void executeStartOfStudyEvents();
static void executeOnEndOfStudy();
static void executeOnStartOfStudy();
static void renameOnEndOfStudy();
static OFString replaceChars( const OFString &srcstr, const OFString &pattern, const OFString &substitute );
static void executeCommand( const OFString &cmd );
static void cleanChildren(pid_t pid, OFBool synch);
static OFCondition acceptUnknownContextsWithPreferredTransferSyntaxes(
T_ASC_Parameters * params,
const char* transferSyntaxes[],
int transferSyntaxCount,
T_ASC_SC_ROLE acceptedRole = ASC_SC_ROLE_DEFAULT);
static int makeTempFile();
/* sort study mode */
enum E_SortStudyMode
{
ESM_None,
ESM_Timestamp,
ESM_StudyInstanceUID,
ESM_PatientName
};
OFBool opt_showPresentationContexts = OFFalse;
OFBool opt_uniqueFilenames = OFFalse;
OFString opt_fileNameExtension;
OFBool opt_timeNames = OFFalse;
int timeNameCounter = -1; // "serial number" to differentiate between files with same timestamp
OFCmdUnsignedInt opt_port = 0;
OFBool opt_refuseAssociation = OFFalse;
OFBool opt_rejectWithoutImplementationUID = OFFalse;
OFCmdUnsignedInt opt_sleepAfter = 0;
OFCmdUnsignedInt opt_sleepDuring = 0;
OFCmdUnsignedInt opt_maxPDU = ASC_DEFAULTMAXPDU;
OFBool opt_useMetaheader = OFTrue;
OFBool opt_acceptAllXfers = OFFalse;
E_TransferSyntax opt_networkTransferSyntax = EXS_Unknown;
E_TransferSyntax opt_writeTransferSyntax = EXS_Unknown;
E_GrpLenEncoding opt_groupLength = EGL_recalcGL;
E_EncodingType opt_sequenceType = EET_ExplicitLength;
E_PaddingEncoding opt_paddingType = EPD_withoutPadding;
OFCmdUnsignedInt opt_filepad = 0;
OFCmdUnsignedInt opt_itempad = 0;
OFCmdUnsignedInt opt_compressionLevel = 0;
OFBool opt_bitPreserving = OFFalse;
OFBool opt_ignore = OFFalse;
OFBool opt_abortDuringStore = OFFalse;
OFBool opt_abortAfterStore = OFFalse;
OFBool opt_promiscuous = OFFalse;
OFBool opt_correctUIDPadding = OFFalse;
OFBool opt_inetd_mode = OFFalse;
OFString callingAETitle; // calling application entity title will be stored here
OFString lastCallingAETitle;
OFString calledAETitle; // called application entity title will be stored here
OFString lastCalledAETitle;
OFString callingPresentationAddress; // remote hostname or IP address will be stored here
OFString lastCallingPresentationAddress;
const char * opt_respondingAETitle = APPLICATIONTITLE;
static OFBool opt_secureConnection = OFFalse; // default: no secure connection
static OFString opt_outputDirectory = "."; // default: output directory equals "."
E_SortStudyMode opt_sortStudyMode = ESM_None; // default: no sorting
static const char *opt_sortStudyDirPrefix = NULL; // default: no directory prefix
OFString lastStudyInstanceUID;
OFString subdirectoryPathAndName;
OFList<OFString> outputFileNameArray;
static const char *opt_execOnReception = NULL; // default: don't execute anything on reception
static const char *opt_execOnEndOfStudy = NULL; // default: don't execute anything on end of study
static const char *opt_execOnStartOfStudy = NULL; // default: don't execute anything on start of study
OFString lastStudySubdirectoryPathAndName;
OFString nextStudySubdirectoryPathAndName;
static OFBool opt_renameOnEndOfStudy = OFFalse; // default: don't rename any files on end of study
static long opt_endOfStudyTimeout = -1; // default: no end of study timeout
static OFBool endOfStudyThroughTimeoutEvent = OFFalse;
static const char *opt_configFile = NULL;
static const char *opt_profileName = NULL;
T_DIMSE_BlockingMode opt_blockMode = DIMSE_BLOCKING;
int opt_dimse_timeout = 0;
int opt_acse_timeout = 30;
#if defined(HAVE_FORK) || defined(_WIN32)
OFBool opt_forkMode = OFFalse;
#endif
OFBool opt_forkedChild = OFFalse;
OFBool opt_execSync = OFFalse; // default: execute in background
#ifdef WITH_OPENSSL
static int opt_keyFileFormat = SSL_FILETYPE_PEM;
static const char *opt_privateKeyFile = NULL;
static const char *opt_certificateFile = NULL;
static const char *opt_passwd = NULL;
#if OPENSSL_VERSION_NUMBER >= 0x0090700fL
static OFString opt_ciphersuites(TLS1_TXT_RSA_WITH_AES_128_SHA ":" SSL3_TXT_RSA_DES_192_CBC3_SHA);
#else
static OFString opt_ciphersuites(SSL3_TXT_RSA_DES_192_CBC3_SHA);
#endif
static const char *opt_readSeedFile = NULL;
static const char *opt_writeSeedFile = NULL;
static DcmCertificateVerification opt_certVerification = DCV_requireCertificate;
static const char *opt_dhparam = NULL;
#endif
#ifdef HAVE_WAITPID
/** signal handler for SIGCHLD signals that immediately cleans up
* terminated children.
*/
#ifdef SIGNAL_HANDLER_WITH_ELLIPSE
extern "C" void sigChildHandler(...)
#else
extern "C" void sigChildHandler(int)
#endif
{
int status = 0;
waitpid( -1, &status, WNOHANG );
signal(SIGCHLD, sigChildHandler);
}
#endif
#define SHORTCOL 4
#define LONGCOL 21
int main(int argc, char *argv[])
{
T_ASC_Network *net;
DcmAssociationConfiguration asccfg;
#ifdef HAVE_GUSI_H
/* needed for Macintosh */
GUSISetup(GUSIwithSIOUXSockets);
GUSISetup(GUSIwithInternetSockets);
#endif
#ifdef HAVE_WINSOCK_H
WSAData winSockData;
/* we need at least version 1.1 */
WORD winSockVersionNeeded = MAKEWORD( 1, 1 );
WSAStartup(winSockVersionNeeded, &winSockData);
#endif
char tempstr[20];
OFString temp_str;
OFConsoleApplication app(OFFIS_CONSOLE_APPLICATION, "DICOM storage (C-STORE) SCP", rcsid);
OFCommandLine cmd;
cmd.setParamColumn(LONGCOL + SHORTCOL + 4);
cmd.addParam("port", "tcp/ip port number to listen on", OFCmdParam::PM_Optional);
cmd.setOptionColumns(LONGCOL, SHORTCOL);
cmd.addGroup("general options:", LONGCOL, SHORTCOL + 2);
cmd.addOption("--help", "-h", "print this help text and exit", OFCommandLine::AF_Exclusive);
cmd.addOption("--version", "print version information and exit", OFCommandLine::AF_Exclusive);
OFLog::addOptions(cmd);
cmd.addOption("--verbose-pc", "+v", "show presentation contexts in verbose mode");
#if defined(HAVE_FORK) || defined(_WIN32)
cmd.addGroup("multi-process options:", LONGCOL, SHORTCOL + 2);
cmd.addOption("--single-process", "single process mode (default)");
cmd.addOption("--fork", "fork child process for each association");
#ifdef _WIN32
cmd.addOption("--forked-child", "process is forked child, internal use only", OFCommandLine::AF_Internal);
#endif
#endif
cmd.addGroup("network options:");
cmd.addSubGroup("association negotiation profile from configuration file:");
cmd.addOption("--config-file", "-xf", 2, "[f]ilename, [p]rofile: string",
"use profile p from config file f");
cmd.addSubGroup("preferred network transfer syntaxes (not with --config-file):");
cmd.addOption("--prefer-uncompr", "+x=", "prefer explicit VR local byte order (default)");
cmd.addOption("--prefer-little", "+xe", "prefer explicit VR little endian TS");
cmd.addOption("--prefer-big", "+xb", "prefer explicit VR big endian TS");
cmd.addOption("--prefer-lossless", "+xs", "prefer default JPEG lossless TS");
cmd.addOption("--prefer-jpeg8", "+xy", "prefer default JPEG lossy TS for 8 bit data");
cmd.addOption("--prefer-jpeg12", "+xx", "prefer default JPEG lossy TS for 12 bit data");
cmd.addOption("--prefer-j2k-lossless", "+xv", "prefer JPEG 2000 lossless TS");
cmd.addOption("--prefer-j2k-lossy", "+xw", "prefer JPEG 2000 lossy TS");
cmd.addOption("--prefer-jls-lossless", "+xt", "prefer JPEG-LS lossless TS");
cmd.addOption("--prefer-jls-lossy", "+xu", "prefer JPEG-LS lossy TS");
cmd.addOption("--prefer-mpeg2", "+xm", "prefer MPEG2 Main Profile @ Main Level TS");
cmd.addOption("--prefer-mpeg2-high", "+xh", "prefer MPEG2 Main Profile @ High Level TS");
cmd.addOption("--prefer-rle", "+xr", "prefer RLE lossless TS");
#ifdef WITH_ZLIB
cmd.addOption("--prefer-deflated", "+xd", "prefer deflated expl. VR little endian TS");
#endif
cmd.addOption("--implicit", "+xi", "accept implicit VR little endian TS only");
cmd.addOption("--accept-all", "+xa", "accept all supported transfer syntaxes");
#ifdef WITH_TCPWRAPPER
cmd.addSubGroup("network host access control (tcp wrapper):");
cmd.addOption("--access-full", "-ac", "accept connections from any host (default)");
cmd.addOption("--access-control", "+ac", "enforce host access control rules");
#endif
cmd.addSubGroup("other network options:");
#ifdef HAVE_CONFIG_H
// this option is only offered on Posix platforms
cmd.addOption("--inetd", "-id", "run from inetd super server (not with --fork)");
#endif
cmd.addOption("--acse-timeout", "-ta", 1, "[s]econds: integer (default: 30)", "timeout for ACSE messages");
cmd.addOption("--dimse-timeout", "-td", 1, "[s]econds: integer (default: unlimited)", "timeout for DIMSE messages");
OFString opt1 = "set my AE title (default: ";
opt1 += APPLICATIONTITLE;
opt1 += ")";
cmd.addOption("--aetitle", "-aet", 1, "[a]etitle: string", opt1.c_str());
OFString opt3 = "set max receive pdu to n bytes (def.: ";
sprintf(tempstr, "%ld", OFstatic_cast(long, ASC_DEFAULTMAXPDU));
opt3 += tempstr;
opt3 += ")";
OFString opt4 = "[n]umber of bytes: integer (";
sprintf(tempstr, "%ld", OFstatic_cast(long, ASC_MINIMUMPDUSIZE));
opt4 += tempstr;
opt4 += "..";
sprintf(tempstr, "%ld", OFstatic_cast(long, ASC_MAXIMUMPDUSIZE));
opt4 += tempstr;
opt4 += ")";
cmd.addOption("--max-pdu", "-pdu", 1, opt4.c_str(), opt3.c_str());
cmd.addOption("--disable-host-lookup", "-dhl", "disable hostname lookup");
cmd.addOption("--refuse", "refuse association");
cmd.addOption("--reject", "reject association if no implement. class UID");
cmd.addOption("--ignore", "ignore store data, receive but do not store");
cmd.addOption("--sleep-after", 1, "[s]econds: integer",
"sleep s seconds after store (default: 0)");
cmd.addOption("--sleep-during", 1, "[s]econds: integer",
"sleep s seconds during store (default: 0)");
cmd.addOption("--abort-after", "abort association after receipt of C-STORE-RQ\n(but before sending response)");
cmd.addOption("--abort-during", "abort association during receipt of C-STORE-RQ");
cmd.addOption("--promiscuous", "-pm", "promiscuous mode, accept unknown SOP classes\n(not with --config-file)");
cmd.addOption("--uid-padding", "-up", "silently correct space-padded UIDs");
cmd.addGroup("output options:");
cmd.addSubGroup("general:");
cmd.addOption("--output-directory", "-od", 1, "[d]irectory: string (default: \".\")", "write received objects to existing directory d");
cmd.addSubGroup("bit preserving mode:");
cmd.addOption("--normal", "-B", "allow implicit format conversions (default)");
cmd.addOption("--bit-preserving", "+B", "write data exactly as read");
cmd.addSubGroup("output file format:");
cmd.addOption("--write-file", "+F", "write file format (default)");
cmd.addOption("--write-dataset", "-F", "write data set without file meta information");
cmd.addSubGroup("output transfer syntax (not with --bit-preserving or compressed transmission):");
cmd.addOption("--write-xfer-same", "+t=", "write with same TS as input (default)");
cmd.addOption("--write-xfer-little", "+te", "write with explicit VR little endian TS");
cmd.addOption("--write-xfer-big", "+tb", "write with explicit VR big endian TS");
cmd.addOption("--write-xfer-implicit", "+ti", "write with implicit VR little endian TS");
#ifdef WITH_ZLIB
cmd.addOption("--write-xfer-deflated", "+td", "write with deflated expl. VR little endian TS");
#endif
cmd.addSubGroup("post-1993 value representations (not with --bit-preserving):");
cmd.addOption("--enable-new-vr", "+u", "enable support for new VRs (UN/UT) (default)");
cmd.addOption("--disable-new-vr", "-u", "disable support for new VRs, convert to OB");
cmd.addSubGroup("group length encoding (not with --bit-preserving):");
cmd.addOption("--group-length-recalc", "+g=", "recalculate group lengths if present (default)");
cmd.addOption("--group-length-create", "+g", "always write with group length elements");
cmd.addOption("--group-length-remove", "-g", "always write without group length elements");
cmd.addSubGroup("length encoding in sequences and items (not with --bit-preserving):");
cmd.addOption("--length-explicit", "+e", "write with explicit lengths (default)");
cmd.addOption("--length-undefined", "-e", "write with undefined lengths");
cmd.addSubGroup("data set trailing padding (not with --write-dataset or --bit-preserving):");
cmd.addOption("--padding-off", "-p", "no padding (default)");
cmd.addOption("--padding-create", "+p", 2, "[f]ile-pad [i]tem-pad: integer",
"align file on multiple of f bytes and items\non multiple of i bytes");
#ifdef WITH_ZLIB
cmd.addSubGroup("deflate compression level (only with --write-xfer-deflated/same):");
cmd.addOption("--compression-level", "+cl", 1, "[l]evel: integer (default: 6)",
"0=uncompressed, 1=fastest, 9=best compression");
#endif
cmd.addSubGroup("sorting into subdirectories (not with --bit-preserving):");
cmd.addOption("--sort-conc-studies", "-ss", 1, "[p]refix: string",
"sort studies using prefix p and a timestamp");
cmd.addOption("--sort-on-study-uid", "-su", 1, "[p]refix: string",
"sort studies using prefix p and the Study\nInstance UID");
cmd.addOption("--sort-on-patientname", "-sp", "sort studies using the Patient's Name and\na timestamp");
cmd.addSubGroup("filename generation:");
cmd.addOption("--default-filenames", "-uf", "generate filename from instance UID (default)");
cmd.addOption("--unique-filenames", "+uf", "generate unique filenames");
cmd.addOption("--timenames", "-tn", "generate filename from creation time");
cmd.addOption("--filename-extension", "-fe", 1, "[e]xtension: string",
"append e to all filenames");
cmd.addGroup("event options:", LONGCOL, SHORTCOL + 2);
cmd.addOption("--exec-on-reception", "-xcr", 1, "[c]ommand: string",
"execute command c after having received and\nprocessed one C-STORE-RQ message");
cmd.addOption("--exec-on-eostudy", "-xcs", 1, "[c]ommand: string",
"execute command c after having received and\nprocessed all C-STORE-RQ messages that belong\nto one study");
cmd.addOption("--exec-on-sostudy", "-xcss", 1, "[c]ommand: string",
"execute command c before receiving or\nprocessing any C-STORE-RQ message that belongs\nto a new study");
cmd.addOption("--rename-on-eostudy", "-rns", "having received and processed all C-STORE-RQ\nmessages that belong to one study, rename\noutput files according to certain pattern");
cmd.addOption("--eostudy-timeout", "-tos", 1, "[t]imeout: integer",
"specifies a timeout of t seconds for\nend-of-study determination");
cmd.addOption("--exec-sync", "-xs", "execute command synchronously in foreground");
#ifdef WITH_OPENSSL
cmd.addGroup("transport layer security (TLS) options:");
cmd.addSubGroup("transport protocol stack:");
cmd.addOption("--disable-tls", "-tls", "use normal TCP/IP connection (default)");
cmd.addOption("--enable-tls", "+tls", 2, "[p]rivate key file, [c]ertificate file: string",
"use authenticated secure TLS connection");
cmd.addSubGroup("private key password (only with --enable-tls):");
cmd.addOption("--std-passwd", "+ps", "prompt user to type password on stdin (default)");
cmd.addOption("--use-passwd", "+pw", 1, "[p]assword: string",
"use specified password");
cmd.addOption("--null-passwd", "-pw", "use empty string as password");
cmd.addSubGroup("key and certificate file format:");
cmd.addOption("--pem-keys", "-pem", "read keys and certificates as PEM file (def.)");
cmd.addOption("--der-keys", "-der", "read keys and certificates as DER file");
cmd.addSubGroup("certification authority:");
cmd.addOption("--add-cert-file", "+cf", 1, "[c]ertificate filename: string",
"add certificate file to list of certificates", OFCommandLine::AF_NoWarning);
cmd.addOption("--add-cert-dir", "+cd", 1, "[c]ertificate directory: string",
"add certificates in d to list of certificates", OFCommandLine::AF_NoWarning);
cmd.addSubGroup("ciphersuite:");
cmd.addOption("--cipher", "+cs", 1, "[c]iphersuite name: string",
"add ciphersuite to list of negotiated suites");
cmd.addOption("--dhparam", "+dp", 1, "[f]ilename: string",
"read DH parameters for DH/DSS ciphersuites");
cmd.addSubGroup("pseudo random generator:");
cmd.addOption("--seed", "+rs", 1, "[f]ilename: string",
"seed random generator with contents of f");
cmd.addOption("--write-seed", "+ws", "write back modified seed (only with --seed)");
cmd.addOption("--write-seed-file", "+wf", 1, "[f]ilename: string (only with --seed)",
"write modified seed to file f");
cmd.addSubGroup("peer authentication");
cmd.addOption("--require-peer-cert", "-rc", "verify peer certificate, fail if absent (def.)");
cmd.addOption("--verify-peer-cert", "-vc", "verify peer certificate if present");
cmd.addOption("--ignore-peer-cert", "-ic", "don't verify peer certificate");
#endif
/* evaluate command line */
prepareCmdLineArgs(argc, argv, OFFIS_CONSOLE_APPLICATION);
if (app.parseCommandLine(cmd, argc, argv, OFCommandLine::PF_ExpandWildcards))
{
/* print help text and exit */
if (cmd.getArgCount() == 0)
app.printUsage();
/* check exclusive options first */
if (cmd.hasExclusiveOption())
{
if (cmd.findOption("--version"))
{
app.printHeader(OFTrue /*print host identifier*/);
COUT << OFendl << "External libraries used:";
#if !defined(WITH_ZLIB) && !defined(WITH_OPENSSL) && !defined(WITH_TCPWRAPPER)
COUT << " none" << OFendl;
#else
COUT << OFendl;
#endif
#ifdef WITH_ZLIB
COUT << "- ZLIB, Version " << zlibVersion() << OFendl;
#endif
#ifdef WITH_OPENSSL
COUT << "- " << OPENSSL_VERSION_TEXT << OFendl;
#endif
#ifdef WITH_TCPWRAPPER
COUT << "- LIBWRAP" << OFendl;
#endif
return 0;
}
}
#ifdef HAVE_CONFIG_H
if (cmd.findOption("--inetd"))
{
opt_inetd_mode = OFTrue;
opt_forkMode = OFFalse;
// duplicate stdin, which is the socket passed by inetd
int inetd_fd = dup(0);
if (inetd_fd < 0) exit(99);
close(0); // close stdin
close(1); // close stdout
close(2); // close stderr
// open new file descriptor for stdin
int fd = open("/dev/null", O_RDONLY);
if (fd != 0) exit(99);
// create new file descriptor for stdout
fd = makeTempFile();
if (fd != 1) exit(99);
// create new file descriptor for stderr
fd = makeTempFile();
if (fd != 2) exit(99);
dcmExternalSocketHandle.set(inetd_fd);
// the port number is not really used. Set to non-privileged port number
// to avoid failing the privilege test.
opt_port = 1024;
}
#endif
#if defined(HAVE_FORK) || defined(_WIN32)
cmd.beginOptionBlock();
if (cmd.findOption("--single-process"))
opt_forkMode = OFFalse;
if (cmd.findOption("--fork"))
{
app.checkConflict("--inetd", "--fork", opt_inetd_mode);
opt_forkMode = OFTrue;
}
cmd.endOptionBlock();
#ifdef _WIN32
if (cmd.findOption("--forked-child")) opt_forkedChild = OFTrue;
#endif
#endif
if (opt_inetd_mode)
{
// port number is not required in inetd mode
if (cmd.getParamCount() > 0)
OFLOG_WARN(storescpLogger, "Parameter port not required in inetd mode");
} else {
// omitting the port number is only allowed in inetd mode
if (cmd.getParamCount() == 0)
app.printError("Missing parameter port");
else
app.checkParam(cmd.getParamAndCheckMinMax(1, opt_port, 1, 65535));
}
OFLog::configureFromCommandLine(cmd, app);
if (cmd.findOption("--verbose-pc"))
{
app.checkDependence("--verbose-pc", "verbose mode", storescpLogger.isEnabledFor(OFLogger::INFO_LOG_LEVEL));
opt_showPresentationContexts = OFTrue;
}
cmd.beginOptionBlock();
if (cmd.findOption("--prefer-uncompr"))
{
opt_acceptAllXfers = OFFalse;
opt_networkTransferSyntax = EXS_Unknown;
}
if (cmd.findOption("--prefer-little")) opt_networkTransferSyntax = EXS_LittleEndianExplicit;
if (cmd.findOption("--prefer-big")) opt_networkTransferSyntax = EXS_BigEndianExplicit;
if (cmd.findOption("--prefer-lossless")) opt_networkTransferSyntax = EXS_JPEGProcess14SV1TransferSyntax;
if (cmd.findOption("--prefer-jpeg8")) opt_networkTransferSyntax = EXS_JPEGProcess1TransferSyntax;
if (cmd.findOption("--prefer-jpeg12")) opt_networkTransferSyntax = EXS_JPEGProcess2_4TransferSyntax;
if (cmd.findOption("--prefer-j2k-lossless")) opt_networkTransferSyntax = EXS_JPEG2000LosslessOnly;
if (cmd.findOption("--prefer-j2k-lossy")) opt_networkTransferSyntax = EXS_JPEG2000;
if (cmd.findOption("--prefer-jls-lossless")) opt_networkTransferSyntax = EXS_JPEGLSLossless;
if (cmd.findOption("--prefer-jls-lossy")) opt_networkTransferSyntax = EXS_JPEGLSLossy;
if (cmd.findOption("--prefer-mpeg2")) opt_networkTransferSyntax = EXS_MPEG2MainProfileAtMainLevel;
if (cmd.findOption("--prefer-mpeg2-high")) opt_networkTransferSyntax = EXS_MPEG2MainProfileAtHighLevel;
if (cmd.findOption("--prefer-rle")) opt_networkTransferSyntax = EXS_RLELossless;
#ifdef WITH_ZLIB
if (cmd.findOption("--prefer-deflated")) opt_networkTransferSyntax = EXS_DeflatedLittleEndianExplicit;
#endif
if (cmd.findOption("--implicit")) opt_networkTransferSyntax = EXS_LittleEndianImplicit;
if (cmd.findOption("--accept-all"))
{
opt_acceptAllXfers = OFTrue;
opt_networkTransferSyntax = EXS_Unknown;
}
cmd.endOptionBlock();
if (opt_networkTransferSyntax != EXS_Unknown) opt_acceptAllXfers = OFFalse;
if (cmd.findOption("--acse-timeout"))
{
OFCmdSignedInt opt_timeout = 0;
app.checkValue(cmd.getValueAndCheckMin(opt_timeout, 1));
opt_acse_timeout = OFstatic_cast(int, opt_timeout);
}
if (cmd.findOption("--dimse-timeout"))
{
OFCmdSignedInt opt_timeout = 0;
app.checkValue(cmd.getValueAndCheckMin(opt_timeout, 1));
opt_dimse_timeout = OFstatic_cast(int, opt_timeout);
opt_blockMode = DIMSE_NONBLOCKING;
}
if (cmd.findOption("--aetitle")) app.checkValue(cmd.getValue(opt_respondingAETitle));
if (cmd.findOption("--max-pdu")) app.checkValue(cmd.getValueAndCheckMinMax(opt_maxPDU, ASC_MINIMUMPDUSIZE, ASC_MAXIMUMPDUSIZE));
if (cmd.findOption("--disable-host-lookup")) dcmDisableGethostbyaddr.set(OFTrue);
if (cmd.findOption("--refuse")) opt_refuseAssociation = OFTrue;
if (cmd.findOption("--reject")) opt_rejectWithoutImplementationUID = OFTrue;
if (cmd.findOption("--ignore")) opt_ignore = OFTrue;
if (cmd.findOption("--sleep-after")) app.checkValue(cmd.getValueAndCheckMin(opt_sleepAfter, 0));
if (cmd.findOption("--sleep-during")) app.checkValue(cmd.getValueAndCheckMin(opt_sleepDuring, 0));
if (cmd.findOption("--abort-after")) opt_abortAfterStore = OFTrue;
if (cmd.findOption("--abort-during")) opt_abortDuringStore = OFTrue;
if (cmd.findOption("--promiscuous")) opt_promiscuous = OFTrue;
if (cmd.findOption("--uid-padding")) opt_correctUIDPadding = OFTrue;
if (cmd.findOption("--config-file"))
{
// check conflicts with other command line options
app.checkConflict("--config-file", "--prefer-little", opt_networkTransferSyntax == EXS_LittleEndianExplicit);
app.checkConflict("--config-file", "--prefer-big", opt_networkTransferSyntax == EXS_BigEndianExplicit);
app.checkConflict("--config-file", "--prefer-lossless", opt_networkTransferSyntax == EXS_JPEGProcess14SV1TransferSyntax);
app.checkConflict("--config-file", "--prefer-jpeg8", opt_networkTransferSyntax == EXS_JPEGProcess1TransferSyntax);
app.checkConflict("--config-file", "--prefer-jpeg12", opt_networkTransferSyntax == EXS_JPEGProcess2_4TransferSyntax);
app.checkConflict("--config-file", "--prefer-j2k-lossless", opt_networkTransferSyntax == EXS_JPEG2000LosslessOnly);
app.checkConflict("--config-file", "--prefer-j2k-lossy", opt_networkTransferSyntax == EXS_JPEG2000);
app.checkConflict("--config-file", "--prefer-jls-lossless", opt_networkTransferSyntax == EXS_JPEGLSLossless);
app.checkConflict("--config-file", "--prefer-jls-lossy", opt_networkTransferSyntax == EXS_JPEGLSLossy);
app.checkConflict("--config-file", "--prefer-mpeg2", opt_networkTransferSyntax == EXS_MPEG2MainProfileAtMainLevel);
app.checkConflict("--config-file", "--prefer-mpeg2-high", opt_networkTransferSyntax == EXS_MPEG2MainProfileAtHighLevel);
app.checkConflict("--config-file", "--prefer-rle", opt_networkTransferSyntax == EXS_RLELossless);
#ifdef WITH_ZLIB
app.checkConflict("--config-file", "--prefer-deflated", opt_networkTransferSyntax == EXS_DeflatedLittleEndianExplicit);
#endif
app.checkConflict("--config-file", "--implicit", opt_networkTransferSyntax == EXS_LittleEndianImplicit);
app.checkConflict("--config-file", "--accept-all", opt_acceptAllXfers);
app.checkConflict("--config-file", "--promiscuous", opt_promiscuous);
app.checkValue(cmd.getValue(opt_configFile));
app.checkValue(cmd.getValue(opt_profileName));
// read configuration file
OFCondition cond = DcmAssociationConfigurationFile::initialize(asccfg, opt_configFile);
if (cond.bad())
{
OFLOG_FATAL(storescpLogger, "cannot read config file: " << cond.text());
return 1;
}
/* perform name mangling for config file key */
OFString sprofile;
const unsigned char *c = OFreinterpret_cast(const unsigned char *, opt_profileName);
while (*c)
{
if (! isspace(*c)) sprofile += OFstatic_cast(char, toupper(*c));
++c;
}
if (!asccfg.isKnownProfile(sprofile.c_str()))
{
OFLOG_FATAL(storescpLogger, "unknown configuration profile name: " << sprofile);
return 1;
}
if (!asccfg.isValidSCPProfile(sprofile.c_str()))
{
OFLOG_FATAL(storescpLogger, "profile '" << sprofile << "' is not valid for SCP use, duplicate abstract syntaxes found");
return 1;
}
}
#ifdef WITH_TCPWRAPPER
cmd.beginOptionBlock();
if (cmd.findOption("--access-full")) dcmTCPWrapperDaemonName.set(NULL);
if (cmd.findOption("--access-control")) dcmTCPWrapperDaemonName.set(OFFIS_CONSOLE_APPLICATION);
cmd.endOptionBlock();
#endif
if (cmd.findOption("--output-directory")) app.checkValue(cmd.getValue(opt_outputDirectory));
cmd.beginOptionBlock();
if (cmd.findOption("--normal")) opt_bitPreserving = OFFalse;
if (cmd.findOption("--bit-preserving")) opt_bitPreserving = OFTrue;
cmd.endOptionBlock();
cmd.beginOptionBlock();
if (cmd.findOption("--write-file")) opt_useMetaheader = OFTrue;
if (cmd.findOption("--write-dataset")) opt_useMetaheader = OFFalse;
cmd.endOptionBlock();
cmd.beginOptionBlock();
if (cmd.findOption("--write-xfer-same")) opt_writeTransferSyntax = EXS_Unknown;
if (cmd.findOption("--write-xfer-little"))
{
app.checkConflict("--write-xfer-little", "--accept-all", opt_acceptAllXfers);
app.checkConflict("--write-xfer-little", "--bit-preserving", opt_bitPreserving);
app.checkConflict("--write-xfer-little", "--prefer-lossless", opt_networkTransferSyntax == EXS_JPEGProcess14SV1TransferSyntax);
app.checkConflict("--write-xfer-little", "--prefer-jpeg8", opt_networkTransferSyntax == EXS_JPEGProcess1TransferSyntax);
app.checkConflict("--write-xfer-little", "--prefer-jpeg12", opt_networkTransferSyntax == EXS_JPEGProcess2_4TransferSyntax);
app.checkConflict("--write-xfer-little", "--prefer-j2k-lossless", opt_networkTransferSyntax == EXS_JPEG2000LosslessOnly);
app.checkConflict("--write-xfer-little", "--prefer-j2k-lossy", opt_networkTransferSyntax == EXS_JPEG2000);
app.checkConflict("--write-xfer-little", "--prefer-jls-lossless", opt_networkTransferSyntax == EXS_JPEGLSLossless);
app.checkConflict("--write-xfer-little", "--prefer-jls-lossy", opt_networkTransferSyntax == EXS_JPEGLSLossy);
app.checkConflict("--write-xfer-little", "--prefer-mpeg2", opt_networkTransferSyntax == EXS_MPEG2MainProfileAtMainLevel);
app.checkConflict("--write-xfer-little", "--prefer-mpeg2-high", opt_networkTransferSyntax == EXS_MPEG2MainProfileAtHighLevel);
app.checkConflict("--write-xfer-little", "--prefer-rle", opt_networkTransferSyntax == EXS_RLELossless);
// we don't have to check a conflict for --prefer-deflated because we can always convert that to uncompressed.
opt_writeTransferSyntax = EXS_LittleEndianExplicit;
}
if (cmd.findOption("--write-xfer-big"))
{
app.checkConflict("--write-xfer-big", "--accept-all", opt_acceptAllXfers);
app.checkConflict("--write-xfer-big", "--bit-preserving", opt_bitPreserving);
app.checkConflict("--write-xfer-big", "--prefer-lossless", opt_networkTransferSyntax == EXS_JPEGProcess14SV1TransferSyntax);
app.checkConflict("--write-xfer-big", "--prefer-jpeg8", opt_networkTransferSyntax == EXS_JPEGProcess1TransferSyntax);
app.checkConflict("--write-xfer-big", "--prefer-jpeg12", opt_networkTransferSyntax == EXS_JPEGProcess2_4TransferSyntax);
app.checkConflict("--write-xfer-big", "--prefer-j2k-lossless", opt_networkTransferSyntax == EXS_JPEG2000LosslessOnly);
app.checkConflict("--write-xfer-big", "--prefer-j2k-lossy", opt_networkTransferSyntax == EXS_JPEG2000);
app.checkConflict("--write-xfer-big", "--prefer-jls-lossless", opt_networkTransferSyntax == EXS_JPEGLSLossless);
app.checkConflict("--write-xfer-big", "--prefer-jls-lossy", opt_networkTransferSyntax == EXS_JPEGLSLossy);
app.checkConflict("--write-xfer-big", "--prefer-mpeg2", opt_networkTransferSyntax == EXS_MPEG2MainProfileAtMainLevel);
app.checkConflict("--write-xfer-big", "--prefer-mpeg2-high", opt_networkTransferSyntax == EXS_MPEG2MainProfileAtHighLevel);
app.checkConflict("--write-xfer-big", "--prefer-rle", opt_networkTransferSyntax == EXS_RLELossless);
// we don't have to check a conflict for --prefer-deflated because we can always convert that to uncompressed.
opt_writeTransferSyntax = EXS_BigEndianExplicit;
}
if (cmd.findOption("--write-xfer-implicit"))
{
app.checkConflict("--write-xfer-implicit", "--accept-all", opt_acceptAllXfers);
app.checkConflict("--write-xfer-implicit", "--bit-preserving", opt_bitPreserving);
app.checkConflict("--write-xfer-implicit", "--prefer-lossless", opt_networkTransferSyntax == EXS_JPEGProcess14SV1TransferSyntax);
app.checkConflict("--write-xfer-implicit", "--prefer-jpeg8", opt_networkTransferSyntax == EXS_JPEGProcess1TransferSyntax);
app.checkConflict("--write-xfer-implicit", "--prefer-jpeg12", opt_networkTransferSyntax == EXS_JPEGProcess2_4TransferSyntax);
app.checkConflict("--write-xfer-implicit", "--prefer-j2k-lossless", opt_networkTransferSyntax == EXS_JPEG2000LosslessOnly);
app.checkConflict("--write-xfer-implicit", "--prefer-j2k-lossy", opt_networkTransferSyntax == EXS_JPEG2000);
app.checkConflict("--write-xfer-implicit", "--prefer-jls-lossless", opt_networkTransferSyntax == EXS_JPEGLSLossless);
app.checkConflict("--write-xfer-implicit", "--prefer-jls-lossy", opt_networkTransferSyntax == EXS_JPEGLSLossy);
app.checkConflict("--write-xfer-implicit", "--prefer-mpeg2", opt_networkTransferSyntax == EXS_MPEG2MainProfileAtMainLevel);
app.checkConflict("--write-xfer-implicit", "--prefer-mpeg2-high", opt_networkTransferSyntax == EXS_MPEG2MainProfileAtHighLevel);
app.checkConflict("--write-xfer-implicit", "--prefer-rle", opt_networkTransferSyntax == EXS_RLELossless);
// we don't have to check a conflict for --prefer-deflated because we can always convert that to uncompressed.
opt_writeTransferSyntax = EXS_LittleEndianImplicit;
}
#ifdef WITH_ZLIB
if (cmd.findOption("--write-xfer-deflated"))
{
app.checkConflict("--write-xfer-deflated", "--accept-all", opt_acceptAllXfers);
app.checkConflict("--write-xfer-deflated", "--bit-preserving", opt_bitPreserving);
app.checkConflict("--write-xfer-deflated", "--prefer-lossless", opt_networkTransferSyntax == EXS_JPEGProcess14SV1TransferSyntax);
app.checkConflict("--write-xfer-deflated", "--prefer-jpeg8", opt_networkTransferSyntax == EXS_JPEGProcess1TransferSyntax);
app.checkConflict("--write-xfer-deflated", "--prefer-jpeg12", opt_networkTransferSyntax == EXS_JPEGProcess2_4TransferSyntax);
app.checkConflict("--write-xfer-deflated", "--prefer-j2k-lossless", opt_networkTransferSyntax == EXS_JPEG2000LosslessOnly);
app.checkConflict("--write-xfer-deflated", "--prefer-j2k-lossy", opt_networkTransferSyntax == EXS_JPEG2000);
app.checkConflict("--write-xfer-deflated", "--prefer-jls-lossless", opt_networkTransferSyntax == EXS_JPEGLSLossless);
app.checkConflict("--write-xfer-deflated", "--prefer-jls-lossy", opt_networkTransferSyntax == EXS_JPEGLSLossy);
app.checkConflict("--write-xfer-deflated", "--prefer-mpeg2", opt_networkTransferSyntax == EXS_MPEG2MainProfileAtMainLevel);
app.checkConflict("--write-xfer-deflated", "--prefer-mpeg2-high", opt_networkTransferSyntax == EXS_MPEG2MainProfileAtHighLevel);
app.checkConflict("--write-xfer-deflated", "--prefer-rle", opt_networkTransferSyntax == EXS_RLELossless);
opt_writeTransferSyntax = EXS_DeflatedLittleEndianExplicit;
}
#endif
cmd.endOptionBlock();
cmd.beginOptionBlock();
if (cmd.findOption("--enable-new-vr"))
{
app.checkConflict("--enable-new-vr", "--bit-preserving", opt_bitPreserving);
dcmEnableUnknownVRGeneration.set(OFTrue);
dcmEnableUnlimitedTextVRGeneration.set(OFTrue);
}
if (cmd.findOption("--disable-new-vr"))
{
app.checkConflict("--disable-new-vr", "--bit-preserving", opt_bitPreserving);
dcmEnableUnknownVRGeneration.set(OFFalse);
dcmEnableUnlimitedTextVRGeneration.set(OFFalse);
}
cmd.endOptionBlock();
cmd.beginOptionBlock();
if (cmd.findOption("--group-length-recalc"))
{
app.checkConflict("--group-length-recalc", "--bit-preserving", opt_bitPreserving);
opt_groupLength = EGL_recalcGL;
}
if (cmd.findOption("--group-length-create"))
{
app.checkConflict("--group-length-create", "--bit-preserving", opt_bitPreserving);
opt_groupLength = EGL_withGL;
}
if (cmd.findOption("--group-length-remove"))
{
app.checkConflict("--group-length-remove", "--bit-preserving", opt_bitPreserving);
opt_groupLength = EGL_withoutGL;
}
cmd.endOptionBlock();
cmd.beginOptionBlock();
if (cmd.findOption("--length-explicit"))
{
app.checkConflict("--length-explicit", "--bit-preserving", opt_bitPreserving);
opt_sequenceType = EET_ExplicitLength;
}
if (cmd.findOption("--length-undefined"))
{
app.checkConflict("--length-undefined", "--bit-preserving", opt_bitPreserving);
opt_sequenceType = EET_UndefinedLength;
}
cmd.endOptionBlock();
cmd.beginOptionBlock();
if (cmd.findOption("--padding-off")) opt_paddingType = EPD_withoutPadding;
if (cmd.findOption("--padding-create"))
{
app.checkConflict("--padding-create", "--write-dataset", !opt_useMetaheader);
app.checkConflict("--padding-create", "--bit-preserving", opt_bitPreserving);
app.checkValue(cmd.getValueAndCheckMin(opt_filepad, 0));
app.checkValue(cmd.getValueAndCheckMin(opt_itempad, 0));
opt_paddingType = EPD_withPadding;
}
cmd.endOptionBlock();
#ifdef WITH_ZLIB
if (cmd.findOption("--compression-level"))
{
app.checkDependence("--compression-level", "--write-xfer-deflated or --write-xfer-same",
(opt_writeTransferSyntax == EXS_DeflatedLittleEndianExplicit) || (opt_writeTransferSyntax == EXS_Unknown));
app.checkValue(cmd.getValueAndCheckMinMax(opt_compressionLevel, 0, 9));
dcmZlibCompressionLevel.set(OFstatic_cast(int, opt_compressionLevel));
}
#endif
cmd.beginOptionBlock();
if (cmd.findOption("--sort-conc-studies"))
{
app.checkConflict("--sort-conc-studies", "--bit-preserving", opt_bitPreserving);
app.checkValue(cmd.getValue(opt_sortStudyDirPrefix));
opt_sortStudyMode = ESM_Timestamp;
}
if (cmd.findOption("--sort-on-study-uid"))
{
app.checkConflict("--sort-on-study-uid", "--bit-preserving", opt_bitPreserving);
app.checkValue(cmd.getValue(opt_sortStudyDirPrefix));
opt_sortStudyMode = ESM_StudyInstanceUID;
}
if (cmd.findOption("--sort-on-patientname"))
{
app.checkConflict("--sort-on-patientname", "--bit-preserving", opt_bitPreserving);
opt_sortStudyDirPrefix = NULL;
opt_sortStudyMode = ESM_PatientName;
}
cmd.endOptionBlock();
cmd.beginOptionBlock();
if (cmd.findOption("--default-filenames")) opt_uniqueFilenames = OFFalse;
if (cmd.findOption("--unique-filenames")) opt_uniqueFilenames = OFTrue;
cmd.endOptionBlock();
if (cmd.findOption("--timenames")) opt_timeNames = OFTrue;
if (cmd.findOption("--filename-extension"))
app.checkValue(cmd.getValue(opt_fileNameExtension));
if (cmd.findOption("--timenames"))
app.checkConflict("--timenames", "--unique-filenames", opt_uniqueFilenames);
if (cmd.findOption("--exec-on-reception")) app.checkValue(cmd.getValue(opt_execOnReception));
if (cmd.findOption("--exec-on-eostudy"))
{
#ifdef _WIN32
app.checkConflict("--exec-on-eostudy", "--fork on Windows systems", opt_forkMode);
#endif
app.checkDependence("--exec-on-eostudy", "--sort-conc-studies, --sort-on-study-uid or --sort-on-patientname", opt_sortStudyMode != ESM_None );
app.checkValue(cmd.getValue(opt_execOnEndOfStudy));
}
if (cmd.findOption("--exec-on-sostudy"))
{
#ifdef _WIN32
app.checkConflict("--exec-on-sostudy", "--fork on Windows systems (probably)", opt_forkMode);
#endif
app.checkDependence("--exec-on-sostudy", "--sort-conc-studies, --sort-on-study-uid or --sort-on-patientname", opt_sortStudyMode != ESM_None );
app.checkValue(cmd.getValue(opt_execOnStartOfStudy));
}
if (cmd.findOption("--rename-on-eostudy"))
{
#ifdef _WIN32
app.checkConflict("--rename-on-eostudy", "--fork on Windows systems", opt_forkMode);
#endif
app.checkDependence("--rename-on-eostudy", "--sort-conc-studies, --sort-on-study-uid or --sort-on-patientname", opt_sortStudyMode != ESM_None );
opt_renameOnEndOfStudy = OFTrue;
}
if (cmd.findOption("--eostudy-timeout"))
{
app.checkDependence("--eostudy-timeout", "--sort-conc-studies, --sort-on-study-uid, --sort-on-patientname, --exec-on-eostudy or --rename-on-eostudy",
(opt_sortStudyMode != ESM_None) || (opt_execOnEndOfStudy != NULL) || opt_renameOnEndOfStudy);
app.checkValue(cmd.getValueAndCheckMin(opt_endOfStudyTimeout, 0));
}
if (cmd.findOption("--exec-sync")) opt_execSync = OFTrue;
}
/* print resource identifier */
OFLOG_DEBUG(storescpLogger, rcsid << OFendl);
#ifdef WITH_OPENSSL
cmd.beginOptionBlock();
if (cmd.findOption("--disable-tls")) opt_secureConnection = OFFalse;
if (cmd.findOption("--enable-tls"))
{
opt_secureConnection = OFTrue;
app.checkValue(cmd.getValue(opt_privateKeyFile));
app.checkValue(cmd.getValue(opt_certificateFile));
}
cmd.endOptionBlock();
cmd.beginOptionBlock();
if (cmd.findOption("--std-passwd"))
{
app.checkDependence("--std-passwd", "--enable-tls", opt_secureConnection);
opt_passwd = NULL;
}
if (cmd.findOption("--use-passwd"))
{
app.checkDependence("--use-passwd", "--enable-tls", opt_secureConnection);
app.checkValue(cmd.getValue(opt_passwd));
}
if (cmd.findOption("--null-passwd"))
{
app.checkDependence("--null-passwd", "--enable-tls", opt_secureConnection);
opt_passwd = "";
}
cmd.endOptionBlock();
cmd.beginOptionBlock();
if (cmd.findOption("--pem-keys")) opt_keyFileFormat = SSL_FILETYPE_PEM;
if (cmd.findOption("--der-keys")) opt_keyFileFormat = SSL_FILETYPE_ASN1;
cmd.endOptionBlock();
if (cmd.findOption("--dhparam"))
{
app.checkValue(cmd.getValue(opt_dhparam));
}
if (cmd.findOption("--seed"))
{
app.checkValue(cmd.getValue(opt_readSeedFile));
}
cmd.beginOptionBlock();
if (cmd.findOption("--write-seed"))
{
app.checkDependence("--write-seed", "--seed", opt_readSeedFile != NULL);
opt_writeSeedFile = opt_readSeedFile;
}
if (cmd.findOption("--write-seed-file"))
{
app.checkDependence("--write-seed-file", "--seed", opt_readSeedFile != NULL);
app.checkValue(cmd.getValue(opt_writeSeedFile));
}
cmd.endOptionBlock();
cmd.beginOptionBlock();
if (cmd.findOption("--require-peer-cert")) opt_certVerification = DCV_requireCertificate;
if (cmd.findOption("--verify-peer-cert")) opt_certVerification = DCV_checkCertificate;
if (cmd.findOption("--ignore-peer-cert")) opt_certVerification = DCV_ignoreCertificate;
cmd.endOptionBlock();
const char *current = NULL;
const char *currentOpenSSL;
if (cmd.findOption("--cipher", 0, OFCommandLine::FOM_First))
{
opt_ciphersuites.clear();
do
{
app.checkValue(cmd.getValue(current));
if (NULL == (currentOpenSSL = DcmTLSTransportLayer::findOpenSSLCipherSuiteName(current)))
{
OFLOG_FATAL(storescpLogger, "ciphersuite '" << current << "' is unknown, known ciphersuites are:");
unsigned long numSuites = DcmTLSTransportLayer::getNumberOfCipherSuites();
for (unsigned long cs = 0; cs < numSuites; cs++)
{
OFLOG_FATAL(storescpLogger, " " << DcmTLSTransportLayer::getTLSCipherSuiteName(cs));
}
return 1;
}
else
{
if (opt_ciphersuites.length() > 0) opt_ciphersuites += ":";
opt_ciphersuites += currentOpenSSL;
}
} while (cmd.findOption("--cipher", 0, OFCommandLine::FOM_Next));
}
#endif
#ifdef HAVE_GETEUID
/* if port is privileged we must be as well */
if (opt_port < 1024)
{
if (geteuid() != 0)
{
OFLOG_FATAL(storescpLogger, "cannot listen on port " << opt_port << ", insufficient privileges");
return 1;
}
}
#endif
/* make sure data dictionary is loaded */
if (!dcmDataDict.isDictionaryLoaded())
{
OFLOG_WARN(storescpLogger, "no data dictionary loaded, check environment variable: "
<< DCM_DICT_ENVIRONMENT_VARIABLE);
}
/* if the output directory does not equal "." (default directory) */
if (opt_outputDirectory != ".")
{
/* if there is a path separator at the end of the path, get rid of it */
OFStandard::normalizeDirName(opt_outputDirectory, opt_outputDirectory);
/* check if the specified directory exists and if it is a directory.
* If the output directory is invalid, dump an error message and terminate execution.
*/
if (!OFStandard::dirExists(opt_outputDirectory))
{
OFLOG_FATAL(storescpLogger, "specified output directory does not exist");
return 1;
}
}
/* check if the output directory is writeable */
if (!OFStandard::isWriteable(opt_outputDirectory))
{
OFLOG_FATAL(storescpLogger, "specified output directory is not writeable");
return 1;
}
#ifdef HAVE_FORK
if (opt_forkMode)
DUL_requestForkOnTransportConnectionReceipt(argc, argv);
#elif defined(_WIN32)
if (opt_forkedChild)
{
// child process
DUL_markProcessAsForkedChild();
char buf[256];
DWORD bytesRead = 0;
HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
// read socket handle number from stdin, i.e. the anonymous pipe
// to which our parent process has written the handle number.
if (ReadFile(hStdIn, buf, sizeof(buf), &bytesRead, NULL))
{
// make sure buffer is zero terminated
buf[bytesRead] = '\0';
dcmExternalSocketHandle.set(atoi(buf));
}
else
{
OFLOG_ERROR(storescpLogger, "cannot read socket handle: " << GetLastError());
return 1;
}
}
else
{
// parent process
if (opt_forkMode)
DUL_requestForkOnTransportConnectionReceipt(argc, argv);
}
#endif
/* initialize network, i.e. create an instance of T_ASC_Network*. */
OFCondition cond = ASC_initializeNetwork(NET_ACCEPTOR, OFstatic_cast(int, opt_port), opt_acse_timeout, &net);
if (cond.bad())
{
OFLOG_ERROR(storescpLogger, "cannot create network: " << DimseCondition::dump(temp_str, cond));
return 1;
}
#ifdef HAVE_GETUID
/* return to normal uid so that we can't do too much damage in case
* things go very wrong. Only does someting if the program is setuid
* root, and run by another user. Running as root user may be
* potentially disasterous if this program screws up badly.
*/
setuid(getuid());
#endif
#ifdef WITH_OPENSSL
DcmTLSTransportLayer *tLayer = NULL;
if (opt_secureConnection)
{
tLayer = new DcmTLSTransportLayer(DICOM_APPLICATION_ACCEPTOR, opt_readSeedFile);
if (tLayer == NULL)
{
OFLOG_FATAL(storescpLogger, "unable to create TLS transport layer");
return 1;
}
if (cmd.findOption("--add-cert-file", 0, OFCommandLine::FOM_First))
{
do
{
app.checkValue(cmd.getValue(current));
if (TCS_ok != tLayer->addTrustedCertificateFile(current, opt_keyFileFormat))
{
OFLOG_WARN(storescpLogger, "unable to load certificate file '" << current << "', ignoring");
}
} while (cmd.findOption("--add-cert-file", 0, OFCommandLine::FOM_Next));
}
if (cmd.findOption("--add-cert-dir", 0, OFCommandLine::FOM_First))
{
do
{
app.checkValue(cmd.getValue(current));
if (TCS_ok != tLayer->addTrustedCertificateDir(current, opt_keyFileFormat))
{
OFLOG_WARN(storescpLogger, "unable to load certificates from directory '" << current << "', ignoring");
}
} while (cmd.findOption("--add-cert-dir", 0, OFCommandLine::FOM_Next));
}
if (opt_dhparam && !(tLayer->setTempDHParameters(opt_dhparam)))
{
OFLOG_WARN(storescpLogger, "unable to load temporary DH parameter file '" << opt_dhparam << "', ignoring");
}
if (opt_passwd) tLayer->setPrivateKeyPasswd(opt_passwd);
if (TCS_ok != tLayer->setPrivateKeyFile(opt_privateKeyFile, opt_keyFileFormat))
{
OFLOG_WARN(storescpLogger, "unable to load private TLS key from '" << opt_privateKeyFile << "'");
return 1;
}
if (TCS_ok != tLayer->setCertificateFile(opt_certificateFile, opt_keyFileFormat))
{
OFLOG_WARN(storescpLogger, "unable to load certificate from '" << opt_certificateFile << "'");
return 1;
}
if (! tLayer->checkPrivateKeyMatchesCertificate())
{
OFLOG_WARN(storescpLogger, "private key '" << opt_privateKeyFile << "' and certificate '" << opt_certificateFile << "' do not match");
return 1;
}
if (TCS_ok != tLayer->setCipherSuites(opt_ciphersuites.c_str()))
{
OFLOG_WARN(storescpLogger, "unable to set selected cipher suites");
return 1;
}
tLayer->setCertificateVerification(opt_certVerification);
cond = ASC_setTransportLayer(net, tLayer, 0);
if (cond.bad())
{
OFLOG_ERROR(storescpLogger, DimseCondition::dump(temp_str, cond));
return 1;
}
}
#endif
#ifdef HAVE_WAITPID
// register signal handler
signal(SIGCHLD, sigChildHandler);
#endif
while (cond.good())
{
/* receive an association and acknowledge or reject it. If the association was */
/* acknowledged, offer corresponding services and invoke one or more if required. */
cond = acceptAssociation(net, asccfg);
/* remove zombie child processes */
cleanChildren(-1, OFFalse);
#ifdef WITH_OPENSSL
/* since storescp is usually terminated with SIGTERM or the like,
* we write back an updated random seed after every association handled.
*/
if (tLayer && opt_writeSeedFile)
{
if (tLayer->canWriteRandomSeed())
{
if (!tLayer->writeRandomSeed(opt_writeSeedFile))
OFLOG_WARN(storescpLogger, "cannot write random seed file '" << opt_writeSeedFile << "', ignoring");
}
else
{
OFLOG_WARN(storescpLogger, "cannot write random seed, ignoring");
}
}
#endif
// if running in inetd mode, we always terminate after one association
if (opt_inetd_mode) break;
// if running in multi-process mode, always terminate child after one association
if (DUL_processIsForkedChild()) break;
}
/* drop the network, i.e. free memory of T_ASC_Network* structure. This call */
/* is the counterpart of ASC_initializeNetwork(...) which was called above. */
cond = ASC_dropNetwork(&net);
if (cond.bad())
{
OFLOG_ERROR(storescpLogger, DimseCondition::dump(temp_str, cond));
return 1;
}
#ifdef HAVE_WINSOCK_H
WSACleanup();
#endif
#ifdef WITH_OPENSSL
delete tLayer;
#endif
return 0;
}
static OFCondition acceptAssociation(T_ASC_Network *net, DcmAssociationConfiguration& asccfg)
{
char buf[BUFSIZ];
T_ASC_Association *assoc;
OFCondition cond;
OFString sprofile;
OFString temp_str;
#ifdef PRIVATE_STORESCP_VARIABLES
PRIVATE_STORESCP_VARIABLES
#endif
const char* knownAbstractSyntaxes[] =
{
UID_VerificationSOPClass
};
const char* transferSyntaxes[] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL };
int numTransferSyntaxes = 0;
// try to receive an association. Here we either want to use blocking or
// non-blocking, depending on if the option --eostudy-timeout is set.
if( opt_endOfStudyTimeout == -1 )
cond = ASC_receiveAssociation(net, &assoc, opt_maxPDU, NULL, NULL, opt_secureConnection);
else
cond = ASC_receiveAssociation(net, &assoc, opt_maxPDU, NULL, NULL, opt_secureConnection, DUL_NOBLOCK, OFstatic_cast(int, opt_endOfStudyTimeout));
if (cond.code() == DULC_FORKEDCHILD)
{
// OFLOG_DEBUG(storescpLogger, DimseCondition::dump(temp_str, cond));
goto cleanup;
}
// if some kind of error occured, take care of it
if (cond.bad())
{
// check what kind of error occurred. If no association was
// received, check if certain other conditions are met
if( cond == DUL_NOASSOCIATIONREQUEST )
{
// If in addition to the fact that no association was received also option --eostudy-timeout is set
// and if at the same time there is still a study which is considered to be open (i.e. we were actually
// expecting to receive more objects that belong to this study) (this is the case if lastStudyInstanceUID
// does not equal NULL), we have to consider that all objects for the current study have been received.
// In such an "end-of-study" case, we might have to execute certain optional functions which were specified
// by the user through command line options passed to storescp.
if( opt_endOfStudyTimeout != -1 && !lastStudyInstanceUID.empty() )
{
// indicate that the end-of-study-event occured through a timeout event.
// This knowledge will be necessary in function renameOnEndOFStudy().
endOfStudyThroughTimeoutEvent = OFTrue;
// before we actually execute those optional functions, we need to determine the path and name
// of the subdirectory into which the DICOM files for the last study were written.
lastStudySubdirectoryPathAndName = subdirectoryPathAndName;
// now we can finally handle end-of-study events which might have to be executed
executeEndOfStudyEvents();
// also, we need to clear lastStudyInstanceUID to indicate
// that the last study is not considered to be open any more.
lastStudyInstanceUID.clear();
// also, we need to clear subdirectoryPathAndName
subdirectoryPathAndName.clear();
// reset the endOfStudyThroughTimeoutEvent variable.
endOfStudyThroughTimeoutEvent = OFFalse;
}
}
// If something else was wrong we might have to dump an error message.
else
{
OFLOG_ERROR(storescpLogger, "Receiving Association failed: " << DimseCondition::dump(temp_str, cond));
}
// no matter what kind of error occurred, we need to do a cleanup
goto cleanup;
}
#if defined(HAVE_FORK) || defined(_WIN32)
if (opt_forkMode)
OFLOG_INFO(storescpLogger, "Association Received in " << (DUL_processIsForkedChild() ? "child" : "parent")
<< " process (pid: " << OFStandard::getProcessID() << ")");
else
#endif
OFLOG_INFO(storescpLogger, "Association Received");
/* dump presentation contexts if required */
if (opt_showPresentationContexts)
OFLOG_INFO(storescpLogger, "Parameters:" << OFendl << ASC_dumpParameters(temp_str, assoc->params, ASC_ASSOC_RQ));
else
OFLOG_DEBUG(storescpLogger, "Parameters:" << OFendl << ASC_dumpParameters(temp_str, assoc->params, ASC_ASSOC_RQ));
if (opt_refuseAssociation)
{
T_ASC_RejectParameters rej =
{
ASC_RESULT_REJECTEDPERMANENT,
ASC_SOURCE_SERVICEUSER,
ASC_REASON_SU_NOREASON
};
OFLOG_INFO(storescpLogger, "Refusing Association (forced via command line)");
cond = ASC_rejectAssociation(assoc, &rej);
if (cond.bad())
{
OFLOG_ERROR(storescpLogger, "Association Reject Failed: " << DimseCondition::dump(temp_str, cond));
}
goto cleanup;
}
switch (opt_networkTransferSyntax)
{
case EXS_LittleEndianImplicit:
/* we only support Little Endian Implicit */
transferSyntaxes[0] = UID_LittleEndianImplicitTransferSyntax;
numTransferSyntaxes = 1;
break;
case EXS_LittleEndianExplicit:
/* we prefer Little Endian Explicit */
transferSyntaxes[0] = UID_LittleEndianExplicitTransferSyntax;
transferSyntaxes[1] = UID_BigEndianExplicitTransferSyntax;
transferSyntaxes[2] = UID_LittleEndianImplicitTransferSyntax;
numTransferSyntaxes = 3;
break;
case EXS_BigEndianExplicit:
/* we prefer Big Endian Explicit */
transferSyntaxes[0] = UID_BigEndianExplicitTransferSyntax;
transferSyntaxes[1] = UID_LittleEndianExplicitTransferSyntax;
transferSyntaxes[2] = UID_LittleEndianImplicitTransferSyntax;
numTransferSyntaxes = 3;
break;
case EXS_JPEGProcess14SV1TransferSyntax:
/* we prefer JPEGLossless:Hierarchical-1stOrderPrediction (default lossless) */
transferSyntaxes[0] = UID_JPEGProcess14SV1TransferSyntax;
transferSyntaxes[1] = UID_LittleEndianExplicitTransferSyntax;
transferSyntaxes[2] = UID_BigEndianExplicitTransferSyntax;
transferSyntaxes[3] = UID_LittleEndianImplicitTransferSyntax;
numTransferSyntaxes = 4;
break;
case EXS_JPEGProcess1TransferSyntax:
/* we prefer JPEGBaseline (default lossy for 8 bit images) */
transferSyntaxes[0] = UID_JPEGProcess1TransferSyntax;
transferSyntaxes[1] = UID_LittleEndianExplicitTransferSyntax;
transferSyntaxes[2] = UID_BigEndianExplicitTransferSyntax;
transferSyntaxes[3] = UID_LittleEndianImplicitTransferSyntax;
numTransferSyntaxes = 4;
break;
case EXS_JPEGProcess2_4TransferSyntax:
/* we prefer JPEGExtended (default lossy for 12 bit images) */
transferSyntaxes[0] = UID_JPEGProcess2_4TransferSyntax;
transferSyntaxes[1] = UID_LittleEndianExplicitTransferSyntax;
transferSyntaxes[2] = UID_BigEndianExplicitTransferSyntax;
transferSyntaxes[3] = UID_LittleEndianImplicitTransferSyntax;
numTransferSyntaxes = 4;
break;
case EXS_JPEG2000LosslessOnly:
/* we prefer JPEG2000 Lossless */
transferSyntaxes[0] = UID_JPEG2000LosslessOnlyTransferSyntax;
transferSyntaxes[1] = UID_LittleEndianExplicitTransferSyntax;
transferSyntaxes[2] = UID_BigEndianExplicitTransferSyntax;
transferSyntaxes[3] = UID_LittleEndianImplicitTransferSyntax;
numTransferSyntaxes = 4;
break;
case EXS_JPEG2000:
/* we prefer JPEG2000 Lossy */
transferSyntaxes[0] = UID_JPEG2000TransferSyntax;
transferSyntaxes[1] = UID_LittleEndianExplicitTransferSyntax;
transferSyntaxes[2] = UID_BigEndianExplicitTransferSyntax;
transferSyntaxes[3] = UID_LittleEndianImplicitTransferSyntax;
numTransferSyntaxes = 4;
break;
case EXS_JPEGLSLossless:
/* we prefer JPEG-LS Lossless */
transferSyntaxes[0] = UID_JPEGLSLosslessTransferSyntax;
transferSyntaxes[1] = UID_LittleEndianExplicitTransferSyntax;
transferSyntaxes[2] = UID_BigEndianExplicitTransferSyntax;
transferSyntaxes[3] = UID_LittleEndianImplicitTransferSyntax;
numTransferSyntaxes = 4;
break;
case EXS_JPEGLSLossy:
/* we prefer JPEG-LS Lossy */
transferSyntaxes[0] = UID_JPEGLSLossyTransferSyntax;
transferSyntaxes[1] = UID_LittleEndianExplicitTransferSyntax;
transferSyntaxes[2] = UID_BigEndianExplicitTransferSyntax;
transferSyntaxes[3] = UID_LittleEndianImplicitTransferSyntax;
numTransferSyntaxes = 4;
break;
case EXS_MPEG2MainProfileAtMainLevel:
/* we prefer MPEG2 MP@ML */
transferSyntaxes[0] = UID_MPEG2MainProfileAtMainLevelTransferSyntax;
transferSyntaxes[1] = UID_LittleEndianExplicitTransferSyntax;
transferSyntaxes[2] = UID_BigEndianExplicitTransferSyntax;
transferSyntaxes[3] = UID_LittleEndianImplicitTransferSyntax;
numTransferSyntaxes = 4;
break;
case EXS_MPEG2MainProfileAtHighLevel:
/* we prefer MPEG2 MP@HL */
transferSyntaxes[0] = UID_MPEG2MainProfileAtHighLevelTransferSyntax;
transferSyntaxes[1] = UID_LittleEndianExplicitTransferSyntax;
transferSyntaxes[2] = UID_BigEndianExplicitTransferSyntax;
transferSyntaxes[3] = UID_LittleEndianImplicitTransferSyntax;
numTransferSyntaxes = 4;
break;
case EXS_RLELossless:
/* we prefer RLE Lossless */
transferSyntaxes[0] = UID_RLELosslessTransferSyntax;
transferSyntaxes[1] = UID_LittleEndianExplicitTransferSyntax;
transferSyntaxes[2] = UID_BigEndianExplicitTransferSyntax;
transferSyntaxes[3] = UID_LittleEndianImplicitTransferSyntax;
numTransferSyntaxes = 4;
break;
#ifdef WITH_ZLIB
case EXS_DeflatedLittleEndianExplicit:
/* we prefer Deflated Explicit VR Little Endian */
transferSyntaxes[0] = UID_DeflatedExplicitVRLittleEndianTransferSyntax;
transferSyntaxes[1] = UID_LittleEndianExplicitTransferSyntax;
transferSyntaxes[2] = UID_BigEndianExplicitTransferSyntax;
transferSyntaxes[3] = UID_LittleEndianImplicitTransferSyntax;
numTransferSyntaxes = 4;
break;
#endif
default:
if (opt_acceptAllXfers)
{
/* we accept all supported transfer syntaxes
* (similar to "AnyTransferSyntax" in "storescp.cfg")
*/
transferSyntaxes[0] = UID_JPEG2000TransferSyntax;
transferSyntaxes[1] = UID_JPEG2000LosslessOnlyTransferSyntax;
transferSyntaxes[2] = UID_JPEGProcess2_4TransferSyntax;
transferSyntaxes[3] = UID_JPEGProcess1TransferSyntax;
transferSyntaxes[4] = UID_JPEGProcess14SV1TransferSyntax;
transferSyntaxes[5] = UID_JPEGLSLossyTransferSyntax;
transferSyntaxes[6] = UID_JPEGLSLosslessTransferSyntax;
transferSyntaxes[7] = UID_RLELosslessTransferSyntax;
transferSyntaxes[8] = UID_MPEG2MainProfileAtMainLevelTransferSyntax;
transferSyntaxes[9] = UID_MPEG2MainProfileAtHighLevelTransferSyntax;
transferSyntaxes[10] = UID_DeflatedExplicitVRLittleEndianTransferSyntax;
if (gLocalByteOrder == EBO_LittleEndian)
{
transferSyntaxes[11] = UID_LittleEndianExplicitTransferSyntax;
transferSyntaxes[12] = UID_BigEndianExplicitTransferSyntax;
} else {
transferSyntaxes[11] = UID_BigEndianExplicitTransferSyntax;
transferSyntaxes[12] = UID_LittleEndianExplicitTransferSyntax;
}
transferSyntaxes[13] = UID_LittleEndianImplicitTransferSyntax;
numTransferSyntaxes = 14;
} else {
/* We prefer explicit transfer syntaxes.
* If we are running on a Little Endian machine we prefer
* LittleEndianExplicitTransferSyntax to BigEndianTransferSyntax.
*/
if (gLocalByteOrder == EBO_LittleEndian) /* defined in dcxfer.h */
{
transferSyntaxes[0] = UID_LittleEndianExplicitTransferSyntax;
transferSyntaxes[1] = UID_BigEndianExplicitTransferSyntax;
}
else
{
transferSyntaxes[0] = UID_BigEndianExplicitTransferSyntax;
transferSyntaxes[1] = UID_LittleEndianExplicitTransferSyntax;
}
transferSyntaxes[2] = UID_LittleEndianImplicitTransferSyntax;
numTransferSyntaxes = 3;
}
break;
}
if (opt_profileName)
{
/* perform name mangling for config file key */
const unsigned char *c = OFreinterpret_cast(const unsigned char *, opt_profileName);
while (*c)
{
if (!isspace(*c)) sprofile += OFstatic_cast(char, toupper(*c));
++c;
}
/* set presentation contexts as defined in config file */
cond = asccfg.evaluateAssociationParameters(sprofile.c_str(), *assoc);
if (cond.bad())
{
OFLOG_DEBUG(storescpLogger, DimseCondition::dump(temp_str, cond));
goto cleanup;
}
}
else
{
/* accept the Verification SOP Class if presented */
cond = ASC_acceptContextsWithPreferredTransferSyntaxes( assoc->params, knownAbstractSyntaxes, DIM_OF(knownAbstractSyntaxes), transferSyntaxes, numTransferSyntaxes);
if (cond.bad())
{
OFLOG_DEBUG(storescpLogger, DimseCondition::dump(temp_str, cond));
goto cleanup;
}
/* the array of Storage SOP Class UIDs comes from dcuid.h */
cond = ASC_acceptContextsWithPreferredTransferSyntaxes( assoc->params, dcmAllStorageSOPClassUIDs, numberOfAllDcmStorageSOPClassUIDs, transferSyntaxes, numTransferSyntaxes);
if (cond.bad())
{
OFLOG_DEBUG(storescpLogger, DimseCondition::dump(temp_str, cond));
goto cleanup;
}
if (opt_promiscuous)
{
/* accept everything not known not to be a storage SOP class */
cond = acceptUnknownContextsWithPreferredTransferSyntaxes(
assoc->params, transferSyntaxes, numTransferSyntaxes);
if (cond.bad())
{
OFLOG_DEBUG(storescpLogger, DimseCondition::dump(temp_str, cond));
goto cleanup;
}
}
}
/* set our app title */
ASC_setAPTitles(assoc->params, NULL, NULL, opt_respondingAETitle);
/* acknowledge or reject this association */
cond = ASC_getApplicationContextName(assoc->params, buf);
if ((cond.bad()) || strcmp(buf, UID_StandardApplicationContext) != 0)
{
/* reject: the application context name is not supported */
T_ASC_RejectParameters rej =
{
ASC_RESULT_REJECTEDPERMANENT,
ASC_SOURCE_SERVICEUSER,
ASC_REASON_SU_APPCONTEXTNAMENOTSUPPORTED
};
OFLOG_INFO(storescpLogger, "Association Rejected: Bad Application Context Name: " << buf);
cond = ASC_rejectAssociation(assoc, &rej);
if (cond.bad())
{
OFLOG_DEBUG(storescpLogger, DimseCondition::dump(temp_str, cond));
}
goto cleanup;
}
else if (opt_rejectWithoutImplementationUID && strlen(assoc->params->theirImplementationClassUID) == 0)
{
/* reject: the no implementation Class UID provided */
T_ASC_RejectParameters rej =
{
ASC_RESULT_REJECTEDPERMANENT,
ASC_SOURCE_SERVICEUSER,
ASC_REASON_SU_NOREASON
};
OFLOG_INFO(storescpLogger, "Association Rejected: No Implementation Class UID provided");
cond = ASC_rejectAssociation(assoc, &rej);
if (cond.bad())
{
OFLOG_DEBUG(storescpLogger, DimseCondition::dump(temp_str, cond));
}
goto cleanup;
}
else
{
#ifdef PRIVATE_STORESCP_CODE
PRIVATE_STORESCP_CODE
#endif
cond = ASC_acknowledgeAssociation(assoc);
if (cond.bad())
{
OFLOG_ERROR(storescpLogger, DimseCondition::dump(temp_str, cond));
goto cleanup;
}
OFLOG_INFO(storescpLogger, "Association Acknowledged (Max Send PDV: " << assoc->sendPDVLength << ")");
if (ASC_countAcceptedPresentationContexts(assoc->params) == 0)
OFLOG_INFO(storescpLogger, " (but no valid presentation contexts)");
/* dump the presentation contexts which have been accepted/refused */
if (opt_showPresentationContexts)
OFLOG_INFO(storescpLogger, ASC_dumpParameters(temp_str, assoc->params, ASC_ASSOC_AC));
else
OFLOG_DEBUG(storescpLogger, ASC_dumpParameters(temp_str, assoc->params, ASC_ASSOC_AC));
}
#ifdef BUGGY_IMPLEMENTATION_CLASS_UID_PREFIX
/* active the dcmPeerRequiresExactUIDCopy workaround code
* (see comments in dimse.h) for a implementation class UID
* prefix known to exhibit the buggy behaviour.
*/
if (0 == strncmp(assoc->params->theirImplementationClassUID,
BUGGY_IMPLEMENTATION_CLASS_UID_PREFIX,
strlen(BUGGY_IMPLEMENTATION_CLASS_UID_PREFIX)))
{
dcmEnableAutomaticInputDataCorrection.set(OFFalse);
dcmPeerRequiresExactUIDCopy.set(OFTrue);
}
#endif
// store previous values for later use
lastCallingAETitle = callingAETitle;
lastCalledAETitle = calledAETitle;
lastCallingPresentationAddress = callingPresentationAddress;
// store calling and called aetitle in global variables to enable
// the --exec options using them. Enclose in quotation marks because
// aetitles may contain space characters.
DIC_AE callingTitle;
DIC_AE calledTitle;
if (ASC_getAPTitles(assoc->params, callingTitle, calledTitle, NULL).good())
{
callingAETitle = "\"";
callingAETitle += OFSTRING_GUARD(callingTitle);
callingAETitle += "\"";
calledAETitle = "\"";
calledAETitle += OFSTRING_GUARD(calledTitle);
calledAETitle += "\"";
}
else
{
// should never happen
callingAETitle.clear();
calledAETitle.clear();
}
// store calling presentation address (i.e. remote hostname)
callingPresentationAddress = OFSTRING_GUARD(assoc->params->DULparams.callingPresentationAddress);
/* now do the real work, i.e. receive DIMSE commmands over the network connection */
/* which was established and handle these commands correspondingly. In case of */
/* storscp only C-ECHO-RQ and C-STORE-RQ commands can be processed. */
cond = processCommands(assoc);
if (cond == DUL_PEERREQUESTEDRELEASE)
{
OFLOG_INFO(storescpLogger, "Association Release");
cond = ASC_acknowledgeRelease(assoc);
}
else if (cond == DUL_PEERABORTEDASSOCIATION)
{
OFLOG_INFO(storescpLogger, "Association Aborted");
}
else
{
OFLOG_ERROR(storescpLogger, "DIMSE failure (aborting association): " << DimseCondition::dump(temp_str, cond));
/* some kind of error so abort the association */
cond = ASC_abortAssociation(assoc);
}
cleanup:
if (cond.code() == DULC_FORKEDCHILD) return cond;
cond = ASC_dropSCPAssociation(assoc);
if (cond.bad())
{
OFLOG_FATAL(storescpLogger, DimseCondition::dump(temp_str, cond));
exit(1);
}
cond = ASC_destroyAssociation(&assoc);
if (cond.bad())
{
OFLOG_FATAL(storescpLogger, DimseCondition::dump(temp_str, cond));
exit(1);
}
return cond;
}
static OFCondition
processCommands(T_ASC_Association * assoc)
/*
* This function receives DIMSE commmands over the network connection
* and handles these commands correspondingly. Note that in case of
* storscp only C-ECHO-RQ and C-STORE-RQ commands can be processed.
*
* Parameters:
* assoc - [in] The association (network connection to another DICOM application).
*/
{
OFCondition cond = EC_Normal;
T_DIMSE_Message msg;
T_ASC_PresentationContextID presID = 0;
DcmDataset *statusDetail = NULL;
// start a loop to be able to receive more than one DIMSE command
while( cond == EC_Normal || cond == DIMSE_NODATAAVAILABLE || cond == DIMSE_OUTOFRESOURCES )
{
// receive a DIMSE command over the network
if( opt_endOfStudyTimeout == -1 )
cond = DIMSE_receiveCommand(assoc, DIMSE_BLOCKING, 0, &presID, &msg, &statusDetail);
else
cond = DIMSE_receiveCommand(assoc, DIMSE_NONBLOCKING, OFstatic_cast(int, opt_endOfStudyTimeout), &presID, &msg, &statusDetail);
// check what kind of error occurred. If no data was
// received, check if certain other conditions are met
if( cond == DIMSE_NODATAAVAILABLE )
{
// If in addition to the fact that no data was received also option --eostudy-timeout is set and
// if at the same time there is still a study which is considered to be open (i.e. we were actually
// expecting to receive more objects that belong to this study) (this is the case if lastStudyInstanceUID
// does not equal NULL), we have to consider that all objects for the current study have been received.
// In such an "end-of-study" case, we might have to execute certain optional functions which were specified
// by the user through command line options passed to storescp.
if( opt_endOfStudyTimeout != -1 && !lastStudyInstanceUID.empty() )
{
// indicate that the end-of-study-event occured through a timeout event.
// This knowledge will be necessary in function renameOnEndOFStudy().
endOfStudyThroughTimeoutEvent = OFTrue;
// before we actually execute those optional functions, we need to determine the path and name
// of the subdirectory into which the DICOM files for the last study were written.
lastStudySubdirectoryPathAndName = subdirectoryPathAndName;
// now we can finally handle end-of-study events which might have to be executed
executeEndOfStudyEvents();
// also, we need to clear lastStudyInstanceUID to indicate
// that the last study is not considered to be open any more.
lastStudyInstanceUID.clear();
// also, we need to clear subdirectoryPathAndName
subdirectoryPathAndName.clear();
// reset the endOfStudyThroughTimeoutEvent variable.
endOfStudyThroughTimeoutEvent = OFFalse;
}
}
// if the command which was received has extra status
// detail information, dump this information
if (statusDetail != NULL)
{
OFLOG_WARN(storescpLogger, "Status Detail:" << OFendl << DcmObject::PrintHelper(*statusDetail));
delete statusDetail;
}
// check if peer did release or abort, or if we have a valid message
if (cond == EC_Normal)
{
// in case we received a valid message, process this command
// note that storescp can only process a C-ECHO-RQ and a C-STORE-RQ
switch (msg.CommandField)
{
case DIMSE_C_ECHO_RQ:
// process C-ECHO-Request
cond = echoSCP(assoc, &msg, presID);
break;
case DIMSE_C_STORE_RQ:
// process C-STORE-Request
cond = storeSCP(assoc, &msg, presID);
break;
default:
// we cannot handle this kind of message
cond = DIMSE_BADCOMMANDTYPE;
OFLOG_ERROR(storescpLogger, "cannot handle command: 0x"
<< STD_NAMESPACE hex << OFstatic_cast(unsigned, msg.CommandField));
break;
}
}
}
return cond;
}
static OFCondition echoSCP( T_ASC_Association * assoc, T_DIMSE_Message * msg, T_ASC_PresentationContextID presID)
{
OFString temp_str;
OFLOG_INFO(storescpLogger, "Received Echo Request");
OFLOG_DEBUG(storescpLogger, DIMSE_dumpMessage(temp_str, msg->msg.CEchoRQ, DIMSE_INCOMING, NULL, presID));
/* the echo succeeded !! */
OFCondition cond = DIMSE_sendEchoResponse(assoc, presID, &msg->msg.CEchoRQ, STATUS_Success, NULL);
if (cond.bad())
{
OFLOG_ERROR(storescpLogger, "Echo SCP Failed: " << DimseCondition::dump(temp_str, cond));
}
return cond;
}
// substitute non-ASCII characters with ASCII "equivalents"
static void mapCharacterAndAppendToString(Uint8 c,
OFString &output)
{
static const char *latin1_table[] =
{
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", // Codes 0-15
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", // Codes 16-31
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", // Codes 32-47
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "_", "_", "_", "_", "_", "_", // Codes 48-63
"_", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", // Codes 64-79
"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "_", "_", "_", "_", "_", // Codes 80-95
"_", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", // Codes 96-111
"p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "_", "_", "_", "_", "_", // Codes 112-127
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", // Codes 128-143
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", // Codes 144-159
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", // Codes 160-175
"_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", "_", // Codes 176-191
"A", "A", "A", "A", "Ae","A", "A", "C", "E", "E", "E", "E", "I", "I", "I", "I", // Codes 192-107
"D", "N", "O", "O", "O", "O", "Oe","_", "O", "U", "U", "U", "Ue","Y", "_", "ss",// Codes 108-123
"a", "a", "a", "a", "ae","a", "a", "c", "e", "e", "e", "e", "i", "i", "i", "i", // Codes 124-141
"d", "n", "o", "o", "o", "o", "oe","_", "o", "u", "u", "u", "ue","y", "_", "y" // Codes 142-157
};
output += latin1_table[c];
}
struct StoreCallbackData
{
char* imageFileName;
DcmFileFormat* dcmff;
T_ASC_Association* assoc;
};
static void
storeSCPCallback(
void *callbackData,
T_DIMSE_StoreProgress *progress,
T_DIMSE_C_StoreRQ *req,
char * /*imageFileName*/, DcmDataset **imageDataSet,
T_DIMSE_C_StoreRSP *rsp,
DcmDataset **statusDetail)
/*
* This function.is used to indicate progress when storescp receives instance data over the
* network. On the final call to this function (identified by progress->state == DIMSE_StoreEnd)
* this function will store the data set which was received over the network to a file.
* Earlier calls to this function will simply cause some information to be dumped to stdout.
*
* Parameters:
* callbackData - [in] data for this callback function
* progress - [in] The state of progress. (identifies if this is the initial or final call
* to this function, or a call in between these two calls.
* req - [in] The original store request message.
* imageFileName - [in] The path to and name of the file the information shall be written to.
* imageDataSet - [in] The data set which shall be stored in the image file
* rsp - [inout] the C-STORE-RSP message (will be sent after the call to this function)
* statusDetail - [inout] This variable can be used to capture detailed information with regard to
* the status information which is captured in the status element (0000,0900). Note
* that this function does specify any such information, the pointer will be set to NULL.
*/
{
DIC_UI sopClass;
DIC_UI sopInstance;
// determine if the association shall be aborted
if( (opt_abortDuringStore && progress->state != DIMSE_StoreBegin) ||
(opt_abortAfterStore && progress->state == DIMSE_StoreEnd) )
{
OFLOG_INFO(storescpLogger, "ABORT initiated (due to command line options)");
ASC_abortAssociation((OFstatic_cast(StoreCallbackData*, callbackData))->assoc);
rsp->DimseStatus = STATUS_STORE_Refused_OutOfResources;
return;
}
// if opt_sleepAfter is set, the user requires that the application shall
// sleep a certain amount of seconds after having received one PDU.
if (opt_sleepDuring > 0)
{
OFStandard::sleep(OFstatic_cast(unsigned int, opt_sleepDuring));
}
// dump some information if required (depending on the progress state)
// We can't use oflog for the pdu output, but we use a special logger for
// generating this output. If it is set to level "INFO" we generate the
// output, if it's set to "DEBUG" then we'll assume that there is debug output
// generated for each PDU elsewhere.
OFLogger progressLogger = OFLog::getLogger("dcmtk.apps." OFFIS_CONSOLE_APPLICATION ".progress");
if (progressLogger.getChainedLogLevel() == OFLogger::INFO_LOG_LEVEL)
{
switch (progress->state)
{
case DIMSE_StoreBegin:
COUT << "RECV: ";
break;
case DIMSE_StoreEnd:
COUT << OFendl;
break;
default:
COUT << '.';
break;
}
COUT.flush();
}
// if this is the final call of this function, save the data which was received to a file
// (note that we could also save the image somewhere else, put it in database, etc.)
if (progress->state == DIMSE_StoreEnd)
{
OFString tmpStr;
// do not send status detail information
*statusDetail = NULL;
// remember callback data
StoreCallbackData *cbdata = OFstatic_cast(StoreCallbackData *, callbackData);
// Concerning the following line: an appropriate status code is already set in the resp structure,
// it need not be success. For example, if the caller has already detected an out of resources problem
// then the status will reflect this. The callback function is still called to allow cleanup.
//rsp->DimseStatus = STATUS_Success;
// we want to write the received information to a file only if this information
// is present and the options opt_bitPreserving and opt_ignore are not set.
if ((imageDataSet != NULL) && (*imageDataSet != NULL) && !opt_bitPreserving && !opt_ignore)
{
OFString fileName;
// in case one of the --sort-xxx options is set, we need to perform some particular steps to
// determine the actual name of the output file
if (opt_sortStudyMode != ESM_None)
{
// determine the study instance UID in the (current) DICOM object that has just been received
OFString currentStudyInstanceUID;
if ((*imageDataSet)->findAndGetOFString(DCM_StudyInstanceUID, currentStudyInstanceUID).bad() || currentStudyInstanceUID.empty())
{
OFLOG_ERROR(storescpLogger, "element StudyInstanceUID " << DCM_StudyInstanceUID << " absent or empty in data set");
rsp->DimseStatus = STATUS_STORE_Error_CannotUnderstand;
return;
}
// if --sort-on-patientname is active, we need to extract the
// patient's name (format: last_name^first_name)
OFString currentPatientName;
if (opt_sortStudyMode == ESM_PatientName)
{
OFString tmpName;
if ((*imageDataSet)->findAndGetOFString(DCM_PatientName, tmpName).bad() || tmpName.empty())
{
// default if patient name is missing or empty
tmpName = "ANONYMOUS";
OFLOG_WARN(storescpLogger, "element PatientName " << DCM_PatientName << " absent or empty in data set, using '"
<< tmpName << "' instead");
}
/* substitute non-ASCII characters in patient name to ASCII "equivalent" */
const size_t length = tmpName.length();
for (size_t i = 0; i < length; i++)
mapCharacterAndAppendToString(tmpName[i], currentPatientName);
}
// if this is the first DICOM object that was received or if the study instance UID in the
// current DICOM object does not equal the last object's study instance UID we need to create
// a new subdirectory in which the current DICOM object will be stored
if (lastStudyInstanceUID.empty() || (lastStudyInstanceUID != currentStudyInstanceUID))
{
// if lastStudyInstanceUID is non-empty, we have just completed receiving all objects for one
// study. In such a case, we need to set a certain indicator variable (lastStudySubdirectoryPathAndName),
// so that we know that executeOnEndOfStudy() might have to be executed later. In detail, this indicator
// variable will contain the path and name of the last study's subdirectory, so that we can still remember
// this directory, when we execute executeOnEndOfStudy(). The memory that is allocated for this variable
// here will be freed after the execution of executeOnEndOfStudy().
if (!lastStudyInstanceUID.empty())
lastStudySubdirectoryPathAndName = subdirectoryPathAndName;
// create the new lastStudyInstanceUID value according to the value in the current DICOM object
lastStudyInstanceUID = currentStudyInstanceUID;
// get the current time (needed for subdirectory name)
OFDateTime dateTime;
dateTime.setCurrentDateTime();
// create a name for the new subdirectory.
char timestamp[32];
sprintf(timestamp, "%04u%02u%02u_%02u%02u%02u%03u",
dateTime.getDate().getYear(), dateTime.getDate().getMonth(), dateTime.getDate().getDay(),
dateTime.getTime().getHour(), dateTime.getTime().getMinute(), dateTime.getTime().getIntSecond(), dateTime.getTime().getMilliSecond());
OFString subdirectoryName;
switch (opt_sortStudyMode)
{
case ESM_Timestamp:
// pattern: "[prefix]_[YYYYMMDD]_[HHMMSSMMM]"
subdirectoryName = opt_sortStudyDirPrefix;
if (!subdirectoryName.empty())
subdirectoryName += '_';
subdirectoryName += timestamp;
break;
case ESM_StudyInstanceUID:
// pattern: "[prefix]_[Study Instance UID]"
subdirectoryName = opt_sortStudyDirPrefix;
if (!subdirectoryName.empty())
subdirectoryName += '_';
subdirectoryName += currentStudyInstanceUID;
break;
case ESM_PatientName:
// pattern: "[Patient's Name]_[YYYYMMDD]_[HHMMSSMMM]"
subdirectoryName = currentPatientName;
subdirectoryName += '_';
subdirectoryName += timestamp;
break;
case ESM_None:
break;
}
// create subdirectoryPathAndName (string with full path to new subdirectory)
OFStandard::combineDirAndFilename(subdirectoryPathAndName, OFStandard::getDirNameFromPath(tmpStr, cbdata->imageFileName), subdirectoryName);
/* if currentStudyInstanceUID is non-empty, this indicates that a new study was received. We need to set a certain indicator variable (nextStudySubdirectoryPathAndName),
* so that we know that executeOnStartOfStudy() needs to be executed.
==== by Zhe Liu, 2016/12/1 ==== */
if (!currentStudyInstanceUID.empty())
nextStudySubdirectoryPathAndName = subdirectoryPathAndName;
// check if the subdirectory already exists
// if it already exists dump a warning
if( OFStandard::dirExists(subdirectoryPathAndName) )
OFLOG_WARN(storescpLogger, "subdirectory for study already exists: " << subdirectoryPathAndName);
else
{
// if it does not exist create it
OFLOG_INFO(storescpLogger, "creating new subdirectory for study: " << subdirectoryPathAndName);
#ifdef HAVE_WINDOWS_H
if( _mkdir( subdirectoryPathAndName.c_str() ) == -1 )
#else
if( mkdir( subdirectoryPathAndName.c_str(), S_IRWXU | S_IRWXG | S_IRWXO ) == -1 )
#endif
{
OFLOG_ERROR(storescpLogger, "could not create subdirectory for study: " << subdirectoryPathAndName);
rsp->DimseStatus = STATUS_STORE_Error_CannotUnderstand;
return;
}
// all objects of a study have been received, so a new subdirectory is started.
// ->timename counter can be reset, because the next filename can't cause a duplicate.
// if no reset would be done, files of a new study (->new directory) would start with a counter in filename
if (opt_timeNames)
timeNameCounter = -1;
}
}
/* Now lastStudyInstanceUID == currentStudyInstanceUID, which means it is from the same exam
If another series come from the same exam, then the StudyInstanceUID remains the same, but the subdirectory is not there anymore
We need to create the same subdirectory again
==== by Zhe Liu, 2015/8/1 ==== */
else {
if( ! OFStandard::dirExists(subdirectoryPathAndName) )
{
// if it does not exist, re-create it
OFLOG_INFO(storescpLogger, "re-creating subdirectory for study: " << subdirectoryPathAndName);
#ifdef HAVE_WINDOWS_H
if( _mkdir( subdirectoryPathAndName.c_str() ) == -1 )
#else
if( mkdir( subdirectoryPathAndName.c_str(), S_IRWXU | S_IRWXG | S_IRWXO ) == -1 )
#endif
{
OFLOG_ERROR(storescpLogger, "could not create subdirectory for study: " << subdirectoryPathAndName);
rsp->DimseStatus = STATUS_STORE_Error_CannotUnderstand;
return;
}
// all objects of the previous series have been received, so a new subdirectory is started.
if (opt_timeNames)
timeNameCounter = -1;
}
}
/* ==== by Zhe Liu, 2015/8/1 ==== */
// integrate subdirectory name into file name (note that cbdata->imageFileName currently contains both
// path and file name; however, the path refers to the output directory captured in opt_outputDirectory)
OFStandard::combineDirAndFilename(fileName, subdirectoryPathAndName, OFStandard::getFilenameFromPath(tmpStr, cbdata->imageFileName));
// update global variable outputFileNameArray
// (might be used in executeOnReception() and renameOnEndOfStudy)
outputFileNameArray.push_back(tmpStr);
}
// if no --sort-xxx option is set, the determination of the output file name is simple
else
{
fileName = cbdata->imageFileName;
// update global variables outputFileNameArray
// (might be used in executeOnReception() and renameOnEndOfStudy)
outputFileNameArray.push_back(OFStandard::getFilenameFromPath(tmpStr, fileName));
}
// determine the transfer syntax which shall be used to write the information to the file
E_TransferSyntax xfer = opt_writeTransferSyntax;
if (xfer == EXS_Unknown) xfer = (*imageDataSet)->getOriginalXfer();
// store file either with meta header or as pure dataset
OFLOG_INFO(storescpLogger, "storing DICOM file: " << fileName);
if (OFStandard::fileExists(fileName))
{
OFLOG_WARN(storescpLogger, "DICOM file already exists, overwriting: " << fileName);
}
OFCondition cond = cbdata->dcmff->saveFile(fileName.c_str(), xfer, opt_sequenceType, opt_groupLength,
opt_paddingType, OFstatic_cast(Uint32, opt_filepad), OFstatic_cast(Uint32, opt_itempad),
(opt_useMetaheader) ? EWM_fileformat : EWM_dataset);
if (cond.bad())
{
OFLOG_ERROR(storescpLogger, "cannot write DICOM file: " << fileName << ": " << cond.text());
rsp->DimseStatus = STATUS_STORE_Refused_OutOfResources;
}
// check the image to make sure it is consistent, i.e. that its sopClass and sopInstance correspond
// to those mentioned in the request. If not, set the status in the response message variable.
if ((rsp->DimseStatus == STATUS_Success)&&(!opt_ignore))
{
// which SOP class and SOP instance ?
if (!DU_findSOPClassAndInstanceInDataSet(*imageDataSet, sopClass, sopInstance, opt_correctUIDPadding))
{
OFLOG_ERROR(storescpLogger, "bad DICOM file: " << fileName);
rsp->DimseStatus = STATUS_STORE_Error_CannotUnderstand;
}
else if (strcmp(sopClass, req->AffectedSOPClassUID) != 0)
{
rsp->DimseStatus = STATUS_STORE_Error_DataSetDoesNotMatchSOPClass;
}
else if (strcmp(sopInstance, req->AffectedSOPInstanceUID) != 0)
{
rsp->DimseStatus = STATUS_STORE_Error_DataSetDoesNotMatchSOPClass;
}
}
}
// in case opt_bitPreserving is set, do some other things
if( opt_bitPreserving )
{
// we need to set outputFileNameArray and outputFileNameArrayCnt to be
// able to perform the placeholder substitution in executeOnReception()
outputFileNameArray.push_back(OFStandard::getFilenameFromPath(tmpStr, cbdata->imageFileName));
}
}
}
static OFCondition storeSCP(
T_ASC_Association *assoc,
T_DIMSE_Message *msg,
T_ASC_PresentationContextID presID)
/*
* This function processes a DIMSE C-STORE-RQ commmand that was
* received over the network connection.
*
* Parameters:
* assoc - [in] The association (network connection to another DICOM application).
* msg - [in] The DIMSE C-STORE-RQ message that was received.
* presID - [in] The ID of the presentation context which was specified in the PDV which contained
* the DIMSE command.
*/
{
OFCondition cond = EC_Normal;
T_DIMSE_C_StoreRQ *req;
char imageFileName[2048];
// assign the actual information of the C-STORE-RQ command to a local variable
req = &msg->msg.CStoreRQ;
// if opt_ignore is set, the user requires that the data shall be received but not
// stored. in this case, we want to create a corresponding temporary filename for
// a file in which the data shall be stored temporarily. If this is not the case,
// create a real filename (consisting of path and filename) for a real file.
if (opt_ignore)
{
#ifdef _WIN32
tmpnam(imageFileName);
#else
strcpy(imageFileName, NULL_DEVICE_NAME);
#endif
}
else
{
// 3 possibilities: create unique filenames (fn), create timestamp fn, create fn from SOP Instance UIDs
if (opt_uniqueFilenames)
{
// create unique filename by generating a temporary UID and using ".X." as an infix
char buf[70];
dcmGenerateUniqueIdentifier(buf);
sprintf(imageFileName, "%s%c%s.X.%s%s", opt_outputDirectory.c_str(), PATH_SEPARATOR, dcmSOPClassUIDToModality(req->AffectedSOPClassUID, "UNKNOWN"),
buf, opt_fileNameExtension.c_str());
}
else if (opt_timeNames)
{
// create a name for the new file. pattern: "[YYYYMMDDHHMMSSMMM]_[NUMBER].MODALITY[EXTENSION]" (use current datetime)
// get the current time (needed for file name)
OFDateTime dateTime;
dateTime.setCurrentDateTime();
// used to hold prospective filename
char cmpFileName[2048];
// next if/else block generates prospective filename, that is compared to last written filename
if (timeNameCounter == -1)
{
// timeNameCounter not set -> last written filename has to be without "serial number"
sprintf(cmpFileName, "%04u%02u%02u%02u%02u%02u%03u.%s%s",
dateTime.getDate().getYear(), dateTime.getDate().getMonth(), dateTime.getDate().getDay(),
dateTime.getTime().getHour(), dateTime.getTime().getMinute(), dateTime.getTime().getIntSecond(), dateTime.getTime().getMilliSecond(),
dcmSOPClassUIDToModality(req->AffectedSOPClassUID, "UNKNOWN"), opt_fileNameExtension.c_str());
}
else
{
// counter was active before, so generate filename with "serial number" for comparison
sprintf(cmpFileName, "%04u%02u%02u%02u%02u%02u%03u_%04u.%s%s", // millisecond version
dateTime.getDate().getYear(), dateTime.getDate().getMonth(), dateTime.getDate().getDay(),
dateTime.getTime().getHour(), dateTime.getTime().getMinute(), dateTime.getTime().getIntSecond(), dateTime.getTime().getMilliSecond(),
timeNameCounter, dcmSOPClassUIDToModality(req->AffectedSOPClassUID, "UNKNOWN"), opt_fileNameExtension.c_str());
}
if ( (outputFileNameArray.size()!=0) && (outputFileNameArray.back() == cmpFileName) )
{
// if this is not the first run and the prospective filename is equal to the last written filename
// generate one with a serial number (incremented by 1)
timeNameCounter++;
sprintf(imageFileName, "%s%c%04u%02u%02u%02u%02u%02u%03u_%04u.%s%s", opt_outputDirectory.c_str(), PATH_SEPARATOR, // millisecond version
dateTime.getDate().getYear(), dateTime.getDate().getMonth(), dateTime.getDate().getDay(),
dateTime.getTime().getHour(), dateTime.getTime().getMinute(), dateTime.getTime().getIntSecond(), dateTime.getTime().getMilliSecond(),
timeNameCounter, dcmSOPClassUIDToModality(req->AffectedSOPClassUID, "UNKNOWN"), opt_fileNameExtension.c_str());
}
else
{
// first run or filenames are different: create filename without serial number
sprintf(imageFileName, "%s%c%04u%02u%02u%02u%02u%02u%03u.%s%s", opt_outputDirectory.c_str(), PATH_SEPARATOR, // millisecond version
dateTime.getDate().getYear(), dateTime.getDate().getMonth(), dateTime.getDate().getDay(),
dateTime.getTime().getHour(), dateTime.getTime().getMinute(),dateTime.getTime().getIntSecond(), dateTime.getTime().getMilliSecond(),
dcmSOPClassUIDToModality(req->AffectedSOPClassUID, "UNKNOWN"), opt_fileNameExtension.c_str());
// reset counter, because timestamp and therefore filename has changed
timeNameCounter = -1;
}
}
else
{
// don't create new UID, use the study instance UID as found in object
sprintf(imageFileName, "%s%c%s.%s%s", opt_outputDirectory.c_str(), PATH_SEPARATOR, dcmSOPClassUIDToModality(req->AffectedSOPClassUID, "UNKNOWN"),
req->AffectedSOPInstanceUID, opt_fileNameExtension.c_str());
}
}
// dump some information if required
OFString str;
OFLOG_INFO(storescpLogger, "Received Store Request: MsgID " << req->MessageID << ", ("
<< dcmSOPClassUIDToModality(req->AffectedSOPClassUID, "OT") << ")");
OFLOG_DEBUG(storescpLogger, DIMSE_dumpMessage(str, *req, DIMSE_INCOMING, NULL, presID));
// intialize some variables
StoreCallbackData callbackData;
callbackData.assoc = assoc;
callbackData.imageFileName = imageFileName;
DcmFileFormat dcmff;
callbackData.dcmff = &dcmff;
// store SourceApplicationEntityTitle in metaheader
if (assoc && assoc->params)
{
const char *aet = assoc->params->DULparams.callingAPTitle;
if (aet) dcmff.getMetaInfo()->putAndInsertString(DCM_SourceApplicationEntityTitle, aet);
}
// define an address where the information which will be received over the network will be stored
DcmDataset *dset = dcmff.getDataset();
// if opt_bitPreserving is set, the user requires that the data shall be
// written exactly as it was received. Depending on this option, function
// DIMSE_storeProvider must be called with certain parameters.
if (opt_bitPreserving)
{
cond = DIMSE_storeProvider(assoc, presID, req, imageFileName, opt_useMetaheader, NULL,
storeSCPCallback, &callbackData, opt_blockMode, opt_dimse_timeout);
}
else
{
cond = DIMSE_storeProvider(assoc, presID, req, NULL, opt_useMetaheader, &dset,
storeSCPCallback, &callbackData, opt_blockMode, opt_dimse_timeout);
}
// if some error occured, dump corresponding information and remove the outfile if necessary
if (cond.bad())
{
OFString temp_str;
OFLOG_ERROR(storescpLogger, "Store SCP Failed: " << DimseCondition::dump(temp_str, cond));
// remove file
if (!opt_ignore)
{
if (strcmp(imageFileName, NULL_DEVICE_NAME) != 0)
OFStandard::deleteFile(imageFileName);
}
}
#ifdef _WIN32
else if (opt_ignore)
{
if (strcmp(imageFileName, NULL_DEVICE_NAME) != 0)
OFStandard::deleteFile(imageFileName); // delete the temporary file
}
#endif
// if everything was successful so far and option --exec-on-reception is set,
// we want to execute a certain command which was passed to the application
if( cond.good() && opt_execOnReception != NULL )
executeOnReception();
// if everything was successful so far, go ahead and handle possible end-of-study events
if( cond.good() )
executeEndOfStudyEvents();
// if everything was successful so far, go ahead and handle possible start-of-study events
if( cond.good() )
executeStartOfStudyEvents();
// if opt_sleepAfter is set, the user requires that the application shall
// sleep a certain amount of seconds after storing the instance data.
if (opt_sleepAfter > 0)
{
OFStandard::sleep(OFstatic_cast(unsigned int, opt_sleepAfter));
}
// return return value
return cond;
}
static void executeEndOfStudyEvents()
/*
* This function deals with the execution of end-of-study-events. In detail,
* events that need to take place are sepcified by the user through certain
* command line options. The options that define these end-of-study-events
* are "--rename-on-eostudy" and "--exec-on-eostudy".
*
* Parameters:
* none.
*/
{
// if option --rename-on-eostudy is set and variable lastStudySubdirectoryPathAndName
// does not equal NULL (i.e. we received all objects that belong to one study, or - in
// other words - it is the end of one study) we want to rename the output files that
// belong to the last study. (Note that these files are captured in outputFileNameArray)
if( opt_renameOnEndOfStudy && !lastStudySubdirectoryPathAndName.empty() )
renameOnEndOfStudy();
// if option --exec-on-eostudy is set and variable lastStudySubdirectoryPathAndName does
// not equal NULL (i.e. we received all objects that belong to one study, or - in other
// words - it is the end of one study) we want to execute a certain command which was
// passed to the application
if( opt_execOnEndOfStudy != NULL && !lastStudySubdirectoryPathAndName.empty() )
executeOnEndOfStudy();
lastStudySubdirectoryPathAndName.clear();
}
static void executeStartOfStudyEvents()
/*
* This function deals with the execution of start-of-study-events. In detail,
* events that need to take place are specified by the user through certain
* command line options. The options that define these start-of-study-events
* are "--exec-on-sostudy".
*
* Parameters:
* none.
==== by Zhe Liu, 2016/12/1 ==== */
{
// if option --exec-on-sostudy is set and variable nextStudySubdirectoryPathAndName does
// not equal NULL (i.e. we received some object that belongs to a new study, or - in other
// words - it is the start of one study) we want to execute a certain command which was
// passed to the application
if( opt_execOnStartOfStudy != NULL && !nextStudySubdirectoryPathAndName.empty() )
executeOnStartOfStudy();
nextStudySubdirectoryPathAndName.clear();
}
static void executeOnReception()
/*
* This function deals with the execution of the command line which was passed
* to option --exec-on-reception of the storescp. This command line is captured
* in opt_execOnReception. Note that the command line can contain the placeholders
* PATH_PLACEHOLDER and FILENAME_PLACEHOLDER which need to be substituted before the command line is actually
* executed. PATH_PLACEHOLDER will be substituted by the path to the output directory into which
* the last file was written; FILENAME_PLACEHOLDER will be substituted by the filename of the last
* file which was written.
*
* Parameters:
* none.
*/
{
OFString cmd = opt_execOnReception;
// in case a file was actually written
if( !opt_ignore )
{
// perform substitution for placeholder #p (depending on presence of any --sort-xxx option)
OFString dir = (opt_sortStudyMode == ESM_None) ? opt_outputDirectory : subdirectoryPathAndName;
cmd = replaceChars( cmd, OFString(PATH_PLACEHOLDER), dir );
// perform substitution for placeholder #f; note that outputFileNameArray.back()
// always contains the name of the file (without path) which was written last.
OFString outputFileName = outputFileNameArray.back();
cmd = replaceChars( cmd, OFString(FILENAME_PLACEHOLDER), outputFileName );
}
// perform substitution for placeholder #a
cmd = replaceChars( cmd, OFString(CALLING_AETITLE_PLACEHOLDER), callingAETitle );
// perform substitution for placeholder #c
cmd = replaceChars( cmd, OFString(CALLED_AETITLE_PLACEHOLDER), calledAETitle );
// perform substitution for placeholder #r
cmd = replaceChars( cmd, OFString(CALLING_PRESENTATION_ADDRESS_PLACEHOLDER), callingPresentationAddress );
// Execute command in a new process
executeCommand( cmd );
}
static void renameOnEndOfStudy()
/*
* This function deals with renaming the last study's output files. In detail, these file's
* current filenames will be changed to a filename that corresponds to the pattern [modality-
* prefix][consecutive-numbering]. The current filenames of all files that belong to the study
* are captured in outputFileNameArray. The new filenames will be calculated whithin this
* function: The [modality-prefix] will be taken from the old filename,
* [consecutive-numbering] is a consecutively numbered, 6 digit number which will be calculated
* starting from 000001.
*
* Parameters:
* none.
*/
{
int counter = 1;
OFListIterator(OFString) first = outputFileNameArray.begin();
OFListIterator(OFString) last = outputFileNameArray.end();
// before we deal with all the filenames which are included in the array, we need to distinguish
// two different cases: If endOfStudyThroughTimeoutEvent is not true, the last filename in the array
// refers to a file that belongs to a new study of which the first object was just received. (In this
// case there are at least two filenames in the array). Then, this last filename is - at the end of the
// following loop - not supposed to be deleted from the array. If endOfStudyThroughTimeoutEvent is true,
// all filenames that are captured in the array, refer to files that belong to the same study. Hence,
// all of these files shall be renamed and all of the filenames within the array shall be deleted.
if( !endOfStudyThroughTimeoutEvent ) --last;
// rename all files that belong to the last study
while (first != last)
{
// determine the new file name: The first two characters of the old file name make up the [modality-prefix].
// The value for [consecutive-numbering] will be determined using the counter variable.
char modalityId[3];
char newFileName[9];
if (opt_timeNames)
{
// modality prefix are the first 2 characters after serial number (if present)
size_t serialPos = (*first).find("_");
if (serialPos != OFString_npos)
{
//serial present: copy modality prefix (skip serial: 1 digit "_" + 4 digits serial + 1 digit ".")
OFStandard::strlcpy( modalityId, (*first).substr(serialPos+6, 2).c_str(), 3 );
}
else
{
//serial not present, copy starts directly after first "." (skip 17 for timestamp, one for ".")
OFStandard::strlcpy( modalityId, (*first).substr(18, 2).c_str(), 3 );
}
}
else
{
OFStandard::strlcpy( modalityId, (*first).c_str(), 3 );
}
sprintf( newFileName, "%s%06d", modalityId, counter );
// create two strings containing path and file name for
// the current filename and the future filename
OFString oldPathAndFileName;
oldPathAndFileName = lastStudySubdirectoryPathAndName;
oldPathAndFileName += PATH_SEPARATOR;
oldPathAndFileName += *first;
OFString newPathAndFileName;
newPathAndFileName = lastStudySubdirectoryPathAndName;
newPathAndFileName += PATH_SEPARATOR;
newPathAndFileName += newFileName;
// rename file
if( rename( oldPathAndFileName.c_str(), newPathAndFileName.c_str() ) != 0 )
OFLOG_WARN(storescpLogger, "cannot rename file '" << oldPathAndFileName << "' to '" << newPathAndFileName << "'");
// remove entry from list
first = outputFileNameArray.erase(first);
// increase counter
counter++;
}
}
static void executeOnEndOfStudy()
/*
* This function deals with the execution of the command line which was passed
* to option --exec-on-eostudy of the storescp. This command line is captured
* in opt_execOnEndOfStudy. Note that the command line can contain the placeholder
* PATH_PLACEHOLDER which needs to be substituted before the command line is actually executed.
* In detail, PATH_PLACEHOLDER will be substituted by the path to the output directory into which
* the files of the last study were written.
*
* Parameters:
* none.
*/
{
OFString cmd = opt_execOnEndOfStudy;
// perform substitution for placeholder #p; #p will be substituted by lastStudySubdirectoryPathAndName
cmd = replaceChars( cmd, OFString(PATH_PLACEHOLDER), lastStudySubdirectoryPathAndName );
// perform substitution for placeholder #a
cmd = replaceChars( cmd, OFString(CALLING_AETITLE_PLACEHOLDER), (endOfStudyThroughTimeoutEvent) ? callingAETitle : lastCallingAETitle );
// perform substitution for placeholder #c
cmd = replaceChars( cmd, OFString(CALLED_AETITLE_PLACEHOLDER), (endOfStudyThroughTimeoutEvent) ? calledAETitle : lastCalledAETitle );
// perform substitution for placeholder #r
cmd = replaceChars( cmd, OFString(CALLING_PRESENTATION_ADDRESS_PLACEHOLDER), (endOfStudyThroughTimeoutEvent) ? callingPresentationAddress : lastCallingPresentationAddress );
// Execute command in a new process
executeCommand( cmd );
}
static void executeOnStartOfStudy()
/*
* This function deals with the execution of the command line which was passed
* to option --exec-on-sostudy of the storescp. This command line is captured
* in opt_execOnStartOfStudy. Note that the command line can contain the placeholder
* PATH_PLACEHOLDER which needs to be substituted before the command line is actually executed.
* In detail, PATH_PLACEHOLDER will be substituted by the path to the output directory into which
* the files of the next study were written.
*
* Parameters:
* none.
==== by Zhe Liu, 2016/12/1 ==== */
{
OFString cmd = opt_execOnStartOfStudy;
// perform substitution for placeholder #p; #p will be substituted by nextStudySubdirectoryPathAndName
cmd = replaceChars( cmd, OFString(PATH_PLACEHOLDER), nextStudySubdirectoryPathAndName );
// perform substitution for placeholder #a
cmd = replaceChars( cmd, OFString(CALLING_AETITLE_PLACEHOLDER), callingAETitle);
// perform substitution for placeholder #c
cmd = replaceChars( cmd, OFString(CALLED_AETITLE_PLACEHOLDER), calledAETitle);
// perform substitution for placeholder #r
cmd = replaceChars( cmd, OFString(CALLING_PRESENTATION_ADDRESS_PLACEHOLDER), callingPresentationAddress);
// Execute command in a new process
executeCommand( cmd );
}
static OFString replaceChars( const OFString &srcstr, const OFString &pattern, const OFString &substitute )
/*
* This function replaces all occurrences of pattern in srcstr with substitute and returns
* the result as a new OFString variable. Note that srcstr itself will not be changed,
*
* Parameters:
* srcstr - [in] The source string.
* pattern - [in] The pattern string which shall be substituted.
* substitute - [in] The substitute for pattern in srcstr.
*/
{
OFString result = srcstr;
size_t pos = 0;
while( pos != OFString_npos )
{
pos = result.find( pattern, pos );
if( pos != OFString_npos )
{
result.replace( pos, pattern.size(), substitute );
pos += substitute.size();
}
}
return( result );
}
static void executeCommand( const OFString &cmd )
/*
* This function executes the given command line. The execution will be
* performed in a new process which can be run in the background
* so that it does not slow down the execution of storescp.
*
* Parameters:
* cmd - [in] The command which shall be executed.
*/
{
#ifdef HAVE_FORK
pid_t pid = fork();
if( pid < 0 ) // in case fork failed, dump an error message
OFLOG_ERROR(storescpLogger, "cannot execute command '" << cmd << "' (fork failed)");
else if (pid > 0)
{
/* we are the parent process */
/* remove pending zombie child processes */
cleanChildren(pid, opt_execSync);
}
else // in case we are the child process, execute the command etc.
{
// execute command through execl will terminate the child process.
// Since we only have a single command string and not a list of arguments,
// we 'emulate' a call to system() by passing the command to /bin/sh
// which hopefully exists on all Posix systems.
if (execl( "/bin/sh", "/bin/sh", "-c", cmd.c_str(), NULL ) < 0)
OFLOG_ERROR(storescpLogger, "cannot execute /bin/sh");
// if execl succeeds, this part will not get executed.
// if execl fails, there is not much we can do except bailing out.
abort();
}
#else
PROCESS_INFORMATION procinfo;
STARTUPINFO sinfo;
OFBitmanipTemplate<char>::zeroMem((char *)&sinfo, sizeof(sinfo));
sinfo.cb = sizeof(sinfo);
// execute command (Attention: Do not pass DETACHED_PROCESS as sixth argument to the below
// called function because in such a case the execution of batch-files is not going to work.)
if( !CreateProcess(NULL, OFconst_cast(char *, cmd.c_str()), NULL, NULL, 0, 0, NULL, NULL, &sinfo, &procinfo) )
OFLOG_ERROR(storescpLogger, "cannot execute command '" << cmd << "'");
if (opt_execSync)
{
// Wait until child process exits (makes execution synchronous)
WaitForSingleObject(procinfo.hProcess, INFINITE);
}
// Close process and thread handles to avoid resource leak
CloseHandle(procinfo.hProcess);
CloseHandle(procinfo.hThread);
#endif
}
static void cleanChildren(pid_t pid, OFBool synch)
/*
* This function removes child processes that have terminated,
* i.e. converted to zombies. Should be called now and then.
*/
{
#ifdef HAVE_WAITPID
int stat_loc;
#elif HAVE_WAIT3
struct rusage rusage;
#if defined(__NeXT__)
/* some systems need a union wait as argument to wait3 */
union wait status;
#else
int status;
#endif
#endif
#if defined(HAVE_WAITPID) || defined(HAVE_WAIT3)
int child = 1;
int options = synch ? 0 : WNOHANG;
while (child > 0)
{
#ifdef HAVE_WAITPID
child = OFstatic_cast(int, waitpid(pid, &stat_loc, options));
#elif defined(HAVE_WAIT3)
child = wait3(&status, options, &rusage);
#endif
if (child < 0)
{
if (errno != ECHILD)
{
char buf[256];
OFLOG_WARN(storescpLogger, "wait for child failed: " << OFStandard::strerror(errno, buf, sizeof(buf)));
}
}
if (synch) child = -1; // break out of loop
}
#endif
}
static
DUL_PRESENTATIONCONTEXT *
findPresentationContextID(LST_HEAD * head,
T_ASC_PresentationContextID presentationContextID)
{
DUL_PRESENTATIONCONTEXT *pc;
LST_HEAD **l;
OFBool found = OFFalse;
if (head == NULL)
return NULL;
l = &head;
if (*l == NULL)
return NULL;
pc = OFstatic_cast(DUL_PRESENTATIONCONTEXT *, LST_Head(l));
(void)LST_Position(l, OFstatic_cast(LST_NODE *, pc));
while (pc && !found) {
if (pc->presentationContextID == presentationContextID) {
found = OFTrue;
} else {
pc = OFstatic_cast(DUL_PRESENTATIONCONTEXT *, LST_Next(l));
}
}
return pc;
}
/** accept all presenstation contexts for unknown SOP classes,
* i.e. UIDs appearing in the list of abstract syntaxes
* where no corresponding name is defined in the UID dictionary.
* @param params pointer to association parameters structure
* @param transferSyntax transfer syntax to accept
* @param acceptedRole SCU/SCP role to accept
*/
static OFCondition acceptUnknownContextsWithTransferSyntax(
T_ASC_Parameters * params,
const char* transferSyntax,
T_ASC_SC_ROLE acceptedRole)
{
OFCondition cond = EC_Normal;
int n, i, k;
DUL_PRESENTATIONCONTEXT *dpc;
T_ASC_PresentationContext pc;
OFBool accepted = OFFalse;
OFBool abstractOK = OFFalse;
n = ASC_countPresentationContexts(params);
for (i = 0; i < n; i++)
{
cond = ASC_getPresentationContext(params, i, &pc);
if (cond.bad()) return cond;
abstractOK = OFFalse;
accepted = OFFalse;
if (dcmFindNameOfUID(pc.abstractSyntax) == NULL)
{
abstractOK = OFTrue;
/* check the transfer syntax */
for (k = 0; (k < OFstatic_cast(int, pc.transferSyntaxCount)) && !accepted; k++)
{
if (strcmp(pc.proposedTransferSyntaxes[k], transferSyntax) == 0)
{
accepted = OFTrue;
}
}
}
if (accepted)
{
cond = ASC_acceptPresentationContext(
params, pc.presentationContextID,
transferSyntax, acceptedRole);
if (cond.bad()) return cond;
} else {
T_ASC_P_ResultReason reason;
/* do not refuse if already accepted */
dpc = findPresentationContextID(params->DULparams.acceptedPresentationContext,
pc.presentationContextID);
if ((dpc == NULL) || ((dpc != NULL) && (dpc->result != ASC_P_ACCEPTANCE)))
{
if (abstractOK) {
reason = ASC_P_TRANSFERSYNTAXESNOTSUPPORTED;
} else {
reason = ASC_P_ABSTRACTSYNTAXNOTSUPPORTED;
}
/*
* If previously this presentation context was refused
* because of bad transfer syntax let it stay that way.
*/
if ((dpc != NULL) && (dpc->result == ASC_P_TRANSFERSYNTAXESNOTSUPPORTED))
reason = ASC_P_TRANSFERSYNTAXESNOTSUPPORTED;
cond = ASC_refusePresentationContext(params, pc.presentationContextID, reason);
if (cond.bad()) return cond;
}
}
}
return EC_Normal;
}
/** accept all presenstation contexts for unknown SOP classes,
* i.e. UIDs appearing in the list of abstract syntaxes
* where no corresponding name is defined in the UID dictionary.
* This method is passed a list of "preferred" transfer syntaxes.
* @param params pointer to association parameters structure
* @param transferSyntax transfer syntax to accept
* @param acceptedRole SCU/SCP role to accept
*/
static OFCondition acceptUnknownContextsWithPreferredTransferSyntaxes(
T_ASC_Parameters * params,
const char* transferSyntaxes[], int transferSyntaxCount,
T_ASC_SC_ROLE acceptedRole)
{
OFCondition cond = EC_Normal;
/*
** Accept in the order "least wanted" to "most wanted" transfer
** syntax. Accepting a transfer syntax will override previously
** accepted transfer syntaxes.
*/
for (int i = transferSyntaxCount - 1; i >= 0; i--)
{
cond = acceptUnknownContextsWithTransferSyntax(params, transferSyntaxes[i], acceptedRole);
if (cond.bad()) return cond;
}
return cond;
}
#ifdef HAVE_CONFIG_H
static int makeTempFile()
{
char tempfile[30];
OFStandard::strlcpy(tempfile, "/tmp/storescp_XXXXXX", 30);
#ifdef HAVE_MKSTEMP
return mkstemp(tempfile);
#else /* ! HAVE_MKSTEMP */
mktemp(tempfile);
return open(tempfile, O_WRONLY|O_CREAT|O_APPEND, 0644);
#endif
}
#endif
/*
** CVS Log
** $Log: storescp.cc,v $
** Revision 1.137 2010-11-04 10:22:50 joergr
** Made sure that options --exec/rename-on-eostudy are never used with --fork on
** Windows systems (since this does not work due to the current implementation).
**
** Revision 1.136 2010-10-20 07:41:35 uli
** Made sure isalpha() & friends are only called with valid arguments.
**
** Revision 1.135 2010-10-14 13:13:42 joergr
** Updated copyright header. Added reference to COPYRIGHT file.
**
** Revision 1.134 2010-10-04 10:51:46 joergr
** Introduced new substitution variable "#r" for the calling presentation
** address (i.e. the hostname or IP address of the peer storage SCU).
**
** Revision 1.133 2010-09-16 08:28:40 uli
** Log DUL errors on the ERROR level instead of INFO.
**
** Revision 1.132 2010-09-14 11:46:23 uli
** Log DUL errors on the INFO level instead of DEBUG.
**
** Revision 1.131 2010-09-10 13:58:10 joergr
** Revised warning message to indicate that existing DICOM file is overwritten.
**
** Revision 1.130 2010-09-07 07:54:45 uli
** Fixed a missing addOption() call.
**
** Revision 1.129 2010-09-02 12:12:48 joergr
** Added support for "MPEG2 Main Profile @ High Level" transfer syntax.
**
** Revision 1.128 2010-08-09 13:19:31 joergr
** Updated data dictionary to 2009 edition of the DICOM standard. From now on,
** the official "keyword" is used for the attribute name which results in a
** number of minor changes (e.g. "PatientsName" is now called "PatientName").
**
** Revision 1.127 2010-06-04 08:07:03 joergr
** Added support for option --exec-sync to Unix systems (before: Windows only).
**
** Revision 1.126 2010-06-02 14:42:59 joergr
** Replaced calls to strerror() by new helper function OFStandard::strerror()
** which results in using the thread safe version of strerror() if available.
**
** Revision 1.125 2010-05-18 16:10:25 joergr
** Replaced '\n' by OFendl in log messages.
**
** Revision 1.124 2010-05-10 09:47:53 joergr
** Added warning message when output file already exists. Output details on
** error condition if output file cannot be written.
**
** Revision 1.123 2010-03-23 15:20:13 joergr
** Use printError() method for command line parsing errors only. After the
** resource identifier has been printed to the log stream use "oflog" instead.
**
** Revision 1.122 2010-01-20 13:49:47 uli
** Added OFStandard::getProcessID().
**
** Revision 1.121 2010-01-04 16:14:40 joergr
** Fixed issue with --sort-conc-studies option by slightly reworking the file
** and directory name string handling (use helper functions from "ofstd").
** Added info log message that shows the name of the stored DICOM file.
**
** Revision 1.120 2009-12-02 16:13:23 joergr
** Make sure that dcmSOPClassUIDToModality() never returns NULL when passed to
** the log stream in order to avoid an application crash.
**
** Revision 1.119 2009-12-01 10:16:07 joergr
** Sightly modified log messages.
**
** Revision 1.118 2009-12-01 09:53:01 joergr
** Added new command line option --verbose-pc that allows for showing the
** presentation contexts in verbose mode. Sightly modified log messages.
**
** Revision 1.117 2009-11-18 11:53:58 uli
** Switched to logging mechanism provided by the "new" oflog module.
**
** Revision 1.116 2009-11-12 10:13:01 joergr
** Fixed issue with --accept-all command line option which caused the other
** --prefer-xxx options to be ignored under certain conditions.
**
** Revision 1.115 2009-08-21 09:47:34 joergr
** Added parameter 'writeMode' to save/write methods which allows for specifying
** whether to write a dataset or fileformat as well as whether to update the
** file meta information or to create a new file meta information header.
**
** Revision 1.114 2009-08-19 11:55:44 meichel
** Added additional includes needed for Sun Studio 11 on Solaris.
**
** Revision 1.113 2009-08-04 10:08:42 joergr
** Added output of Presentation Context ID of the C-STORE message in debug mode.
**
** Revision 1.112 2009-06-04 10:16:24 joergr
** Added new flag that can be used to avoid wrong warning messages (in debug
** mode) that an option has possibly never been checked.
**
** Revision 1.111 2009-05-28 10:12:56 joergr
** Fixed issue with substitution variables "#a" and "#c": In some cases, the AE
** titles from the wrong association were used during execute on end-of-study.
**
** Revision 1.110 2009-04-23 16:51:41 joergr
** Changed the condition under which the process is terminated in inetd mode
** (the behavior should be identical but now the source code is more clear).
**
** Revision 1.109 2009-04-22 13:32:02 joergr
** Made inetd code and documentation more consistent with ppsscpfs.
**
** Revision 1.108 2009-04-21 14:09:22 joergr
** Fixed minor inconsistencies in manpage / syntax usage.
**
** Revision 1.107 2009-04-17 11:51:58 joergr
** Added new command line option --single-process in order to explicitly
** indicate what the default behavior is (no multi-processing).
**
** Revision 1.106 2009-04-06 11:37:56 joergr
** Also check whether the output directory is writable if it's the current
** directory (".").
**
** Revision 1.105 2009-03-06 14:53:53 joergr
** Made error/warning messages and verbose output more consistent with movescu.
** Added check whether output directory is writable (not only existent).
** Made use of debug mode (instead of verbose mode) where appropriate.
**
** Revision 1.104 2009-03-05 18:14:05 joergr
** Added new command line option --sort-on-study-uid.
** Renamed command line option --sort-on-patientsname to --sort-on-patientname.
** Slightly reworked (simplified) code on the creation of subdirectory names.
** Made warning and error messages more consistent throughout the tool. Changed
** output from stderr to CERR and from stdout to COUT. Introduced general
** OFStandard methods where appropriate. Fixed description of command line option.
**
** Revision 1.103 2009-02-06 16:08:44 joergr
** Added support for JPEG-LS and MPEG2 transfer syntaxes.
** Fixed minor inconsistencies with regard to transfer syntaxes.
** Added new option that allows for accepting all supported transfer syntaxes.
** Call OFConsoleApplication::checkDependence() where appropriate.
**
** Revision 1.102 2009-01-07 17:19:53 joergr
** Avoid double output of resource identifier for forked children (Win32).
**
** Revision 1.101 2008-11-20 12:06:06 joergr
** Moved command line option --output-directory to "output" section and made
** syntax description more consistent with other DCMTK tools.
**
** Revision 1.100 2008-11-03 15:44:26 joergr
** Removed "option block" encapsulation from option --compression-level.
**
** Revision 1.99 2008-11-03 15:29:03 joergr
** Made documentation of --compression-level more consistent with other options.
**
** Revision 1.98 2008-09-25 16:00:58 joergr
** Added support for printing the expanded command line arguments.
** Always output the resource identifier of the command line tool in debug mode.
**
** Revision 1.97 2006-10-27 11:59:53 joergr
** Fixed problem with unknown (e.g. private) SOP Classes.
**
** Revision 1.96 2006/08/15 16:04:28 meichel
** Updated the code in module dcmnet to correctly compile when
** all standard C++ classes remain in namespace std.
**
** Revision 1.95 2006/07/27 14:12:45 joergr
** Changed parameter "exclusive" of method addOption() from type OFBool into an
** integer parameter "flags". Prepended prefix "PF_" to parseLine() flags.
** Option "--help" is no longer an exclusive option by default.
** Added new addOption() flag for internal options that are not shown in the
** syntax usage output. Used e.g. for the "--fork" option in storescp.
** Added optional library "LIBWRAP" to output of option "--version".
**
** Revision 1.94 2006/07/17 10:51:56 joergr
** Fixed layout and formatting issues.
**
** Revision 1.93 2006/07/14 15:46:36 meichel
** Added new command line option --sort-on-patientsname that sorts images into
** study folders named by the patient's name followed by a timestamp.
**
** Revision 1.92 2006/06/23 10:24:41 meichel
** All Store SCPs in DCMTK now store the source application entity title in the
** metaheader, both in normal and in bit-preserving mode.
**
** Revision 1.91 2006/02/23 12:51:32 joergr
** Fixed layout and formatting issues.
**
** Revision 1.90 2006/02/03 10:21:59 joergr
** Print help text if no command line argument is specified. This is the default
** behaviour of most DCMTK tools.
** Fixed inconsistent source code layout.
**
** Revision 1.89 2005/12/19 10:31:12 joergr
** Changed printf() type for return value of getpid() to "%ld" and added
** explicit typecast, needed for Solaris.
**
** Revision 1.88 2005/12/16 13:07:03 meichel
** Changed type to size_t to make code safe on 64bit platforms
**
** Revision 1.87 2005/12/14 14:27:36 joergr
** Added missing header file "fcntl.h", needed for Solaris.
** Replaced "string::npos" by "OFString_npos".
** Changed printf() type for return value of getpid() to "%d".
**
** Revision 1.86 2005/12/14 10:45:55 meichel
** Including csignal if present, needed on Solaris.
**
** Revision 1.85 2005/12/08 15:44:21 meichel
** Changed include path schema for all DCMTK header files
**
** Revision 1.84 2005/11/28 16:28:53 meichel
** Fixed resource leak in Win32 command execution.
** Added option --exec-sync that causes synchronous command execution on Windows.
**
** Revision 1.83 2005/11/25 11:31:03 meichel
** StoreSCP now supports multi-process mode both on Posix and Win32 platforms
** where a separate client process is forked for each incoming association.
**
** Revision 1.82 2005/11/23 16:10:23 meichel
** Added support for AES ciphersuites in TLS module. All TLS-enabled
** tools now support the "AES TLS Secure Transport Connection Profile".
**
** Revision 1.81 2005/11/17 13:45:16 meichel
** Added command line options for DIMSE and ACSE timeouts
**
** Revision 1.80 2005/11/16 14:58:07 meichel
** Set association timeout in ASC_initializeNetwork to 30 seconds. This improves
** the responsiveness of the tools if the peer blocks during assoc negotiation.
**
** Revision 1.79 2005/11/11 16:09:00 onken
** Added options for JPEG2000 support (lossy and lossless)
**
** Revision 1.78 2005/11/10 09:13:21 onken
** Added option "--timenames" to support filenames based on timestamps.
** Added option "--file-extension", that allows to append a suffix
** to each filename.
**
** Revision 1.77 2005/10/25 08:55:43 meichel
** Updated list of UIDs and added support for new transfer syntaxes
** and storage SOP classes.
**
** Revision 1.76 2005/08/30 08:35:23 meichel
** Added command line option --inetd, which allows storescp to run from inetd.
**
** Revision 1.75 2005/02/22 09:40:54 meichel
** Fixed two bugs in "bit-preserving" Store SCP code. Errors while creating or
** writing the DICOM file (e.g. file system full) now result in a DIMSE error
** response (out of resources) being sent back to the SCU.
**
** Revision 1.74 2004/08/03 16:46:00 meichel
** Minor changes for platforms on which strchr/strrchr return a const pointer.
**
** Revision 1.73 2004/04/07 16:58:55 meichel
** Added OFconst_cast, required on Win32
**
** Revision 1.72 2004/04/07 10:01:16 meichel
** Removed call to system() and execl to /bin/false which does not exist
** on some BSD platforms.
**
** Revision 1.71 2004/04/07 09:42:34 meichel
** Updated sorting and command execution code in storescp to use OFString
** and OFList. This will hopefully fix the remaining memory leaks.
**
** Revision 1.70 2004/04/06 18:11:24 joergr
** Added missing suffix "TransferSyntax" to some transfer syntax constants.
**
** Revision 1.69 2004/02/25 12:18:06 meichel
** Added a few dummy macros allowing for future private extensions
**
** Revision 1.68 2004/02/13 14:17:39 joergr
** Removed acknowledgements with e-mail addresses from CVS log.
**
** Revision 1.67 2004/02/12 14:05:17 wilkens
** Corrected bug in storescp that options "-xcr" and "+B" (or "--ignore") could
** not be used together. Now they can.
**
** Revision 1.66 2003/08/14 10:58:47 meichel
** Added check if association configuration profile is valid for SCP use
**
** Revision 1.65 2003/08/11 18:31:15 joergr
** Included "ctype" header file required for gcc 3.2.3 on Debian Linux.
**
** Revision 1.64 2003/06/11 15:46:24 meichel
** Added support for configuration file based association negotiation
** profiles
**
** Revision 1.63 2003/06/10 14:17:35 meichel
** Added option to create unique filenames, even if receiving the same
** SOP instance multiple times. Exec options now allow to pass the calling
** and called aetitle on the command line.
**
** Revision 1.62 2003/06/10 14:05:57 meichel
** Added support for TCP wrappers based host access control
**
** Revision 1.61 2003/06/06 09:44:40 meichel
** Added static sleep function in class OFStandard. This replaces the various
** calls to sleep(), Sleep() and usleep() throughout the toolkit.
**
** Revision 1.60 2002/11/27 13:04:31 meichel
** Adapted module dcmnet to use of new header file ofstdinc.h
**
** Revision 1.59 2002/11/26 08:43:21 meichel
** Replaced all includes for "zlib.h" with <zlib.h>
** to avoid inclusion of zlib.h in the makefile dependencies.
**
** Revision 1.58 2002/11/25 18:00:19 meichel
** Converted compile time option to leniently handle space padded UIDs
** in the Storage Service Class into command line / config file option.
**
** Revision 1.57 2002/09/23 17:53:47 joergr
** Added new command line option "--version" which prints the name and version
** number of external libraries used (incl. preparation for future support of
** 'config.guess' host identifiers).
**
** Revision 1.56 2002/09/10 16:04:33 meichel
** Added experimental "promiscuous" mode to storescp. In this mode,
** activated by the --promiscuous command line option, all presentation
** contexts not known not to be Storage SOP Classes are accepted.
**
** Revision 1.55 2002/09/02 15:35:57 meichel
** Added --prefer-deflated, --write-xfer-deflated and --compression-level
** options to storescp
**
** Revision 1.54 2002/08/21 10:18:27 meichel
** Adapted code to new loadFile and saveFile methods, thus removing direct
** use of the DICOM stream classes.
**
** Revision 1.53 2002/08/02 10:59:56 meichel
** Execute options in storescp now clean up zombie child processes
** as they should.
**
** Revision 1.52 2002/04/19 10:46:11 joergr
** Added new helper routines to get the milli and micro seconds part as well as
** the integral value of seconds.
**
** Revision 1.51 2002/04/11 12:47:33 joergr
** Replaced direct call of system routines by new standard date and time
** functions.
** Use the new standard file system routines like fileExists() etc.
**
** Revision 1.50 2001/12/19 09:59:43 meichel
** Added prototype declaration for gettimeofday() for systems like Ultrix
** where the function is known but no prototype present in the system headers.
**
** Revision 1.49 2001/12/14 12:18:06 wilkens
** Fixed a bug in storescp that prevented the application from working correctly
** under Unix.
**
** Revision 1.48 2001/12/14 09:51:51 joergr
** Modified use of time routines to keep gcc on Mac OS X happy.
**
** Revision 1.47 2001/12/11 15:12:01 joergr
** Fixed warning reported by cygwin gcc compiler.
**
** Revision 1.46 2001/12/11 14:11:49 joergr
** Replaced occurrences of strncpy by more secure strlcpy (see ofstd.h).
** Added type cast to keep old Sun compilers quiet.
** Modified description of command line option -tos.
**
** Revision 1.45 2001/12/06 14:11:11 joergr
** Made description and layout of command line options more consistent.
**
** Revision 1.44 2001/11/30 10:01:34 wilkens
** Changed description of command line options.
**
** Revision 1.43 2001/11/28 14:23:33 wilkens
** Fixed a problem with storescp. Execution of batch-files through new options
** --exec-on-reception and --exec-on-eostudy is now possible also for optimized
** executable.
**
** Revision 1.41 2001/11/09 15:56:25 joergr
** Renamed some of the getValue/getParam methods to avoid ambiguities reported
** by certain compilers.
**
** Revision 1.40 2001/11/01 14:39:01 wilkens
** Added lots of comments.
**
** Revision 1.39 2001/10/12 10:18:21 meichel
** Replaced the CONDITION types, constants and functions in the dcmnet module
** by an OFCondition based implementation which eliminates the global condition
** stack. This is a major change, caveat emptor!
**
** Revision 1.38 2001/09/28 13:21:41 joergr
** Replaced "cerr" by "CERR".
**
** Revision 1.37 2001/06/01 15:50:02 meichel
** Updated copyright header
**
** Revision 1.36 2001/06/01 11:01:57 meichel
** Implemented global flag and command line option to disable reverse
** DNS hostname lookup using gethostbyaddr when accepting associations.
**
** Revision 1.35 2000/12/15 13:28:14 meichel
** Global flag to enable/disable workaround code for some buggy Store SCUs
** in DIMSE_storeProvider(). If enabled, an illegal space-padding in the
** Affected SOP Instance UID field of the C-STORE-RQ message is retained
** in the corresponding C-STORE-RSP message.
**
** Revision 1.34 2000/11/10 18:07:43 meichel
** Mixed up strcmp and strcpy - oops.
**
** Revision 1.33 2000/11/10 16:25:04 meichel
** Fixed problem with DIMSE routines which attempted to delete /dev/null
** under certain circumstances, which could lead to disastrous results if
** tools were run with root permissions (what they shouldn't).
**
** Revision 1.32 2000/08/10 14:50:49 meichel
** Added initial OpenSSL support.
**
** Revision 1.31 2000/06/07 13:56:18 meichel
** Output stream now passed as mandatory parameter to ASC_dumpParameters.
**
** Revision 1.30 2000/04/14 16:29:27 meichel
** Removed default value from output stream passed to print() method.
** Required for use in multi-thread environments.
**
** Revision 1.29 2000/03/08 16:43:16 meichel
** Updated copyright header.
**
** Revision 1.28 2000/02/29 11:49:50 meichel
** Removed support for VS value representation. This was proposed in CP 101
** but never became part of the standard.
**
** Revision 1.27 2000/02/23 15:12:21 meichel
** Corrected macro for Borland C++ Builder 4 workaround.
**
** Revision 1.26 2000/02/03 11:50:09 meichel
** Moved UID related functions from dcmnet (diutil.h) to dcmdata (dcuid.h)
** where they belong. Renamed access functions to dcmSOPClassUIDToModality
** and dcmGuessModalityBytes.
**
** Revision 1.25 2000/02/01 10:24:03 meichel
** Avoiding to include <stdlib.h> as extern "C" on Borland C++ Builder 4,
** workaround for bug in compiler header files.
**
** Revision 1.24 1999/10/07 17:26:19 meichel
** Corrected typo in storescup error message
**
** Revision 1.23 1999/04/29 10:02:54 meichel
** Adapted findscu to new command line option scheme
**
** Revision 1.22 1999/04/28 08:29:07 meichel
** Adapted storescp to new command line option scheme.
** Added support for transmission of compressed images.
**
** Revision 1.21 1999/04/27 17:24:40 meichel
** Adapted storescp to new command line option scheme.
** Added support for transmission of compressed images.
**
** Revision 1.20 1999/03/29 11:19:55 meichel
** Cleaned up dcmnet code for char* to const char* assignments.
**
** Revision 1.19 1998/08/10 08:53:36 meichel
** renamed member variable in DIMSE structures from "Status" to
** "DimseStatus". This is required if dcmnet is used together with
** <X11/Xlib.h> where Status is #define'd as int.
**
** Revision 1.18 1998/02/06 15:07:30 meichel
** Removed many minor problems (name clashes, unreached code)
** reported by Sun CC4 with "+w" or Sun CC2.
**
** Revision 1.17 1998/01/14 14:35:55 hewett
** Modified existing -u command line option to also disable generation
** of UT and VS (previously just disabled generation of UN).
**
** Revision 1.16 1997/09/12 13:21:50 meichel
** Command line option '-h' in storescp now works correctly.
**
** Revision 1.15 1997/08/05 07:36:21 andreas
** - Corrected error in DUL finite state machine
** SCPs shall close sockets after the SCU have closed the socket in
** a normal association release. Therfore, an ARTIM timer is described
** in DICOM part 8 that is not implemented correctly in the
** DUL. Since the whole DUL finite state machine is affected, we
** decided to solve the proble outside the fsm. Now it is necessary to call the
** ASC_DropSCPAssociation() after the calling ASC_acknowledgeRelease().
** - Change needed version number of WINSOCK to 1.1
** to support WINDOWS 95
**
** Revision 1.14 1997/07/24 13:10:55 andreas
** - Removed Warnings from SUN CC 2.0.1
**
** Revision 1.13 1997/07/21 08:37:04 andreas
** - Replace all boolean types (BOOLEAN, CTNBOOLEAN, DICOM_BOOL, BOOL)
** with one unique boolean type OFBool.
**
** Revision 1.12 1997/05/29 15:52:57 meichel
** Added constant for dcmtk release date in dcuid.h.
** All dcmtk applications now contain a version string
** which is displayed with the command line options ("usage" message)
** and which can be queried in the binary with the "ident" command.
**
** Revision 1.11 1997/05/27 15:44:53 meichel
** Corrected typo in storescp help texts.
**
** Revision 1.10 1997/05/23 10:44:20 meichel
** Major rewrite of storescp application. See CHANGES for details.
** Changes to interfaces of some DIMSE functions.
**
** Revision 1.9 1997/05/22 13:29:59 hewett
** Modified the test for presence of a data dictionary to use the
** method DcmDataDictionary::isDictionaryLoaded().
**
** Revision 1.8 1997/05/16 08:31:34 andreas
** - Revised handling of GroupLength elements and support of
** DataSetTrailingPadding elements. The enumeratio E_GrpLenEncoding
** got additional enumeration values (for a description see dctypes.h).
** addGroupLength and removeGroupLength methods are replaced by
** computeGroupLengthAndPadding. To support Padding, the parameters of
** element and sequence write functions changed.
**
** Revision 1.7 1997/03/27 16:11:27 hewett
** Added command line switches allowing generation of UN to
** be disabled (it is enabled by default).
**
** Revision 1.6 1996/12/16 15:14:00 hewett
** Added bugfix for WINSOCK support. The required WINSOCK version
** number was being incorrectly set to version 0.1. The fixed
** WINSOCK initialisation now uses the MAKEWORD macro to correctly
** set the required version number. This bugfix was contributed
** by Dr. Yongjian Bao of Innomed GmbH, Germany.
**
** Revision 1.5 1996/09/27 14:05:05 hewett
** Added calls to initialise WINSOCK library for Win32 environment. Only
** compiled in if HAVE_WINSOCK_H
**
** Revision 1.4 1996/09/27 08:24:30 hewett
** System header files now enclosed with BEGIN_EXTERN_C/END_EXTERN_C
**
** Revision 1.3 1996/09/24 16:20:32 hewett
** Now uses global table of Storage SOP Class UIDs (from dcuid.h).
** Added preliminary support for the Macintosh environment (GUSI library).
**
** Revision 1.2 1996/09/03 11:39:03 hewett
** Added copyright information.
**
** Revision 1.1.1.1 1996/03/26 18:38:44 hewett
** Initial Release.
**
**
*/
|
//-----------------------------------------------------------------------------------
// Code generated by the Toolify Robotics GmbH extension for the SmartMDSD Toolchain
//
// Toolify Robotics GmbH
// Weinbergweg 216
// 89075 Ulm
//
// Information about the SmartSoft MDSD Toolchain is available at:
// www.servicerobotik-ulm.de
//
// Please do not modify this file. It will be re-generated
// running the code generator.
//-----------------------------------------------------------------------------------
#include "CommMobileManipulatorStateJSON.hh"
#include "CommManipulatorObjectsJSON/CommManipulatorStateJSON.hh"
#include "CommBasicObjectsJSON/CommBaseStateJSON.hh"
namespace CommManipulatorObjectsIDL {
void to_json(const CommManipulatorObjectsIDL::CommMobileManipulatorState& obj, nlohmann::json& j)
{
// manipulator_state: CommManipulatorState
to_json(obj.manipulator_state, j["manipulator_state"]);
// base_state: CommBaseState
to_json(obj.base_state, j["base_state"]);
}
/**
* this transformation handles missing values and checks for correct types:
* - missing primitive type values (including simple arrays) are set to zero values
* - missing object type values are skipped entirely
* - types are checked before performing the type-cast operation
*/
void from_json(const nlohmann::json& j, CommManipulatorObjectsIDL::CommMobileManipulatorState& obj)
{
// manipulator_state: CommManipulatorState
if(j.contains("manipulator_state") && j["manipulator_state"].is_object()) {
//from_json(j["manipulator_state"], obj.manipulator_state);
obj.manipulator_state = j["manipulator_state"].get<CommManipulatorObjectsIDL::CommManipulatorState>();
}
// base_state: CommBaseState
if(j.contains("base_state") && j["base_state"].is_object()) {
//from_json(j["base_state"], obj.base_state);
obj.base_state = j["base_state"].get<CommBasicObjectsIDL::CommBaseState>();
}
}
} // end namespace CommManipulatorObjectsIDL
|
/*
* Copyright 2019 Carnegie Technologies
*
* 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 <cstddef>
#include "basic/MemHandle.hpp"
#include "basic/Buffer.hpp"
#include "ProtoError.hpp"
#include "ExtProtoError.hpp"
namespace Pravala
{
class Json;
/// @brief Class that should be inherited by all protocol messages
class Serializable
{
public:
/// @brief The max length of the length header.
/// (the length field's header plus the actual length).
static const size_t MaxLengthHeaderSize;
/// @brief The field ID of the 'length' field.
static const uint32_t LengthVarFieldId;
/// @brief The type of the length variable.
/// It uses signed type for compatibility with Java.
typedef int32_t LengthVarType;
/// @brief Serializes content of the object to the buffer
///
/// First it calls setupDefines(). Next it verifies the validity of the object by calling validate().
/// Then it calls serializeFields().
///
/// It appends serialized data to the buffer. This function does not encode message's length.
///
/// @param [in] buf The buffer to serialize the data to
/// @param [out] extError Pointer to extended error code if it should be used (only modified on error).
/// @return The error code
virtual ProtoError serialize ( Buffer & buf, ExtProtoError * extError = 0 );
/// @brief Serializes content of the object to the buffer.
/// Convenience function, it internally creates a buffer to append to, and generates a MemHandle based on it.
/// This function does not encode message's length.
///
/// @param [out] data This MemHandle will be set to contain the serialized content of the object.
/// @param [in] preAllocateMemory The number of bytes to pre-allocate in the buffer.
/// @param [out] extError Pointer to extended error code if it should be used (only modified on error).
/// @return The error code
inline ProtoError serialize (
MemHandle & data, size_t preAllocateMemory = 0, ExtProtoError * extError = 0 )
{
Buffer buf ( preAllocateMemory );
const ProtoError eCode = serialize ( buf, extError );
if ( IS_OK ( eCode ) )
{
data = buf.getHandle();
}
return eCode;
}
/// @brief Serializes content of the object to a Json object.
///
/// First it calls setupDefines(). Next it verifies the validity of the object by calling validate().
/// Then it calls serializeFields().
///
/// @note It only works if the protocol implementation was generated with Json output enabled.
/// @param [out] json The Json object to serialize the data into.
/// It will be cleared before inserting elements to it.
/// @param [out] extError Pointer to extended error code if it should be used (only modified on error).
/// @return The error code
virtual ProtoError serialize ( Json & json, ExtProtoError * extError = 0 );
/// @brief Serializes content of the object to the buffer
///
/// It calls serialize() and also encodes the total payload's length.
/// This version appends to an existing buffer. The drawback is that the payload length
/// is always encoded using the maximum number of bytes.
///
/// @param [in] buf The buffer to serialize the data to
/// @param [out] extError Pointer to extended error code if it should be used (only modified on error).
/// @return The error code
ProtoError serializeWithLength ( Buffer & buf, ExtProtoError * extError = 0 );
/// @brief Serializes content of the object to the buffer
///
/// It calls serialize() and also encodes the total payload's length.
/// It returns new buffer with the serialized content of the object.
/// This version creates a new buffer instead of appending to an existing one.
/// The advantage over the other version is that the payload length is encoded in more
/// efficient method, and instead of always using the maximum number of bytes for that
/// field it encodes it using smaller number of bytes that depends on the actual length.
///
/// @param [out] errCode The pointer to an error code. If it is non-zero the error code
/// is placed there.
/// @param [out] extError Pointer to extended error code if it should be used (only modified on error).
/// @return A new buffer with serialized content of the message, or 0 on error.
MemHandle serializeWithLength ( ProtoError * errCode = 0, ExtProtoError * extError = 0 );
/// @brief Deserializes data from the buffer
///
/// It uses deserializeField() to deserialize each of the fields in the message.
/// Then it checks validity of the data read using validate() function.
///
/// @param [in] buf The buffer to deserialize the data from.
/// @param [in] offset Offset in the buffer.
/// @param [in] dataSize The size of data (starting at given offset).
/// @param [out] extError Pointer to extended error code if it should be used (only modified on error).
/// @return The error code
virtual ProtoError deserialize (
const MemHandle & buf, size_t offset, size_t dataSize,
ExtProtoError * extError = 0 );
/// @brief Deserializes data from the buffer
///
/// It uses deserializeField() to deserialize each of the fields in the message.
/// Then it checks validity of the data read using validate() function.
///
/// @param [in] buf The buffer to deserialize the data from (the entire buffer is used).
/// @param [out] extError Pointer to extended error code if it should be used (only modified on error).
/// @return The error code
inline ProtoError deserialize ( const MemHandle & buf, ExtProtoError * extError = 0 )
{
return deserialize ( buf, 0, buf.size(), extError );
}
/// @brief Deserializes data from the buffer.
///
/// It detects the length of the message by reading the 'length field' that should be included in the buffer.
/// Then it calls deserialize().
///
/// @param [in] buf The buffer to deserialize the data from
/// @param [in,out] offset Offset in the buffer to start from.
/// It is modified (only if the message is deserialized properly).
/// @param [out] missingBytes If used, the number of missing bytes is placed there.
/// It is only set when 'Error::IncompleteData' is returned.
/// @param [out] extError Pointer to extended error code if it should be used (only modified on error).
/// @return The error code
ProtoError deserializeWithLength (
const MemHandle & buf, size_t & offset, size_t * missingBytes = 0,
ExtProtoError * extError = 0 );
/// @brief Deserializes data from the buffer and consumes that data in the buffer.
///
/// It is a convenience wrapper around deserializeWithLength ( MemHandle, ... ) function.
/// It creates a MemHandle based on the entire buffer, clears the buffer and then
/// deserializes the message. If there are any bytes that were not used - data that belongs
/// to the next message, or all of the data in case there were any errors while deserializing,
/// all the data is put back in the buffer.
///
/// There should be no performance difference between this approach and using RwBuffer::consumeData,
/// since re-adding all of the data back to the buffer doesn't require creating copies.
/// On the other hand, if any data was consumed, memory reallocation and copying data happens in both cases
/// (simply moving the data within existing memory - which would be slightly faster - is not possible,
/// because - since we succeeded - there is a reference to the original data in SerializableMessage::_orgBuf).
///
/// The preferred method, however, is to use MemHandle in a loop.
/// Once there is a buffer with some data in it, a MemHandle should be created and the buffer cleared.
/// Next the deserializeWithLength ( MemHandle ) version should be used and, on success,
/// any remaining memory should be put in a new MemHandle using MemHandle::getHandle
/// and deserializeWithLength ( MemHandle ) should be called on the new handle.
/// Once there is an error (more data is needed), the remaining MemHandle should be appended to
/// the original (now empty) buffer.
///
/// @param [in] buf The buffer to deserialize the data from.
/// @param [out] missingBytes If used, the number of missing bytes is placed there.
/// It is only set when 'Error::IncompleteData' is returned.
/// @param [out] extError Pointer to extended error code if it should be used (only modified on error).
/// @return The error code.
ProtoError deserializeWithLength ( Buffer & buf, size_t * missingBytes = 0, ExtProtoError * extError = 0 );
/// @brief Clears the content.
///
/// All fields will either be set to their default values (or 0 if not set) or their clear()
/// method will be called and they will be set as not present.
virtual void clear() = 0;
/// @brief Checks validity of the data
///
/// Returns success if all required fields in this and all inherited objects (if any)
/// are present and have legal values. If this is used by external code on messages
/// or structures that are to be sent (NOT on received ones!)
/// it is probably a good idea to call setupDefines() first.
/// @param [out] extError Pointer to extended error code if it should be used (only modified on error).
/// @return Standard error code
virtual ProtoError validate ( ExtProtoError * extError = 0 ) const = 0;
/// @brief Sets the values of all the fields 'defined' by this and all inherited objects (if any)
virtual void setupDefines() = 0;
/// @brief Virtual destructor
virtual ~Serializable();
protected:
/// @brief Serializes all fields to the buffer
/// @param [in] buf The buffer to serialize the data to
/// @param [out] extError Pointer to extended error code if it should be used (only modified on error).
/// @return The error code
virtual ProtoError serializeFields ( Buffer & buf, ExtProtoError * extError ) = 0;
/// @brief Serializes all fields of the object to a Json object.
/// @note The default implementation returns 'Unsupported' error.
/// @param [out] json The Json object to serialize the data into.
/// It will be cleared before inserting elements to it.
/// @param [out] extError Pointer to extended error code if it should be used (only modified on error).
/// @return The error code
virtual ProtoError serializeFields ( Json & json, ExtProtoError * extError );
/// @brief Deserializes a single field from the buffer
///
/// @param [in] fieldId The ID of the field.
/// @param [in] wireType Encoding type.
/// @param [in] buf The buffer to deserialize the data from
/// @param [in] offset Offset in the buffer.
/// @param [in] fieldSize The size of this field (starting at given offset).
/// @param [out] extError Pointer to extended error code if it should be used (only modified on error).
/// @return Standard error code; ProtocolWarning is treated as success and may mean that this message
/// didn't know the field, OR it was a valid object field, which, in turn,
/// experienced ProtocolWarning at some point.
virtual ProtoError deserializeField (
uint32_t fieldId, uint8_t wireType, const MemHandle & buf,
size_t offset, size_t fieldSize,
ExtProtoError * extError ) = 0;
};
}
|
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/activity_log/activity_actions.h"
#include <memory>
#include <string>
#include <utility>
#include "base/format_macros.h"
#include "base/json/json_string_value_serializer.h"
#include "base/memory/ptr_util.h"
#include "base/memory/scoped_refptr.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/values.h"
#include "chrome/browser/extensions/activity_log/activity_action_constants.h"
#include "chrome/browser/extensions/activity_log/fullstream_ui_policy.h"
#include "extensions/common/constants.h"
#include "extensions/common/dom_action_types.h"
#include "url/gurl.h"
namespace constants = activity_log_constants;
namespace activity_log = extensions::api::activity_log_private;
namespace extensions {
namespace {
std::string Serialize(const base::Value* value) {
std::string value_as_text;
if (!value) {
value_as_text = "null";
} else {
JSONStringValueSerializer serializer(&value_as_text);
serializer.SerializeAndOmitBinaryValues(*value);
}
return value_as_text;
}
} // namespace
using api::activity_log_private::ExtensionActivity;
Action::Action(const std::string& extension_id,
const base::Time& time,
const ActionType action_type,
const std::string& api_name,
int64_t action_id)
: extension_id_(extension_id),
time_(time),
action_type_(action_type),
api_name_(api_name),
page_incognito_(false),
arg_incognito_(false),
count_(0),
action_id_(action_id) {}
Action::~Action() {}
// TODO(mvrable): As an optimization, we might return this directly if the
// refcount is one. However, there are likely to be other stray references in
// many cases that will prevent this optimization.
scoped_refptr<Action> Action::Clone() const {
auto clone = base::MakeRefCounted<Action>(
extension_id(), time(), action_type(), api_name(), action_id());
if (args())
clone->set_args(base::WrapUnique(args()->DeepCopy()));
clone->set_page_url(page_url());
clone->set_page_title(page_title());
clone->set_page_incognito(page_incognito());
clone->set_arg_url(arg_url());
clone->set_arg_incognito(arg_incognito());
if (other())
clone->set_other(base::WrapUnique(other()->DeepCopy()));
return clone;
}
void Action::set_args(std::unique_ptr<base::ListValue> args) {
args_ = std::move(args);
}
base::ListValue* Action::mutable_args() {
if (!args_.get()) {
args_.reset(new base::ListValue());
}
return args_.get();
}
void Action::set_page_url(const GURL& page_url) {
page_url_ = page_url;
}
void Action::set_arg_url(const GURL& arg_url) {
arg_url_ = arg_url;
}
void Action::set_other(std::unique_ptr<base::DictionaryValue> other) {
other_ = std::move(other);
}
base::DictionaryValue* Action::mutable_other() {
if (!other_.get()) {
other_.reset(new base::DictionaryValue());
}
return other_.get();
}
std::string Action::SerializePageUrl() const {
return (page_incognito() ? constants::kIncognitoUrl : "") + page_url().spec();
}
void Action::ParsePageUrl(const std::string& url) {
set_page_incognito(base::StartsWith(url, constants::kIncognitoUrl,
base::CompareCase::SENSITIVE));
if (page_incognito())
set_page_url(GURL(url.substr(strlen(constants::kIncognitoUrl))));
else
set_page_url(GURL(url));
}
std::string Action::SerializeArgUrl() const {
return (arg_incognito() ? constants::kIncognitoUrl : "") + arg_url().spec();
}
void Action::ParseArgUrl(const std::string& url) {
set_arg_incognito(base::StartsWith(url, constants::kIncognitoUrl,
base::CompareCase::SENSITIVE));
if (arg_incognito())
set_arg_url(GURL(url.substr(strlen(constants::kIncognitoUrl))));
else
set_arg_url(GURL(url));
}
ExtensionActivity Action::ConvertToExtensionActivity() {
ExtensionActivity result;
// We do this translation instead of using the same enum because the database
// values need to be stable; this allows us to change the extension API
// without affecting the database.
switch (action_type()) {
case ACTION_API_CALL:
result.activity_type = activity_log::EXTENSION_ACTIVITY_TYPE_API_CALL;
break;
case ACTION_API_EVENT:
result.activity_type = activity_log::EXTENSION_ACTIVITY_TYPE_API_EVENT;
break;
case ACTION_CONTENT_SCRIPT:
result.activity_type =
activity_log::EXTENSION_ACTIVITY_TYPE_CONTENT_SCRIPT;
break;
case ACTION_DOM_ACCESS:
result.activity_type = activity_log::EXTENSION_ACTIVITY_TYPE_DOM_ACCESS;
break;
case ACTION_DOM_EVENT:
result.activity_type = activity_log::EXTENSION_ACTIVITY_TYPE_DOM_EVENT;
break;
case ACTION_WEB_REQUEST:
result.activity_type = activity_log::EXTENSION_ACTIVITY_TYPE_WEB_REQUEST;
break;
case UNUSED_ACTION_API_BLOCKED:
case ACTION_ANY:
default:
// This shouldn't be reached, but some people might have old or otherwise
// weird db entries. Treat it like an API call if that happens.
result.activity_type = activity_log::EXTENSION_ACTIVITY_TYPE_API_CALL;
break;
}
result.extension_id.reset(new std::string(extension_id()));
result.time.reset(new double(time().ToJsTime()));
result.count.reset(new double(count()));
result.api_call.reset(new std::string(api_name()));
result.args.reset(new std::string(Serialize(args())));
if (action_id() != -1)
result.activity_id.reset(
new std::string(base::StringPrintf("%" PRId64, action_id())));
if (page_url().is_valid()) {
if (!page_title().empty())
result.page_title.reset(new std::string(page_title()));
result.page_url.reset(new std::string(SerializePageUrl()));
}
if (arg_url().is_valid())
result.arg_url.reset(new std::string(SerializeArgUrl()));
if (other()) {
std::unique_ptr<ExtensionActivity::Other> other_field(
new ExtensionActivity::Other);
bool prerender;
if (other()->GetBooleanWithoutPathExpansion(constants::kActionPrerender,
&prerender)) {
other_field->prerender.reset(new bool(prerender));
}
const base::DictionaryValue* web_request;
if (other()->GetDictionaryWithoutPathExpansion(constants::kActionWebRequest,
&web_request)) {
other_field->web_request.reset(new std::string(
ActivityLogPolicy::Util::Serialize(web_request)));
}
std::string extra;
if (other()->GetStringWithoutPathExpansion(constants::kActionExtra, &extra))
other_field->extra.reset(new std::string(extra));
int dom_verb;
if (other()->GetIntegerWithoutPathExpansion(constants::kActionDomVerb,
&dom_verb)) {
switch (static_cast<DomActionType::Type>(dom_verb)) {
case DomActionType::GETTER:
other_field->dom_verb =
activity_log::EXTENSION_ACTIVITY_DOM_VERB_GETTER;
break;
case DomActionType::SETTER:
other_field->dom_verb =
activity_log::EXTENSION_ACTIVITY_DOM_VERB_SETTER;
break;
case DomActionType::METHOD:
other_field->dom_verb =
activity_log::EXTENSION_ACTIVITY_DOM_VERB_METHOD;
break;
case DomActionType::INSERTED:
other_field->dom_verb =
activity_log::EXTENSION_ACTIVITY_DOM_VERB_INSERTED;
break;
case DomActionType::XHR:
other_field->dom_verb = activity_log::EXTENSION_ACTIVITY_DOM_VERB_XHR;
break;
case DomActionType::WEBREQUEST:
other_field->dom_verb =
activity_log::EXTENSION_ACTIVITY_DOM_VERB_WEBREQUEST;
break;
case DomActionType::MODIFIED:
other_field->dom_verb =
activity_log::EXTENSION_ACTIVITY_DOM_VERB_MODIFIED;
break;
default:
other_field->dom_verb =
activity_log::EXTENSION_ACTIVITY_DOM_VERB_NONE;
}
} else {
other_field->dom_verb = activity_log::EXTENSION_ACTIVITY_DOM_VERB_NONE;
}
result.other = std::move(other_field);
}
return result;
}
std::string Action::PrintForDebug() const {
std::string result = base::StringPrintf("ACTION ID=%" PRId64, action_id());
result += " EXTENSION ID=" + extension_id() + " CATEGORY=";
switch (action_type_) {
case ACTION_API_CALL:
result += "api_call";
break;
case ACTION_API_EVENT:
result += "api_event_callback";
break;
case ACTION_WEB_REQUEST:
result += "webrequest";
break;
case ACTION_CONTENT_SCRIPT:
result += "content_script";
break;
case UNUSED_ACTION_API_BLOCKED:
// This is deprecated.
result += "api_blocked";
break;
case ACTION_DOM_EVENT:
result += "dom_event";
break;
case ACTION_DOM_ACCESS:
result += "dom_access";
break;
default:
result += base::StringPrintf("type%d", static_cast<int>(action_type_));
}
result += " API=" + api_name_;
if (args_.get()) {
result += " ARGS=" + Serialize(args_.get());
}
if (page_url_.is_valid()) {
if (page_incognito_)
result += " PAGE_URL=(incognito)" + page_url_.spec();
else
result += " PAGE_URL=" + page_url_.spec();
}
if (!page_title_.empty()) {
base::Value title(page_title_);
result += " PAGE_TITLE=" + Serialize(&title);
}
if (arg_url_.is_valid()) {
if (arg_incognito_)
result += " ARG_URL=(incognito)" + arg_url_.spec();
else
result += " ARG_URL=" + arg_url_.spec();
}
if (other_.get()) {
result += " OTHER=" + Serialize(other_.get());
}
result += base::StringPrintf(" COUNT=%d", count_);
return result;
}
bool ActionComparator::operator()(
const scoped_refptr<Action>& lhs,
const scoped_refptr<Action>& rhs) const {
if (lhs->time() != rhs->time())
return lhs->time() < rhs->time();
else if (lhs->action_id() != rhs->action_id())
return lhs->action_id() < rhs->action_id();
else
return ActionComparatorExcludingTimeAndActionId()(lhs, rhs);
}
bool ActionComparatorExcludingTimeAndActionId::operator()(
const scoped_refptr<Action>& lhs,
const scoped_refptr<Action>& rhs) const {
if (lhs->extension_id() != rhs->extension_id())
return lhs->extension_id() < rhs->extension_id();
if (lhs->action_type() != rhs->action_type())
return lhs->action_type() < rhs->action_type();
if (lhs->api_name() != rhs->api_name())
return lhs->api_name() < rhs->api_name();
// args might be null; treat a null value as less than all non-null values,
// including the empty string.
if (!lhs->args() && rhs->args())
return true;
if (lhs->args() && !rhs->args())
return false;
if (lhs->args() && rhs->args()) {
std::string lhs_args = ActivityLogPolicy::Util::Serialize(lhs->args());
std::string rhs_args = ActivityLogPolicy::Util::Serialize(rhs->args());
if (lhs_args != rhs_args)
return lhs_args < rhs_args;
}
// Compare URLs as strings, and treat the incognito flag as a separate field.
if (lhs->page_url().spec() != rhs->page_url().spec())
return lhs->page_url().spec() < rhs->page_url().spec();
if (lhs->page_incognito() != rhs->page_incognito())
return lhs->page_incognito() < rhs->page_incognito();
if (lhs->page_title() != rhs->page_title())
return lhs->page_title() < rhs->page_title();
if (lhs->arg_url().spec() != rhs->arg_url().spec())
return lhs->arg_url().spec() < rhs->arg_url().spec();
if (lhs->arg_incognito() != rhs->arg_incognito())
return lhs->arg_incognito() < rhs->arg_incognito();
// other is treated much like the args field.
if (!lhs->other() && rhs->other())
return true;
if (lhs->other() && !rhs->other())
return false;
if (lhs->other() && rhs->other()) {
std::string lhs_other = ActivityLogPolicy::Util::Serialize(lhs->other());
std::string rhs_other = ActivityLogPolicy::Util::Serialize(rhs->other());
if (lhs_other != rhs_other)
return lhs_other < rhs_other;
}
// All fields compare as equal if this point is reached.
return false;
}
} // namespace extensions
|
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, 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 Willow Garage 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.
*********************************************************************/
/* Author: Dave Coleman */
// Qt
#include <QVBoxLayout>
#include <QPushButton>
#include <QMessageBox>
#include <QApplication>
#include <QSplitter>
#include <QRegExp>
// ROS
#include "configuration_files_widget.h"
#include <srdfdom/model.h> // use their struct datastructures
#include <ros/ros.h>
// Boost
#include <boost/algorithm/string.hpp> // for trimming whitespace from user input
#include <boost/filesystem.hpp> // for creating folders/files
// Read write files
#include <iostream> // For writing yaml and launch files
#include <fstream>
namespace moveit_setup_assistant
{
// Boost file system
namespace fs = boost::filesystem;
const std::string SETUP_ASSISTANT_FILE = ".setup_assistant";
// ******************************************************************************************
// Outer User Interface for MoveIt! Configuration Assistant
// ******************************************************************************************
ConfigurationFilesWidget::ConfigurationFilesWidget(QWidget* parent,
moveit_setup_assistant::MoveItConfigDataPtr config_data)
: SetupScreenWidget(parent), config_data_(config_data), has_generated_pkg_(false), first_focusGiven_(true)
{
// Basic widget container
QVBoxLayout* layout = new QVBoxLayout();
// Top Header Area ------------------------------------------------
HeaderWidget* header =
new HeaderWidget("Generate Configuration Files",
"Create or update the configuration files package needed to run your robot with MoveIt. Uncheck "
"files to disable them from being generated - this is useful if you have made custom changes to "
"them. Files in orange have been automatically detected as changed.",
this);
layout->addWidget(header);
// Path Widget ----------------------------------------------------
// Stack Path Dialog
stack_path_ = new LoadPathWidget("Configuration Package Save Path",
"Specify the desired directory for the MoveIt! configuration package to be "
"generated. Overwriting an existing configuration package directory is acceptable. "
"Example: <i>/u/robot/ros/pr2_moveit_config</i>",
this, true); // is directory
layout->addWidget(stack_path_);
// Pass the package path from start screen to configuration files screen
stack_path_->setPath(config_data_->config_pkg_path_);
// Generated Files List -------------------------------------------
QLabel* generated_list = new QLabel("Files to be generated: (checked)", this);
layout->addWidget(generated_list);
QSplitter* splitter = new QSplitter(Qt::Horizontal, this);
splitter->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
// List Box
action_list_ = new QListWidget(this);
action_list_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
connect(action_list_, SIGNAL(currentRowChanged(int)), this, SLOT(changeActionDesc(int)));
// Description
action_label_ = new QLabel(this);
action_label_->setFrameShape(QFrame::StyledPanel);
action_label_->setFrameShadow(QFrame::Raised);
action_label_->setLineWidth(1);
action_label_->setMidLineWidth(0);
action_label_->setWordWrap(true);
action_label_->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
action_label_->setMinimumWidth(100);
action_label_->setAlignment(Qt::AlignTop);
action_label_->setOpenExternalLinks(true); // open with web browser
// Add to splitter
splitter->addWidget(action_list_);
splitter->addWidget(action_label_);
// Add Layout
layout->addWidget(splitter);
// Progress bar and generate buttons ---------------------------------------------------
QHBoxLayout* hlayout1 = new QHBoxLayout();
// Progress Bar
progress_bar_ = new QProgressBar(this);
progress_bar_->setMaximum(100);
progress_bar_->setMinimum(0);
hlayout1->addWidget(progress_bar_);
// hlayout1->setContentsMargins( 20, 30, 20, 30 );
// Generate Package Button
btn_save_ = new QPushButton("&Generate Package", this);
// btn_save_->setMinimumWidth(180);
btn_save_->setMinimumHeight(40);
connect(btn_save_, SIGNAL(clicked()), this, SLOT(savePackage()));
hlayout1->addWidget(btn_save_);
// Add Layout
layout->addLayout(hlayout1);
// Bottom row --------------------------------------------------
QHBoxLayout* hlayout3 = new QHBoxLayout();
// Success label
success_label_ = new QLabel(this);
QFont success_label_font(QFont().defaultFamily(), 12, QFont::Bold);
success_label_->setFont(success_label_font);
success_label_->hide(); // only show once the files have been generated
success_label_->setText("Configuration package generated successfully!");
hlayout3->addWidget(success_label_);
hlayout3->setAlignment(success_label_, Qt::AlignRight);
// Exit button
QPushButton* btn_exit = new QPushButton("E&xit Setup Assistant", this);
btn_exit->setMinimumWidth(180);
connect(btn_exit, SIGNAL(clicked()), this, SLOT(exitSetupAssistant()));
hlayout3->addWidget(btn_exit);
hlayout3->setAlignment(btn_exit, Qt::AlignRight);
layout->addLayout(hlayout3);
// Finish Layout --------------------------------------------------
this->setLayout(layout);
}
// ******************************************************************************************
// Populate the 'Files to be generated' list
// ******************************************************************************************
bool ConfigurationFilesWidget::loadGenFiles()
{
GenerateFile file; // re-used
std::string template_path; // re-used
const std::string robot_name = config_data_->srdf_->robot_name_;
gen_files_.clear(); // reset vector
// Get template package location ----------------------------------------------------------------------
fs::path template_package_path = config_data_->setup_assistant_path_;
template_package_path /= "templates";
template_package_path /= "moveit_config_pkg_template";
config_data_->template_package_path_ = template_package_path.make_preferred().native().c_str();
if (!fs::is_directory(config_data_->template_package_path_))
{
QMessageBox::critical(
this, "Error Generating",
QString("Unable to find package template directory: ").append(config_data_->template_package_path_.c_str()));
return false;
}
// -------------------------------------------------------------------------------------------------------------------
// ROS PACKAGE FILES AND FOLDERS ----------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------
// package.xml --------------------------------------------------------------------------------------
// Note: we call the file package.xml.template so that it isn't automatically indexed by rosprofile
// in the scenario where we want to disabled the setup_assistant by renaming its root package.xml
file.file_name_ = "package.xml";
file.rel_path_ = file.file_name_;
template_path = config_data_->appendPaths(config_data_->template_package_path_, "package.xml.template");
file.description_ = "Defines a ROS package";
file.gen_func_ = boost::bind(&ConfigurationFilesWidget::copyTemplate, this, template_path, _1);
file.write_on_changes = MoveItConfigData::AUTHOR_INFO;
gen_files_.push_back(file);
// CMakeLists.txt --------------------------------------------------------------------------------------
file.file_name_ = "CMakeLists.txt";
file.rel_path_ = file.file_name_;
template_path = config_data_->appendPaths(config_data_->template_package_path_, file.file_name_);
file.description_ = "CMake build system configuration file";
file.gen_func_ = boost::bind(&ConfigurationFilesWidget::copyTemplate, this, template_path, _1);
file.write_on_changes = 0;
gen_files_.push_back(file);
// -------------------------------------------------------------------------------------------------------------------
// CONIG FILES -------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------
std::string config_path = "config";
// config/ --------------------------------------------------------------------------------------
file.file_name_ = "config/";
file.rel_path_ = file.file_name_;
file.description_ = "Folder containing all MoveIt! configuration files for your robot. This folder is required and "
"cannot be disabled.";
file.gen_func_ = boost::bind(&ConfigurationFilesWidget::createFolder, this, _1);
file.write_on_changes = 0;
gen_files_.push_back(file);
// robot.srdf ----------------------------------------------------------------------------------------------
file.file_name_ = config_data_->srdf_pkg_relative_path_.empty() ? config_data_->urdf_model_->getName() + ".srdf" :
config_data_->srdf_pkg_relative_path_;
file.rel_path_ = config_data_->srdf_pkg_relative_path_.empty() ?
config_data_->appendPaths(config_path, file.file_name_) :
config_data_->srdf_pkg_relative_path_;
file.description_ = "SRDF (<a href='http://www.ros.org/wiki/srdf'>Semantic Robot Description Format</a>) is a "
"representation of semantic information about robots. This format is intended to represent "
"information about the robot that is not in the URDF file, but it is useful for a variety of "
"applications. The intention is to include information that has a semantic aspect to it.";
file.gen_func_ = boost::bind(&srdf::SRDFWriter::writeSRDF, config_data_->srdf_, _1);
file.write_on_changes = MoveItConfigData::SRDF;
gen_files_.push_back(file);
// special step required so the generated .setup_assistant yaml has this value
config_data_->srdf_pkg_relative_path_ = file.rel_path_;
// ompl_planning.yaml --------------------------------------------------------------------------------------
file.file_name_ = "ompl_planning.yaml";
file.rel_path_ = config_data_->appendPaths(config_path, file.file_name_);
file.description_ = "Configures the OMPL (<a href='http://ompl.kavrakilab.org/'>Open Motion Planning Library</a>) "
"planning plugin. For every planning group defined in the SRDF, a number of planning "
"configurations are specified (under planner_configs). Additionally, default settings for the "
"state space to plan in for a particular group can be specified, such as the collision checking "
"resolution. Each planning configuration specified for a group must be defined under the "
"planner_configs tag. While defining a planner configuration, the only mandatory parameter is "
"'type', which is the name of the motion planner to be used. Any other planner-specific "
"parameters can be defined but are optional.";
file.gen_func_ = boost::bind(&MoveItConfigData::outputOMPLPlanningYAML, config_data_, _1);
file.write_on_changes = MoveItConfigData::GROUPS;
gen_files_.push_back(file);
// chomp_planning.yaml --------------------------------------------------------------------------------------
file.file_name_ = "chomp_planning.yaml";
file.rel_path_ = config_data_->appendPaths(config_path, file.file_name_);
file.description_ = "Specifies which chomp planning plugin parameters to be used for the CHOMP planner";
file.gen_func_ = boost::bind(&MoveItConfigData::outputCHOMPPlanningYAML, config_data_, _1);
file.write_on_changes = MoveItConfigData::GROUPS; // need to double check if this is actually correct!
gen_files_.push_back(file);
// kinematics.yaml --------------------------------------------------------------------------------------
file.file_name_ = "kinematics.yaml";
file.rel_path_ = config_data_->appendPaths(config_path, file.file_name_);
file.description_ = "Specifies which kinematic solver plugin to use for each planning group in the SRDF, as well as "
"the kinematic solver search resolution.";
file.gen_func_ = boost::bind(&MoveItConfigData::outputKinematicsYAML, config_data_, _1);
file.write_on_changes = MoveItConfigData::GROUPS | MoveItConfigData::GROUP_KINEMATICS;
gen_files_.push_back(file);
// joint_limits.yaml --------------------------------------------------------------------------------------
file.file_name_ = "joint_limits.yaml";
file.rel_path_ = config_data_->appendPaths(config_path, file.file_name_);
file.description_ = "Contains additional information about joints that appear in your planning groups that is not "
"contained in the URDF, as well as allowing you to set maximum and minimum limits for velocity "
"and acceleration than those contained in your URDF. This information is used by our trajectory "
"filtering system to assign reasonable velocities and timing for the trajectory before it is "
"passed to the robots controllers.";
file.gen_func_ = boost::bind(&MoveItConfigData::outputJointLimitsYAML, config_data_, _1);
file.write_on_changes = 0; // Can they be changed?
gen_files_.push_back(file);
// fake_controllers.yaml --------------------------------------------------------------------------------------
file.file_name_ = "fake_controllers.yaml";
file.rel_path_ = config_data_->appendPaths(config_path, file.file_name_);
file.description_ = "Creates dummy configurations for controllers that correspond to defined groups. This is mostly "
"useful for testing.";
file.gen_func_ = boost::bind(&MoveItConfigData::outputFakeControllersYAML, config_data_, _1);
file.write_on_changes = MoveItConfigData::GROUPS;
gen_files_.push_back(file);
// ros_controllers.yaml --------------------------------------------------------------------------------------
file.file_name_ = "ros_controllers.yaml";
file.rel_path_ = config_data_->appendPaths(config_path, file.file_name_);
file.description_ = "Creates configurations for ros_controllers.";
file.gen_func_ = boost::bind(&MoveItConfigData::outputROSControllersYAML, config_data_, _1);
file.write_on_changes = MoveItConfigData::GROUPS;
gen_files_.push_back(file);
// sensors_3d.yaml --------------------------------------------------------------------------------------
file.file_name_ = "sensors_3d.yaml";
file.rel_path_ = config_data_->appendPaths(config_path, file.file_name_);
file.description_ = "Creates configurations 3d sensors.";
file.gen_func_ = boost::bind(&MoveItConfigData::output3DSensorPluginYAML, config_data_, _1);
file.write_on_changes = MoveItConfigData::SENSORS_CONFIG;
gen_files_.push_back(file);
// -------------------------------------------------------------------------------------------------------------------
// LAUNCH FILES ------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------
std::string launch_path = "launch";
const std::string template_launch_path = config_data_->appendPaths(config_data_->template_package_path_, launch_path);
// launch/ --------------------------------------------------------------------------------------
file.file_name_ = "launch/";
file.rel_path_ = file.file_name_;
file.description_ =
"Folder containing all MoveIt! launch files for your robot. This folder is required and cannot be "
"disabled.";
file.gen_func_ = boost::bind(&ConfigurationFilesWidget::createFolder, this, _1);
file.write_on_changes = 0;
gen_files_.push_back(file);
// move_group.launch --------------------------------------------------------------------------------------
file.file_name_ = "move_group.launch";
file.rel_path_ = config_data_->appendPaths(launch_path, file.file_name_);
template_path = config_data_->appendPaths(template_launch_path, file.file_name_);
file.description_ = "Launches the move_group node that provides the MoveGroup action and other parameters <a "
"href='http://moveit.ros.org/doxygen/"
"classmoveit_1_1planning__interface_1_1MoveGroup.html#details'>MoveGroup action</a>";
file.gen_func_ = boost::bind(&ConfigurationFilesWidget::copyTemplate, this, template_path, _1);
file.write_on_changes = 0;
gen_files_.push_back(file);
// planning_context.launch --------------------------------------------------------------------------------------
file.file_name_ = "planning_context.launch";
file.rel_path_ = config_data_->appendPaths(launch_path, file.file_name_);
template_path = config_data_->appendPaths(template_launch_path, file.file_name_);
file.description_ = "Loads settings for the ROS parameter server, required for running MoveIt. This includes the "
"SRDF, joints_limits.yaml file, ompl_planning.yaml file, optionally the URDF, etc";
file.gen_func_ = boost::bind(&ConfigurationFilesWidget::copyTemplate, this, template_path, _1);
file.write_on_changes = 0;
gen_files_.push_back(file);
// moveit_rviz.launch --------------------------------------------------------------------------------------
file.file_name_ = "moveit_rviz.launch";
file.rel_path_ = config_data_->appendPaths(launch_path, file.file_name_);
template_path = config_data_->appendPaths(template_launch_path, file.file_name_);
file.description_ = "Visualize in Rviz the robot's planning groups running with interactive markers that allow goal "
"states to be set.";
file.gen_func_ = boost::bind(&ConfigurationFilesWidget::copyTemplate, this, template_path, _1);
file.write_on_changes = 0;
gen_files_.push_back(file);
// ompl_planning_pipeline.launch
// --------------------------------------------------------------------------------------
file.file_name_ = "ompl_planning_pipeline.launch.xml";
file.rel_path_ = config_data_->appendPaths(launch_path, file.file_name_);
template_path = config_data_->appendPaths(template_launch_path, file.file_name_);
file.description_ = "Intended to be included in other launch files that require the OMPL planning plugin. Defines "
"the proper plugin name on the parameter server and a default selection of planning request "
"adapters.";
file.gen_func_ = boost::bind(&ConfigurationFilesWidget::copyTemplate, this, template_path, _1);
file.write_on_changes = 0;
gen_files_.push_back(file);
// chomp_planning_pipeline.launch
// --------------------------------------------------------------------------------------
file.file_name_ = "chomp_planning_pipeline.launch.xml";
file.rel_path_ = config_data_->appendPaths(launch_path, file.file_name_);
template_path = config_data_->appendPaths(template_launch_path, file.file_name_);
file.description_ = "Intended to be included in other launch files that require the CHOMP planning plugin. Defines "
"the proper plugin name on the parameter server and a default selection of planning request "
"adapters.";
file.gen_func_ = boost::bind(&ConfigurationFilesWidget::copyTemplate, this, template_path, _1);
file.write_on_changes = 0;
gen_files_.push_back(file);
// planning_pipeline.launch --------------------------------------------------------------------------------------
file.file_name_ = "planning_pipeline.launch.xml";
file.rel_path_ = config_data_->appendPaths(launch_path, file.file_name_);
template_path = config_data_->appendPaths(template_launch_path, file.file_name_);
file.description_ = "Helper launch file that can choose between different planning pipelines to be loaded.";
file.gen_func_ = boost::bind(&ConfigurationFilesWidget::copyTemplate, this, template_path, _1);
file.write_on_changes = 0;
gen_files_.push_back(file);
// warehouse_settings.launch --------------------------------------------------------------------------------------
file.file_name_ = "warehouse_settings.launch.xml";
file.rel_path_ = config_data_->appendPaths(launch_path, file.file_name_);
template_path = config_data_->appendPaths(template_launch_path, file.file_name_);
file.description_ = "Helper launch file that specifies default settings for MongoDB.";
file.gen_func_ = boost::bind(&ConfigurationFilesWidget::copyTemplate, this, template_path, _1);
file.write_on_changes = 0;
gen_files_.push_back(file);
// warehouse.launch --------------------------------------------------------------------------------------
file.file_name_ = "warehouse.launch";
file.rel_path_ = config_data_->appendPaths(launch_path, file.file_name_);
template_path = config_data_->appendPaths(template_launch_path, file.file_name_);
file.description_ = "Launch file for starting MongoDB.";
file.gen_func_ = boost::bind(&ConfigurationFilesWidget::copyTemplate, this, template_path, _1);
file.write_on_changes = 0;
gen_files_.push_back(file);
// default_warehouse_db.launch --------------------------------------------------------------------------------------
file.file_name_ = "default_warehouse_db.launch";
file.rel_path_ = config_data_->appendPaths(launch_path, file.file_name_);
template_path = config_data_->appendPaths(template_launch_path, file.file_name_);
file.description_ = "Launch file for starting the warehouse with a default MongoDB.";
file.gen_func_ = boost::bind(&ConfigurationFilesWidget::copyTemplate, this, template_path, _1);
file.write_on_changes = 0;
gen_files_.push_back(file);
// run_benchmark_ompl.launch --------------------------------------------------------------------------------------
file.file_name_ = "run_benchmark_ompl.launch";
file.rel_path_ = config_data_->appendPaths(launch_path, file.file_name_);
template_path = config_data_->appendPaths(template_launch_path, file.file_name_);
file.description_ = "Launch file for benchmarking OMPL planners";
file.gen_func_ = boost::bind(&ConfigurationFilesWidget::copyTemplate, this, template_path, _1);
file.write_on_changes = 0;
gen_files_.push_back(file);
// sensor_manager.launch --------------------------------------------------------------------------------------
file.file_name_ = "sensor_manager.launch.xml";
file.rel_path_ = config_data_->appendPaths(launch_path, file.file_name_);
template_path = config_data_->appendPaths(template_launch_path, file.file_name_);
file.description_ = "Helper launch file that can choose between different sensor managers to be loaded.";
file.gen_func_ = boost::bind(&ConfigurationFilesWidget::copyTemplate, this, template_path, _1);
file.write_on_changes = 0;
gen_files_.push_back(file);
// robot_moveit_controller_manager.launch ------------------------------------------------------------------
file.file_name_ = robot_name + "_moveit_controller_manager.launch.xml";
file.rel_path_ = config_data_->appendPaths(launch_path, file.file_name_);
template_path = config_data_->appendPaths(template_launch_path, "moveit_controller_manager.launch.xml");
file.description_ = "Placeholder for settings specific to the MoveIt! controller manager implemented for you robot.";
file.gen_func_ = boost::bind(&ConfigurationFilesWidget::copyTemplate, this, template_path, _1);
file.write_on_changes = 0;
gen_files_.push_back(file);
// robot_moveit_sensor_manager.launch ------------------------------------------------------------------
file.file_name_ = robot_name + "_moveit_sensor_manager.launch.xml";
file.rel_path_ = config_data_->appendPaths(launch_path, file.file_name_);
template_path = config_data_->appendPaths(template_launch_path, "moveit_sensor_manager.launch.xml");
file.description_ = "Placeholder for settings specific to the MoveIt! sensor manager implemented for you robot.";
file.gen_func_ = boost::bind(&ConfigurationFilesWidget::copyTemplate, this, template_path, _1);
file.write_on_changes = 0;
gen_files_.push_back(file);
// trajectory_execution.launch ------------------------------------------------------------------
file.file_name_ = "trajectory_execution.launch.xml";
file.rel_path_ = config_data_->appendPaths(launch_path, file.file_name_);
template_path = config_data_->appendPaths(template_launch_path, file.file_name_);
file.description_ = "Loads settings for the ROS parameter server required for executing trajectories using the "
"trajectory_execution_manager::TrajectoryExecutionManager.";
file.gen_func_ = boost::bind(&ConfigurationFilesWidget::copyTemplate, this, template_path, _1);
file.write_on_changes = 0;
gen_files_.push_back(
file); // trajectory_execution.launch ------------------------------------------------------------------
file.file_name_ = "fake_moveit_controller_manager.launch.xml";
file.rel_path_ = config_data_->appendPaths(launch_path, file.file_name_);
template_path = config_data_->appendPaths(template_launch_path, file.file_name_);
file.description_ = "Loads a fake controller plugin.";
file.gen_func_ = boost::bind(&ConfigurationFilesWidget::copyTemplate, this, template_path, _1);
file.write_on_changes = 0;
gen_files_.push_back(file);
// demo.launch ------------------------------------------------------------------
file.file_name_ = "demo.launch";
file.rel_path_ = config_data_->appendPaths(launch_path, file.file_name_);
template_path = config_data_->appendPaths(template_launch_path, file.file_name_);
file.description_ = "Run a demo of MoveIt.";
file.gen_func_ = boost::bind(&ConfigurationFilesWidget::copyTemplate, this, template_path, _1);
file.write_on_changes = 0;
gen_files_.push_back(file);
// joystick_control.launch ------------------------------------------------------------------
file.file_name_ = "joystick_control.launch";
file.rel_path_ = config_data_->appendPaths(launch_path, file.file_name_);
template_path = config_data_->appendPaths(template_launch_path, file.file_name_);
file.description_ = "Control the Rviz Motion Planning Plugin with a joystick";
file.gen_func_ = boost::bind(&ConfigurationFilesWidget::copyTemplate, this, template_path, _1);
file.write_on_changes = 0;
gen_files_.push_back(file);
// setup_assistant.launch ------------------------------------------------------------------
file.file_name_ = "setup_assistant.launch";
file.rel_path_ = config_data_->appendPaths(launch_path, file.file_name_);
template_path = config_data_->appendPaths(
template_launch_path, "edit_configuration_package.launch"); // named this so that this launch file is not mixed
// up with the SA's real launch file
file.description_ = "Launch file for easily re-starting the MoveIt! Setup Assistant to edit this robot's generated "
"configuration package.";
file.gen_func_ = boost::bind(&ConfigurationFilesWidget::copyTemplate, this, template_path, _1);
file.write_on_changes = 0;
gen_files_.push_back(file);
// ros_controllers.launch ------------------------------------------------------------------
file.file_name_ = "ros_controllers.launch";
file.rel_path_ = config_data_->appendPaths(launch_path, file.file_name_);
template_path = config_data_->appendPaths(template_launch_path, "ros_controllers.launch");
file.description_ = "ros_controllers launch file";
file.gen_func_ = boost::bind(&ConfigurationFilesWidget::copyTemplate, this, template_path, _1);
file.write_on_changes = MoveItConfigData::GROUPS;
gen_files_.push_back(file);
// moveit.rviz ------------------------------------------------------------------
file.file_name_ = "moveit.rviz";
file.rel_path_ = config_data_->appendPaths(launch_path, file.file_name_);
template_path = config_data_->appendPaths(template_launch_path, "moveit.rviz");
file.description_ = "Configuration file for Rviz with the Motion Planning Plugin already setup. Used by passing "
"roslaunch moveit_rviz.launch config:=true";
file.gen_func_ = boost::bind(&ConfigurationFilesWidget::copyTemplate, this, template_path, _1);
file.write_on_changes = 0;
gen_files_.push_back(file);
// -------------------------------------------------------------------------------------------------------------------
// OTHER FILES -------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------
// .setup_assistant ------------------------------------------------------------------
file.file_name_ = SETUP_ASSISTANT_FILE;
file.rel_path_ = file.file_name_;
file.description_ = "MoveIt! Setup Assistant's hidden settings file. You should not need to edit this file.";
file.gen_func_ = boost::bind(&MoveItConfigData::outputSetupAssistantFile, config_data_, _1);
file.write_on_changes = -1; // write on any changes
gen_files_.push_back(file);
return true;
}
// ******************************************************************************************
// Verify with user if certain screens have not been completed
// ******************************************************************************************
bool ConfigurationFilesWidget::checkDependencies()
{
QStringList dependencies;
bool requiredActions = false;
// Check that at least 1 planning group exists
if (!config_data_->srdf_->groups_.size())
{
dependencies << "No robot model planning groups have been created";
}
// Check that at least 1 link pair is disabled from collision checking
if (!config_data_->srdf_->disabled_collisions_.size())
{
dependencies << "No self-collisions have been disabled";
}
// Check that there is at least 1 end effector added
if (!config_data_->srdf_->end_effectors_.size())
{
dependencies << "No end effectors have been added";
}
// Check that there is at least 1 virtual joint added
if (!config_data_->srdf_->virtual_joints_.size())
{
dependencies << "No virtual joints have been added";
}
// Check that there is a author name
if (config_data_->author_name_.find_first_not_of(' ') == std::string::npos)
{
// There is no name or it consists of whitespaces only
dependencies << "<b>No author name added</b>";
requiredActions = true;
}
// Check that email information is filled
QRegExp mailRegex("\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b");
mailRegex.setCaseSensitivity(Qt::CaseInsensitive);
mailRegex.setPatternSyntax(QRegExp::RegExp);
QString testEmail = QString::fromStdString(config_data_->author_email_);
if (!mailRegex.exactMatch(testEmail))
{
dependencies << "<b>No valid email address added</b>";
requiredActions = true;
}
// Display all accumumlated errors:
if (dependencies.size())
{
// Create a dependency message
QString dep_message;
if (!requiredActions)
{
dep_message = "Some setup steps have not been completed. None of the steps are required, but here is a reminder "
"of what was not filled in, just in case something was forgotten:<br /><ul>";
}
else
{
dep_message = "Some setup steps have not been completed. Please fix the required steps (printed in bold), "
"otherwise the setup cannot be completed:<br /><ul>";
}
for (int i = 0; i < dependencies.size(); ++i)
{
dep_message.append("<li>").append(dependencies.at(i)).append("</li>");
}
if (!requiredActions)
{
dep_message.append("</ul><br/>Press Ok to continue generating files.");
if (QMessageBox::question(this, "Incomplete MoveIt! Setup Assistant Steps", dep_message,
QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Cancel)
{
return false; // abort
}
}
else
{
QMessageBox::warning(this, "Incomplete MoveIt! Setup Assistant Steps", dep_message);
return false;
}
}
return true;
}
// ******************************************************************************************
// A function for showing progress and user feedback about what happened
// ******************************************************************************************
void ConfigurationFilesWidget::updateProgress()
{
action_num_++;
// Calc percentage
progress_bar_->setValue(double(action_num_) / gen_files_.size() * 100);
// allow the progress bar to be shown
QApplication::processEvents();
}
// ******************************************************************************************
// Display the selected action in the desc box
// ******************************************************************************************
void ConfigurationFilesWidget::changeActionDesc(int id)
{
// Only allow event if list is not empty
if (id >= 0)
{
// Show the selected text
action_label_->setText(action_desc_.at(id));
}
}
// ******************************************************************************************
// Disable or enable item in gen_files_ array
// ******************************************************************************************
void ConfigurationFilesWidget::changeCheckedState(QListWidgetItem* item)
{
std::size_t index = item->data(Qt::UserRole).toUInt();
bool generate = (item->checkState() == Qt::Checked);
if (!generate && (gen_files_[index].write_on_changes & config_data_->changes))
{
QMessageBox::warning(this, "Package Generation", "You should generate this file to ensure your changes will take "
"effect.");
}
// Enable/disable file
gen_files_[index].generate_ = generate;
}
// ******************************************************************************************
// Called when setup assistant navigation switches to this screen
// ******************************************************************************************
void ConfigurationFilesWidget::focusGiven()
{
if (first_focusGiven_)
{
// only generate list once
first_focusGiven_ = false;
// Load this list of all files to be generated
loadGenFiles();
}
// Which files have been modified outside the Setup Assistant?
bool files_already_modified = checkGenFiles();
// disable reaction to checkbox changes
disconnect(action_list_, SIGNAL(itemChanged(QListWidgetItem*)), this, SLOT(changeCheckedState(QListWidgetItem*)));
// Show files in GUI
bool have_conflicting_changes = showGenFiles();
// react to manual changes only (not programmatic ones)
connect(action_list_, SIGNAL(itemChanged(QListWidgetItem*)), this, SLOT(changeCheckedState(QListWidgetItem*)));
// Allow list box to populate
QApplication::processEvents();
if (files_already_modified)
{
// Some were found to be modified
QString msg("Some files have been modified outside of the Setup Assistant (according to timestamp). "
"The Setup Assistant will not overwrite these changes by default because often changing configuration "
"files manually is necessary, "
"but we recommend you check the list and enable the checkbox next to files you would like to "
"overwrite. ");
if (have_conflicting_changes)
msg += "<br/><font color='red'>Attention:</font> Some files (<font color='red'>marked red</font>) are changed "
"both, externally and in Setup Assistant.";
QMessageBox::information(this, "Files Modified", msg);
}
}
// ******************************************************************************************
// Check the list of files to be generated for modification
// Returns true if files were detected as modified
// ******************************************************************************************
bool ConfigurationFilesWidget::checkGenFiles()
{
// Check if we are 'editing' a prev generated config pkg
if (config_data_->config_pkg_path_.empty())
return false; // this is a new package
// Check if we have the previous modification timestamp to compare agains
if (config_data_->config_pkg_generated_timestamp_ == 0)
return false; // this package has not been generated with a timestamp, backwards compatible.
static const std::time_t TIME_MOD_TOLERANCE = 10;
// Check all old file's modification time
bool found_modified = false;
for (int i = 0; i < gen_files_.size(); ++i)
{
GenerateFile* file = &gen_files_[i];
fs::path file_path = config_data_->appendPaths(config_data_->config_pkg_path_, file->rel_path_);
// Don't disable folders from being generated
if (fs::is_directory(file_path))
continue;
if (fs::is_regular_file(file_path))
{
std::time_t mod_time = fs::last_write_time(file_path);
// ROS_DEBUG_STREAM("File " << file->file_name_ << " file modified " << mod_time << " pkg modified " <<
// config_data_->config_pkg_generated_timestamp_);
if (mod_time > config_data_->config_pkg_generated_timestamp_ + TIME_MOD_TOLERANCE ||
mod_time < config_data_->config_pkg_generated_timestamp_ - TIME_MOD_TOLERANCE)
{
ROS_INFO_STREAM("Manual editing detected: not over-writing by default file " << file->file_name_);
if (file->write_on_changes & config_data_->changes)
ROS_WARN_STREAM("Editing in Setup Assistant conflicts with external editing of file " << file->file_name_);
file->generate_ = false; // do not overwrite by default
file->modified_ = true;
found_modified = true;
}
else
{
file->modified_ = false;
}
}
}
// Warn user if files have been modified outside Setup Assistant
return found_modified;
}
// ******************************************************************************************
// Show the list of files to be generated
// ******************************************************************************************
bool ConfigurationFilesWidget::showGenFiles()
{
bool have_conflicting_changes = false;
action_list_->clear();
// Display this list in the GUI
for (std::size_t i = 0; i < gen_files_.size(); ++i)
{
GenerateFile* file = &gen_files_[i];
// Create a formatted row
QListWidgetItem* item = new QListWidgetItem(QString(file->rel_path_.c_str()), action_list_, 0);
fs::path file_path = config_data_->appendPaths(config_data_->config_pkg_path_, file->rel_path_);
// Checkbox
item->setCheckState(file->generate_ ? Qt::Checked : Qt::Unchecked);
// externally modified?
if (file->modified_)
{
if (file->write_on_changes & config_data_->changes)
{
have_conflicting_changes = true;
item->setForeground(QBrush(QColor(255, 0, 0)));
}
else
item->setForeground(QBrush(QColor(255, 135, 0)));
}
// Don't allow folders to be disabled
if (fs::is_directory(file_path))
{
item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
}
// Link the gen_files_ index to this item
item->setData(Qt::UserRole, QVariant(static_cast<qulonglong>(i)));
// Add actions to list
action_list_->addItem(item);
action_desc_.append(QString(file->description_.c_str()));
}
// Select the first item in the list so that a description is visible
action_list_->setCurrentRow(0);
return have_conflicting_changes;
}
// ******************************************************************************************
// Save configuration click event
// ******************************************************************************************
void ConfigurationFilesWidget::savePackage()
{
// Feedback
success_label_->hide();
// Reset the progress bar counter and GUI stuff
action_num_ = 0;
progress_bar_->setValue(0);
if (!generatePackage())
{
ROS_ERROR_STREAM("Failed to generate entire configuration package");
return;
}
// Alert user it completed successfully --------------------------------------------------
progress_bar_->setValue(100);
success_label_->show();
has_generated_pkg_ = true;
}
// ******************************************************************************************
// Save package using default path
// ******************************************************************************************
bool ConfigurationFilesWidget::generatePackage()
{
// Get path name
std::string new_package_path = stack_path_->getPath();
// Check that a valid stack package name has been given
if (new_package_path.empty())
{
QMessageBox::warning(this, "Error Generating", "No package path provided. Please choose a directory location to "
"generate the MoveIt! configuration files.");
return false;
}
// Check setup assist deps
if (!checkDependencies())
return false; // canceled
// Check that all groups have components
if (!noGroupsEmpty())
return false; // not ready
// Trim whitespace from user input
boost::trim(new_package_path);
// Get the package name ---------------------------------------------------------------------------------
new_package_name_ = getPackageName(new_package_path);
const std::string setup_assistant_file = config_data_->appendPaths(new_package_path, SETUP_ASSISTANT_FILE);
// Make sure old package is correct package type and verify over write
if (fs::is_directory(new_package_path) && !fs::is_empty(new_package_path))
{
// Check if the old package is a setup assistant package. If it is not, quit
if (!fs::is_regular_file(setup_assistant_file))
{
QMessageBox::warning(
this, "Incorrect Folder/Package",
QString("The chosen package location already exists but was not previously created using this MoveIt! Setup "
"Assistant. "
"If this is a mistake, add the missing file: ")
.append(setup_assistant_file.c_str()));
return false;
}
// Confirm overwrite
if (QMessageBox::question(
this, "Confirm Package Update",
QString("Are you sure you want to overwrite this existing package with updated configurations?<br /><i>")
.append(new_package_path.c_str())
.append("</i>"),
QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Cancel)
{
return false; // abort
}
}
else // this is a new package (but maybe the folder already exists)
{
// Create new directory ------------------------------------------------------------------
try
{
fs::create_directory(new_package_path) && !fs::is_directory(new_package_path);
}
catch (...)
{
QMessageBox::critical(this, "Error Generating Files",
QString("Unable to create directory ").append(new_package_path.c_str()));
return false;
}
}
// Begin to create files and folders ----------------------------------------------------------------------
std::string absolute_path;
for (int i = 0; i < gen_files_.size(); ++i)
{
GenerateFile* file = &gen_files_[i];
// Check if we should skip this file
if (!file->generate_)
{
continue;
}
// Create the absolute path
absolute_path = config_data_->appendPaths(new_package_path, file->rel_path_);
ROS_DEBUG_STREAM("Creating file " << absolute_path);
// Run the generate function
if (!file->gen_func_(absolute_path))
{
// Error occured
QMessageBox::critical(this, "Error Generating File", QString("Failed to generate folder or file: '")
.append(file->rel_path_.c_str())
.append("' at location:\n")
.append(absolute_path.c_str()));
return false;
}
updateProgress(); // Increment and update GUI
}
return true;
}
// ******************************************************************************************
// Quit the program because we are done
// ******************************************************************************************
void ConfigurationFilesWidget::exitSetupAssistant()
{
if (has_generated_pkg_ ||
QMessageBox::question(this, "Exit Setup Assistant",
QString("Are you sure you want to exit the MoveIt! Setup Assistant?"),
QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Ok)
{
QApplication::quit();
}
}
// ******************************************************************************************
// Get the last folder name in a directory path
// ******************************************************************************************
const std::string ConfigurationFilesWidget::getPackageName(std::string package_path)
{
// Remove end slash if there is one
if (!package_path.compare(package_path.size() - 1, 1, "/"))
{
package_path = package_path.substr(0, package_path.size() - 1);
}
// Get the last directory name
std::string package_name;
fs::path fs_package_path = package_path;
package_name = fs_package_path.filename().c_str();
// check for empty
if (package_name.empty())
package_name = "unknown";
return package_name;
}
// ******************************************************************************************
// Check that no group is empty (without links/joints/etc)
// ******************************************************************************************
bool ConfigurationFilesWidget::noGroupsEmpty()
{
// Loop through all groups
for (std::vector<srdf::Model::Group>::const_iterator group_it = config_data_->srdf_->groups_.begin();
group_it != config_data_->srdf_->groups_.end(); ++group_it)
{
// Whenever 1 of the 4 component types are found, stop checking this group
if (group_it->joints_.size())
continue;
if (group_it->links_.size())
continue;
if (group_it->chains_.size())
continue;
if (group_it->subgroups_.size())
continue;
// This group has no contents, bad
QMessageBox::warning(
this, "Empty Group",
QString("The planning group '")
.append(group_it->name_.c_str())
.append("' is empty and has no subcomponents associated with it (joints/links/chains/subgroups). You must "
"edit or remove this planning group before this configuration package can be saved."));
return false;
}
return true; // good
}
// ******************************************************************************************
// Load the strings that will be replaced in all templates
// ******************************************************************************************
void ConfigurationFilesWidget::loadTemplateStrings()
{
// Pair 1
addTemplateString("[GENERATED_PACKAGE_NAME]", new_package_name_);
// Pair 2
std::string urdf_location = config_data_->urdf_pkg_name_.empty() ? config_data_->urdf_path_ :
"$(find " + config_data_->urdf_pkg_name_ + ")/" +
config_data_->urdf_pkg_relative_path_;
addTemplateString("[URDF_LOCATION]", urdf_location);
// Pair 3
if (config_data_->urdf_from_xacro_)
addTemplateString("[URDF_LOAD_ATTRIBUTE]",
"command=\"xacro " + config_data_->xacro_args_ + " '" + urdf_location + "'\"");
else
addTemplateString("[URDF_LOAD_ATTRIBUTE]", "textfile=\"" + urdf_location + "\"");
// Pair 4
addTemplateString("[ROBOT_NAME]", config_data_->srdf_->robot_name_);
// Pair 5
addTemplateString("[ROBOT_ROOT_LINK]", config_data_->getRobotModel()->getRootLinkName());
// Pair 6
addTemplateString("[PLANNING_FRAME]", config_data_->getRobotModel()->getModelFrame());
// Pair 7
std::stringstream vjb;
for (std::size_t i = 0; i < config_data_->srdf_->virtual_joints_.size(); ++i)
{
const srdf::Model::VirtualJoint& vj = config_data_->srdf_->virtual_joints_[i];
if (vj.type_ != "fixed")
vjb << " <node pkg=\"tf\" type=\"static_transform_publisher\" name=\"virtual_joint_broadcaster_" << i
<< "\" args=\"0 0 0 0 0 0 " << vj.parent_frame_ << " " << vj.child_link_ << " 100\" />" << std::endl;
}
addTemplateString("[VIRTUAL_JOINT_BROADCASTER]", vjb.str());
// Pair 8 - Add dependencies to package.xml if the robot.urdf file is relative to a ROS package
if (config_data_->urdf_pkg_name_.empty())
{
addTemplateString("[OTHER_DEPENDENCIES", ""); // not relative to a ROS package
}
else
{
std::stringstream deps;
deps << "<build_depend>" << config_data_->urdf_pkg_name_ << "</build_depend>\n";
deps << " <run_depend>" << config_data_->urdf_pkg_name_ << "</run_depend>\n";
addTemplateString("[OTHER_DEPENDENCIES]", deps.str()); // not relative to a ROS package
}
// Pair 9 - Add ROS Controllers to ros_controllers.launch file
if (config_data_->getROSControllers().empty())
{
addTemplateString("[ROS_CONTROLLERS]", "");
}
else
{
std::stringstream controllers;
for (std::vector<ROSControlConfig>::iterator controller_it = config_data_->getROSControllers().begin();
controller_it != config_data_->getROSControllers().end(); ++controller_it)
{
controllers << controller_it->name_ << " ";
}
addTemplateString("[ROS_CONTROLLERS]", controllers.str());
}
addTemplateString("[AUTHOR_NAME]", config_data_->author_name_);
addTemplateString("[AUTHOR_EMAIL]", config_data_->author_email_);
}
// ******************************************************************************************
// Insert a string pair into the template_strings_ datastructure
// ******************************************************************************************
bool ConfigurationFilesWidget::addTemplateString(const std::string& key, const std::string& value)
{
template_strings_.push_back(std::pair<std::string, std::string>(key, value));
return true;
}
// ******************************************************************************************
// Copy a template from location <template_path> to location <output_path> and replace package name
// ******************************************************************************************
bool ConfigurationFilesWidget::copyTemplate(const std::string& template_path, const std::string& output_path)
{
// Check if template strings have been loaded yet
if (template_strings_.empty())
{
loadTemplateStrings();
}
// Error check file
if (!fs::is_regular_file(template_path))
{
ROS_ERROR_STREAM("Unable to find template file " << template_path);
return false;
}
// Load file
std::ifstream template_stream(template_path.c_str());
if (!template_stream.good()) // File not found
{
ROS_ERROR_STREAM("Unable to load file " << template_path);
return false;
}
// Load the file to a string using an efficient memory allocation technique
std::string template_string;
template_stream.seekg(0, std::ios::end);
template_string.reserve(template_stream.tellg());
template_stream.seekg(0, std::ios::beg);
template_string.assign((std::istreambuf_iterator<char>(template_stream)), std::istreambuf_iterator<char>());
template_stream.close();
// Replace keywords in string ------------------------------------------------------------
for (int i = 0; i < template_strings_.size(); ++i)
{
boost::replace_all(template_string, template_strings_[i].first, template_strings_[i].second);
}
// Save string to new location -----------------------------------------------------------
std::ofstream output_stream(output_path.c_str(), std::ios_base::trunc);
if (!output_stream.good())
{
ROS_ERROR_STREAM("Unable to open file for writing " << output_path);
return false;
}
output_stream << template_string.c_str();
output_stream.close();
return true; // file created successfully
}
// ******************************************************************************************
// Create a folder
// ******************************************************************************************
bool ConfigurationFilesWidget::createFolder(const std::string& output_path)
{
if (!fs::is_directory(output_path))
{
if (!fs::create_directory(output_path))
{
QMessageBox::critical(this, "Error Generating Files",
QString("Unable to create directory ").append(output_path.c_str()));
return false;
}
}
return true;
}
} // namespace
|
// Copyright 2018 Slightech Co., Ltd. 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 <opencv2/highgui/highgui.hpp>
#include "mynteye/logger.h"
#include "mynteye/api/api.h"
#include "util_cv.h"
MYNTEYE_USE_NAMESPACE
int main(int argc, char *argv[]) {
auto &&api = API::Create(argc, argv);
if (!api) return 1;
std::int32_t frame_rate = 0;
bool ok;
auto &&request = api->SelectStreamRequest(&ok);
if (!ok) return 1;
api->ConfigStreamRequest(request);
Model model = api->GetModel();
// Set manual exposure options fo s1030
if (model == Model::STANDARD) {
// manual-exposure: 1
api->SetOptionValue(Option::EXPOSURE_MODE, 1);
// gain: range [0,48], default 24
api->SetOptionValue(Option::GAIN, 24);
// brightness/exposure_time: range [0,240], default 120
api->SetOptionValue(Option::BRIGHTNESS, 120);
// contrast/black_level_calibration: range [0,254], default 116
api->SetOptionValue(Option::CONTRAST, 116);
frame_rate = api->GetOptionValue(Option::FRAME_RATE);
LOG(INFO) << "Enable manual-exposure";
LOG(INFO) << "Set EXPOSURE_MODE to "
<< api->GetOptionValue(Option::EXPOSURE_MODE);
LOG(INFO) << "Set GAIN to " << api->GetOptionValue(Option::GAIN);
LOG(INFO) << "Set BRIGHTNESS to "
<< api->GetOptionValue(Option::BRIGHTNESS);
LOG(INFO) << "Set CONTRAST to " << api->GetOptionValue(Option::CONTRAST);
}
// Set manual exposure options fo S2000/S2100/S210A/S200B
if (model == Model::STANDARD2 || model == Model::STANDARD210A ||
model == Model::STANDARD200B) {
// manual-exposure: 1
api->SetOptionValue(Option::EXPOSURE_MODE, 1);
// brightness/exposure_time: range [1,255], default 70
api->SetOptionValue(Option::BRIGHTNESS, 70);
LOG(INFO) << "Enable manual-exposure";
LOG(INFO) << "Set EXPOSURE_MODE to "
<< api->GetOptionValue(Option::EXPOSURE_MODE);
LOG(INFO) << "Set BRIGHTNESS to "
<< api->GetOptionValue(Option::BRIGHTNESS);
}
api->Start(Source::VIDEO_STREAMING);
CVPainter painter(frame_rate);
cv::namedWindow("frame");
while (true) {
api->WaitForStreams();
auto &&left_data = api->GetStreamData(Stream::LEFT);
auto &&right_data = api->GetStreamData(Stream::RIGHT);
cv::Mat img;
cv::hconcat(left_data.frame, right_data.frame, img);
painter.DrawImgData(img, *left_data.img);
cv::imshow("frame", img);
char key = static_cast<char>(cv::waitKey(1));
if (key == 27 || key == 'q' || key == 'Q') { // ESC/Q
break;
}
}
api->Stop(Source::VIDEO_STREAMING);
return 0;
}
|
/*
* Copyright (C) 2011 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 "WebHitTestResultData.h"
#include "WebCoreArgumentCoders.h"
#include <WebCore/Document.h>
#include <WebCore/Frame.h>
#include <WebCore/FrameView.h>
#include <WebCore/HitTestResult.h>
#include <WebCore/Node.h>
#include <WebCore/RenderObject.h>
#include <WebCore/SharedBuffer.h>
#include <wtf/URL.h>
#include <wtf/text/WTFString.h>
namespace WebKit {
using namespace WebCore;
WebHitTestResultData::WebHitTestResultData()
{
}
WebHitTestResultData::WebHitTestResultData(const WebCore::HitTestResult& hitTestResult, const String& toolTipText)
: absoluteImageURL(hitTestResult.absoluteImageURL().string())
, absolutePDFURL(hitTestResult.absolutePDFURL().string())
, absoluteLinkURL(hitTestResult.absoluteLinkURL().string())
, absoluteMediaURL(hitTestResult.absoluteMediaURL().string())
, linkLabel(hitTestResult.textContent())
, linkTitle(hitTestResult.titleDisplayString())
, linkSuggestedFilename(hitTestResult.linkSuggestedFilename())
, isContentEditable(hitTestResult.isContentEditable())
, elementBoundingBox(elementBoundingBoxInWindowCoordinates(hitTestResult))
, isScrollbar(IsScrollbar::No)
, isSelected(hitTestResult.isSelected())
, isTextNode(hitTestResult.innerNode() && hitTestResult.innerNode()->isTextNode())
, isOverTextInsideFormControlElement(hitTestResult.isOverTextInsideFormControlElement())
, isDownloadableMedia(hitTestResult.isDownloadableMedia())
, toolTipText(toolTipText)
, imageSize(0)
{
if (auto* scrollbar = hitTestResult.scrollbar())
isScrollbar = scrollbar->orientation() == HorizontalScrollbar ? IsScrollbar::Horizontal : IsScrollbar::Vertical;
}
WebHitTestResultData::WebHitTestResultData(const WebCore::HitTestResult& hitTestResult, bool includeImage)
: absoluteImageURL(hitTestResult.absoluteImageURL().string())
, absolutePDFURL(hitTestResult.absolutePDFURL().string())
, absoluteLinkURL(hitTestResult.absoluteLinkURL().string())
, absoluteMediaURL(hitTestResult.absoluteMediaURL().string())
, linkLabel(hitTestResult.textContent())
, linkTitle(hitTestResult.titleDisplayString())
, linkSuggestedFilename(hitTestResult.linkSuggestedFilename())
, isContentEditable(hitTestResult.isContentEditable())
, elementBoundingBox(elementBoundingBoxInWindowCoordinates(hitTestResult))
, isScrollbar(IsScrollbar::No)
, isSelected(hitTestResult.isSelected())
, isTextNode(hitTestResult.innerNode() && hitTestResult.innerNode()->isTextNode())
, isOverTextInsideFormControlElement(hitTestResult.isOverTextInsideFormControlElement())
, isDownloadableMedia(hitTestResult.isDownloadableMedia())
, imageSize(0)
{
if (auto* scrollbar = hitTestResult.scrollbar())
isScrollbar = scrollbar->orientation() == HorizontalScrollbar ? IsScrollbar::Horizontal : IsScrollbar::Vertical;
if (!includeImage)
return;
if (Image* image = hitTestResult.image()) {
RefPtr<SharedBuffer> buffer = image->data();
if (buffer) {
imageSharedMemory = WebKit::SharedMemory::allocate(buffer->size());
memcpy(imageSharedMemory->data(), buffer->data(), buffer->size());
imageSize = buffer->size();
}
}
}
WebHitTestResultData::~WebHitTestResultData()
{
}
void WebHitTestResultData::encode(IPC::Encoder& encoder) const
{
encoder << absoluteImageURL;
encoder << absolutePDFURL;
encoder << absoluteLinkURL;
encoder << absoluteMediaURL;
encoder << linkLabel;
encoder << linkTitle;
encoder << linkSuggestedFilename;
encoder << isContentEditable;
encoder << elementBoundingBox;
encoder << isScrollbar;
encoder << isSelected;
encoder << isTextNode;
encoder << isOverTextInsideFormControlElement;
encoder << isDownloadableMedia;
encoder << lookupText;
encoder << toolTipText;
encoder << dictionaryPopupInfo;
WebKit::SharedMemory::Handle imageHandle;
if (imageSharedMemory && imageSharedMemory->data())
imageSharedMemory->createHandle(imageHandle, WebKit::SharedMemory::Protection::ReadOnly);
encoder << imageHandle;
encoder << imageSize;
bool hasLinkTextIndicator = linkTextIndicator;
encoder << hasLinkTextIndicator;
if (hasLinkTextIndicator)
encoder << linkTextIndicator->data();
platformEncode(encoder);
}
bool WebHitTestResultData::decode(IPC::Decoder& decoder, WebHitTestResultData& hitTestResultData)
{
if (!decoder.decode(hitTestResultData.absoluteImageURL)
|| !decoder.decode(hitTestResultData.absolutePDFURL)
|| !decoder.decode(hitTestResultData.absoluteLinkURL)
|| !decoder.decode(hitTestResultData.absoluteMediaURL)
|| !decoder.decode(hitTestResultData.linkLabel)
|| !decoder.decode(hitTestResultData.linkTitle)
|| !decoder.decode(hitTestResultData.linkSuggestedFilename)
|| !decoder.decode(hitTestResultData.isContentEditable)
|| !decoder.decode(hitTestResultData.elementBoundingBox)
|| !decoder.decode(hitTestResultData.isScrollbar)
|| !decoder.decode(hitTestResultData.isSelected)
|| !decoder.decode(hitTestResultData.isTextNode)
|| !decoder.decode(hitTestResultData.isOverTextInsideFormControlElement)
|| !decoder.decode(hitTestResultData.isDownloadableMedia)
|| !decoder.decode(hitTestResultData.lookupText)
|| !decoder.decode(hitTestResultData.toolTipText)
|| !decoder.decode(hitTestResultData.dictionaryPopupInfo))
return false;
WebKit::SharedMemory::Handle imageHandle;
if (!decoder.decode(imageHandle))
return false;
if (!imageHandle.isNull())
hitTestResultData.imageSharedMemory = WebKit::SharedMemory::map(imageHandle, WebKit::SharedMemory::Protection::ReadOnly);
if (!decoder.decode(hitTestResultData.imageSize))
return false;
if (hitTestResultData.imageSharedMemory) {
// SharedMemory:size() is rounded up to the nearest page.
if (hitTestResultData.imageSize > hitTestResultData.imageSharedMemory->size())
return false;
} else if (hitTestResultData.imageSize)
return false;
bool hasLinkTextIndicator;
if (!decoder.decode(hasLinkTextIndicator))
return false;
if (hasLinkTextIndicator) {
Optional<WebCore::TextIndicatorData> indicatorData;
decoder >> indicatorData;
if (!indicatorData)
return false;
hitTestResultData.linkTextIndicator = WebCore::TextIndicator::create(*indicatorData);
}
return platformDecode(decoder, hitTestResultData);
}
#if !PLATFORM(MAC)
void WebHitTestResultData::platformEncode(IPC::Encoder& encoder) const
{
}
bool WebHitTestResultData::platformDecode(IPC::Decoder& decoder, WebHitTestResultData& hitTestResultData)
{
return true;
}
#endif // !PLATFORM(MAC)
IntRect WebHitTestResultData::elementBoundingBoxInWindowCoordinates(const WebCore::HitTestResult& hitTestResult)
{
Node* node = hitTestResult.innerNonSharedNode();
if (!node)
return IntRect();
Frame* frame = node->document().frame();
if (!frame)
return IntRect();
FrameView* view = frame->view();
if (!view)
return IntRect();
RenderObject* renderer = node->renderer();
if (!renderer)
return IntRect();
return view->contentsToWindow(renderer->absoluteBoundingBoxRect());
}
} // WebKit
|
//==--- defines_elementary.hpp ---- Preprocessor directives (simplified) ---==//
//
// 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
//
//===----------------------------------------------------------------------===//
#pragma once
#ifndef __SYCL_DISABLE_NAMESPACE_INLINE__
#define __SYCL_INLINE_NAMESPACE(X) inline namespace X
#else
#define __SYCL_INLINE_NAMESPACE(X) namespace X
#endif // __SYCL_DISABLE_NAMESPACE_INLINE__
#ifndef __has_attribute
#define __has_attribute(x) 0
#endif
#ifndef __has_builtin
#define __has_builtin(x) 0
#endif // __has_builtin
#ifndef __SYCL_ALWAYS_INLINE
#if __has_attribute(always_inline)
#define __SYCL_ALWAYS_INLINE __attribute__((always_inline))
#else
#define __SYCL_ALWAYS_INLINE
#endif
#endif // __SYCL_ALWAYS_INLINE
#ifndef SYCL_EXTERNAL
#define SYCL_EXTERNAL
#endif
#ifndef __SYCL_ID_QUERIES_FIT_IN_INT__
#define __SYCL_ID_QUERIES_FIT_IN_INT__ 0
#endif
#ifndef __SYCL_DEPRECATED
#ifndef SYCL_DISABLE_DEPRECATION_WARNINGS
#define __SYCL_DEPRECATED(message) [[deprecated(message)]]
#else // SYCL_DISABLE_DEPRECATION_WARNINGS
#define __SYCL_DEPRECATED(message)
#endif // SYCL_DISABLE_DEPRECATION_WARNINGS
#endif // __SYCL_DEPRECATED
#ifndef __SYCL2020_DEPRECATED
#if SYCL_LANGUAGE_VERSION >= 202001 && \
!defined(SYCL2020_DISABLE_DEPRECATION_WARNINGS)
#define __SYCL2020_DEPRECATED(message) __SYCL_DEPRECATED(message)
#else
#define __SYCL2020_DEPRECATED(message)
#endif
#endif // __SYCL2020_DEPRECATED
#ifndef __SYCL_INLINE_CONSTEXPR
// inline constexpr is a C++17 feature
#if __cplusplus >= 201703L
#define __SYCL_INLINE_CONSTEXPR inline constexpr
#else
#define __SYCL_INLINE_CONSTEXPR static constexpr
#endif
#endif // __SYCL_INLINE_CONSTEXPR
#ifndef __SYCL_HAS_CPP_ATTRIBUTE
#if defined(__cplusplus) && defined(__has_cpp_attribute)
#define __SYCL_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
#else
#define __SYCL_HAS_CPP_ATTRIBUTE(x) 0
#endif
#endif
#ifndef __SYCL_FALLTHROUGH
#if defined(__cplusplus) && __cplusplus > 201402L && \
__SYCL_HAS_CPP_ATTRIBUTE(fallthrough)
#define __SYCL_FALLTHROUGH [[fallthrough]]
#elif __SYCL_HAS_CPP_ATTRIBUTE(gnu::fallthrough)
#define __SYCL_FALLTHROUGH [[gnu::fallthrough]]
#elif __has_attribute(fallthrough)
#define __SYCL_FALLTHROUGH __attribute__((fallthrough))
#elif __SYCL_HAS_CPP_ATTRIBUTE(clang::fallthrough)
#define __SYCL_FALLTHROUGH [[clang::fallthrough]]
#else
#define __SYCL_FALLTHROUGH
#endif
#endif // __SYCL_FALLTHROUGH
// define __SYCL_WARNING convenience macro to report compiler warnings
#if defined(__GNUC__)
#define __SYCL_GCC_PRAGMA(x) _Pragma(#x)
#define __SYCL_WARNING(msg) __SYCL_GCC_PRAGMA(GCC warning msg)
#elif defined(_MSC_VER) && !defined(__clang__)
#define __SYCL_QUOTE1(x) #x
#define __SYCL_QUOTE(x) __SYCL_QUOTE1(x)
#define __SYCL_SRC_LOC __FILE__ ":" __SYCL_QUOTE(__LINE__)
#define __SYCL_WARNING(msg) __pragma(message(__SYCL_SRC_LOC " warning: " msg))
#else // clang et. al.
// clang emits "warning:" in the message pragma output
#define __SYCL_WARNING(msg) __pragma(message(msg))
#endif // __GNUC__
|
//
// 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) 2018 NVIDIA Corporation. All rights reserved.
// This file was generated by NvParameterized/scripts/GenParameterized.pl
#include "ClothingPhysicalMeshParameters_0p1.h"
#include <string.h>
#include <stdlib.h>
using namespace NvParameterized;
namespace nvidia
{
namespace parameterized
{
using namespace ClothingPhysicalMeshParameters_0p1NS;
const char* const ClothingPhysicalMeshParameters_0p1Factory::vptr =
NvParameterized::getVptr<ClothingPhysicalMeshParameters_0p1, ClothingPhysicalMeshParameters_0p1::ClassAlignment>();
const uint32_t NumParamDefs = 77;
static NvParameterized::DefinitionImpl* ParamDefTable; // now allocated in buildTree [NumParamDefs];
static const size_t ParamLookupChildrenTable[] =
{
1, 28, 35, 37, 38, 44, 52, 58, 59, 60, 68, 74, 75, 76, 2, 3, 4, 5, 7, 9, 11, 13,
18, 20, 22, 24, 25, 26, 27, 6, 8, 10, 12, 14, 15, 16, 17, 19, 21, 23, 29, 30, 31,
32, 33, 34, 36, 39, 40, 41, 42, 43, 45, 46, 47, 48, 49, 50, 51, 53, 54, 55, 56, 57,
61, 62, 63, 64, 65, 66, 67, 69, 70, 71, 72, 73,
};
#define TENUM(type) nvidia::##type
#define CHILDREN(index) &ParamLookupChildrenTable[index]
static const NvParameterized::ParamLookupNode ParamLookupTable[NumParamDefs] =
{
{ TYPE_STRUCT, false, 0, CHILDREN(0), 14 },
{ TYPE_STRUCT, false, (size_t)(&((ParametersStruct*)0)->physicalMesh), CHILDREN(14), 15 }, // physicalMesh
{ TYPE_U32, false, (size_t)(&((PhysicalMesh_Type*)0)->numVertices), NULL, 0 }, // physicalMesh.numVertices
{ TYPE_U32, false, (size_t)(&((PhysicalMesh_Type*)0)->numIndices), NULL, 0 }, // physicalMesh.numIndices
{ TYPE_U32, false, (size_t)(&((PhysicalMesh_Type*)0)->numBonesPerVertex), NULL, 0 }, // physicalMesh.numBonesPerVertex
{ TYPE_ARRAY, true, (size_t)(&((PhysicalMesh_Type*)0)->vertices), CHILDREN(29), 1 }, // physicalMesh.vertices
{ TYPE_VEC3, false, 1 * sizeof(physx::PxVec3), NULL, 0 }, // physicalMesh.vertices[]
{ TYPE_ARRAY, true, (size_t)(&((PhysicalMesh_Type*)0)->normals), CHILDREN(30), 1 }, // physicalMesh.normals
{ TYPE_VEC3, false, 1 * sizeof(physx::PxVec3), NULL, 0 }, // physicalMesh.normals[]
{ TYPE_ARRAY, true, (size_t)(&((PhysicalMesh_Type*)0)->skinningNormals), CHILDREN(31), 1 }, // physicalMesh.skinningNormals
{ TYPE_VEC3, false, 1 * sizeof(physx::PxVec3), NULL, 0 }, // physicalMesh.skinningNormals[]
{ TYPE_ARRAY, true, (size_t)(&((PhysicalMesh_Type*)0)->vertexFlags), CHILDREN(32), 1 }, // physicalMesh.vertexFlags
{ TYPE_U32, false, 1 * sizeof(uint32_t), NULL, 0 }, // physicalMesh.vertexFlags[]
{ TYPE_ARRAY, true, (size_t)(&((PhysicalMesh_Type*)0)->constrainCoefficients), CHILDREN(33), 1 }, // physicalMesh.constrainCoefficients
{ TYPE_STRUCT, false, 1 * sizeof(ConstrainCoefficient_Type), CHILDREN(34), 3 }, // physicalMesh.constrainCoefficients[]
{ TYPE_F32, false, (size_t)(&((ConstrainCoefficient_Type*)0)->maxDistance), NULL, 0 }, // physicalMesh.constrainCoefficients[].maxDistance
{ TYPE_F32, false, (size_t)(&((ConstrainCoefficient_Type*)0)->collisionSphereRadius), NULL, 0 }, // physicalMesh.constrainCoefficients[].collisionSphereRadius
{ TYPE_F32, false, (size_t)(&((ConstrainCoefficient_Type*)0)->collisionSphereDistance), NULL, 0 }, // physicalMesh.constrainCoefficients[].collisionSphereDistance
{ TYPE_ARRAY, true, (size_t)(&((PhysicalMesh_Type*)0)->boneIndices), CHILDREN(37), 1 }, // physicalMesh.boneIndices
{ TYPE_U16, false, 1 * sizeof(uint16_t), NULL, 0 }, // physicalMesh.boneIndices[]
{ TYPE_ARRAY, true, (size_t)(&((PhysicalMesh_Type*)0)->boneWeights), CHILDREN(38), 1 }, // physicalMesh.boneWeights
{ TYPE_F32, false, 1 * sizeof(float), NULL, 0 }, // physicalMesh.boneWeights[]
{ TYPE_ARRAY, true, (size_t)(&((PhysicalMesh_Type*)0)->indices), CHILDREN(39), 1 }, // physicalMesh.indices
{ TYPE_U32, false, 1 * sizeof(uint32_t), NULL, 0 }, // physicalMesh.indices[]
{ TYPE_F32, false, (size_t)(&((PhysicalMesh_Type*)0)->maximumMaxDistance), NULL, 0 }, // physicalMesh.maximumMaxDistance
{ TYPE_F32, false, (size_t)(&((PhysicalMesh_Type*)0)->shortestEdgeLength), NULL, 0 }, // physicalMesh.shortestEdgeLength
{ TYPE_F32, false, (size_t)(&((PhysicalMesh_Type*)0)->averageEdgeLength), NULL, 0 }, // physicalMesh.averageEdgeLength
{ TYPE_BOOL, false, (size_t)(&((PhysicalMesh_Type*)0)->isTetrahedralMesh), NULL, 0 }, // physicalMesh.isTetrahedralMesh
{ TYPE_ARRAY, true, (size_t)(&((ParametersStruct*)0)->submeshes), CHILDREN(40), 1 }, // submeshes
{ TYPE_STRUCT, false, 1 * sizeof(PhysicalSubmesh_Type), CHILDREN(41), 5 }, // submeshes[]
{ TYPE_U32, false, (size_t)(&((PhysicalSubmesh_Type*)0)->numIndices), NULL, 0 }, // submeshes[].numIndices
{ TYPE_U32, false, (size_t)(&((PhysicalSubmesh_Type*)0)->numVertices), NULL, 0 }, // submeshes[].numVertices
{ TYPE_U32, false, (size_t)(&((PhysicalSubmesh_Type*)0)->cookedDataOffset), NULL, 0 }, // submeshes[].cookedDataOffset
{ TYPE_U32, false, (size_t)(&((PhysicalSubmesh_Type*)0)->cookedDataLength), NULL, 0 }, // submeshes[].cookedDataLength
{ TYPE_POINTER, false, (size_t)(&((PhysicalSubmesh_Type*)0)->nxDeformableMesh), NULL, 0 }, // submeshes[].nxDeformableMesh
{ TYPE_ARRAY, true, (size_t)(&((ParametersStruct*)0)->deformableCookedData), CHILDREN(46), 1 }, // deformableCookedData
{ TYPE_U8, false, 1 * sizeof(uint8_t), NULL, 0 }, // deformableCookedData[]
{ TYPE_U32, false, (size_t)(&((ParametersStruct*)0)->deformableCookedDataVersion), NULL, 0 }, // deformableCookedDataVersion
{ TYPE_ARRAY, true, (size_t)(&((ParametersStruct*)0)->physicalLods), CHILDREN(47), 1 }, // physicalLods
{ TYPE_STRUCT, false, 1 * sizeof(PhysicalLod_Type), CHILDREN(48), 4 }, // physicalLods[]
{ TYPE_U32, false, (size_t)(&((PhysicalLod_Type*)0)->costWithoutIterations), NULL, 0 }, // physicalLods[].costWithoutIterations
{ TYPE_U32, false, (size_t)(&((PhysicalLod_Type*)0)->submeshId), NULL, 0 }, // physicalLods[].submeshId
{ TYPE_F32, false, (size_t)(&((PhysicalLod_Type*)0)->solverIterationScale), NULL, 0 }, // physicalLods[].solverIterationScale
{ TYPE_F32, false, (size_t)(&((PhysicalLod_Type*)0)->maxDistanceReduction), NULL, 0 }, // physicalLods[].maxDistanceReduction
{ TYPE_ARRAY, true, (size_t)(&((ParametersStruct*)0)->transitionUpB), CHILDREN(52), 1 }, // transitionUpB
{ TYPE_STRUCT, false, 1 * sizeof(SkinClothMapB_Type), CHILDREN(53), 6 }, // transitionUpB[]
{ TYPE_VEC3, false, (size_t)(&((SkinClothMapB_Type*)0)->vtxTetraBary), NULL, 0 }, // transitionUpB[].vtxTetraBary
{ TYPE_U32, false, (size_t)(&((SkinClothMapB_Type*)0)->vertexIndexPlusOffset), NULL, 0 }, // transitionUpB[].vertexIndexPlusOffset
{ TYPE_VEC3, false, (size_t)(&((SkinClothMapB_Type*)0)->nrmTetraBary), NULL, 0 }, // transitionUpB[].nrmTetraBary
{ TYPE_U32, false, (size_t)(&((SkinClothMapB_Type*)0)->faceIndex0), NULL, 0 }, // transitionUpB[].faceIndex0
{ TYPE_U32, false, (size_t)(&((SkinClothMapB_Type*)0)->tetraIndex), NULL, 0 }, // transitionUpB[].tetraIndex
{ TYPE_U32, false, (size_t)(&((SkinClothMapB_Type*)0)->submeshIndex), NULL, 0 }, // transitionUpB[].submeshIndex
{ TYPE_ARRAY, true, (size_t)(&((ParametersStruct*)0)->transitionUpC), CHILDREN(59), 1 }, // transitionUpC
{ TYPE_STRUCT, false, 1 * sizeof(SkinClothMapC_Type), CHILDREN(60), 4 }, // transitionUpC[]
{ TYPE_VEC3, false, (size_t)(&((SkinClothMapC_Type*)0)->vertexBary), NULL, 0 }, // transitionUpC[].vertexBary
{ TYPE_U32, false, (size_t)(&((SkinClothMapC_Type*)0)->faceIndex0), NULL, 0 }, // transitionUpC[].faceIndex0
{ TYPE_VEC3, false, (size_t)(&((SkinClothMapC_Type*)0)->normalBary), NULL, 0 }, // transitionUpC[].normalBary
{ TYPE_U32, false, (size_t)(&((SkinClothMapC_Type*)0)->vertexIndexPlusOffset), NULL, 0 }, // transitionUpC[].vertexIndexPlusOffset
{ TYPE_F32, false, (size_t)(&((ParametersStruct*)0)->transitionUpThickness), NULL, 0 }, // transitionUpThickness
{ TYPE_F32, false, (size_t)(&((ParametersStruct*)0)->transitionUpOffset), NULL, 0 }, // transitionUpOffset
{ TYPE_ARRAY, true, (size_t)(&((ParametersStruct*)0)->transitionDownB), CHILDREN(64), 1 }, // transitionDownB
{ TYPE_STRUCT, false, 1 * sizeof(SkinClothMapB_Type), CHILDREN(65), 6 }, // transitionDownB[]
{ TYPE_VEC3, false, (size_t)(&((SkinClothMapB_Type*)0)->vtxTetraBary), NULL, 0 }, // transitionDownB[].vtxTetraBary
{ TYPE_U32, false, (size_t)(&((SkinClothMapB_Type*)0)->vertexIndexPlusOffset), NULL, 0 }, // transitionDownB[].vertexIndexPlusOffset
{ TYPE_VEC3, false, (size_t)(&((SkinClothMapB_Type*)0)->nrmTetraBary), NULL, 0 }, // transitionDownB[].nrmTetraBary
{ TYPE_U32, false, (size_t)(&((SkinClothMapB_Type*)0)->faceIndex0), NULL, 0 }, // transitionDownB[].faceIndex0
{ TYPE_U32, false, (size_t)(&((SkinClothMapB_Type*)0)->tetraIndex), NULL, 0 }, // transitionDownB[].tetraIndex
{ TYPE_U32, false, (size_t)(&((SkinClothMapB_Type*)0)->submeshIndex), NULL, 0 }, // transitionDownB[].submeshIndex
{ TYPE_ARRAY, true, (size_t)(&((ParametersStruct*)0)->transitionDownC), CHILDREN(71), 1 }, // transitionDownC
{ TYPE_STRUCT, false, 1 * sizeof(SkinClothMapC_Type), CHILDREN(72), 4 }, // transitionDownC[]
{ TYPE_VEC3, false, (size_t)(&((SkinClothMapC_Type*)0)->vertexBary), NULL, 0 }, // transitionDownC[].vertexBary
{ TYPE_U32, false, (size_t)(&((SkinClothMapC_Type*)0)->faceIndex0), NULL, 0 }, // transitionDownC[].faceIndex0
{ TYPE_VEC3, false, (size_t)(&((SkinClothMapC_Type*)0)->normalBary), NULL, 0 }, // transitionDownC[].normalBary
{ TYPE_U32, false, (size_t)(&((SkinClothMapC_Type*)0)->vertexIndexPlusOffset), NULL, 0 }, // transitionDownC[].vertexIndexPlusOffset
{ TYPE_F32, false, (size_t)(&((ParametersStruct*)0)->transitionDownThickness), NULL, 0 }, // transitionDownThickness
{ TYPE_F32, false, (size_t)(&((ParametersStruct*)0)->transitionDownOffset), NULL, 0 }, // transitionDownOffset
{ TYPE_U32, false, (size_t)(&((ParametersStruct*)0)->referenceCount), NULL, 0 }, // referenceCount
};
bool ClothingPhysicalMeshParameters_0p1::mBuiltFlag = false;
NvParameterized::MutexType ClothingPhysicalMeshParameters_0p1::mBuiltFlagMutex;
ClothingPhysicalMeshParameters_0p1::ClothingPhysicalMeshParameters_0p1(NvParameterized::Traits* traits, void* buf, int32_t* refCount) :
NvParameters(traits, buf, refCount)
{
//mParameterizedTraits->registerFactory(className(), &ClothingPhysicalMeshParameters_0p1FactoryInst);
if (!buf) //Do not init data if it is inplace-deserialized
{
initDynamicArrays();
initStrings();
initReferences();
initDefaults();
}
}
ClothingPhysicalMeshParameters_0p1::~ClothingPhysicalMeshParameters_0p1()
{
freeStrings();
freeReferences();
freeDynamicArrays();
}
void ClothingPhysicalMeshParameters_0p1::destroy()
{
// We cache these fields here to avoid overwrite in destructor
bool doDeallocateSelf = mDoDeallocateSelf;
NvParameterized::Traits* traits = mParameterizedTraits;
int32_t* refCount = mRefCount;
void* buf = mBuffer;
this->~ClothingPhysicalMeshParameters_0p1();
NvParameters::destroy(this, traits, doDeallocateSelf, refCount, buf);
}
const NvParameterized::DefinitionImpl* ClothingPhysicalMeshParameters_0p1::getParameterDefinitionTree(void)
{
if (!mBuiltFlag) // Double-checked lock
{
NvParameterized::MutexType::ScopedLock lock(mBuiltFlagMutex);
if (!mBuiltFlag)
{
buildTree();
}
}
return(&ParamDefTable[0]);
}
const NvParameterized::DefinitionImpl* ClothingPhysicalMeshParameters_0p1::getParameterDefinitionTree(void) const
{
ClothingPhysicalMeshParameters_0p1* tmpParam = const_cast<ClothingPhysicalMeshParameters_0p1*>(this);
if (!mBuiltFlag) // Double-checked lock
{
NvParameterized::MutexType::ScopedLock lock(mBuiltFlagMutex);
if (!mBuiltFlag)
{
tmpParam->buildTree();
}
}
return(&ParamDefTable[0]);
}
NvParameterized::ErrorType ClothingPhysicalMeshParameters_0p1::getParameterHandle(const char* long_name, Handle& handle) const
{
ErrorType Ret = NvParameters::getParameterHandle(long_name, handle);
if (Ret != ERROR_NONE)
{
return(Ret);
}
size_t offset;
void* ptr;
getVarPtr(handle, ptr, offset);
if (ptr == NULL)
{
return(ERROR_INDEX_OUT_OF_RANGE);
}
return(ERROR_NONE);
}
NvParameterized::ErrorType ClothingPhysicalMeshParameters_0p1::getParameterHandle(const char* long_name, Handle& handle)
{
ErrorType Ret = NvParameters::getParameterHandle(long_name, handle);
if (Ret != ERROR_NONE)
{
return(Ret);
}
size_t offset;
void* ptr;
getVarPtr(handle, ptr, offset);
if (ptr == NULL)
{
return(ERROR_INDEX_OUT_OF_RANGE);
}
return(ERROR_NONE);
}
void ClothingPhysicalMeshParameters_0p1::getVarPtr(const Handle& handle, void*& ptr, size_t& offset) const
{
ptr = getVarPtrHelper(&ParamLookupTable[0], const_cast<ClothingPhysicalMeshParameters_0p1::ParametersStruct*>(¶meters()), handle, offset);
}
/* Dynamic Handle Indices */
void ClothingPhysicalMeshParameters_0p1::freeParameterDefinitionTable(NvParameterized::Traits* traits)
{
if (!traits)
{
return;
}
if (!mBuiltFlag) // Double-checked lock
{
return;
}
NvParameterized::MutexType::ScopedLock lock(mBuiltFlagMutex);
if (!mBuiltFlag)
{
return;
}
for (uint32_t i = 0; i < NumParamDefs; ++i)
{
ParamDefTable[i].~DefinitionImpl();
}
traits->free(ParamDefTable);
mBuiltFlag = false;
}
#define PDEF_PTR(index) (&ParamDefTable[index])
void ClothingPhysicalMeshParameters_0p1::buildTree(void)
{
uint32_t allocSize = sizeof(NvParameterized::DefinitionImpl) * NumParamDefs;
ParamDefTable = (NvParameterized::DefinitionImpl*)(mParameterizedTraits->alloc(allocSize));
memset(ParamDefTable, 0, allocSize);
for (uint32_t i = 0; i < NumParamDefs; ++i)
{
NV_PARAM_PLACEMENT_NEW(ParamDefTable + i, NvParameterized::DefinitionImpl)(*mParameterizedTraits);
}
// Initialize DefinitionImpl node: nodeIndex=0, longName=""
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[0];
ParamDef->init("", TYPE_STRUCT, "STRUCT", true);
}
// Initialize DefinitionImpl node: nodeIndex=1, longName="physicalMesh"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[1];
ParamDef->init("physicalMesh", TYPE_STRUCT, "PhysicalMesh", true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "The physical mesh data.", true);
ParamDefTable[1].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=2, longName="physicalMesh.numVertices"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[2];
ParamDef->init("numVertices", TYPE_U32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Number of vertices of this mesh", true);
ParamDefTable[2].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=3, longName="physicalMesh.numIndices"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[3];
ParamDef->init("numIndices", TYPE_U32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Number of indices of this mesh", true);
ParamDefTable[3].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=4, longName="physicalMesh.numBonesPerVertex"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[4];
ParamDef->init("numBonesPerVertex", TYPE_U32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Number of bone weights/indices per vertex", true);
ParamDefTable[4].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=5, longName="physicalMesh.vertices"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[5];
ParamDef->init("vertices", TYPE_ARRAY, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Array of vertices", true);
ParamDefTable[5].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
ParamDef->setArraySize(-1);
}
// Initialize DefinitionImpl node: nodeIndex=6, longName="physicalMesh.vertices[]"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[6];
ParamDef->init("vertices", TYPE_VEC3, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Array of vertices", true);
ParamDefTable[6].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=7, longName="physicalMesh.normals"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[7];
ParamDef->init("normals", TYPE_ARRAY, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("longDescription", "These are the normals provided by the user. The mesh-mesh skinning will try to restore them as good\nas possible throughout simulation. Note, they can differ from the skinningNormals quite drastically.\n", true);
HintTable[1].init("shortDescription", "Array of normals", true);
ParamDefTable[7].setHints((const NvParameterized::Hint**)HintPtrTable, 2);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
ParamDef->setArraySize(-1);
}
// Initialize DefinitionImpl node: nodeIndex=8, longName="physicalMesh.normals[]"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[8];
ParamDef->init("normals", TYPE_VEC3, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("longDescription", "These are the normals provided by the user. The mesh-mesh skinning will try to restore them as good\nas possible throughout simulation. Note, they can differ from the skinningNormals quite drastically.\n", true);
HintTable[1].init("shortDescription", "Array of normals", true);
ParamDefTable[8].setHints((const NvParameterized::Hint**)HintPtrTable, 2);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=9, longName="physicalMesh.skinningNormals"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[9];
ParamDef->init("skinningNormals", TYPE_ARRAY, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("DONOTSERIALIZE", uint64_t(1), true);
ParamDefTable[9].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#else
static HintImpl HintTable[3];
static Hint* HintPtrTable[3] = { &HintTable[0], &HintTable[1], &HintTable[2], };
HintTable[0].init("DONOTSERIALIZE", uint64_t(1), true);
HintTable[1].init("longDescription", "These are only needed at authoring time. They reflect what will come out of physics and are thus needed\nto create the mesh-mesh skinning.\n", true);
HintTable[2].init("shortDescription", "Array of skinning normals", true);
ParamDefTable[9].setHints((const NvParameterized::Hint**)HintPtrTable, 3);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
ParamDef->setArraySize(-1);
}
// Initialize DefinitionImpl node: nodeIndex=10, longName="physicalMesh.skinningNormals[]"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[10];
ParamDef->init("skinningNormals", TYPE_VEC3, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("DONOTSERIALIZE", uint64_t(1), true);
ParamDefTable[10].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#else
static HintImpl HintTable[3];
static Hint* HintPtrTable[3] = { &HintTable[0], &HintTable[1], &HintTable[2], };
HintTable[0].init("DONOTSERIALIZE", uint64_t(1), true);
HintTable[1].init("longDescription", "These are only needed at authoring time. They reflect what will come out of physics and are thus needed\nto create the mesh-mesh skinning.\n", true);
HintTable[2].init("shortDescription", "Array of skinning normals", true);
ParamDefTable[10].setHints((const NvParameterized::Hint**)HintPtrTable, 3);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=11, longName="physicalMesh.vertexFlags"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[11];
ParamDef->init("vertexFlags", TYPE_ARRAY, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Specify per vertex flags for the mesh (see NxClothVertexFlags and NxSoftBodyVertexFlags).", true);
ParamDefTable[11].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
ParamDef->setArraySize(-1);
}
// Initialize DefinitionImpl node: nodeIndex=12, longName="physicalMesh.vertexFlags[]"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[12];
ParamDef->init("vertexFlags", TYPE_U32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Specify per vertex flags for the mesh (see NxClothVertexFlags and NxSoftBodyVertexFlags).", true);
ParamDefTable[12].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=13, longName="physicalMesh.constrainCoefficients"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[13];
ParamDef->init("constrainCoefficients", TYPE_ARRAY, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("longDescription", "These are not provided but computed by copying values from the graphical mesh to the physical mesh.\n", true);
HintTable[1].init("shortDescription", "The clothing constrain coefficients for this mesh.", true);
ParamDefTable[13].setHints((const NvParameterized::Hint**)HintPtrTable, 2);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
ParamDef->setArraySize(-1);
}
// Initialize DefinitionImpl node: nodeIndex=14, longName="physicalMesh.constrainCoefficients[]"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[14];
ParamDef->init("constrainCoefficients", TYPE_STRUCT, "ConstrainCoefficient", true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("longDescription", "These are not provided but computed by copying values from the graphical mesh to the physical mesh.\n", true);
HintTable[1].init("shortDescription", "The clothing constrain coefficients for this mesh.", true);
ParamDefTable[14].setHints((const NvParameterized::Hint**)HintPtrTable, 2);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=15, longName="physicalMesh.constrainCoefficients[].maxDistance"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[15];
ParamDef->init("maxDistance", TYPE_F32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Maximum distance this vertex is allowed to travel from its skinned position.", true);
ParamDefTable[15].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=16, longName="physicalMesh.constrainCoefficients[].collisionSphereRadius"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[16];
ParamDef->init("collisionSphereRadius", TYPE_F32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Size of the Backstop collision sphere.", true);
ParamDefTable[16].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=17, longName="physicalMesh.constrainCoefficients[].collisionSphereDistance"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[17];
ParamDef->init("collisionSphereDistance", TYPE_F32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Distance of the Backstop collision sphere.", true);
ParamDefTable[17].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=18, longName="physicalMesh.boneIndices"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[18];
ParamDef->init("boneIndices", TYPE_ARRAY, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("longDescription", "Note: contains numVertices * numBonesPerVertex elements.\n", true);
HintTable[1].init("shortDescription", "The bone indices per vertex", true);
ParamDefTable[18].setHints((const NvParameterized::Hint**)HintPtrTable, 2);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
ParamDef->setArraySize(-1);
}
// Initialize DefinitionImpl node: nodeIndex=19, longName="physicalMesh.boneIndices[]"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[19];
ParamDef->init("boneIndices", TYPE_U16, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("longDescription", "Note: contains numVertices * numBonesPerVertex elements.\n", true);
HintTable[1].init("shortDescription", "The bone indices per vertex", true);
ParamDefTable[19].setHints((const NvParameterized::Hint**)HintPtrTable, 2);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=20, longName="physicalMesh.boneWeights"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[20];
ParamDef->init("boneWeights", TYPE_ARRAY, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("longDescription", "Note: contains numVertices * numBonesPerVertex elements.\n", true);
HintTable[1].init("shortDescription", "The bone weights per vertex", true);
ParamDefTable[20].setHints((const NvParameterized::Hint**)HintPtrTable, 2);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
ParamDef->setArraySize(-1);
}
// Initialize DefinitionImpl node: nodeIndex=21, longName="physicalMesh.boneWeights[]"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[21];
ParamDef->init("boneWeights", TYPE_F32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("longDescription", "Note: contains numVertices * numBonesPerVertex elements.\n", true);
HintTable[1].init("shortDescription", "The bone weights per vertex", true);
ParamDefTable[21].setHints((const NvParameterized::Hint**)HintPtrTable, 2);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=22, longName="physicalMesh.indices"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[22];
ParamDef->init("indices", TYPE_ARRAY, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "The index buffer", true);
ParamDefTable[22].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
ParamDef->setArraySize(-1);
}
// Initialize DefinitionImpl node: nodeIndex=23, longName="physicalMesh.indices[]"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[23];
ParamDef->init("indices", TYPE_U32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "The index buffer", true);
ParamDefTable[23].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=24, longName="physicalMesh.maximumMaxDistance"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[24];
ParamDef->init("maximumMaxDistance", TYPE_F32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("longDescription", "This is used to deduct how much a physical LoD can reduce the max distance.\n", true);
HintTable[1].init("shortDescription", "The maximum max-distance value for all the vertices.", true);
ParamDefTable[24].setHints((const NvParameterized::Hint**)HintPtrTable, 2);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=25, longName="physicalMesh.shortestEdgeLength"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[25];
ParamDef->init("shortestEdgeLength", TYPE_F32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Mesh statistic, only needed for debug rendering.", true);
ParamDefTable[25].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=26, longName="physicalMesh.averageEdgeLength"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[26];
ParamDef->init("averageEdgeLength", TYPE_F32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Mesh statistic, useful for selecting the thickness of the mesh-mesh skinning.", true);
ParamDefTable[26].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=27, longName="physicalMesh.isTetrahedralMesh"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[27];
ParamDef->init("isTetrahedralMesh", TYPE_BOOL, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Are we storing triangles or tetrahedrons in this mesh.", true);
ParamDefTable[27].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=28, longName="submeshes"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[28];
ParamDef->init("submeshes", TYPE_ARRAY, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "A list of submeshes with a varying fraction of the full mesh.", true);
ParamDefTable[28].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
ParamDef->setArraySize(-1);
}
// Initialize DefinitionImpl node: nodeIndex=29, longName="submeshes[]"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[29];
ParamDef->init("submeshes", TYPE_STRUCT, "PhysicalSubmesh", true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "A list of submeshes with a varying fraction of the full mesh.", true);
ParamDefTable[29].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=30, longName="submeshes[].numIndices"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[30];
ParamDef->init("numIndices", TYPE_U32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("longDescription", "This is only a part of the mesh where all max distances exceed a certain value.\n", true);
HintTable[1].init("shortDescription", "Size of the index buffer", true);
ParamDefTable[30].setHints((const NvParameterized::Hint**)HintPtrTable, 2);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=31, longName="submeshes[].numVertices"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[31];
ParamDef->init("numVertices", TYPE_U32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("longDescription", "This is only a part of the mesh where all max distances exceed a certain value.\n", true);
HintTable[1].init("shortDescription", "Size of the vertex buffers", true);
ParamDefTable[31].setHints((const NvParameterized::Hint**)HintPtrTable, 2);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=32, longName="submeshes[].cookedDataOffset"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[32];
ParamDef->init("cookedDataOffset", TYPE_U32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("longDescription", "The cooked data for all Submeshes are collected into one array. This is the offset where to start reading.\n", true);
HintTable[1].init("shortDescription", "Offset into parent's cooked data array", true);
ParamDefTable[32].setHints((const NvParameterized::Hint**)HintPtrTable, 2);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=33, longName="submeshes[].cookedDataLength"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[33];
ParamDef->init("cookedDataLength", TYPE_U32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("longDescription", "The cooked data for all Submeshes are collected into one array. This is how much data needs to be read.\n", true);
HintTable[1].init("shortDescription", "Length of the cooked data", true);
ParamDefTable[33].setHints((const NvParameterized::Hint**)HintPtrTable, 2);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=34, longName="submeshes[].nxDeformableMesh"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[34];
ParamDef->init("nxDeformableMesh", TYPE_POINTER, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("DONOTSERIALIZE", uint64_t(1), true);
HintTable[1].init("TYPE", "NxClothMesh or NxSoftBodyMesh", true);
ParamDefTable[34].setHints((const NvParameterized::Hint**)HintPtrTable, 2);
#else
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("DONOTSERIALIZE", uint64_t(1), true);
HintTable[1].init("TYPE", "NxClothMesh or NxSoftBodyMesh", true);
ParamDefTable[34].setHints((const NvParameterized::Hint**)HintPtrTable, 2);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=35, longName="deformableCookedData"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[35];
ParamDef->init("deformableCookedData", TYPE_ARRAY, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("longDescription", "All LoDs cook the data into the same buffer, one after the other.\n", true);
HintTable[1].init("shortDescription", "The cooked data for all the deformable meshes.", true);
ParamDefTable[35].setHints((const NvParameterized::Hint**)HintPtrTable, 2);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
ParamDef->setArraySize(-1);
}
// Initialize DefinitionImpl node: nodeIndex=36, longName="deformableCookedData[]"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[36];
ParamDef->init("deformableCookedData", TYPE_U8, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("longDescription", "All LoDs cook the data into the same buffer, one after the other.\n", true);
HintTable[1].init("shortDescription", "The cooked data for all the deformable meshes.", true);
ParamDefTable[36].setHints((const NvParameterized::Hint**)HintPtrTable, 2);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=37, longName="deformableCookedDataVersion"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[37];
ParamDef->init("deformableCookedDataVersion", TYPE_U32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("longDescription", "When loading into a different PhysX version, it will cook again on loading.\n", true);
HintTable[1].init("shortDescription", "The PhysX SDK Version this data was cooked from", true);
ParamDefTable[37].setHints((const NvParameterized::Hint**)HintPtrTable, 2);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=38, longName="physicalLods"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[38];
ParamDef->init("physicalLods", TYPE_ARRAY, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "The different Physical LoDs", true);
ParamDefTable[38].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
ParamDef->setArraySize(-1);
}
// Initialize DefinitionImpl node: nodeIndex=39, longName="physicalLods[]"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[39];
ParamDef->init("physicalLods", TYPE_STRUCT, "PhysicalLod", true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "The different Physical LoDs", true);
ParamDefTable[39].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=40, longName="physicalLods[].costWithoutIterations"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[40];
ParamDef->init("costWithoutIterations", TYPE_U32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "costs are numVertices * numSolverIterations. This is numVertices", true);
ParamDefTable[40].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=41, longName="physicalLods[].submeshId"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[41];
ParamDef->init("submeshId", TYPE_U32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Index of the Submesh that belongs to this LoD.", true);
ParamDefTable[41].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=42, longName="physicalLods[].solverIterationScale"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[42];
ParamDef->init("solverIterationScale", TYPE_F32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Take only a fraction of the Mesh's solver iterations for this LoD.", true);
ParamDefTable[42].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=43, longName="physicalLods[].maxDistanceReduction"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[43];
ParamDef->init("maxDistanceReduction", TYPE_F32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "The amount of maxDistance that gets subtracted when this LoD is active.", true);
ParamDefTable[43].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=44, longName="transitionUpB"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[44];
ParamDef->init("transitionUpB", TYPE_ARRAY, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Transition between this and the next graphical LoD.", true);
ParamDefTable[44].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
ParamDef->setArraySize(-1);
}
// Initialize DefinitionImpl node: nodeIndex=45, longName="transitionUpB[]"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[45];
ParamDef->init("transitionUpB", TYPE_STRUCT, "SkinClothMapB", true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Transition between this and the next graphical LoD.", true);
ParamDefTable[45].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=46, longName="transitionUpB[].vtxTetraBary"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[46];
ParamDef->init("vtxTetraBary", TYPE_VEC3, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "The barycentric coordinate into the implicit tetrahedron.", true);
ParamDefTable[46].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=47, longName="transitionUpB[].vertexIndexPlusOffset"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[47];
ParamDef->init("vertexIndexPlusOffset", TYPE_U32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "The vertex index in the graphical mesh (the target index).", true);
ParamDefTable[47].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=48, longName="transitionUpB[].nrmTetraBary"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[48];
ParamDef->init("nrmTetraBary", TYPE_VEC3, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "The barycentric coordinate of (vertex+normal). When vertex is subtracted this will result in the normal again.", true);
ParamDefTable[48].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=49, longName="transitionUpB[].faceIndex0"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[49];
ParamDef->init("faceIndex0", TYPE_U32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "First index of the 3 consecutive indices making the physical triangle.", true);
ParamDefTable[49].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=50, longName="transitionUpB[].tetraIndex"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[50];
ParamDef->init("tetraIndex", TYPE_U32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Selects which of the 6 implicit tetrahedrons is used for the mapping.", true);
ParamDefTable[50].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=51, longName="transitionUpB[].submeshIndex"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[51];
ParamDef->init("submeshIndex", TYPE_U32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("DONOTSERIALIZE", uint64_t(1), true);
ParamDefTable[51].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#else
static HintImpl HintTable[3];
static Hint* HintPtrTable[3] = { &HintTable[0], &HintTable[1], &HintTable[2], };
HintTable[0].init("DONOTSERIALIZE", uint64_t(1), true);
HintTable[1].init("longDescription", "This is only needed during the authoring stage and thus does not need to be serialized.\n", true);
HintTable[2].init("shortDescription", "Index into which Physical Submesh/LoD this element of the mapping belongs to.", true);
ParamDefTable[51].setHints((const NvParameterized::Hint**)HintPtrTable, 3);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=52, longName="transitionUpC"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[52];
ParamDef->init("transitionUpC", TYPE_ARRAY, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Transition between this and the next graphical LoD.", true);
ParamDefTable[52].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
ParamDef->setArraySize(-1);
}
// Initialize DefinitionImpl node: nodeIndex=53, longName="transitionUpC[]"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[53];
ParamDef->init("transitionUpC", TYPE_STRUCT, "SkinClothMapC", true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Transition between this and the next graphical LoD.", true);
ParamDefTable[53].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=54, longName="transitionUpC[].vertexBary"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[54];
ParamDef->init("vertexBary", TYPE_VEC3, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "The barycentric coordinate into the triangle.", true);
ParamDefTable[54].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=55, longName="transitionUpC[].faceIndex0"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[55];
ParamDef->init("faceIndex0", TYPE_U32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "First index of the 3 consecutive indices making the physical triangle.", true);
ParamDefTable[55].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=56, longName="transitionUpC[].normalBary"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[56];
ParamDef->init("normalBary", TYPE_VEC3, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "The barycentric coordinate of (vertex+normal). When vertex is subtracted this will result in the normal again.", true);
ParamDefTable[56].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=57, longName="transitionUpC[].vertexIndexPlusOffset"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[57];
ParamDef->init("vertexIndexPlusOffset", TYPE_U32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "The vertex index in the graphical mesh (the target index).", true);
ParamDefTable[57].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=58, longName="transitionUpThickness"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[58];
ParamDef->init("transitionUpThickness", TYPE_F32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "The thickness of the transition map", true);
ParamDefTable[58].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=59, longName="transitionUpOffset"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[59];
ParamDef->init("transitionUpOffset", TYPE_F32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "The normal offset of the transition map", true);
ParamDefTable[59].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=60, longName="transitionDownB"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[60];
ParamDef->init("transitionDownB", TYPE_ARRAY, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Transition between this and the previous graphical LoD.", true);
ParamDefTable[60].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
ParamDef->setArraySize(-1);
}
// Initialize DefinitionImpl node: nodeIndex=61, longName="transitionDownB[]"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[61];
ParamDef->init("transitionDownB", TYPE_STRUCT, "SkinClothMapB", true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Transition between this and the previous graphical LoD.", true);
ParamDefTable[61].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=62, longName="transitionDownB[].vtxTetraBary"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[62];
ParamDef->init("vtxTetraBary", TYPE_VEC3, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "The barycentric coordinate into the implicit tetrahedron.", true);
ParamDefTable[62].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=63, longName="transitionDownB[].vertexIndexPlusOffset"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[63];
ParamDef->init("vertexIndexPlusOffset", TYPE_U32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "The vertex index in the graphical mesh (the target index).", true);
ParamDefTable[63].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=64, longName="transitionDownB[].nrmTetraBary"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[64];
ParamDef->init("nrmTetraBary", TYPE_VEC3, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "The barycentric coordinate of (vertex+normal). When vertex is subtracted this will result in the normal again.", true);
ParamDefTable[64].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=65, longName="transitionDownB[].faceIndex0"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[65];
ParamDef->init("faceIndex0", TYPE_U32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "First index of the 3 consecutive indices making the physical triangle.", true);
ParamDefTable[65].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=66, longName="transitionDownB[].tetraIndex"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[66];
ParamDef->init("tetraIndex", TYPE_U32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Selects which of the 6 implicit tetrahedrons is used for the mapping.", true);
ParamDefTable[66].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=67, longName="transitionDownB[].submeshIndex"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[67];
ParamDef->init("submeshIndex", TYPE_U32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("DONOTSERIALIZE", uint64_t(1), true);
ParamDefTable[67].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#else
static HintImpl HintTable[3];
static Hint* HintPtrTable[3] = { &HintTable[0], &HintTable[1], &HintTable[2], };
HintTable[0].init("DONOTSERIALIZE", uint64_t(1), true);
HintTable[1].init("longDescription", "This is only needed during the authoring stage and thus does not need to be serialized.\n", true);
HintTable[2].init("shortDescription", "Index into which Physical Submesh/LoD this element of the mapping belongs to.", true);
ParamDefTable[67].setHints((const NvParameterized::Hint**)HintPtrTable, 3);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=68, longName="transitionDownC"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[68];
ParamDef->init("transitionDownC", TYPE_ARRAY, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Transition between this and the previous graphical LoD.", true);
ParamDefTable[68].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
ParamDef->setArraySize(-1);
}
// Initialize DefinitionImpl node: nodeIndex=69, longName="transitionDownC[]"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[69];
ParamDef->init("transitionDownC", TYPE_STRUCT, "SkinClothMapC", true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Transition between this and the previous graphical LoD.", true);
ParamDefTable[69].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=70, longName="transitionDownC[].vertexBary"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[70];
ParamDef->init("vertexBary", TYPE_VEC3, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "The barycentric coordinate into the triangle.", true);
ParamDefTable[70].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=71, longName="transitionDownC[].faceIndex0"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[71];
ParamDef->init("faceIndex0", TYPE_U32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "First index of the 3 consecutive indices making the physical triangle.", true);
ParamDefTable[71].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=72, longName="transitionDownC[].normalBary"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[72];
ParamDef->init("normalBary", TYPE_VEC3, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "The barycentric coordinate of (vertex+normal). When vertex is subtracted this will result in the normal again.", true);
ParamDefTable[72].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=73, longName="transitionDownC[].vertexIndexPlusOffset"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[73];
ParamDef->init("vertexIndexPlusOffset", TYPE_U32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "The vertex index in the graphical mesh (the target index).", true);
ParamDefTable[73].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=74, longName="transitionDownThickness"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[74];
ParamDef->init("transitionDownThickness", TYPE_F32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "The thickness of the transition map", true);
ParamDefTable[74].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=75, longName="transitionDownOffset"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[75];
ParamDef->init("transitionDownOffset", TYPE_F32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "The normal offset of the transition map", true);
ParamDefTable[75].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=76, longName="referenceCount"
{
NvParameterized::DefinitionImpl* ParamDef = &ParamDefTable[76];
ParamDef->init("referenceCount", TYPE_U32, NULL, true);
#ifdef NV_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("READONLY", uint64_t(1), true);
ParamDefTable[76].setHints((const NvParameterized::Hint**)HintPtrTable, 1);
#else
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("READONLY", uint64_t(1), true);
HintTable[1].init("shortDescription", "Only used internally, do not modify", true);
ParamDefTable[76].setHints((const NvParameterized::Hint**)HintPtrTable, 2);
#endif /* NV_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// SetChildren for: nodeIndex=0, longName=""
{
static Definition* Children[14];
Children[0] = PDEF_PTR(1);
Children[1] = PDEF_PTR(28);
Children[2] = PDEF_PTR(35);
Children[3] = PDEF_PTR(37);
Children[4] = PDEF_PTR(38);
Children[5] = PDEF_PTR(44);
Children[6] = PDEF_PTR(52);
Children[7] = PDEF_PTR(58);
Children[8] = PDEF_PTR(59);
Children[9] = PDEF_PTR(60);
Children[10] = PDEF_PTR(68);
Children[11] = PDEF_PTR(74);
Children[12] = PDEF_PTR(75);
Children[13] = PDEF_PTR(76);
ParamDefTable[0].setChildren(Children, 14);
}
// SetChildren for: nodeIndex=1, longName="physicalMesh"
{
static Definition* Children[15];
Children[0] = PDEF_PTR(2);
Children[1] = PDEF_PTR(3);
Children[2] = PDEF_PTR(4);
Children[3] = PDEF_PTR(5);
Children[4] = PDEF_PTR(7);
Children[5] = PDEF_PTR(9);
Children[6] = PDEF_PTR(11);
Children[7] = PDEF_PTR(13);
Children[8] = PDEF_PTR(18);
Children[9] = PDEF_PTR(20);
Children[10] = PDEF_PTR(22);
Children[11] = PDEF_PTR(24);
Children[12] = PDEF_PTR(25);
Children[13] = PDEF_PTR(26);
Children[14] = PDEF_PTR(27);
ParamDefTable[1].setChildren(Children, 15);
}
// SetChildren for: nodeIndex=5, longName="physicalMesh.vertices"
{
static Definition* Children[1];
Children[0] = PDEF_PTR(6);
ParamDefTable[5].setChildren(Children, 1);
}
// SetChildren for: nodeIndex=7, longName="physicalMesh.normals"
{
static Definition* Children[1];
Children[0] = PDEF_PTR(8);
ParamDefTable[7].setChildren(Children, 1);
}
// SetChildren for: nodeIndex=9, longName="physicalMesh.skinningNormals"
{
static Definition* Children[1];
Children[0] = PDEF_PTR(10);
ParamDefTable[9].setChildren(Children, 1);
}
// SetChildren for: nodeIndex=11, longName="physicalMesh.vertexFlags"
{
static Definition* Children[1];
Children[0] = PDEF_PTR(12);
ParamDefTable[11].setChildren(Children, 1);
}
// SetChildren for: nodeIndex=13, longName="physicalMesh.constrainCoefficients"
{
static Definition* Children[1];
Children[0] = PDEF_PTR(14);
ParamDefTable[13].setChildren(Children, 1);
}
// SetChildren for: nodeIndex=14, longName="physicalMesh.constrainCoefficients[]"
{
static Definition* Children[3];
Children[0] = PDEF_PTR(15);
Children[1] = PDEF_PTR(16);
Children[2] = PDEF_PTR(17);
ParamDefTable[14].setChildren(Children, 3);
}
// SetChildren for: nodeIndex=18, longName="physicalMesh.boneIndices"
{
static Definition* Children[1];
Children[0] = PDEF_PTR(19);
ParamDefTable[18].setChildren(Children, 1);
}
// SetChildren for: nodeIndex=20, longName="physicalMesh.boneWeights"
{
static Definition* Children[1];
Children[0] = PDEF_PTR(21);
ParamDefTable[20].setChildren(Children, 1);
}
// SetChildren for: nodeIndex=22, longName="physicalMesh.indices"
{
static Definition* Children[1];
Children[0] = PDEF_PTR(23);
ParamDefTable[22].setChildren(Children, 1);
}
// SetChildren for: nodeIndex=28, longName="submeshes"
{
static Definition* Children[1];
Children[0] = PDEF_PTR(29);
ParamDefTable[28].setChildren(Children, 1);
}
// SetChildren for: nodeIndex=29, longName="submeshes[]"
{
static Definition* Children[5];
Children[0] = PDEF_PTR(30);
Children[1] = PDEF_PTR(31);
Children[2] = PDEF_PTR(32);
Children[3] = PDEF_PTR(33);
Children[4] = PDEF_PTR(34);
ParamDefTable[29].setChildren(Children, 5);
}
// SetChildren for: nodeIndex=35, longName="deformableCookedData"
{
static Definition* Children[1];
Children[0] = PDEF_PTR(36);
ParamDefTable[35].setChildren(Children, 1);
}
// SetChildren for: nodeIndex=38, longName="physicalLods"
{
static Definition* Children[1];
Children[0] = PDEF_PTR(39);
ParamDefTable[38].setChildren(Children, 1);
}
// SetChildren for: nodeIndex=39, longName="physicalLods[]"
{
static Definition* Children[4];
Children[0] = PDEF_PTR(40);
Children[1] = PDEF_PTR(41);
Children[2] = PDEF_PTR(42);
Children[3] = PDEF_PTR(43);
ParamDefTable[39].setChildren(Children, 4);
}
// SetChildren for: nodeIndex=44, longName="transitionUpB"
{
static Definition* Children[1];
Children[0] = PDEF_PTR(45);
ParamDefTable[44].setChildren(Children, 1);
}
// SetChildren for: nodeIndex=45, longName="transitionUpB[]"
{
static Definition* Children[6];
Children[0] = PDEF_PTR(46);
Children[1] = PDEF_PTR(47);
Children[2] = PDEF_PTR(48);
Children[3] = PDEF_PTR(49);
Children[4] = PDEF_PTR(50);
Children[5] = PDEF_PTR(51);
ParamDefTable[45].setChildren(Children, 6);
}
// SetChildren for: nodeIndex=52, longName="transitionUpC"
{
static Definition* Children[1];
Children[0] = PDEF_PTR(53);
ParamDefTable[52].setChildren(Children, 1);
}
// SetChildren for: nodeIndex=53, longName="transitionUpC[]"
{
static Definition* Children[4];
Children[0] = PDEF_PTR(54);
Children[1] = PDEF_PTR(55);
Children[2] = PDEF_PTR(56);
Children[3] = PDEF_PTR(57);
ParamDefTable[53].setChildren(Children, 4);
}
// SetChildren for: nodeIndex=60, longName="transitionDownB"
{
static Definition* Children[1];
Children[0] = PDEF_PTR(61);
ParamDefTable[60].setChildren(Children, 1);
}
// SetChildren for: nodeIndex=61, longName="transitionDownB[]"
{
static Definition* Children[6];
Children[0] = PDEF_PTR(62);
Children[1] = PDEF_PTR(63);
Children[2] = PDEF_PTR(64);
Children[3] = PDEF_PTR(65);
Children[4] = PDEF_PTR(66);
Children[5] = PDEF_PTR(67);
ParamDefTable[61].setChildren(Children, 6);
}
// SetChildren for: nodeIndex=68, longName="transitionDownC"
{
static Definition* Children[1];
Children[0] = PDEF_PTR(69);
ParamDefTable[68].setChildren(Children, 1);
}
// SetChildren for: nodeIndex=69, longName="transitionDownC[]"
{
static Definition* Children[4];
Children[0] = PDEF_PTR(70);
Children[1] = PDEF_PTR(71);
Children[2] = PDEF_PTR(72);
Children[3] = PDEF_PTR(73);
ParamDefTable[69].setChildren(Children, 4);
}
mBuiltFlag = true;
}
void ClothingPhysicalMeshParameters_0p1::initStrings(void)
{
}
void ClothingPhysicalMeshParameters_0p1::initDynamicArrays(void)
{
physicalMesh.vertices.buf = NULL;
physicalMesh.vertices.isAllocated = true;
physicalMesh.vertices.elementSize = sizeof(physx::PxVec3);
physicalMesh.vertices.arraySizes[0] = 0;
physicalMesh.normals.buf = NULL;
physicalMesh.normals.isAllocated = true;
physicalMesh.normals.elementSize = sizeof(physx::PxVec3);
physicalMesh.normals.arraySizes[0] = 0;
physicalMesh.skinningNormals.buf = NULL;
physicalMesh.skinningNormals.isAllocated = true;
physicalMesh.skinningNormals.elementSize = sizeof(physx::PxVec3);
physicalMesh.skinningNormals.arraySizes[0] = 0;
physicalMesh.vertexFlags.buf = NULL;
physicalMesh.vertexFlags.isAllocated = true;
physicalMesh.vertexFlags.elementSize = sizeof(uint32_t);
physicalMesh.vertexFlags.arraySizes[0] = 0;
physicalMesh.constrainCoefficients.buf = NULL;
physicalMesh.constrainCoefficients.isAllocated = true;
physicalMesh.constrainCoefficients.elementSize = sizeof(ConstrainCoefficient_Type);
physicalMesh.constrainCoefficients.arraySizes[0] = 0;
physicalMesh.boneIndices.buf = NULL;
physicalMesh.boneIndices.isAllocated = true;
physicalMesh.boneIndices.elementSize = sizeof(uint16_t);
physicalMesh.boneIndices.arraySizes[0] = 0;
physicalMesh.boneWeights.buf = NULL;
physicalMesh.boneWeights.isAllocated = true;
physicalMesh.boneWeights.elementSize = sizeof(float);
physicalMesh.boneWeights.arraySizes[0] = 0;
physicalMesh.indices.buf = NULL;
physicalMesh.indices.isAllocated = true;
physicalMesh.indices.elementSize = sizeof(uint32_t);
physicalMesh.indices.arraySizes[0] = 0;
submeshes.buf = NULL;
submeshes.isAllocated = true;
submeshes.elementSize = sizeof(PhysicalSubmesh_Type);
submeshes.arraySizes[0] = 0;
deformableCookedData.buf = NULL;
deformableCookedData.isAllocated = true;
deformableCookedData.elementSize = sizeof(uint8_t);
deformableCookedData.arraySizes[0] = 0;
physicalLods.buf = NULL;
physicalLods.isAllocated = true;
physicalLods.elementSize = sizeof(PhysicalLod_Type);
physicalLods.arraySizes[0] = 0;
transitionUpB.buf = NULL;
transitionUpB.isAllocated = true;
transitionUpB.elementSize = sizeof(SkinClothMapB_Type);
transitionUpB.arraySizes[0] = 0;
transitionUpC.buf = NULL;
transitionUpC.isAllocated = true;
transitionUpC.elementSize = sizeof(SkinClothMapC_Type);
transitionUpC.arraySizes[0] = 0;
transitionDownB.buf = NULL;
transitionDownB.isAllocated = true;
transitionDownB.elementSize = sizeof(SkinClothMapB_Type);
transitionDownB.arraySizes[0] = 0;
transitionDownC.buf = NULL;
transitionDownC.isAllocated = true;
transitionDownC.elementSize = sizeof(SkinClothMapC_Type);
transitionDownC.arraySizes[0] = 0;
}
void ClothingPhysicalMeshParameters_0p1::initDefaults(void)
{
freeStrings();
freeReferences();
freeDynamicArrays();
physicalMesh.numVertices = uint32_t(0);
physicalMesh.numIndices = uint32_t(0);
physicalMesh.numBonesPerVertex = uint32_t(0);
physicalMesh.maximumMaxDistance = float(0);
physicalMesh.shortestEdgeLength = float(0);
physicalMesh.averageEdgeLength = float(0);
physicalMesh.isTetrahedralMesh = bool(false);
deformableCookedDataVersion = uint32_t(0);
transitionUpThickness = float(0);
transitionUpOffset = float(0);
transitionDownThickness = float(0);
transitionDownOffset = float(0);
referenceCount = uint32_t(0);
initDynamicArrays();
initStrings();
initReferences();
}
void ClothingPhysicalMeshParameters_0p1::initReferences(void)
{
}
void ClothingPhysicalMeshParameters_0p1::freeDynamicArrays(void)
{
if (physicalMesh.vertices.isAllocated && physicalMesh.vertices.buf)
{
mParameterizedTraits->free(physicalMesh.vertices.buf);
}
if (physicalMesh.normals.isAllocated && physicalMesh.normals.buf)
{
mParameterizedTraits->free(physicalMesh.normals.buf);
}
if (physicalMesh.skinningNormals.isAllocated && physicalMesh.skinningNormals.buf)
{
mParameterizedTraits->free(physicalMesh.skinningNormals.buf);
}
if (physicalMesh.vertexFlags.isAllocated && physicalMesh.vertexFlags.buf)
{
mParameterizedTraits->free(physicalMesh.vertexFlags.buf);
}
if (physicalMesh.constrainCoefficients.isAllocated && physicalMesh.constrainCoefficients.buf)
{
mParameterizedTraits->free(physicalMesh.constrainCoefficients.buf);
}
if (physicalMesh.boneIndices.isAllocated && physicalMesh.boneIndices.buf)
{
mParameterizedTraits->free(physicalMesh.boneIndices.buf);
}
if (physicalMesh.boneWeights.isAllocated && physicalMesh.boneWeights.buf)
{
mParameterizedTraits->free(physicalMesh.boneWeights.buf);
}
if (physicalMesh.indices.isAllocated && physicalMesh.indices.buf)
{
mParameterizedTraits->free(physicalMesh.indices.buf);
}
if (submeshes.isAllocated && submeshes.buf)
{
mParameterizedTraits->free(submeshes.buf);
}
if (deformableCookedData.isAllocated && deformableCookedData.buf)
{
mParameterizedTraits->free(deformableCookedData.buf);
}
if (physicalLods.isAllocated && physicalLods.buf)
{
mParameterizedTraits->free(physicalLods.buf);
}
if (transitionUpB.isAllocated && transitionUpB.buf)
{
mParameterizedTraits->free(transitionUpB.buf);
}
if (transitionUpC.isAllocated && transitionUpC.buf)
{
mParameterizedTraits->free(transitionUpC.buf);
}
if (transitionDownB.isAllocated && transitionDownB.buf)
{
mParameterizedTraits->free(transitionDownB.buf);
}
if (transitionDownC.isAllocated && transitionDownC.buf)
{
mParameterizedTraits->free(transitionDownC.buf);
}
}
void ClothingPhysicalMeshParameters_0p1::freeStrings(void)
{
}
void ClothingPhysicalMeshParameters_0p1::freeReferences(void)
{
}
} // namespace parameterized
} // namespace nvidia
|
#include "formulationEvent.h"
formulationEvent::formulationEvent()
{
}
void formulationEvent::set_Type(char T)
{
type = T;
}
int formulationEvent::get_Type()
{
return type;
}
void formulationEvent::set_TargetLocation(int TLoc)
{
targetLocation = TLoc;
}
int formulationEvent::get_TargetLocation()
{
return targetLocation;
}
void formulationEvent::set_MissionDuration(int MDur)
{
missionDuration = MDur;
}
int formulationEvent::get_MissionDuration()
{
return missionDuration;
}
void formulationEvent::set_Significance(int Sig)
{
significance = Sig;
}
int formulationEvent::get_Significance()
{
return significance;
}
void formulationEvent::Execute(PriorityQueue<Mission>&EmergQ, LinkedQueue<Mission>&PolarQ)
{
Mission* FM = new Mission() ;
FM->setFD(get_EventDay());
FM->setID(get_MissionID());
FM->setType(type);
FM->setMDUR(missionDuration);
FM->settargetLoction(targetLocation);
FM->setSignificance(significance);
if (type == 'E')
EmergQ.push(*FM,significance);//lazem neghayar esm push da -> ykoun enqueue IMPORTANT
if (type == 'P')
PolarQ.enqueue(*FM);
}
|
#include <ros/ros.h>
#include <autoware_msgs/VehicleCmd.h>
static ros::Subscriber sub;
static ros::Publisher pub;
void ndt_cb(const autoware_msgs::VehicleCmd& msg){
sensor_msgs::Image out;
out = msg;
out.header.stamp = ros::Time::now();
pub.publish(out);
}
int main(int argc, char** argv){
ros::init(argc, argv, "lkas_combiner");
ros::NodeHandle nh;
sub = nh.subscribe("/vehicle_cmd_ndt", 1, camera_cb);
pub = nh.advertise<autoware_msgs::VehicleCmd>("/vehicle_cmd", 1);
while(ros::ok())
ros::spin();
return 0;
}
|
/*
Part of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)
Copyright 2017-2019 University of Huddersfield.
Licensed under the BSD-3 License.
See license.md file in the project root for full license information.
This project has received funding from the European Research Council (ERC)
under the European Union’s Horizon 2020 research and innovation programme
(grant agreement No 725899).
*/
#include <clients/rt/HPSSClient.hpp>
#include <FluidParameterDump.hpp>
int main(int argc, char *argv[]) {
using namespace fluid::client;
if (!argc) std::cerr << "Please pass a folder to write to";
std::cout << "Write JSON to " << argv[1];
ParameterDump<RTHPSSClient>::dump("HPSS", argv[1]);
return 0;
}
|
// Compress/CopyCoder.cpp
#include "StdAfx.h"
#include "../../../C/Alloc.h"
#include "../Common/StreamUtils.h"
#include "CopyCoder.h"
namespace NCompress {
static const UInt32 kBufferSize = 1 << 17;
CCopyCoder::~CCopyCoder()
{
::MidFree(_buffer);
}
STDMETHODIMP CCopyCoder::Code(ISequentialInStream *inStream,
ISequentialOutStream *outStream,
const UInt64 * /* inSize */, const UInt64 *outSize,
ICompressProgressInfo *progress)
{
if (_buffer == 0)
{
_buffer = (Byte *)::MidAlloc(kBufferSize);
if (_buffer == 0)
return E_OUTOFMEMORY;
}
TotalSize = 0;
for (;;)
{
UInt32 size = kBufferSize;
if (outSize != 0)
if (size > *outSize - TotalSize)
size = (UInt32)(*outSize - TotalSize);
RINOK(inStream->Read(_buffer, size, &size));
if (size == 0)
break;
if (outStream)
{
RINOK(WriteStream(outStream, _buffer, size));
}
TotalSize += size;
if (progress != NULL)
{
RINOK(progress->SetRatioInfo(&TotalSize, &TotalSize));
}
}
return S_OK;
}
STDMETHODIMP CCopyCoder::GetInStreamProcessedSize(UInt64 *value)
{
*value = TotalSize;
return S_OK;
}
HRESULT CopyStream(ISequentialInStream *inStream, ISequentialOutStream *outStream, ICompressProgressInfo *progress)
{
CMyComPtr<ICompressCoder> copyCoder = new NCompress::CCopyCoder;
return copyCoder->Code(inStream, outStream, NULL, NULL, progress);
}
}
|
///////////////////////////////////////////////////////////////////////////////
// This file is distributed under the University of Illinois/NCSA Open Source
// License. See LICENSE file in top directory for details.
//
// Copyright (c) 2020 QMCPACK developers.
//
// File developed by: Fionn Malone, malone14@llnl.gov, LLNL
//
// File created by: Fionn Malone, malone14@llnl.gov, LLNL
////////////////////////////////////////////////////////////////////////////////
#include<cassert>
#include <complex>
#include<hip/hip_runtime.h>
#include <thrust/complex.h>
#include<hip/hip_runtime.h>
#include "AFQMC/Numerics/detail/HIP/Kernels/hip_settings.h"
#include "AFQMC/Memory/HIP/hip_utilities.h"
namespace kernels
{
// many ways to do this! sloppy for now!
template<typename T, typename T2>
__global__ void kernel_tbt_mv_plus( int dim, int nrow, int ncol, T* A, int lda,
T2 const* x, int incx)
{
// assuming a single block
if( blockIdx.x > 0 || blockIdx.y > 0 || blockIdx.z > 0) return;
if( threadIdx.x > nrow ) return;
if( threadIdx.y > ncol ) return;
if(dim == 0) {
for(int i=threadIdx.x; i<nrow; i+=blockDim.x)
for(int j=threadIdx.y; j<ncol; j+=blockDim.y)
A[ i*lda+j ] += x[i*incx];
} else {
for(int i=threadIdx.x; i<nrow; i+=blockDim.x)
for(int j=threadIdx.y; j<ncol; j+=blockDim.y)
A[ i*lda+j ] += x[j*incx];
}
}
template<typename T, typename T2>
__global__ void kernel_tbt_mv_minus( int dim, int nrow, int ncol, T* A, int lda,
T2 const* x, int incx)
{
// assuming a single block
if( blockIdx.x > 0 || blockIdx.y > 0 || blockIdx.z > 0) return;
if( threadIdx.x > nrow ) return;
if( threadIdx.y > ncol ) return;
if(dim == 0) {
for(int i=threadIdx.x; i<nrow; i+=blockDim.x)
for(int j=threadIdx.y; j<ncol; j+=blockDim.y)
A[ i*lda+j ] -= x[i*incx];
} else {
for(int i=threadIdx.x; i<nrow; i+=blockDim.x)
for(int j=threadIdx.y; j<ncol; j+=blockDim.y)
A[ i*lda+j ] -= x[j*incx];
}
}
template<typename T, typename T2>
__global__ void kernel_tbt_mv_mult( int dim, int nrow, int ncol, T* A, int lda,
T2 const* x, int incx)
{
// assuming a single block
if( blockIdx.x > 0 || blockIdx.y > 0 || blockIdx.z > 0) return;
if( threadIdx.x > nrow ) return;
if( threadIdx.y > ncol ) return;
if(dim == 0) {
for(int i=threadIdx.x; i<nrow; i+=blockDim.x)
for(int j=threadIdx.y; j<ncol; j+=blockDim.y)
A[ i*lda+j ] *= x[i*incx];
} else {
for(int i=threadIdx.x; i<nrow; i+=blockDim.x)
for(int j=threadIdx.y; j<ncol; j+=blockDim.y)
A[ i*lda+j ] *= x[j*incx];
}
}
template<typename T, typename T2>
__global__ void kernel_tbt_mv_div( int dim, int nrow, int ncol, T* A, int lda,
T2 const* x, int incx)
{
// assuming a single block
if( blockIdx.x > 0 || blockIdx.y > 0 || blockIdx.z > 0) return;
if( threadIdx.x > nrow ) return;
if( threadIdx.y > ncol ) return;
if(dim == 0) {
for(int i=threadIdx.x; i<nrow; i+=blockDim.x)
for(int j=threadIdx.y; j<ncol; j+=blockDim.y)
A[ i*lda+j ] /= x[i*incx];
} else {
for(int i=threadIdx.x; i<nrow; i+=blockDim.x)
for(int j=threadIdx.y; j<ncol; j+=blockDim.y)
A[ i*lda+j ] /= x[j*incx];
}
}
void term_by_term_mat_vec_plus( int dim, int nrow, int ncol, std::complex<double>* A, int lda,
std::complex<double>* x, int incx)
{
int xblock_dim = std::min(nrow,32);
int yblock_dim = std::min(ncol,32);
dim3 block_dim(xblock_dim,yblock_dim,1);
hipLaunchKernelGGL(kernel_tbt_mv_plus, dim3(1), dim3(block_dim), 0, 0, dim,nrow,ncol,
reinterpret_cast<thrust::complex<double>*>(A),lda,
reinterpret_cast<thrust::complex<double> const*>(x),incx);
qmc_hip::hip_check(hipGetLastError());
qmc_hip::hip_check(hipDeviceSynchronize());
}
void term_by_term_mat_vec_minus( int dim, int nrow, int ncol, std::complex<double>* A, int lda,
std::complex<double>* x, int incx)
{
int xblock_dim = std::min(nrow,32);
int yblock_dim = std::min(ncol,32);
dim3 block_dim(xblock_dim,yblock_dim,1);
hipLaunchKernelGGL(kernel_tbt_mv_minus, dim3(1), dim3(block_dim), 0, 0, dim,nrow,ncol,
reinterpret_cast<thrust::complex<double>*>(A),lda,
reinterpret_cast<thrust::complex<double> const*>(x),incx);
qmc_hip::hip_check(hipGetLastError());
qmc_hip::hip_check(hipDeviceSynchronize());
}
void term_by_term_mat_vec_mult( int dim, int nrow, int ncol, std::complex<double>* A, int lda,
std::complex<double>* x, int incx)
{
int xblock_dim = std::min(nrow,32);
int yblock_dim = std::min(ncol,32);
dim3 block_dim(xblock_dim,yblock_dim,1);
hipLaunchKernelGGL(kernel_tbt_mv_mult, dim3(1), dim3(block_dim), 0, 0, dim,nrow,ncol,
reinterpret_cast<thrust::complex<double>*>(A),lda,
reinterpret_cast<thrust::complex<double> const*>(x),incx);
qmc_hip::hip_check(hipGetLastError());
qmc_hip::hip_check(hipDeviceSynchronize());
}
void term_by_term_mat_vec_div( int dim, int nrow, int ncol, std::complex<double>* A, int lda,
std::complex<double>* x, int incx)
{
int xblock_dim = std::min(nrow,32);
int yblock_dim = std::min(ncol,32);
dim3 block_dim(xblock_dim,yblock_dim,1);
hipLaunchKernelGGL(kernel_tbt_mv_div, dim3(1), dim3(block_dim), 0, 0, dim,nrow,ncol,
reinterpret_cast<thrust::complex<double>*>(A),lda,
reinterpret_cast<thrust::complex<double> const*>(x),incx);
qmc_hip::hip_check(hipGetLastError());
qmc_hip::hip_check(hipDeviceSynchronize());
}
void term_by_term_mat_vec_plus( int dim, int nrow, int ncol, std::complex<double>* A, int lda,
double* x, int incx)
{
int xblock_dim = std::min(nrow,32);
int yblock_dim = std::min(ncol,32);
dim3 block_dim(xblock_dim,yblock_dim,1);
hipLaunchKernelGGL(kernel_tbt_mv_plus, dim3(1), dim3(block_dim), 0, 0, dim,nrow,ncol,
reinterpret_cast<thrust::complex<double>*>(A),lda,
x,incx);
qmc_hip::hip_check(hipGetLastError());
qmc_hip::hip_check(hipDeviceSynchronize());
}
void term_by_term_mat_vec_minus( int dim, int nrow, int ncol, std::complex<double>* A, int lda,
double* x, int incx)
{
int xblock_dim = std::min(nrow,32);
int yblock_dim = std::min(ncol,32);
dim3 block_dim(xblock_dim,yblock_dim,1);
hipLaunchKernelGGL(kernel_tbt_mv_minus, dim3(1), dim3(block_dim), 0, 0, dim,nrow,ncol,
reinterpret_cast<thrust::complex<double>*>(A),lda,
x,incx);
qmc_hip::hip_check(hipGetLastError());
qmc_hip::hip_check(hipDeviceSynchronize());
}
void term_by_term_mat_vec_mult( int dim, int nrow, int ncol, std::complex<double>* A, int lda,
double* x, int incx)
{
int xblock_dim = std::min(nrow,32);
int yblock_dim = std::min(ncol,32);
dim3 block_dim(xblock_dim,yblock_dim,1);
hipLaunchKernelGGL(kernel_tbt_mv_mult, dim3(1), dim3(block_dim), 0, 0, dim,nrow,ncol,
reinterpret_cast<thrust::complex<double>*>(A),lda,
x,incx);
qmc_hip::hip_check(hipGetLastError());
qmc_hip::hip_check(hipDeviceSynchronize());
}
void term_by_term_mat_vec_div( int dim, int nrow, int ncol, std::complex<double>* A, int lda,
double* x, int incx)
{
int xblock_dim = std::min(nrow,32);
int yblock_dim = std::min(ncol,32);
dim3 block_dim(xblock_dim,yblock_dim,1);
hipLaunchKernelGGL(kernel_tbt_mv_div, dim3(1), dim3(block_dim), 0, 0, dim,nrow,ncol,
reinterpret_cast<thrust::complex<double>*>(A),lda,
x,incx);
qmc_hip::hip_check(hipGetLastError());
qmc_hip::hip_check(hipDeviceSynchronize());
}
}
|
//----------------------------------*-C++-*----------------------------------//
// Copyright 2021 UT-Battelle, LLC, and other Celeritas developers.
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: (Apache-2.0 OR MIT)
//---------------------------------------------------------------------------//
//! \file RBEnergySampler.i.hh
//---------------------------------------------------------------------------//
#include <cmath>
#include "base/Algorithms.hh"
#include "random/distributions/BernoulliDistribution.hh"
#include "random/distributions/ReciprocalDistribution.hh"
#include "PhysicsConstants.hh"
namespace celeritas
{
namespace detail
{
//---------------------------------------------------------------------------//
/*!
* Construct from incident particle and energy.
*/
CELER_FUNCTION
RBEnergySampler::RBEnergySampler(const RelativisticBremNativeRef& shared,
const ParticleTrackView& particle,
const CutoffView& cutoffs,
const MaterialView& material,
const ElementComponentId& elcomp_id)
: calc_dxsec_(shared, particle, material, elcomp_id)
{
// Min and max kinetic energy limits for sampling the secondary photon
real_type gamma_cutoff = value_as<Energy>(cutoffs.energy(shared.ids.gamma));
real_type inc_energy = value_as<Energy>(particle.energy());
tmin_sq_ = ipow<2>(min(gamma_cutoff, inc_energy));
tmax_sq_ = ipow<2>(min(value_as<Energy>(high_energy_limit()), inc_energy));
CELER_ENSURE(tmax_sq_ >= tmin_sq_);
}
//---------------------------------------------------------------------------//
/*!
* Sample the bremsstrahlung photon energy based on G4eBremsstrahlungRelModel
* of the Geant4 10.7 release.
*/
template<class Engine>
CELER_FUNCTION auto RBEnergySampler::operator()(Engine& rng) -> Energy
{
real_type density_corr = calc_dxsec_.density_correction();
ReciprocalDistribution<real_type> sample_exit_esq(tmin_sq_ + density_corr,
tmax_sq_ + density_corr);
// Sampled energy and corresponding cross section for rejection
real_type gamma_energy{0};
real_type dsigma{0};
do
{
gamma_energy = std::sqrt(sample_exit_esq(rng) - density_corr);
dsigma = calc_dxsec_(Energy{gamma_energy});
} while (!BernoulliDistribution(dsigma / calc_dxsec_.maximum_value())(rng));
return Energy{gamma_energy};
}
//---------------------------------------------------------------------------//
} // namespace detail
} // namespace celeritas
|
/*
*
* Copyright 2015 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "src/core/lib/security/transport/tsi_error.h"
grpc_error* grpc_set_tsi_error_result(grpc_error* error, tsi_result result) {
return grpc_error_set_int(
grpc_error_set_str(
error, GRPC_ERROR_STR_TSI_ERROR,
grpc_slice_from_static_string(tsi_result_to_string(result))),
GRPC_ERROR_INT_TSI_CODE, result);
}
|
#include<bits/stdc++.h>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
#define FZ(n) memset((n),0,sizeof(n))
#define FMO(n) memset((n),-1,sizeof(n))
#define MC(n,m) memcpy((n),(m),sizeof(n))
#define F first
#define S second
#define MP make_pair
#define PB push_back
#define FOR(x,y) for(__typeof(y.begin())x=y.begin();x!=y.end();x++)
#define IOS ios_base::sync_with_stdio(0); cin.tie(0)
#ifdef ONLINE_JUDGE
#define FILEIO(name) \
freopen(name".in", "r", stdin); \
freopen(name".out", "w", stdout);
#else
#define FILEIO(name)
#endif
// Let's Fight!
typedef pair<int, int> pii;
const int MAXN = 55;
int N;
int tarx, tary;
char c[MAXN];
int lb[MAXN], rb[MAXN];
char fc[MAXN];
int diff[MAXN];
int dir[MAXN];
int fv[MAXN];
bool fre[MAXN];
int rem;
vector<pii> vec;
int findval, finddif;
bool dfs1(int i, int x, int y, int tdx, int tdy, int d);
int cval(char ch)
{
if(ch == 'L') return 1;
else if(ch == 'R') return 3;
return 0;
}
void dfs0(int i, int val, int td)
{
if(i >= N)
{
vec.PB(MP(val, val+td));
return;
}
if(!fre[i])
dfs0(i+2, val, td);
else
{
dfs0(i+2, val+lb[i], td+diff[i]);
dfs0(i+2, val-rb[i], td+diff[i]);
}
}
bool dfs2(int i, int val, int td)
{
if(i >= N)
{
rem = findval - val;
return 0 <= rem && rem <= td;
}
if(!fre[i])
return dfs2(i+2, val, td);
else
{
dir[i] = 0;
if(dfs2(i+2, val+lb[i], td+diff[i]))
return true;
dir[i] = 1;
if(dfs2(i+2, val-rb[i], td+diff[i]))
return true;
}
return false;
}
bool any(int lbb, int rbb)
{
auto it = lower_bound(vec.begin(), vec.end(), MP(lbb, 2100000000));
if(it != vec.end())
{
if(it->F <= rbb)
{
findval = it->F;
return true;
}
}
if(it != vec.begin())
{
it--;
if(it->S >= lbb)
{
findval = lbb;
return true;
}
}
return false;
}
bool trans(int i, int x, int y, int tdx, int tdy, int d, char cy, char cx)
{
if(cy == 'L')
d = (d+1)%4;
else
d = (d+3)%4;
if(cy != '?')
{
tdy += diff[i-1];
dir[i-1] = d/2;
if(dir[i-1])
y -= rb[i-1];
else
y += lb[i-1];
}
if(cx == 'L')
d = (d+1)%4;
else
d = (d+3)%4;
tdx += diff[i];
dir[i] = d/2;
if(dir[i])
x -= rb[i];
else
x += lb[i];
return dfs1(i+2, x, y, tdx, tdy, d);
}
bool dfs1(int i, int x, int y, int tdx, int tdy, int d)
{
if(i >= N+2)
{
if(!(x <= tarx && tarx <= x+tdx)) return false;
int lbb = tary-y-tdy, rbb = tary-y;
rem = tarx - x;
return any(lbb, rbb);
}
int qcnt = (c[i-1]=='?') + (c[i]=='?');
if(qcnt == 0)
{
if(trans(i, x, y, tdx, tdy, d, c[i-1], c[i]))
return true;
}
else if(qcnt == 1)
{
if(c[i-1] == '?')
{
if(trans(i, x, y, tdx, tdy, d, 'L', c[i]))
return true;
if(trans(i, x, y, tdx, tdy, d, 'R', c[i]))
return true;
}
else
{
if(trans(i, x, y, tdx, tdy, d, c[i-1], 'L'))
return true;
if(trans(i, x, y, tdx, tdy, d, c[i-1], 'R'))
return true;
}
}
else
{
if(trans(i, x, y, tdx, tdy, d, '?', 'L'))
return true;
if(trans(i, x, y, tdx, tdy, d, '?', 'R'))
return true;
}
return false;
}
void make_vec()
{
vector<pii> nvec = vec;
vec.clear();
sort(nvec.begin(), nvec.end());
int last = -2100000000;
for(auto v: nvec)
{
int l = v.F, r = v.S;
if(l > last)
{
vec.PB(MP(l, r));
last = r;
}
else
{
last = max(last, r);
vec.back().S = last;
}
}
}
int main()
{
IOS;
cin>>N>>tarx>>tary;
for(int i=0; i<N; i++)
cin>>c[i]>>lb[i]>>rb[i];
lb[N] = rb[N] = lb[N+1] = rb[N+1] = 0;
c[N] = c[N+1] = '?';
for(int i=0; i<N+2; i++)
{
fre[i] = true;
diff[i] = rb[i] - lb[i];
}
for(int i=0; i<N; i+=2)
if(c[i] != '?' || c[i+1] != '?')
fre[i] = false;
bool ok = true;
dfs0(0, 0, 0);
make_vec();
ok = dfs1(1, 0, 0, 0, 0, 0);
for(int i=1; i<N; i+=2)
{
int use = min(rem, diff[i]);
if(dir[i])
fv[i] = rb[i] - use;
else
fv[i] = lb[i] + use;
rem -= use;
}
if(!dfs2(0, 0, 0))
ok = false;
rem = tary;
for(int i=0; i<N; i+=2)
{
if(dir[i])
rem += rb[i];
else
rem -= lb[i];
}
for(int i=0; i<N; i+=2)
{
int use = min(rem, diff[i]);
if(dir[i])
fv[i] = rb[i] - use;
else
fv[i] = lb[i] + use;
rem -= use;
}
int curd = 0;
for(int i=0; i<N; i++)
{
int nd = dir[i]*2 + ((i+1)%2);
if((nd+1)%4 == curd)
fc[i] = 'R';
else
fc[i] = 'L';
curd = nd;
}
if(!ok)
{
cout<<-1<<endl;
return 0;
}
else
{
cout<<N<<endl;
for(int i=0; i<N; i++)
cout<<fc[i]<<" "<<fv[i]<<endl;
}
for(int i=0; i<N; i++)
if(c[i] != '?')
assert(c[i] == fc[i]);
int nx = 0, ny = 0;
for(int i=0; i<N; i++)
{
assert(lb[i] <= fv[i] && fv[i] <= rb[i]);
int d = (dir[i] ? -1 : 1) * fv[i];
if(i%2)
nx += d;
else
ny += d;
}
assert(nx == tarx);
assert(ny == tary);
return 0;
}
|
#include <iostream>
using namespace std;
int main()
{
int x = -2, y = 0;
while(x <= 3) {
y = y + 2;
x = x + 1;
//cout << x << " " << y << endl;
}
cout << x << " " << y << endl;
return 0;
}
|
/*
LodePNG version 20190210
Copyright (c) 2005-2019 Lode Vandevenne
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
/*
The manual and changelog are in the header file "lodepng.h"
Rename this file to lodepng.cpp to use it for C++, or to lodepng.c to use it for C.
*/
#ifdef _MSC_VER
#define _CRT_SECURE_NO_DEPRECATE
#pragma warning (disable : 4201)
#ifndef BASISU_NO_ITERATOR_DEBUG_LEVEL
#if defined(_DEBUG) || defined(DEBUG)
//#define _ITERATOR_DEBUG_LEVEL 1
#define _SECURE_SCL 1
#else
#define _SECURE_SCL 0
#define _ITERATOR_DEBUG_LEVEL 0
#endif
#endif
#endif
#include "lodepng.h"
#include <limits.h> /* LONG_MAX */
#include <stdio.h> /* file handling */
#include <stdlib.h> /* allocations */
#if defined(_MSC_VER) && (_MSC_VER >= 1310) /*Visual Studio: A few warning types are not desired here.*/
#pragma warning( disable : 4244 ) /*implicit conversions: not warned by gcc -Wall -Wextra and requires too much casts*/
#pragma warning( disable : 4996 ) /*VS does not like fopen, but fopen_s is not standard C so unusable here*/
#endif /*_MSC_VER */
const char* LODEPNG_VERSION_STRING = "20190210";
/*
This source file is built up in the following large parts. The code sections
with the "LODEPNG_COMPILE_" #defines divide this up further in an intermixed way.
-Tools for C and common code for PNG and Zlib
-C Code for Zlib (huffman, deflate, ...)
-C Code for PNG (file format chunks, adam7, PNG filters, color conversions, ...)
-The C++ wrapper around all of the above
*/
/*The malloc, realloc and free functions defined here with "lodepng_" in front
of the name, so that you can easily change them to others related to your
platform if needed. Everything else in the code calls these. Pass
-DLODEPNG_NO_COMPILE_ALLOCATORS to the compiler, or comment out
#define LODEPNG_COMPILE_ALLOCATORS in the header, to disable the ones here and
define them in your own project's source files without needing to change
lodepng source code. Don't forget to remove "static" if you copypaste them
from here.*/
#ifdef LODEPNG_COMPILE_ALLOCATORS
static void* lodepng_malloc(size_t size) {
#ifdef LODEPNG_MAX_ALLOC
if(size > LODEPNG_MAX_ALLOC) return 0;
#endif
return malloc(size);
}
static void* lodepng_realloc(void* ptr, size_t new_size) {
#ifdef LODEPNG_MAX_ALLOC
if(new_size > LODEPNG_MAX_ALLOC) return 0;
#endif
return realloc(ptr, new_size);
}
static void lodepng_free(void* ptr) {
free(ptr);
}
#else /*LODEPNG_COMPILE_ALLOCATORS*/
void* lodepng_malloc(size_t size);
void* lodepng_realloc(void* ptr, size_t new_size);
void lodepng_free(void* ptr);
#endif /*LODEPNG_COMPILE_ALLOCATORS*/
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
/* // Tools for C, and common code for PNG and Zlib. // */
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
#define LODEPNG_MAX(a, b) (((a) > (b)) ? (a) : (b))
#define LODEPNG_MIN(a, b) (((a) < (b)) ? (a) : (b))
/*
Often in case of an error a value is assigned to a variable and then it breaks
out of a loop (to go to the cleanup phase of a function). This macro does that.
It makes the error handling code shorter and more readable.
Example: if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83);
*/
#define CERROR_BREAK(errorvar, code){\
errorvar = code;\
break;\
}
/*version of CERROR_BREAK that assumes the common case where the error variable is named "error"*/
#define ERROR_BREAK(code) CERROR_BREAK(error, code)
/*Set error var to the error code, and return it.*/
#define CERROR_RETURN_ERROR(errorvar, code){\
errorvar = code;\
return code;\
}
/*Try the code, if it returns error, also return the error.*/
#define CERROR_TRY_RETURN(call){\
unsigned error = call;\
if(error) return error;\
}
/*Set error var to the error code, and return from the void function.*/
#define CERROR_RETURN(errorvar, code){\
errorvar = code;\
return;\
}
/*
About uivector, ucvector and string:
-All of them wrap dynamic arrays or text strings in a similar way.
-LodePNG was originally written in C++. The vectors replace the std::vectors that were used in the C++ version.
-The string tools are made to avoid problems with compilers that declare things like strncat as deprecated.
-They're not used in the interface, only internally in this file as static functions.
-As with many other structs in this file, the init and cleanup functions serve as ctor and dtor.
*/
#ifdef LODEPNG_COMPILE_ZLIB
/*dynamic vector of unsigned ints*/
typedef struct uivector {
unsigned* data;
size_t size; /*size in number of unsigned longs*/
size_t allocsize; /*allocated size in bytes*/
} uivector;
static void uivector_cleanup(void* p) {
((uivector*)p)->size = ((uivector*)p)->allocsize = 0;
lodepng_free(((uivector*)p)->data);
((uivector*)p)->data = NULL;
}
/*returns 1 if success, 0 if failure ==> nothing done*/
static unsigned uivector_reserve(uivector* p, size_t allocsize) {
if(allocsize > p->allocsize) {
size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2);
void* data = lodepng_realloc(p->data, newsize);
if(data) {
p->allocsize = newsize;
p->data = (unsigned*)data;
}
else return 0; /*error: not enough memory*/
}
return 1;
}
/*returns 1 if success, 0 if failure ==> nothing done*/
static unsigned uivector_resize(uivector* p, size_t size) {
if(!uivector_reserve(p, size * sizeof(unsigned))) return 0;
p->size = size;
return 1; /*success*/
}
/*resize and give all new elements the value*/
static unsigned uivector_resizev(uivector* p, size_t size, unsigned value) {
size_t oldsize = p->size, i;
if(!uivector_resize(p, size)) return 0;
for(i = oldsize; i < size; ++i) p->data[i] = value;
return 1;
}
static void uivector_init(uivector* p) {
p->data = NULL;
p->size = p->allocsize = 0;
}
#ifdef LODEPNG_COMPILE_ENCODER
/*returns 1 if success, 0 if failure ==> nothing done*/
static unsigned uivector_push_back(uivector* p, unsigned c) {
if(!uivector_resize(p, p->size + 1)) return 0;
if (!p->data) return 0;
p->data[p->size - 1] = c;
return 1;
}
#endif /*LODEPNG_COMPILE_ENCODER*/
#endif /*LODEPNG_COMPILE_ZLIB*/
/* /////////////////////////////////////////////////////////////////////////// */
/*dynamic vector of unsigned chars*/
typedef struct ucvector {
unsigned char* data;
size_t size; /*used size*/
size_t allocsize; /*allocated size*/
} ucvector;
/*returns 1 if success, 0 if failure ==> nothing done*/
static unsigned ucvector_reserve(ucvector* p, size_t allocsize) {
if(allocsize > p->allocsize) {
size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2);
void* data = lodepng_realloc(p->data, newsize);
if(data) {
p->allocsize = newsize;
p->data = (unsigned char*)data;
}
else return 0; /*error: not enough memory*/
}
return 1;
}
/*returns 1 if success, 0 if failure ==> nothing done*/
static unsigned ucvector_resize(ucvector* p, size_t size) {
if(!ucvector_reserve(p, size * sizeof(unsigned char))) return 0;
p->size = size;
return 1; /*success*/
}
#ifdef LODEPNG_COMPILE_PNG
static void ucvector_cleanup(void* p) {
((ucvector*)p)->size = ((ucvector*)p)->allocsize = 0;
lodepng_free(((ucvector*)p)->data);
((ucvector*)p)->data = NULL;
}
static void ucvector_init(ucvector* p) {
p->data = NULL;
p->size = p->allocsize = 0;
}
#endif /*LODEPNG_COMPILE_PNG*/
#ifdef LODEPNG_COMPILE_ZLIB
/*you can both convert from vector to buffer&size and vica versa. If you use
init_buffer to take over a buffer and size, it is not needed to use cleanup*/
static void ucvector_init_buffer(ucvector* p, unsigned char* buffer, size_t size) {
p->data = buffer;
p->allocsize = p->size = size;
}
#endif /*LODEPNG_COMPILE_ZLIB*/
#if (defined(LODEPNG_COMPILE_PNG) && defined(LODEPNG_COMPILE_ANCILLARY_CHUNKS)) || defined(LODEPNG_COMPILE_ENCODER)
/*returns 1 if success, 0 if failure ==> nothing done*/
static unsigned ucvector_push_back(ucvector* p, unsigned char c) {
if(!ucvector_resize(p, p->size + 1)) return 0;
p->data[p->size - 1] = c;
return 1;
}
#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/
/* ////////////////////////////////////////////////////////////////////////// */
#ifdef LODEPNG_COMPILE_PNG
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*free string pointer and set it to NULL*/
static void string_cleanup(char** out) {
lodepng_free(*out);
*out = NULL;
}
/* dynamically allocates a new string with a copy of the null terminated input text */
static char* alloc_string(const char* in) {
size_t insize = strlen(in);
char* out = (char*)lodepng_malloc(insize + 1);
if(out) {
size_t i;
for(i = 0; i != insize; ++i) {
out[i] = in[i];
}
out[i] = 0;
}
return out;
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
#endif /*LODEPNG_COMPILE_PNG*/
/* ////////////////////////////////////////////////////////////////////////// */
unsigned lodepng_read32bitInt(const unsigned char* buffer) {
return (unsigned)((buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]);
}
#if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)
/*buffer must have at least 4 allocated bytes available*/
static void lodepng_set32bitInt(unsigned char* buffer, unsigned value) {
buffer[0] = (unsigned char)((value >> 24) & 0xff);
buffer[1] = (unsigned char)((value >> 16) & 0xff);
buffer[2] = (unsigned char)((value >> 8) & 0xff);
buffer[3] = (unsigned char)((value ) & 0xff);
}
#endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/
#ifdef LODEPNG_COMPILE_ENCODER
static void lodepng_add32bitInt(ucvector* buffer, unsigned value) {
ucvector_resize(buffer, buffer->size + 4); /*todo: give error if resize failed*/
lodepng_set32bitInt(&buffer->data[buffer->size - 4], value);
}
#endif /*LODEPNG_COMPILE_ENCODER*/
/* ////////////////////////////////////////////////////////////////////////// */
/* / File IO / */
/* ////////////////////////////////////////////////////////////////////////// */
#ifdef LODEPNG_COMPILE_DISK
/* returns negative value on error. This should be pure C compatible, so no fstat. */
static long lodepng_filesize(const char* filename) {
FILE* file;
long size;
file = fopen(filename, "rb");
if(!file) return -1;
if(fseek(file, 0, SEEK_END) != 0) {
fclose(file);
return -1;
}
size = ftell(file);
/* It may give LONG_MAX as directory size, this is invalid for us. */
if(size == LONG_MAX) size = -1;
fclose(file);
return size;
}
/* load file into buffer that already has the correct allocated size. Returns error code.*/
static unsigned lodepng_buffer_file(unsigned char* out, size_t size, const char* filename) {
FILE* file;
size_t readsize;
file = fopen(filename, "rb");
if(!file) return 78;
readsize = fread(out, 1, size, file);
fclose(file);
if (readsize != size) return 78;
return 0;
}
unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename) {
long size = lodepng_filesize(filename);
if (size < 0) return 78;
*outsize = (size_t)size;
*out = (unsigned char*)lodepng_malloc((size_t)size);
if(!(*out) && size > 0) return 83; /*the above malloc failed*/
return lodepng_buffer_file(*out, (size_t)size, filename);
}
/*write given buffer to the file, overwriting the file, it doesn't append to it.*/
unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename) {
FILE* file;
file = fopen(filename, "wb" );
if(!file) return 79;
fwrite(buffer, 1, buffersize, file);
fclose(file);
return 0;
}
#endif /*LODEPNG_COMPILE_DISK*/
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
/* // End of common code and tools. Begin of Zlib related code. // */
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
#ifdef LODEPNG_COMPILE_ZLIB
#ifdef LODEPNG_COMPILE_ENCODER
/*TODO: this ignores potential out of memory errors*/
#define addBitToStream(/*size_t**/ bitpointer, /*ucvector**/ bitstream, /*unsigned char*/ bit){\
/*add a new byte at the end*/\
if(((*bitpointer) & 7) == 0) ucvector_push_back(bitstream, (unsigned char)0);\
/*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/\
(bitstream->data[bitstream->size - 1]) |= (bit << ((*bitpointer) & 0x7));\
++(*bitpointer);\
}
static void addBitsToStream(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits) {
size_t i;
for(i = 0; i != nbits; ++i) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> i) & 1));
}
static void addBitsToStreamReversed(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits) {
size_t i;
for(i = 0; i != nbits; ++i) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> (nbits - 1 - i)) & 1));
}
#endif /*LODEPNG_COMPILE_ENCODER*/
#ifdef LODEPNG_COMPILE_DECODER
#define READBIT(bitpointer, bitstream) ((bitstream[bitpointer >> 3] >> (bitpointer & 0x7)) & (unsigned char)1)
static unsigned char readBitFromStream(size_t* bitpointer, const unsigned char* bitstream) {
unsigned char result = (unsigned char)(READBIT(*bitpointer, bitstream));
++(*bitpointer);
return result;
}
static unsigned readBitsFromStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits) {
unsigned result = 0, i;
for(i = 0; i != nbits; ++i) {
result += ((unsigned)READBIT(*bitpointer, bitstream)) << i;
++(*bitpointer);
}
return result;
}
#endif /*LODEPNG_COMPILE_DECODER*/
/* ////////////////////////////////////////////////////////////////////////// */
/* / Deflate - Huffman / */
/* ////////////////////////////////////////////////////////////////////////// */
#define FIRST_LENGTH_CODE_INDEX 257
#define LAST_LENGTH_CODE_INDEX 285
/*256 literals, the end code, some length codes, and 2 unused codes*/
#define NUM_DEFLATE_CODE_SYMBOLS 288
/*the distance codes have their own symbols, 30 used, 2 unused*/
#define NUM_DISTANCE_SYMBOLS 32
/*the code length codes. 0-15: code lengths, 16: copy previous 3-6 times, 17: 3-10 zeros, 18: 11-138 zeros*/
#define NUM_CODE_LENGTH_CODES 19
/*the base lengths represented by codes 257-285*/
static const unsigned LENGTHBASE[29]
= {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59,
67, 83, 99, 115, 131, 163, 195, 227, 258};
/*the extra bits used by codes 257-285 (added to base length)*/
static const unsigned LENGTHEXTRA[29]
= {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3,
4, 4, 4, 4, 5, 5, 5, 5, 0};
/*the base backwards distances (the bits of distance codes appear after length codes and use their own huffman tree)*/
static const unsigned DISTANCEBASE[30]
= {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513,
769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
/*the extra bits of backwards distances (added to base)*/
static const unsigned DISTANCEEXTRA[30]
= {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8,
8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
/*the order in which "code length alphabet code lengths" are stored, out of this
the huffman tree of the dynamic huffman tree lengths is generated*/
static const unsigned CLCL_ORDER[NUM_CODE_LENGTH_CODES]
= {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
/* ////////////////////////////////////////////////////////////////////////// */
/*
Huffman tree struct, containing multiple representations of the tree
*/
typedef struct HuffmanTree {
unsigned* tree2d;
unsigned* tree1d;
unsigned* lengths; /*the lengths of the codes of the 1d-tree*/
unsigned maxbitlen; /*maximum number of bits a single code can get*/
unsigned numcodes; /*number of symbols in the alphabet = number of codes*/
} HuffmanTree;
/*function used for debug purposes to draw the tree in ascii art with C++*/
/*
static void HuffmanTree_draw(HuffmanTree* tree) {
std::cout << "tree. length: " << tree->numcodes << " maxbitlen: " << tree->maxbitlen << std::endl;
for(size_t i = 0; i != tree->tree1d.size; ++i) {
if(tree->lengths.data[i])
std::cout << i << " " << tree->tree1d.data[i] << " " << tree->lengths.data[i] << std::endl;
}
std::cout << std::endl;
}*/
static void HuffmanTree_init(HuffmanTree* tree) {
tree->tree2d = 0;
tree->tree1d = 0;
tree->lengths = 0;
}
static void HuffmanTree_cleanup(HuffmanTree* tree) {
lodepng_free(tree->tree2d);
lodepng_free(tree->tree1d);
lodepng_free(tree->lengths);
}
/*the tree representation used by the decoder. return value is error*/
static unsigned HuffmanTree_make2DTree(HuffmanTree* tree) {
unsigned nodefilled = 0; /*up to which node it is filled*/
unsigned treepos = 0; /*position in the tree (1 of the numcodes columns)*/
unsigned n, i;
tree->tree2d = (unsigned*)lodepng_malloc(tree->numcodes * 2 * sizeof(unsigned));
if(!tree->tree2d) return 83; /*alloc fail*/
/*
convert tree1d[] to tree2d[][]. In the 2D array, a value of 32767 means
uninited, a value >= numcodes is an address to another bit, a value < numcodes
is a code. The 2 rows are the 2 possible bit values (0 or 1), there are as
many columns as codes - 1.
A good huffman tree has N * 2 - 1 nodes, of which N - 1 are internal nodes.
Here, the internal nodes are stored (what their 0 and 1 option point to).
There is only memory for such good tree currently, if there are more nodes
(due to too long length codes), error 55 will happen
*/
for(n = 0; n < tree->numcodes * 2; ++n) {
tree->tree2d[n] = 32767; /*32767 here means the tree2d isn't filled there yet*/
}
for(n = 0; n < tree->numcodes; ++n) /*the codes*/ {
for(i = 0; i != tree->lengths[n]; ++i) /*the bits for this code*/ {
unsigned char bit = (unsigned char)((tree->tree1d[n] >> (tree->lengths[n] - i - 1)) & 1);
/*oversubscribed, see comment in lodepng_error_text*/
if(treepos > 2147483647 || treepos + 2 > tree->numcodes) return 55;
if(tree->tree2d[2 * treepos + bit] == 32767) /*not yet filled in*/ {
if(i + 1 == tree->lengths[n]) /*last bit*/ {
tree->tree2d[2 * treepos + bit] = n; /*put the current code in it*/
treepos = 0;
} else {
/*put address of the next step in here, first that address has to be found of course
(it's just nodefilled + 1)...*/
++nodefilled;
/*addresses encoded with numcodes added to it*/
tree->tree2d[2 * treepos + bit] = nodefilled + tree->numcodes;
treepos = nodefilled;
}
}
else treepos = tree->tree2d[2 * treepos + bit] - tree->numcodes;
}
}
for(n = 0; n < tree->numcodes * 2; ++n) {
if(tree->tree2d[n] == 32767) tree->tree2d[n] = 0; /*remove possible remaining 32767's*/
}
return 0;
}
/*
Second step for the ...makeFromLengths and ...makeFromFrequencies functions.
numcodes, lengths and maxbitlen must already be filled in correctly. return
value is error.
*/
static unsigned HuffmanTree_makeFromLengths2(HuffmanTree* tree) {
uivector blcount;
uivector nextcode;
unsigned error = 0;
unsigned bits, n;
uivector_init(&blcount);
uivector_init(&nextcode);
tree->tree1d = (unsigned*)lodepng_malloc(tree->numcodes * sizeof(unsigned));
if(!tree->tree1d) error = 83; /*alloc fail*/
if(!uivector_resizev(&blcount, tree->maxbitlen + 1, 0)
|| !uivector_resizev(&nextcode, tree->maxbitlen + 1, 0))
error = 83; /*alloc fail*/
if(!error) {
/*step 1: count number of instances of each code length*/
for(bits = 0; bits != tree->numcodes; ++bits) ++blcount.data[tree->lengths[bits]];
/*step 2: generate the nextcode values*/
for(bits = 1; bits <= tree->maxbitlen; ++bits) {
nextcode.data[bits] = (nextcode.data[bits - 1] + blcount.data[bits - 1]) << 1;
}
/*step 3: generate all the codes*/
for(n = 0; n != tree->numcodes; ++n) {
if(tree->lengths[n] != 0) tree->tree1d[n] = nextcode.data[tree->lengths[n]]++;
}
}
uivector_cleanup(&blcount);
uivector_cleanup(&nextcode);
if(!error) return HuffmanTree_make2DTree(tree);
else return error;
}
/*
given the code lengths (as stored in the PNG file), generate the tree as defined
by Deflate. maxbitlen is the maximum bits that a code in the tree can have.
return value is error.
*/
static unsigned HuffmanTree_makeFromLengths(HuffmanTree* tree, const unsigned* bitlen,
size_t numcodes, unsigned maxbitlen) {
unsigned i;
tree->lengths = (unsigned*)lodepng_malloc(numcodes * sizeof(unsigned));
if(!tree->lengths) return 83; /*alloc fail*/
for(i = 0; i != numcodes; ++i) tree->lengths[i] = bitlen[i];
tree->numcodes = (unsigned)numcodes; /*number of symbols*/
tree->maxbitlen = maxbitlen;
return HuffmanTree_makeFromLengths2(tree);
}
#ifdef LODEPNG_COMPILE_ENCODER
/*BPM: Boundary Package Merge, see "A Fast and Space-Economical Algorithm for Length-Limited Coding",
Jyrki Katajainen, Alistair Moffat, Andrew Turpin, 1995.*/
/*chain node for boundary package merge*/
typedef struct BPMNode {
int weight; /*the sum of all weights in this chain*/
unsigned index; /*index of this leaf node (called "count" in the paper)*/
struct BPMNode* tail; /*the next nodes in this chain (null if last)*/
int in_use;
} BPMNode;
/*lists of chains*/
typedef struct BPMLists {
/*memory pool*/
unsigned memsize;
BPMNode* memory;
unsigned numfree;
unsigned nextfree;
BPMNode** freelist;
/*two heads of lookahead chains per list*/
unsigned listsize;
BPMNode** chains0;
BPMNode** chains1;
} BPMLists;
/*creates a new chain node with the given parameters, from the memory in the lists */
static BPMNode* bpmnode_create(BPMLists* lists, int weight, unsigned index, BPMNode* tail) {
unsigned i;
BPMNode* result;
/*memory full, so garbage collect*/
if(lists->nextfree >= lists->numfree) {
/*mark only those that are in use*/
for(i = 0; i != lists->memsize; ++i) lists->memory[i].in_use = 0;
for(i = 0; i != lists->listsize; ++i) {
BPMNode* node;
for(node = lists->chains0[i]; node != 0; node = node->tail) node->in_use = 1;
for(node = lists->chains1[i]; node != 0; node = node->tail) node->in_use = 1;
}
/*collect those that are free*/
lists->numfree = 0;
for(i = 0; i != lists->memsize; ++i) {
if(!lists->memory[i].in_use) lists->freelist[lists->numfree++] = &lists->memory[i];
}
lists->nextfree = 0;
}
result = lists->freelist[lists->nextfree++];
result->weight = weight;
result->index = index;
result->tail = tail;
return result;
}
/*sort the leaves with stable mergesort*/
static void bpmnode_sort(BPMNode* leaves, size_t num) {
BPMNode* mem = (BPMNode*)lodepng_malloc(sizeof(*leaves) * num);
size_t width, counter = 0;
for(width = 1; width < num; width *= 2) {
BPMNode* a = (counter & 1) ? mem : leaves;
BPMNode* b = (counter & 1) ? leaves : mem;
size_t p;
for(p = 0; p < num; p += 2 * width) {
size_t q = (p + width > num) ? num : (p + width);
size_t r = (p + 2 * width > num) ? num : (p + 2 * width);
size_t i = p, j = q, k;
for(k = p; k < r; k++) {
if(i < q && (j >= r || a[i].weight <= a[j].weight)) b[k] = a[i++];
else b[k] = a[j++];
}
}
counter++;
}
if(counter & 1) memcpy(leaves, mem, sizeof(*leaves) * num);
lodepng_free(mem);
}
/*Boundary Package Merge step, numpresent is the amount of leaves, and c is the current chain.*/
static void boundaryPM(BPMLists* lists, BPMNode* leaves, size_t numpresent, int c, int num) {
unsigned lastindex = lists->chains1[c]->index;
if(c == 0) {
if(lastindex >= numpresent) return;
lists->chains0[c] = lists->chains1[c];
lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, 0);
} else {
/*sum of the weights of the head nodes of the previous lookahead chains.*/
int sum = lists->chains0[c - 1]->weight + lists->chains1[c - 1]->weight;
lists->chains0[c] = lists->chains1[c];
if(lastindex < numpresent && sum > leaves[lastindex].weight) {
lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, lists->chains1[c]->tail);
return;
}
lists->chains1[c] = bpmnode_create(lists, sum, lastindex, lists->chains1[c - 1]);
/*in the end we are only interested in the chain of the last list, so no
need to recurse if we're at the last one (this gives measurable speedup)*/
if(num + 1 < (int)(2 * numpresent - 2)) {
boundaryPM(lists, leaves, numpresent, c - 1, num);
boundaryPM(lists, leaves, numpresent, c - 1, num);
}
}
}
unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies,
size_t numcodes, unsigned maxbitlen) {
unsigned error = 0;
unsigned i;
size_t numpresent = 0; /*number of symbols with non-zero frequency*/
BPMNode* leaves; /*the symbols, only those with > 0 frequency*/
if(numcodes == 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/
if((1u << maxbitlen) < (unsigned)numcodes) return 80; /*error: represent all symbols*/
leaves = (BPMNode*)lodepng_malloc(numcodes * sizeof(*leaves));
if(!leaves) return 83; /*alloc fail*/
for(i = 0; i != numcodes; ++i) {
if(frequencies[i] > 0) {
leaves[numpresent].weight = (int)frequencies[i];
leaves[numpresent].index = i;
++numpresent;
}
}
for(i = 0; i != numcodes; ++i) lengths[i] = 0;
/*ensure at least two present symbols. There should be at least one symbol
according to RFC 1951 section 3.2.7. Some decoders incorrectly require two. To
make these work as well ensure there are at least two symbols. The
Package-Merge code below also doesn't work correctly if there's only one
symbol, it'd give it the theoritical 0 bits but in practice zlib wants 1 bit*/
if(numpresent == 0) {
lengths[0] = lengths[1] = 1; /*note that for RFC 1951 section 3.2.7, only lengths[0] = 1 is needed*/
} else if(numpresent == 1) {
lengths[leaves[0].index] = 1;
lengths[leaves[0].index == 0 ? 1 : 0] = 1;
} else {
BPMLists lists;
BPMNode* node;
bpmnode_sort(leaves, numpresent);
lists.listsize = maxbitlen;
lists.memsize = 2 * maxbitlen * (maxbitlen + 1);
lists.nextfree = 0;
lists.numfree = lists.memsize;
lists.memory = (BPMNode*)lodepng_malloc(lists.memsize * sizeof(*lists.memory));
lists.freelist = (BPMNode**)lodepng_malloc(lists.memsize * sizeof(BPMNode*));
lists.chains0 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*));
lists.chains1 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*));
if(!lists.memory || !lists.freelist || !lists.chains0 || !lists.chains1) error = 83; /*alloc fail*/
if(!error) {
for(i = 0; i != lists.memsize; ++i) lists.freelist[i] = &lists.memory[i];
bpmnode_create(&lists, leaves[0].weight, 1, 0);
bpmnode_create(&lists, leaves[1].weight, 2, 0);
for(i = 0; i != lists.listsize; ++i) {
lists.chains0[i] = &lists.memory[0];
lists.chains1[i] = &lists.memory[1];
}
/*each boundaryPM call adds one chain to the last list, and we need 2 * numpresent - 2 chains.*/
for(i = 2; i != 2 * numpresent - 2; ++i) boundaryPM(&lists, leaves, numpresent, (int)maxbitlen - 1, (int)i);
for(node = lists.chains1[maxbitlen - 1]; node; node = node->tail) {
for(i = 0; i != node->index; ++i) ++lengths[leaves[i].index];
}
}
lodepng_free(lists.memory);
lodepng_free(lists.freelist);
lodepng_free(lists.chains0);
lodepng_free(lists.chains1);
}
lodepng_free(leaves);
return error;
}
/*Create the Huffman tree given the symbol frequencies*/
static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies,
size_t mincodes, size_t numcodes, unsigned maxbitlen) {
unsigned error = 0;
while(!frequencies[numcodes - 1] && numcodes > mincodes) --numcodes; /*trim zeroes*/
tree->maxbitlen = maxbitlen;
tree->numcodes = (unsigned)numcodes; /*number of symbols*/
tree->lengths = (unsigned*)lodepng_realloc(tree->lengths, numcodes * sizeof(unsigned));
if(!tree->lengths) return 83; /*alloc fail*/
/*initialize all lengths to 0*/
memset(tree->lengths, 0, numcodes * sizeof(unsigned));
error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen);
if(!error) error = HuffmanTree_makeFromLengths2(tree);
return error;
}
static unsigned HuffmanTree_getCode(const HuffmanTree* tree, unsigned index) {
return tree->tree1d[index];
}
static unsigned HuffmanTree_getLength(const HuffmanTree* tree, unsigned index) {
return tree->lengths[index];
}
#endif /*LODEPNG_COMPILE_ENCODER*/
/*get the literal and length code tree of a deflated block with fixed tree, as per the deflate specification*/
static unsigned generateFixedLitLenTree(HuffmanTree* tree) {
unsigned i, error = 0;
unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
if(!bitlen) return 83; /*alloc fail*/
/*288 possible codes: 0-255=literals, 256=endcode, 257-285=lengthcodes, 286-287=unused*/
for(i = 0; i <= 143; ++i) bitlen[i] = 8;
for(i = 144; i <= 255; ++i) bitlen[i] = 9;
for(i = 256; i <= 279; ++i) bitlen[i] = 7;
for(i = 280; i <= 287; ++i) bitlen[i] = 8;
error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DEFLATE_CODE_SYMBOLS, 15);
lodepng_free(bitlen);
return error;
}
/*get the distance code tree of a deflated block with fixed tree, as specified in the deflate specification*/
static unsigned generateFixedDistanceTree(HuffmanTree* tree) {
unsigned i, error = 0;
unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));
if(!bitlen) return 83; /*alloc fail*/
/*there are 32 distance codes, but 30-31 are unused*/
for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen[i] = 5;
error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DISTANCE_SYMBOLS, 15);
lodepng_free(bitlen);
return error;
}
#ifdef LODEPNG_COMPILE_DECODER
/*
returns the code, or (unsigned)(-1) if error happened
inbitlength is the length of the complete buffer, in bits (so its byte length times 8)
*/
static unsigned huffmanDecodeSymbol(const unsigned char* in, size_t* bp,
const HuffmanTree* codetree, size_t inbitlength) {
unsigned treepos = 0, ct;
for(;;) {
if(*bp >= inbitlength) return (unsigned)(-1); /*error: end of input memory reached without endcode*/
/*
decode the symbol from the tree. The "readBitFromStream" code is inlined in
the expression below because this is the biggest bottleneck while decoding
*/
ct = codetree->tree2d[(treepos << 1) + READBIT(*bp, in)];
++(*bp);
if(ct < codetree->numcodes) return ct; /*the symbol is decoded, return it*/
else treepos = ct - codetree->numcodes; /*symbol not yet decoded, instead move tree position*/
if(treepos >= codetree->numcodes) return (unsigned)(-1); /*error: it appeared outside the codetree*/
}
}
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_DECODER
/* ////////////////////////////////////////////////////////////////////////// */
/* / Inflator (Decompressor) / */
/* ////////////////////////////////////////////////////////////////////////// */
/*get the tree of a deflated block with fixed tree, as specified in the deflate specification*/
static void getTreeInflateFixed(HuffmanTree* tree_ll, HuffmanTree* tree_d) {
/*TODO: check for out of memory errors*/
generateFixedLitLenTree(tree_ll);
generateFixedDistanceTree(tree_d);
}
/*get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree*/
static unsigned getTreeInflateDynamic(HuffmanTree* tree_ll, HuffmanTree* tree_d,
const unsigned char* in, size_t* bp, size_t inlength) {
/*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated*/
unsigned error = 0;
unsigned n, HLIT, HDIST, HCLEN, i;
size_t inbitlength = inlength * 8;
/*see comments in deflateDynamic for explanation of the context and these variables, it is analogous*/
unsigned* bitlen_ll = 0; /*lit,len code lengths*/
unsigned* bitlen_d = 0; /*dist code lengths*/
/*code length code lengths ("clcl"), the bit lengths of the huffman tree used to compress bitlen_ll and bitlen_d*/
unsigned* bitlen_cl = 0;
HuffmanTree tree_cl; /*the code tree for code length codes (the huffman tree for compressed huffman trees)*/
if((*bp) + 14 > (inlength << 3)) return 49; /*error: the bit pointer is or will go past the memory*/
/*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/
HLIT = readBitsFromStream(bp, in, 5) + 257;
/*number of distance codes. Unlike the spec, the value 1 is added to it here already*/
HDIST = readBitsFromStream(bp, in, 5) + 1;
/*number of code length codes. Unlike the spec, the value 4 is added to it here already*/
HCLEN = readBitsFromStream(bp, in, 4) + 4;
if((*bp) + HCLEN * 3 > (inlength << 3)) return 50; /*error: the bit pointer is or will go past the memory*/
HuffmanTree_init(&tree_cl);
while(!error) {
/*read the code length codes out of 3 * (amount of code length codes) bits*/
bitlen_cl = (unsigned*)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(unsigned));
if(!bitlen_cl) ERROR_BREAK(83 /*alloc fail*/);
for(i = 0; i != NUM_CODE_LENGTH_CODES; ++i) {
if(i < HCLEN) bitlen_cl[CLCL_ORDER[i]] = readBitsFromStream(bp, in, 3);
else bitlen_cl[CLCL_ORDER[i]] = 0; /*if not, it must stay 0*/
}
error = HuffmanTree_makeFromLengths(&tree_cl, bitlen_cl, NUM_CODE_LENGTH_CODES, 7);
if(error) break;
/*now we can use this tree to read the lengths for the tree that this function will return*/
bitlen_ll = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned));
bitlen_d = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned));
if(!bitlen_ll || !bitlen_d) ERROR_BREAK(83 /*alloc fail*/);
for(i = 0; i != NUM_DEFLATE_CODE_SYMBOLS; ++i) bitlen_ll[i] = 0;
for(i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen_d[i] = 0;
/*i is the current symbol we're reading in the part that contains the code lengths of lit/len and dist codes*/
i = 0;
while(i < HLIT + HDIST) {
unsigned code = huffmanDecodeSymbol(in, bp, &tree_cl, inbitlength);
if(code <= 15) /*a length code*/ {
if(i < HLIT) bitlen_ll[i] = code;
else bitlen_d[i - HLIT] = code;
++i;
} else if(code == 16) /*repeat previous*/ {
unsigned replength = 3; /*read in the 2 bits that indicate repeat length (3-6)*/
unsigned value; /*set value to the previous code*/
if(i == 0) ERROR_BREAK(54); /*can't repeat previous if i is 0*/
if((*bp + 2) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
replength += readBitsFromStream(bp, in, 2);
if(i < HLIT + 1) value = bitlen_ll[i - 1];
else value = bitlen_d[i - HLIT - 1];
/*repeat this value in the next lengths*/
for(n = 0; n < replength; ++n) {
if(i >= HLIT + HDIST) ERROR_BREAK(13); /*error: i is larger than the amount of codes*/
if(i < HLIT) bitlen_ll[i] = value;
else bitlen_d[i - HLIT] = value;
++i;
}
} else if(code == 17) /*repeat "0" 3-10 times*/ {
unsigned replength = 3; /*read in the bits that indicate repeat length*/
if((*bp + 3) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
replength += readBitsFromStream(bp, in, 3);
/*repeat this value in the next lengths*/
for(n = 0; n < replength; ++n) {
if(i >= HLIT + HDIST) ERROR_BREAK(14); /*error: i is larger than the amount of codes*/
if(i < HLIT) bitlen_ll[i] = 0;
else bitlen_d[i - HLIT] = 0;
++i;
}
} else if(code == 18) /*repeat "0" 11-138 times*/ {
unsigned replength = 11; /*read in the bits that indicate repeat length*/
if((*bp + 7) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/
replength += readBitsFromStream(bp, in, 7);
/*repeat this value in the next lengths*/
for(n = 0; n < replength; ++n) {
if(i >= HLIT + HDIST) ERROR_BREAK(15); /*error: i is larger than the amount of codes*/
if(i < HLIT) bitlen_ll[i] = 0;
else bitlen_d[i - HLIT] = 0;
++i;
}
} else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ {
if(code == (unsigned)(-1)) {
/*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
(10=no endcode, 11=wrong jump outside of tree)*/
error = (*bp) > inbitlength ? 10 : 11;
}
else error = 16; /*unexisting code, this can never happen*/
break;
}
}
if(error) break;
if(bitlen_ll[256] == 0) ERROR_BREAK(64); /*the length of the end code 256 must be larger than 0*/
/*now we've finally got HLIT and HDIST, so generate the code trees, and the function is done*/
error = HuffmanTree_makeFromLengths(tree_ll, bitlen_ll, NUM_DEFLATE_CODE_SYMBOLS, 15);
if(error) break;
error = HuffmanTree_makeFromLengths(tree_d, bitlen_d, NUM_DISTANCE_SYMBOLS, 15);
break; /*end of error-while*/
}
lodepng_free(bitlen_cl);
lodepng_free(bitlen_ll);
lodepng_free(bitlen_d);
HuffmanTree_cleanup(&tree_cl);
return error;
}
/*inflate a block with dynamic of fixed Huffman tree*/
static unsigned inflateHuffmanBlock(ucvector* out, const unsigned char* in, size_t* bp,
size_t* pos, size_t inlength, unsigned btype) {
unsigned error = 0;
HuffmanTree tree_ll; /*the huffman tree for literal and length codes*/
HuffmanTree tree_d; /*the huffman tree for distance codes*/
size_t inbitlength = inlength * 8;
HuffmanTree_init(&tree_ll);
HuffmanTree_init(&tree_d);
if(btype == 1) getTreeInflateFixed(&tree_ll, &tree_d);
else if(btype == 2) error = getTreeInflateDynamic(&tree_ll, &tree_d, in, bp, inlength);
while(!error) /*decode all symbols until end reached, breaks at end code*/ {
/*code_ll is literal, length or end code*/
unsigned code_ll = huffmanDecodeSymbol(in, bp, &tree_ll, inbitlength);
if(code_ll <= 255) /*literal symbol*/ {
/*ucvector_push_back would do the same, but for some reason the two lines below run 10% faster*/
if(!ucvector_resize(out, (*pos) + 1)) ERROR_BREAK(83 /*alloc fail*/);
out->data[*pos] = (unsigned char)code_ll;
++(*pos);
} else if(code_ll >= FIRST_LENGTH_CODE_INDEX && code_ll <= LAST_LENGTH_CODE_INDEX) /*length code*/ {
unsigned code_d, distance;
unsigned numextrabits_l, numextrabits_d; /*extra bits for length and distance*/
size_t start, forward, backward, length;
/*part 1: get length base*/
length = LENGTHBASE[code_ll - FIRST_LENGTH_CODE_INDEX];
/*part 2: get extra bits and add the value of that to length*/
numextrabits_l = LENGTHEXTRA[code_ll - FIRST_LENGTH_CODE_INDEX];
if((*bp + numextrabits_l) > inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/
length += readBitsFromStream(bp, in, numextrabits_l);
/*part 3: get distance code*/
code_d = huffmanDecodeSymbol(in, bp, &tree_d, inbitlength);
if(code_d > 29) {
if(code_d == (unsigned)(-1)) /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ {
/*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
(10=no endcode, 11=wrong jump outside of tree)*/
error = (*bp) > inlength * 8 ? 10 : 11;
}
else error = 18; /*error: invalid distance code (30-31 are never used)*/
break;
}
distance = DISTANCEBASE[code_d];
/*part 4: get extra bits from distance*/
numextrabits_d = DISTANCEEXTRA[code_d];
if((*bp + numextrabits_d) > inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/
distance += readBitsFromStream(bp, in, numextrabits_d);
/*part 5: fill in all the out[n] values based on the length and dist*/
start = (*pos);
if(distance > start) ERROR_BREAK(52); /*too long backward distance*/
backward = start - distance;
if(!ucvector_resize(out, (*pos) + length)) ERROR_BREAK(83 /*alloc fail*/);
if (distance < length) {
for(forward = 0; forward < length; ++forward) {
out->data[(*pos)++] = out->data[backward++];
}
} else {
memcpy(out->data + *pos, out->data + backward, length);
*pos += length;
}
} else if(code_ll == 256) {
break; /*end code, break the loop*/
} else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ {
/*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol
(10=no endcode, 11=wrong jump outside of tree)*/
error = ((*bp) > inlength * 8) ? 10 : 11;
break;
}
}
HuffmanTree_cleanup(&tree_ll);
HuffmanTree_cleanup(&tree_d);
return error;
}
static unsigned inflateNoCompression(ucvector* out, const unsigned char* in, size_t* bp, size_t* pos, size_t inlength) {
size_t p;
unsigned LEN, NLEN, n, error = 0;
/*go to first boundary of byte*/
while(((*bp) & 0x7) != 0) ++(*bp);
p = (*bp) / 8; /*byte position*/
/*read LEN (2 bytes) and NLEN (2 bytes)*/
if(p + 4 >= inlength) return 52; /*error, bit pointer will jump past memory*/
LEN = in[p] + 256u * in[p + 1]; p += 2;
NLEN = in[p] + 256u * in[p + 1]; p += 2;
/*check if 16-bit NLEN is really the one's complement of LEN*/
if(LEN + NLEN != 65535) return 21; /*error: NLEN is not one's complement of LEN*/
if(!ucvector_resize(out, (*pos) + LEN)) return 83; /*alloc fail*/
/*read the literal data: LEN bytes are now stored in the out buffer*/
if(p + LEN > inlength) return 23; /*error: reading outside of in buffer*/
for(n = 0; n < LEN; ++n) out->data[(*pos)++] = in[p++];
(*bp) = p * 8;
return error;
}
static unsigned lodepng_inflatev(ucvector* out,
const unsigned char* in, size_t insize,
const LodePNGDecompressSettings* settings) {
/*bit pointer in the "in" data, current byte is bp >> 3, current bit is bp & 0x7 (from lsb to msb of the byte)*/
size_t bp = 0;
unsigned BFINAL = 0;
size_t pos = 0; /*byte position in the out buffer*/
unsigned error = 0;
(void)settings;
while(!BFINAL) {
unsigned BTYPE;
if(bp + 2 >= insize * 8) return 52; /*error, bit pointer will jump past memory*/
BFINAL = readBitFromStream(&bp, in);
BTYPE = 1u * readBitFromStream(&bp, in);
BTYPE += 2u * readBitFromStream(&bp, in);
if(BTYPE == 3) return 20; /*error: invalid BTYPE*/
else if(BTYPE == 0) error = inflateNoCompression(out, in, &bp, &pos, insize); /*no compression*/
else error = inflateHuffmanBlock(out, in, &bp, &pos, insize, BTYPE); /*compression, BTYPE 01 or 10*/
if(error) return error;
}
return error;
}
unsigned lodepng_inflate(unsigned char** out, size_t* outsize,
const unsigned char* in, size_t insize,
const LodePNGDecompressSettings* settings) {
unsigned error;
ucvector v;
ucvector_init_buffer(&v, *out, *outsize);
error = lodepng_inflatev(&v, in, insize, settings);
*out = v.data;
*outsize = v.size;
return error;
}
static unsigned inflate(unsigned char** out, size_t* outsize,
const unsigned char* in, size_t insize,
const LodePNGDecompressSettings* settings) {
if(settings->custom_inflate) {
return settings->custom_inflate(out, outsize, in, insize, settings);
} else {
return lodepng_inflate(out, outsize, in, insize, settings);
}
}
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
/* ////////////////////////////////////////////////////////////////////////// */
/* / Deflator (Compressor) / */
/* ////////////////////////////////////////////////////////////////////////// */
static const size_t MAX_SUPPORTED_DEFLATE_LENGTH = 258;
/*bitlen is the size in bits of the code*/
static void addHuffmanSymbol(size_t* bp, ucvector* compressed, unsigned code, unsigned bitlen) {
addBitsToStreamReversed(bp, compressed, code, bitlen);
}
/*search the index in the array, that has the largest value smaller than or equal to the given value,
given array must be sorted (if no value is smaller, it returns the size of the given array)*/
static size_t searchCodeIndex(const unsigned* array, size_t array_size, size_t value) {
/*binary search (only small gain over linear). TODO: use CPU log2 instruction for getting symbols instead*/
size_t left = 1;
size_t right = array_size - 1;
while(left <= right) {
size_t mid = (left + right) >> 1;
if (array[mid] >= value) right = mid - 1;
else left = mid + 1;
}
if(left >= array_size || array[left] > value) left--;
return left;
}
static void addLengthDistance(uivector* values, size_t length, size_t distance) {
/*values in encoded vector are those used by deflate:
0-255: literal bytes
256: end
257-285: length/distance pair (length code, followed by extra length bits, distance code, extra distance bits)
286-287: invalid*/
unsigned length_code = (unsigned)searchCodeIndex(LENGTHBASE, 29, length);
unsigned extra_length = (unsigned)(length - LENGTHBASE[length_code]);
unsigned dist_code = (unsigned)searchCodeIndex(DISTANCEBASE, 30, distance);
unsigned extra_distance = (unsigned)(distance - DISTANCEBASE[dist_code]);
uivector_push_back(values, length_code + FIRST_LENGTH_CODE_INDEX);
uivector_push_back(values, extra_length);
uivector_push_back(values, dist_code);
uivector_push_back(values, extra_distance);
}
/*3 bytes of data get encoded into two bytes. The hash cannot use more than 3
bytes as input because 3 is the minimum match length for deflate*/
static const unsigned HASH_NUM_VALUES = 65536;
static const unsigned HASH_BIT_MASK = 65535; /*HASH_NUM_VALUES - 1, but C90 does not like that as initializer*/
typedef struct Hash {
int* head; /*hash value to head circular pos - can be outdated if went around window*/
/*circular pos to prev circular pos*/
unsigned short* chain;
int* val; /*circular pos to hash value*/
/*TODO: do this not only for zeros but for any repeated byte. However for PNG
it's always going to be the zeros that dominate, so not important for PNG*/
int* headz; /*similar to head, but for chainz*/
unsigned short* chainz; /*those with same amount of zeros*/
unsigned short* zeros; /*length of zeros streak, used as a second hash chain*/
} Hash;
static unsigned hash_init(Hash* hash, unsigned windowsize) {
unsigned i;
hash->head = (int*)lodepng_malloc(sizeof(int) * HASH_NUM_VALUES);
hash->val = (int*)lodepng_malloc(sizeof(int) * windowsize);
hash->chain = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize);
hash->zeros = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize);
hash->headz = (int*)lodepng_malloc(sizeof(int) * (MAX_SUPPORTED_DEFLATE_LENGTH + 1));
hash->chainz = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize);
if(!hash->head || !hash->chain || !hash->val || !hash->headz|| !hash->chainz || !hash->zeros) {
return 83; /*alloc fail*/
}
/*initialize hash table*/
for(i = 0; i != HASH_NUM_VALUES; ++i) hash->head[i] = -1;
for(i = 0; i != windowsize; ++i) hash->val[i] = -1;
for(i = 0; i != windowsize; ++i) hash->chain[i] = i; /*same value as index indicates uninitialized*/
for(i = 0; i <= MAX_SUPPORTED_DEFLATE_LENGTH; ++i) hash->headz[i] = -1;
for(i = 0; i != windowsize; ++i) hash->chainz[i] = i; /*same value as index indicates uninitialized*/
return 0;
}
static void hash_cleanup(Hash* hash) {
lodepng_free(hash->head);
lodepng_free(hash->val);
lodepng_free(hash->chain);
lodepng_free(hash->zeros);
lodepng_free(hash->headz);
lodepng_free(hash->chainz);
}
static unsigned getHash(const unsigned char* data, size_t size, size_t pos) {
unsigned result = 0;
if(pos + 2 < size) {
/*A simple shift and xor hash is used. Since the data of PNGs is dominated
by zeroes due to the filters, a better hash does not have a significant
effect on speed in traversing the chain, and causes more time spend on
calculating the hash.*/
result ^= (unsigned)(data[pos + 0] << 0u);
result ^= (unsigned)(data[pos + 1] << 4u);
result ^= (unsigned)(data[pos + 2] << 8u);
} else {
size_t amount, i;
if(pos >= size) return 0;
amount = size - pos;
for(i = 0; i != amount; ++i) result ^= (unsigned)(data[pos + i] << (i * 8u));
}
return result & HASH_BIT_MASK;
}
static unsigned countZeros(const unsigned char* data, size_t size, size_t pos) {
const unsigned char* start = data + pos;
const unsigned char* end = start + MAX_SUPPORTED_DEFLATE_LENGTH;
if(end > data + size) end = data + size;
data = start;
while(data != end && *data == 0) ++data;
/*subtracting two addresses returned as 32-bit number (max value is MAX_SUPPORTED_DEFLATE_LENGTH)*/
return (unsigned)(data - start);
}
/*wpos = pos & (windowsize - 1)*/
static void updateHashChain(Hash* hash, size_t wpos, unsigned hashval, unsigned short numzeros) {
hash->val[wpos] = (int)hashval;
if(hash->head[hashval] != -1) hash->chain[wpos] = hash->head[hashval];
hash->head[hashval] = (int)wpos;
hash->zeros[wpos] = numzeros;
if(hash->headz[numzeros] != -1) hash->chainz[wpos] = hash->headz[numzeros];
hash->headz[numzeros] = (int)wpos;
}
/*
LZ77-encode the data. Return value is error code. The input are raw bytes, the output
is in the form of unsigned integers with codes representing for example literal bytes, or
length/distance pairs.
It uses a hash table technique to let it encode faster. When doing LZ77 encoding, a
sliding window (of windowsize) is used, and all past bytes in that window can be used as
the "dictionary". A brute force search through all possible distances would be slow, and
this hash technique is one out of several ways to speed this up.
*/
static unsigned encodeLZ77(uivector* out, Hash* hash,
const unsigned char* in, size_t inpos, size_t insize, unsigned windowsize,
unsigned minmatch, unsigned nicematch, unsigned lazymatching) {
size_t pos;
unsigned i, error = 0;
/*for large window lengths, assume the user wants no compression loss. Otherwise, max hash chain length speedup.*/
unsigned maxchainlength = windowsize >= 8192 ? windowsize : windowsize / 8;
unsigned maxlazymatch = windowsize >= 8192 ? MAX_SUPPORTED_DEFLATE_LENGTH : 64;
unsigned usezeros = 1; /*not sure if setting it to false for windowsize < 8192 is better or worse*/
unsigned numzeros = 0;
unsigned offset; /*the offset represents the distance in LZ77 terminology*/
unsigned length;
unsigned lazy = 0;
unsigned lazylength = 0, lazyoffset = 0;
unsigned hashval;
unsigned current_offset, current_length;
unsigned prev_offset;
const unsigned char *lastptr, *foreptr, *backptr;
unsigned hashpos;
if(windowsize == 0 || windowsize > 32768) return 60; /*error: windowsize smaller/larger than allowed*/
if((windowsize & (windowsize - 1)) != 0) return 90; /*error: must be power of two*/
if(nicematch > MAX_SUPPORTED_DEFLATE_LENGTH) nicematch = MAX_SUPPORTED_DEFLATE_LENGTH;
for(pos = inpos; pos < insize; ++pos) {
size_t wpos = pos & (windowsize - 1); /*position for in 'circular' hash buffers*/
unsigned chainlength = 0;
hashval = getHash(in, insize, pos);
if(usezeros && hashval == 0) {
if(numzeros == 0) numzeros = countZeros(in, insize, pos);
else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros;
} else {
numzeros = 0;
}
updateHashChain(hash, wpos, hashval, numzeros);
/*the length and offset found for the current position*/
length = 0;
offset = 0;
hashpos = hash->chain[wpos];
lastptr = &in[insize < pos + MAX_SUPPORTED_DEFLATE_LENGTH ? insize : pos + MAX_SUPPORTED_DEFLATE_LENGTH];
/*search for the longest string*/
prev_offset = 0;
for(;;) {
if(chainlength++ >= maxchainlength) break;
current_offset = (unsigned)(hashpos <= wpos ? wpos - hashpos : wpos - hashpos + windowsize);
if(current_offset < prev_offset) break; /*stop when went completely around the circular buffer*/
prev_offset = current_offset;
if(current_offset > 0) {
/*test the next characters*/
foreptr = &in[pos];
backptr = &in[pos - current_offset];
/*common case in PNGs is lots of zeros. Quickly skip over them as a speedup*/
if(numzeros >= 3) {
unsigned skip = hash->zeros[hashpos];
if(skip > numzeros) skip = numzeros;
backptr += skip;
foreptr += skip;
}
while(foreptr != lastptr && *backptr == *foreptr) /*maximum supported length by deflate is max length*/ {
++backptr;
++foreptr;
}
current_length = (unsigned)(foreptr - &in[pos]);
if(current_length > length) {
length = current_length; /*the longest length*/
offset = current_offset; /*the offset that is related to this longest length*/
/*jump out once a length of max length is found (speed gain). This also jumps
out if length is MAX_SUPPORTED_DEFLATE_LENGTH*/
if(current_length >= nicematch) break;
}
}
if(hashpos == hash->chain[hashpos]) break;
if(numzeros >= 3 && length > numzeros) {
hashpos = hash->chainz[hashpos];
if(hash->zeros[hashpos] != numzeros) break;
} else {
hashpos = hash->chain[hashpos];
/*outdated hash value, happens if particular value was not encountered in whole last window*/
if(hash->val[hashpos] != (int)hashval) break;
}
}
if(lazymatching) {
if(!lazy && length >= 3 && length <= maxlazymatch && length < MAX_SUPPORTED_DEFLATE_LENGTH) {
lazy = 1;
lazylength = length;
lazyoffset = offset;
continue; /*try the next byte*/
}
if(lazy) {
lazy = 0;
if(pos == 0) ERROR_BREAK(81);
if(length > lazylength + 1) {
/*push the previous character as literal*/
if(!uivector_push_back(out, in[pos - 1])) ERROR_BREAK(83 /*alloc fail*/);
} else {
length = lazylength;
offset = lazyoffset;
hash->head[hashval] = -1; /*the same hashchain update will be done, this ensures no wrong alteration*/
hash->headz[numzeros] = -1; /*idem*/
--pos;
}
}
}
if(length >= 3 && offset > windowsize) ERROR_BREAK(86 /*too big (or overflown negative) offset*/);
/*encode it as length/distance pair or literal value*/
if(length < 3) /*only lengths of 3 or higher are supported as length/distance pair*/ {
if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/);
} else if(length < minmatch || (length == 3 && offset > 4096)) {
/*compensate for the fact that longer offsets have more extra bits, a
length of only 3 may be not worth it then*/
if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/);
} else {
addLengthDistance(out, length, offset);
for(i = 1; i < length; ++i) {
++pos;
wpos = pos & (windowsize - 1);
hashval = getHash(in, insize, pos);
if(usezeros && hashval == 0) {
if(numzeros == 0) numzeros = countZeros(in, insize, pos);
else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros;
} else {
numzeros = 0;
}
updateHashChain(hash, wpos, hashval, numzeros);
}
}
} /*end of the loop through each character of input*/
return error;
}
/* /////////////////////////////////////////////////////////////////////////// */
static unsigned deflateNoCompression(ucvector* out, const unsigned char* data, size_t datasize) {
/*non compressed deflate block data: 1 bit BFINAL,2 bits BTYPE,(5 bits): it jumps to start of next byte,
2 bytes LEN, 2 bytes NLEN, LEN bytes literal DATA*/
size_t i, j, numdeflateblocks = (datasize + 65534) / 65535;
unsigned datapos = 0;
for(i = 0; i != numdeflateblocks; ++i) {
unsigned BFINAL, BTYPE, LEN, NLEN;
unsigned char firstbyte;
BFINAL = (i == numdeflateblocks - 1);
BTYPE = 0;
firstbyte = (unsigned char)(BFINAL + ((BTYPE & 1) << 1) + ((BTYPE & 2) << 1));
ucvector_push_back(out, firstbyte);
LEN = 65535;
if(datasize - datapos < 65535) LEN = (unsigned)datasize - datapos;
NLEN = 65535 - LEN;
ucvector_push_back(out, (unsigned char)(LEN & 255));
ucvector_push_back(out, (unsigned char)(LEN >> 8));
ucvector_push_back(out, (unsigned char)(NLEN & 255));
ucvector_push_back(out, (unsigned char)(NLEN >> 8));
/*Decompressed data*/
for(j = 0; j < 65535 && datapos < datasize; ++j) {
ucvector_push_back(out, data[datapos++]);
}
}
return 0;
}
/*
write the lz77-encoded data, which has lit, len and dist codes, to compressed stream using huffman trees.
tree_ll: the tree for lit and len codes.
tree_d: the tree for distance codes.
*/
static void writeLZ77data(size_t* bp, ucvector* out, const uivector* lz77_encoded,
const HuffmanTree* tree_ll, const HuffmanTree* tree_d) {
size_t i = 0;
for(i = 0; i != lz77_encoded->size; ++i) {
unsigned val = lz77_encoded->data[i];
addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_ll, val), HuffmanTree_getLength(tree_ll, val));
if(val > 256) /*for a length code, 3 more things have to be added*/ {
unsigned length_index = val - FIRST_LENGTH_CODE_INDEX;
unsigned n_length_extra_bits = LENGTHEXTRA[length_index];
unsigned length_extra_bits = lz77_encoded->data[++i];
unsigned distance_code = lz77_encoded->data[++i];
unsigned distance_index = distance_code;
unsigned n_distance_extra_bits = DISTANCEEXTRA[distance_index];
unsigned distance_extra_bits = lz77_encoded->data[++i];
addBitsToStream(bp, out, length_extra_bits, n_length_extra_bits);
addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_d, distance_code),
HuffmanTree_getLength(tree_d, distance_code));
addBitsToStream(bp, out, distance_extra_bits, n_distance_extra_bits);
}
}
}
/*Deflate for a block of type "dynamic", that is, with freely, optimally, created huffman trees*/
static unsigned deflateDynamic(ucvector* out, size_t* bp, Hash* hash,
const unsigned char* data, size_t datapos, size_t dataend,
const LodePNGCompressSettings* settings, unsigned final) {
unsigned error = 0;
/*
A block is compressed as follows: The PNG data is lz77 encoded, resulting in
literal bytes and length/distance pairs. This is then huffman compressed with
two huffman trees. One huffman tree is used for the lit and len values ("ll"),
another huffman tree is used for the dist values ("d"). These two trees are
stored using their code lengths, and to compress even more these code lengths
are also run-length encoded and huffman compressed. This gives a huffman tree
of code lengths "cl". The code lenghts used to describe this third tree are
the code length code lengths ("clcl").
*/
/*The lz77 encoded data, represented with integers since there will also be length and distance codes in it*/
uivector lz77_encoded;
HuffmanTree tree_ll; /*tree for lit,len values*/
HuffmanTree tree_d; /*tree for distance codes*/
HuffmanTree tree_cl; /*tree for encoding the code lengths representing tree_ll and tree_d*/
uivector frequencies_ll; /*frequency of lit,len codes*/
uivector frequencies_d; /*frequency of dist codes*/
uivector frequencies_cl; /*frequency of code length codes*/
uivector bitlen_lld; /*lit,len,dist code lenghts (int bits), literally (without repeat codes).*/
uivector bitlen_lld_e; /*bitlen_lld encoded with repeat codes (this is a rudemtary run length compression)*/
/*bitlen_cl is the code length code lengths ("clcl"). The bit lengths of codes to represent tree_cl
(these are written as is in the file, it would be crazy to compress these using yet another huffman
tree that needs to be represented by yet another set of code lengths)*/
uivector bitlen_cl;
size_t datasize = dataend - datapos;
/*
Due to the huffman compression of huffman tree representations ("two levels"), there are some anologies:
bitlen_lld is to tree_cl what data is to tree_ll and tree_d.
bitlen_lld_e is to bitlen_lld what lz77_encoded is to data.
bitlen_cl is to bitlen_lld_e what bitlen_lld is to lz77_encoded.
*/
unsigned BFINAL = final;
size_t numcodes_ll, numcodes_d, i;
unsigned HLIT, HDIST, HCLEN;
uivector_init(&lz77_encoded);
HuffmanTree_init(&tree_ll);
HuffmanTree_init(&tree_d);
HuffmanTree_init(&tree_cl);
uivector_init(&frequencies_ll);
uivector_init(&frequencies_d);
uivector_init(&frequencies_cl);
uivector_init(&bitlen_lld);
uivector_init(&bitlen_lld_e);
uivector_init(&bitlen_cl);
/*This while loop never loops due to a break at the end, it is here to
allow breaking out of it to the cleanup phase on error conditions.*/
while(!error) {
if(settings->use_lz77) {
error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize,
settings->minmatch, settings->nicematch, settings->lazymatching);
if(error) break;
} else {
if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83 /*alloc fail*/);
for(i = datapos; i < dataend; ++i) lz77_encoded.data[i - datapos] = data[i]; /*no LZ77, but still will be Huffman compressed*/
}
if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83 /*alloc fail*/);
if(!uivector_resizev(&frequencies_d, 30, 0)) ERROR_BREAK(83 /*alloc fail*/);
/*Count the frequencies of lit, len and dist codes*/
for(i = 0; i != lz77_encoded.size; ++i) {
unsigned symbol = lz77_encoded.data[i];
++frequencies_ll.data[symbol];
if(symbol > 256) {
unsigned dist = lz77_encoded.data[i + 2];
++frequencies_d.data[dist];
i += 3;
}
}
frequencies_ll.data[256] = 1; /*there will be exactly 1 end code, at the end of the block*/
/*Make both huffman trees, one for the lit and len codes, one for the dist codes*/
error = HuffmanTree_makeFromFrequencies(&tree_ll, frequencies_ll.data, 257, frequencies_ll.size, 15);
if(error) break;
/*2, not 1, is chosen for mincodes: some buggy PNG decoders require at least 2 symbols in the dist tree*/
error = HuffmanTree_makeFromFrequencies(&tree_d, frequencies_d.data, 2, frequencies_d.size, 15);
if(error) break;
numcodes_ll = tree_ll.numcodes; if(numcodes_ll > 286) numcodes_ll = 286;
numcodes_d = tree_d.numcodes; if(numcodes_d > 30) numcodes_d = 30;
/*store the code lengths of both generated trees in bitlen_lld*/
for(i = 0; i != numcodes_ll; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_ll, (unsigned)i));
for(i = 0; i != numcodes_d; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_d, (unsigned)i));
/*run-length compress bitlen_ldd into bitlen_lld_e by using repeat codes 16 (copy length 3-6 times),
17 (3-10 zeroes), 18 (11-138 zeroes)*/
for(i = 0; i != (unsigned)bitlen_lld.size; ++i) {
unsigned j = 0; /*amount of repititions*/
while(i + j + 1 < (unsigned)bitlen_lld.size && bitlen_lld.data[i + j + 1] == bitlen_lld.data[i]) ++j;
if(bitlen_lld.data[i] == 0 && j >= 2) /*repeat code for zeroes*/ {
++j; /*include the first zero*/
if(j <= 10) /*repeat code 17 supports max 10 zeroes*/ {
uivector_push_back(&bitlen_lld_e, 17);
uivector_push_back(&bitlen_lld_e, j - 3);
} else /*repeat code 18 supports max 138 zeroes*/ {
if(j > 138) j = 138;
uivector_push_back(&bitlen_lld_e, 18);
uivector_push_back(&bitlen_lld_e, j - 11);
}
i += (j - 1);
} else if(j >= 3) /*repeat code for value other than zero*/ {
size_t k;
unsigned num = j / 6, rest = j % 6;
uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]);
for(k = 0; k < num; ++k) {
uivector_push_back(&bitlen_lld_e, 16);
uivector_push_back(&bitlen_lld_e, 6 - 3);
}
if(rest >= 3) {
uivector_push_back(&bitlen_lld_e, 16);
uivector_push_back(&bitlen_lld_e, rest - 3);
}
else j -= rest;
i += j;
} else /*too short to benefit from repeat code*/ {
uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]);
}
}
/*generate tree_cl, the huffmantree of huffmantrees*/
if(!uivector_resizev(&frequencies_cl, NUM_CODE_LENGTH_CODES, 0)) ERROR_BREAK(83 /*alloc fail*/);
for(i = 0; i != bitlen_lld_e.size; ++i) {
++frequencies_cl.data[bitlen_lld_e.data[i]];
/*after a repeat code come the bits that specify the number of repetitions,
those don't need to be in the frequencies_cl calculation*/
if(bitlen_lld_e.data[i] >= 16) ++i;
}
error = HuffmanTree_makeFromFrequencies(&tree_cl, frequencies_cl.data,
frequencies_cl.size, frequencies_cl.size, 7);
if(error) break;
if(!uivector_resize(&bitlen_cl, tree_cl.numcodes)) ERROR_BREAK(83 /*alloc fail*/);
for(i = 0; i != tree_cl.numcodes; ++i) {
/*lenghts of code length tree is in the order as specified by deflate*/
bitlen_cl.data[i] = HuffmanTree_getLength(&tree_cl, CLCL_ORDER[i]);
}
while(bitlen_cl.data[bitlen_cl.size - 1] == 0 && bitlen_cl.size > 4) {
/*remove zeros at the end, but minimum size must be 4*/
if(!uivector_resize(&bitlen_cl, bitlen_cl.size - 1)) ERROR_BREAK(83 /*alloc fail*/);
}
if(error) break;
/*
Write everything into the output
After the BFINAL and BTYPE, the dynamic block consists out of the following:
- 5 bits HLIT, 5 bits HDIST, 4 bits HCLEN
- (HCLEN+4)*3 bits code lengths of code length alphabet
- HLIT + 257 code lenghts of lit/length alphabet (encoded using the code length
alphabet, + possible repetition codes 16, 17, 18)
- HDIST + 1 code lengths of distance alphabet (encoded using the code length
alphabet, + possible repetition codes 16, 17, 18)
- compressed data
- 256 (end code)
*/
/*Write block type*/
addBitToStream(bp, out, BFINAL);
addBitToStream(bp, out, 0); /*first bit of BTYPE "dynamic"*/
addBitToStream(bp, out, 1); /*second bit of BTYPE "dynamic"*/
/*write the HLIT, HDIST and HCLEN values*/
HLIT = (unsigned)(numcodes_ll - 257);
HDIST = (unsigned)(numcodes_d - 1);
HCLEN = (unsigned)bitlen_cl.size - 4;
/*trim zeroes for HCLEN. HLIT and HDIST were already trimmed at tree creation*/
while(!bitlen_cl.data[HCLEN + 4 - 1] && HCLEN > 0) --HCLEN;
addBitsToStream(bp, out, HLIT, 5);
addBitsToStream(bp, out, HDIST, 5);
addBitsToStream(bp, out, HCLEN, 4);
/*write the code lenghts of the code length alphabet*/
for(i = 0; i != HCLEN + 4; ++i) addBitsToStream(bp, out, bitlen_cl.data[i], 3);
/*write the lenghts of the lit/len AND the dist alphabet*/
for(i = 0; i != bitlen_lld_e.size; ++i) {
addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_cl, bitlen_lld_e.data[i]),
HuffmanTree_getLength(&tree_cl, bitlen_lld_e.data[i]));
/*extra bits of repeat codes*/
if(bitlen_lld_e.data[i] == 16) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 2);
else if(bitlen_lld_e.data[i] == 17) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 3);
else if(bitlen_lld_e.data[i] == 18) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 7);
}
/*write the compressed data symbols*/
writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d);
/*error: the length of the end code 256 must be larger than 0*/
if(HuffmanTree_getLength(&tree_ll, 256) == 0) ERROR_BREAK(64);
/*write the end code*/
addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256));
break; /*end of error-while*/
}
/*cleanup*/
uivector_cleanup(&lz77_encoded);
HuffmanTree_cleanup(&tree_ll);
HuffmanTree_cleanup(&tree_d);
HuffmanTree_cleanup(&tree_cl);
uivector_cleanup(&frequencies_ll);
uivector_cleanup(&frequencies_d);
uivector_cleanup(&frequencies_cl);
uivector_cleanup(&bitlen_lld_e);
uivector_cleanup(&bitlen_lld);
uivector_cleanup(&bitlen_cl);
return error;
}
static unsigned deflateFixed(ucvector* out, size_t* bp, Hash* hash,
const unsigned char* data,
size_t datapos, size_t dataend,
const LodePNGCompressSettings* settings, unsigned final) {
HuffmanTree tree_ll; /*tree for literal values and length codes*/
HuffmanTree tree_d; /*tree for distance codes*/
unsigned BFINAL = final;
unsigned error = 0;
size_t i;
HuffmanTree_init(&tree_ll);
HuffmanTree_init(&tree_d);
generateFixedLitLenTree(&tree_ll);
generateFixedDistanceTree(&tree_d);
addBitToStream(bp, out, BFINAL);
addBitToStream(bp, out, 1); /*first bit of BTYPE*/
addBitToStream(bp, out, 0); /*second bit of BTYPE*/
if(settings->use_lz77) /*LZ77 encoded*/ {
uivector lz77_encoded;
uivector_init(&lz77_encoded);
error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize,
settings->minmatch, settings->nicematch, settings->lazymatching);
if(!error) writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d);
uivector_cleanup(&lz77_encoded);
} else /*no LZ77, but still will be Huffman compressed*/ {
for(i = datapos; i < dataend; ++i) {
addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, data[i]), HuffmanTree_getLength(&tree_ll, data[i]));
}
}
/*add END code*/
if(!error) addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256));
/*cleanup*/
HuffmanTree_cleanup(&tree_ll);
HuffmanTree_cleanup(&tree_d);
return error;
}
static unsigned lodepng_deflatev(ucvector* out, const unsigned char* in, size_t insize,
const LodePNGCompressSettings* settings) {
unsigned error = 0;
size_t i, blocksize, numdeflateblocks;
size_t bp = 0; /*the bit pointer*/
Hash hash;
if(settings->btype > 2) return 61;
else if(settings->btype == 0) return deflateNoCompression(out, in, insize);
else if(settings->btype == 1) blocksize = insize;
else /*if(settings->btype == 2)*/ {
/*on PNGs, deflate blocks of 65-262k seem to give most dense encoding*/
blocksize = insize / 8 + 8;
if(blocksize < 65536) blocksize = 65536;
if(blocksize > 262144) blocksize = 262144;
}
numdeflateblocks = (insize + blocksize - 1) / blocksize;
if(numdeflateblocks == 0) numdeflateblocks = 1;
error = hash_init(&hash, settings->windowsize);
if(error) return error;
for(i = 0; i != numdeflateblocks && !error; ++i) {
unsigned final = (i == numdeflateblocks - 1);
size_t start = i * blocksize;
size_t end = start + blocksize;
if(end > insize) end = insize;
if(settings->btype == 1) error = deflateFixed(out, &bp, &hash, in, start, end, settings, final);
else if(settings->btype == 2) error = deflateDynamic(out, &bp, &hash, in, start, end, settings, final);
}
hash_cleanup(&hash);
return error;
}
unsigned lodepng_deflate(unsigned char** out, size_t* outsize,
const unsigned char* in, size_t insize,
const LodePNGCompressSettings* settings) {
unsigned error;
ucvector v;
ucvector_init_buffer(&v, *out, *outsize);
error = lodepng_deflatev(&v, in, insize, settings);
*out = v.data;
*outsize = v.size;
return error;
}
static unsigned deflate(unsigned char** out, size_t* outsize,
const unsigned char* in, size_t insize,
const LodePNGCompressSettings* settings) {
if(settings->custom_deflate) {
return settings->custom_deflate(out, outsize, in, insize, settings);
} else {
return lodepng_deflate(out, outsize, in, insize, settings);
}
}
#endif /*LODEPNG_COMPILE_DECODER*/
/* ////////////////////////////////////////////////////////////////////////// */
/* / Adler32 */
/* ////////////////////////////////////////////////////////////////////////// */
static unsigned update_adler32(unsigned adler, const unsigned char* data, unsigned len) {
unsigned s1 = adler & 0xffff;
unsigned s2 = (adler >> 16) & 0xffff;
while(len > 0) {
/*at least 5552 sums can be done before the sums overflow, saving a lot of module divisions*/
unsigned amount = len > 5552 ? 5552 : len;
len -= amount;
while(amount > 0) {
s1 += (*data++);
s2 += s1;
--amount;
}
s1 %= 65521;
s2 %= 65521;
}
return (s2 << 16) | s1;
}
/*Return the adler32 of the bytes data[0..len-1]*/
static unsigned adler32(const unsigned char* data, unsigned len) {
return update_adler32(1L, data, len);
}
/* ////////////////////////////////////////////////////////////////////////// */
/* / Zlib / */
/* ////////////////////////////////////////////////////////////////////////// */
#ifdef LODEPNG_COMPILE_DECODER
unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
size_t insize, const LodePNGDecompressSettings* settings) {
unsigned error = 0;
unsigned CM, CINFO, FDICT;
if(insize < 2) return 53; /*error, size of zlib data too small*/
/*read information from zlib header*/
if((in[0] * 256 + in[1]) % 31 != 0) {
/*error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way*/
return 24;
}
CM = in[0] & 15;
CINFO = (in[0] >> 4) & 15;
/*FCHECK = in[1] & 31;*/ /*FCHECK is already tested above*/
FDICT = (in[1] >> 5) & 1;
/*FLEVEL = (in[1] >> 6) & 3;*/ /*FLEVEL is not used here*/
if(CM != 8 || CINFO > 7) {
/*error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec*/
return 25;
}
if(FDICT != 0) {
/*error: the specification of PNG says about the zlib stream:
"The additional flags shall not specify a preset dictionary."*/
return 26;
}
error = inflate(out, outsize, in + 2, insize - 2, settings);
if(error) return error;
if(!settings->ignore_adler32) {
unsigned ADLER32 = lodepng_read32bitInt(&in[insize - 4]);
unsigned checksum = adler32(*out, (unsigned)(*outsize));
if(checksum != ADLER32) return 58; /*error, adler checksum not correct, data must be corrupted*/
}
return 0; /*no error*/
}
static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
size_t insize, const LodePNGDecompressSettings* settings) {
if(settings->custom_zlib) {
return settings->custom_zlib(out, outsize, in, insize, settings);
} else {
return lodepng_zlib_decompress(out, outsize, in, insize, settings);
}
}
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
size_t insize, const LodePNGCompressSettings* settings) {
/*initially, *out must be NULL and outsize 0, if you just give some random *out
that's pointing to a non allocated buffer, this'll crash*/
ucvector outv;
size_t i;
unsigned error;
unsigned char* deflatedata = 0;
size_t deflatesize = 0;
/*zlib data: 1 byte CMF (CM+CINFO), 1 byte FLG, deflate data, 4 byte ADLER32 checksum of the Decompressed data*/
unsigned CMF = 120; /*0b01111000: CM 8, CINFO 7. With CINFO 7, any window size up to 32768 can be used.*/
unsigned FLEVEL = 0;
unsigned FDICT = 0;
unsigned CMFFLG = 256 * CMF + FDICT * 32 + FLEVEL * 64;
unsigned FCHECK = 31 - CMFFLG % 31;
CMFFLG += FCHECK;
/*ucvector-controlled version of the output buffer, for dynamic array*/
ucvector_init_buffer(&outv, *out, *outsize);
ucvector_push_back(&outv, (unsigned char)(CMFFLG >> 8));
ucvector_push_back(&outv, (unsigned char)(CMFFLG & 255));
error = deflate(&deflatedata, &deflatesize, in, insize, settings);
if(!error) {
unsigned ADLER32 = adler32(in, (unsigned)insize);
for(i = 0; i != deflatesize; ++i) ucvector_push_back(&outv, deflatedata[i]);
lodepng_free(deflatedata);
lodepng_add32bitInt(&outv, ADLER32);
}
*out = outv.data;
*outsize = outv.size;
return error;
}
/* compress using the default or custom zlib function */
static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
size_t insize, const LodePNGCompressSettings* settings) {
if(settings->custom_zlib) {
return settings->custom_zlib(out, outsize, in, insize, settings);
} else {
return lodepng_zlib_compress(out, outsize, in, insize, settings);
}
}
#endif /*LODEPNG_COMPILE_ENCODER*/
#else /*no LODEPNG_COMPILE_ZLIB*/
#ifdef LODEPNG_COMPILE_DECODER
static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in,
size_t insize, const LodePNGDecompressSettings* settings) {
if(!settings->custom_zlib) return 87; /*no custom zlib function provided */
return settings->custom_zlib(out, outsize, in, insize, settings);
}
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in,
size_t insize, const LodePNGCompressSettings* settings) {
if(!settings->custom_zlib) return 87; /*no custom zlib function provided */
return settings->custom_zlib(out, outsize, in, insize, settings);
}
#endif /*LODEPNG_COMPILE_ENCODER*/
#endif /*LODEPNG_COMPILE_ZLIB*/
/* ////////////////////////////////////////////////////////////////////////// */
#ifdef LODEPNG_COMPILE_ENCODER
/*this is a good tradeoff between speed and compression ratio*/
#define DEFAULT_WINDOWSIZE 2048
void lodepng_compress_settings_init(LodePNGCompressSettings* settings) {
/*compress with dynamic huffman tree (not in the mathematical sense, just not the predefined one)*/
settings->btype = 2;
settings->use_lz77 = 1;
settings->windowsize = DEFAULT_WINDOWSIZE;
settings->minmatch = 3;
settings->nicematch = 128;
settings->lazymatching = 1;
settings->custom_zlib = 0;
settings->custom_deflate = 0;
settings->custom_context = 0;
}
const LodePNGCompressSettings lodepng_default_compress_settings = {2, 1, DEFAULT_WINDOWSIZE, 3, 128, 1, 0, 0, 0};
#endif /*LODEPNG_COMPILE_ENCODER*/
#ifdef LODEPNG_COMPILE_DECODER
void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings) {
settings->ignore_adler32 = 0;
settings->custom_zlib = 0;
settings->custom_inflate = 0;
settings->custom_context = 0;
}
const LodePNGDecompressSettings lodepng_default_decompress_settings = {0, 0, 0, 0};
#endif /*LODEPNG_COMPILE_DECODER*/
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
/* // End of Zlib related code. Begin of PNG related code. // */
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
#ifdef LODEPNG_COMPILE_PNG
/* ////////////////////////////////////////////////////////////////////////// */
/* / CRC32 / */
/* ////////////////////////////////////////////////////////////////////////// */
#ifndef LODEPNG_NO_COMPILE_CRC
/* CRC polynomial: 0xedb88320 */
static unsigned lodepng_crc32_table[256] = {
0u, 1996959894u, 3993919788u, 2567524794u, 124634137u, 1886057615u, 3915621685u, 2657392035u,
249268274u, 2044508324u, 3772115230u, 2547177864u, 162941995u, 2125561021u, 3887607047u, 2428444049u,
498536548u, 1789927666u, 4089016648u, 2227061214u, 450548861u, 1843258603u, 4107580753u, 2211677639u,
325883990u, 1684777152u, 4251122042u, 2321926636u, 335633487u, 1661365465u, 4195302755u, 2366115317u,
997073096u, 1281953886u, 3579855332u, 2724688242u, 1006888145u, 1258607687u, 3524101629u, 2768942443u,
901097722u, 1119000684u, 3686517206u, 2898065728u, 853044451u, 1172266101u, 3705015759u, 2882616665u,
651767980u, 1373503546u, 3369554304u, 3218104598u, 565507253u, 1454621731u, 3485111705u, 3099436303u,
671266974u, 1594198024u, 3322730930u, 2970347812u, 795835527u, 1483230225u, 3244367275u, 3060149565u,
1994146192u, 31158534u, 2563907772u, 4023717930u, 1907459465u, 112637215u, 2680153253u, 3904427059u,
2013776290u, 251722036u, 2517215374u, 3775830040u, 2137656763u, 141376813u, 2439277719u, 3865271297u,
1802195444u, 476864866u, 2238001368u, 4066508878u, 1812370925u, 453092731u, 2181625025u, 4111451223u,
1706088902u, 314042704u, 2344532202u, 4240017532u, 1658658271u, 366619977u, 2362670323u, 4224994405u,
1303535960u, 984961486u, 2747007092u, 3569037538u, 1256170817u, 1037604311u, 2765210733u, 3554079995u,
1131014506u, 879679996u, 2909243462u, 3663771856u, 1141124467u, 855842277u, 2852801631u, 3708648649u,
1342533948u, 654459306u, 3188396048u, 3373015174u, 1466479909u, 544179635u, 3110523913u, 3462522015u,
1591671054u, 702138776u, 2966460450u, 3352799412u, 1504918807u, 783551873u, 3082640443u, 3233442989u,
3988292384u, 2596254646u, 62317068u, 1957810842u, 3939845945u, 2647816111u, 81470997u, 1943803523u,
3814918930u, 2489596804u, 225274430u, 2053790376u, 3826175755u, 2466906013u, 167816743u, 2097651377u,
4027552580u, 2265490386u, 503444072u, 1762050814u, 4150417245u, 2154129355u, 426522225u, 1852507879u,
4275313526u, 2312317920u, 282753626u, 1742555852u, 4189708143u, 2394877945u, 397917763u, 1622183637u,
3604390888u, 2714866558u, 953729732u, 1340076626u, 3518719985u, 2797360999u, 1068828381u, 1219638859u,
3624741850u, 2936675148u, 906185462u, 1090812512u, 3747672003u, 2825379669u, 829329135u, 1181335161u,
3412177804u, 3160834842u, 628085408u, 1382605366u, 3423369109u, 3138078467u, 570562233u, 1426400815u,
3317316542u, 2998733608u, 733239954u, 1555261956u, 3268935591u, 3050360625u, 752459403u, 1541320221u,
2607071920u, 3965973030u, 1969922972u, 40735498u, 2617837225u, 3943577151u, 1913087877u, 83908371u,
2512341634u, 3803740692u, 2075208622u, 213261112u, 2463272603u, 3855990285u, 2094854071u, 198958881u,
2262029012u, 4057260610u, 1759359992u, 534414190u, 2176718541u, 4139329115u, 1873836001u, 414664567u,
2282248934u, 4279200368u, 1711684554u, 285281116u, 2405801727u, 4167216745u, 1634467795u, 376229701u,
2685067896u, 3608007406u, 1308918612u, 956543938u, 2808555105u, 3495958263u, 1231636301u, 1047427035u,
2932959818u, 3654703836u, 1088359270u, 936918000u, 2847714899u, 3736837829u, 1202900863u, 817233897u,
3183342108u, 3401237130u, 1404277552u, 615818150u, 3134207493u, 3453421203u, 1423857449u, 601450431u,
3009837614u, 3294710456u, 1567103746u, 711928724u, 3020668471u, 3272380065u, 1510334235u, 755167117u
};
/*Return the CRC of the bytes buf[0..len-1].*/
unsigned lodepng_crc32(const unsigned char* data, size_t length) {
unsigned r = 0xffffffffu;
size_t i;
for(i = 0; i < length; ++i) {
r = lodepng_crc32_table[(r ^ data[i]) & 0xff] ^ (r >> 8);
}
return r ^ 0xffffffffu;
}
#else /* !LODEPNG_NO_COMPILE_CRC */
unsigned lodepng_crc32(const unsigned char* data, size_t length);
#endif /* !LODEPNG_NO_COMPILE_CRC */
/* ////////////////////////////////////////////////////////////////////////// */
/* / Reading and writing single bits and bytes from/to stream for LodePNG / */
/* ////////////////////////////////////////////////////////////////////////// */
static unsigned char readBitFromReversedStream(size_t* bitpointer, const unsigned char* bitstream) {
unsigned char result = (unsigned char)((bitstream[(*bitpointer) >> 3] >> (7 - ((*bitpointer) & 0x7))) & 1);
++(*bitpointer);
return result;
}
static unsigned readBitsFromReversedStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits) {
unsigned result = 0;
size_t i;
for(i = 0 ; i < nbits; ++i) {
result <<= 1;
result |= (unsigned)readBitFromReversedStream(bitpointer, bitstream);
}
return result;
}
#ifdef LODEPNG_COMPILE_DECODER
static void setBitOfReversedStream0(size_t* bitpointer, unsigned char* bitstream, unsigned char bit) {
/*the current bit in bitstream must be 0 for this to work*/
if(bit) {
/*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/
bitstream[(*bitpointer) >> 3] |= (bit << (7 - ((*bitpointer) & 0x7)));
}
++(*bitpointer);
}
#endif /*LODEPNG_COMPILE_DECODER*/
static void setBitOfReversedStream(size_t* bitpointer, unsigned char* bitstream, unsigned char bit) {
/*the current bit in bitstream may be 0 or 1 for this to work*/
if(bit == 0) bitstream[(*bitpointer) >> 3] &= (unsigned char)(~(1 << (7 - ((*bitpointer) & 0x7))));
else bitstream[(*bitpointer) >> 3] |= (1 << (7 - ((*bitpointer) & 0x7)));
++(*bitpointer);
}
/* ////////////////////////////////////////////////////////////////////////// */
/* / PNG chunks / */
/* ////////////////////////////////////////////////////////////////////////// */
unsigned lodepng_chunk_length(const unsigned char* chunk) {
return lodepng_read32bitInt(&chunk[0]);
}
void lodepng_chunk_type(char type[5], const unsigned char* chunk) {
unsigned i;
for(i = 0; i != 4; ++i) type[i] = (char)chunk[4 + i];
type[4] = 0; /*null termination char*/
}
unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type) {
if(strlen(type) != 4) return 0;
return (chunk[4] == type[0] && chunk[5] == type[1] && chunk[6] == type[2] && chunk[7] == type[3]);
}
unsigned char lodepng_chunk_ancillary(const unsigned char* chunk) {
return((chunk[4] & 32) != 0);
}
unsigned char lodepng_chunk_private(const unsigned char* chunk) {
return((chunk[6] & 32) != 0);
}
unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk) {
return((chunk[7] & 32) != 0);
}
unsigned char* lodepng_chunk_data(unsigned char* chunk) {
return &chunk[8];
}
const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk) {
return &chunk[8];
}
unsigned lodepng_chunk_check_crc(const unsigned char* chunk) {
unsigned length = lodepng_chunk_length(chunk);
unsigned CRC = lodepng_read32bitInt(&chunk[length + 8]);
/*the CRC is taken of the data and the 4 chunk type letters, not the length*/
unsigned checksum = lodepng_crc32(&chunk[4], length + 4);
if(CRC != checksum) return 1;
else return 0;
}
void lodepng_chunk_generate_crc(unsigned char* chunk) {
unsigned length = lodepng_chunk_length(chunk);
unsigned CRC = lodepng_crc32(&chunk[4], length + 4);
lodepng_set32bitInt(chunk + 8 + length, CRC);
}
unsigned char* lodepng_chunk_next(unsigned char* chunk) {
if(chunk[0] == 0x89 && chunk[1] == 0x50 && chunk[2] == 0x4e && chunk[3] == 0x47
&& chunk[4] == 0x0d && chunk[5] == 0x0a && chunk[6] == 0x1a && chunk[7] == 0x0a) {
/* Is PNG magic header at start of PNG file. Jump to first actual chunk. */
return chunk + 8;
} else {
unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
return chunk + total_chunk_length;
}
}
const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk) {
if(chunk[0] == 0x89 && chunk[1] == 0x50 && chunk[2] == 0x4e && chunk[3] == 0x47
&& chunk[4] == 0x0d && chunk[5] == 0x0a && chunk[6] == 0x1a && chunk[7] == 0x0a) {
/* Is PNG magic header at start of PNG file. Jump to first actual chunk. */
return chunk + 8;
} else {
unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
return chunk + total_chunk_length;
}
}
unsigned char* lodepng_chunk_find(unsigned char* chunk, const unsigned char* end, const char type[5]) {
for(;;) {
if(chunk + 12 >= end) return 0;
if(lodepng_chunk_type_equals(chunk, type)) return chunk;
chunk = lodepng_chunk_next(chunk);
}
}
const unsigned char* lodepng_chunk_find_const(const unsigned char* chunk, const unsigned char* end, const char type[5]) {
for(;;) {
if(chunk + 12 >= end) return 0;
if(lodepng_chunk_type_equals(chunk, type)) return chunk;
chunk = lodepng_chunk_next_const(chunk);
}
}
unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk) {
unsigned i;
unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
unsigned char *chunk_start, *new_buffer;
size_t new_length = (*outlength) + total_chunk_length;
if(new_length < total_chunk_length || new_length < (*outlength)) return 77; /*integer overflow happened*/
new_buffer = (unsigned char*)lodepng_realloc(*out, new_length);
if(!new_buffer) return 83; /*alloc fail*/
(*out) = new_buffer;
(*outlength) = new_length;
chunk_start = &(*out)[new_length - total_chunk_length];
for(i = 0; i != total_chunk_length; ++i) chunk_start[i] = chunk[i];
return 0;
}
unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length,
const char* type, const unsigned char* data) {
unsigned i;
unsigned char *chunk, *new_buffer;
size_t new_length = (*outlength) + length + 12;
if(new_length < length + 12 || new_length < (*outlength)) return 77; /*integer overflow happened*/
new_buffer = (unsigned char*)lodepng_realloc(*out, new_length);
if(!new_buffer) return 83; /*alloc fail*/
(*out) = new_buffer;
(*outlength) = new_length;
chunk = &(*out)[(*outlength) - length - 12];
/*1: length*/
lodepng_set32bitInt(chunk, (unsigned)length);
/*2: chunk name (4 letters)*/
chunk[4] = (unsigned char)type[0];
chunk[5] = (unsigned char)type[1];
chunk[6] = (unsigned char)type[2];
chunk[7] = (unsigned char)type[3];
/*3: the data*/
for(i = 0; i != length; ++i) chunk[8 + i] = data[i];
/*4: CRC (of the chunkname characters and the data)*/
lodepng_chunk_generate_crc(chunk);
return 0;
}
/* ////////////////////////////////////////////////////////////////////////// */
/* / Color types and such / */
/* ////////////////////////////////////////////////////////////////////////// */
/*return type is a LodePNG error code*/
static unsigned checkColorValidity(LodePNGColorType colortype, unsigned bd) /*bd = bitdepth*/ {
switch(colortype) {
case 0: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37; break; /*gray*/
case 2: if(!( bd == 8 || bd == 16)) return 37; break; /*RGB*/
case 3: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 )) return 37; break; /*palette*/
case 4: if(!( bd == 8 || bd == 16)) return 37; break; /*gray + alpha*/
case 6: if(!( bd == 8 || bd == 16)) return 37; break; /*RGBA*/
default: return 31;
}
return 0; /*allowed color type / bits combination*/
}
static unsigned getNumColorChannels(LodePNGColorType colortype) {
switch(colortype) {
case 0: return 1; /*gray*/
case 2: return 3; /*RGB*/
case 3: return 1; /*palette*/
case 4: return 2; /*gray + alpha*/
case 6: return 4; /*RGBA*/
}
return 0; /*unexisting color type*/
}
static unsigned lodepng_get_bpp_lct(LodePNGColorType colortype, unsigned bitdepth) {
/*bits per pixel is amount of channels * bits per channel*/
return getNumColorChannels(colortype) * bitdepth;
}
/* ////////////////////////////////////////////////////////////////////////// */
void lodepng_color_mode_init(LodePNGColorMode* info) {
info->key_defined = 0;
info->key_r = info->key_g = info->key_b = 0;
info->colortype = LCT_RGBA;
info->bitdepth = 8;
info->palette = 0;
info->palettesize = 0;
}
void lodepng_color_mode_cleanup(LodePNGColorMode* info) {
lodepng_palette_clear(info);
}
unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source) {
size_t i;
lodepng_color_mode_cleanup(dest);
*dest = *source;
if(source->palette) {
dest->palette = (unsigned char*)lodepng_malloc(1024);
if(!dest->palette && source->palettesize) return 83; /*alloc fail*/
for(i = 0; i != source->palettesize * 4; ++i) dest->palette[i] = source->palette[i];
}
return 0;
}
LodePNGColorMode lodepng_color_mode_make(LodePNGColorType colortype, unsigned bitdepth) {
LodePNGColorMode result;
lodepng_color_mode_init(&result);
result.colortype = colortype;
result.bitdepth = bitdepth;
return result;
}
static int lodepng_color_mode_equal(const LodePNGColorMode* a, const LodePNGColorMode* b) {
size_t i;
if(a->colortype != b->colortype) return 0;
if(a->bitdepth != b->bitdepth) return 0;
if(a->key_defined != b->key_defined) return 0;
if(a->key_defined) {
if(a->key_r != b->key_r) return 0;
if(a->key_g != b->key_g) return 0;
if(a->key_b != b->key_b) return 0;
}
if(a->palettesize != b->palettesize) return 0;
for(i = 0; i != a->palettesize * 4; ++i) {
if(a->palette[i] != b->palette[i]) return 0;
}
return 1;
}
void lodepng_palette_clear(LodePNGColorMode* info) {
if(info->palette) lodepng_free(info->palette);
info->palette = 0;
info->palettesize = 0;
}
unsigned lodepng_palette_add(LodePNGColorMode* info,
unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
unsigned char* data;
/*the same resize technique as C++ std::vectors is used, and here it's made so that for a palette with
the max of 256 colors, it'll have the exact alloc size*/
if(!info->palette) /*allocate palette if empty*/ {
/*room for 256 colors with 4 bytes each*/
data = (unsigned char*)lodepng_realloc(info->palette, 1024);
if(!data) return 83; /*alloc fail*/
else info->palette = data;
}
info->palette[4 * info->palettesize + 0] = r;
info->palette[4 * info->palettesize + 1] = g;
info->palette[4 * info->palettesize + 2] = b;
info->palette[4 * info->palettesize + 3] = a;
++info->palettesize;
return 0;
}
/*calculate bits per pixel out of colortype and bitdepth*/
unsigned lodepng_get_bpp(const LodePNGColorMode* info) {
return lodepng_get_bpp_lct(info->colortype, info->bitdepth);
}
unsigned lodepng_get_channels(const LodePNGColorMode* info) {
return getNumColorChannels(info->colortype);
}
unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info) {
return info->colortype == LCT_GREY || info->colortype == LCT_GREY_ALPHA;
}
unsigned lodepng_is_alpha_type(const LodePNGColorMode* info) {
return (info->colortype & 4) != 0; /*4 or 6*/
}
unsigned lodepng_is_palette_type(const LodePNGColorMode* info) {
return info->colortype == LCT_PALETTE;
}
unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info) {
size_t i;
for(i = 0; i != info->palettesize; ++i) {
if(info->palette[i * 4 + 3] < 255) return 1;
}
return 0;
}
unsigned lodepng_can_have_alpha(const LodePNGColorMode* info) {
return info->key_defined
|| lodepng_is_alpha_type(info)
|| lodepng_has_palette_alpha(info);
}
size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) {
size_t bpp = lodepng_get_bpp_lct(colortype, bitdepth);
size_t n = (size_t)w * (size_t)h;
return ((n / 8) * bpp) + ((n & 7) * bpp + 7) / 8;
}
size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color) {
return lodepng_get_raw_size_lct(w, h, color->colortype, color->bitdepth);
}
#ifdef LODEPNG_COMPILE_PNG
#ifdef LODEPNG_COMPILE_DECODER
/*in an idat chunk, each scanline is a multiple of 8 bits, unlike the lodepng output buffer,
and in addition has one extra byte per line: the filter byte. So this gives a larger
result than lodepng_get_raw_size. */
static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, const LodePNGColorMode* color) {
size_t bpp = lodepng_get_bpp(color);
/* + 1 for the filter byte, and possibly plus padding bits per line */
size_t line = ((size_t)(w / 8) * bpp) + 1 + ((w & 7) * bpp + 7) / 8;
return (size_t)h * line;
}
/* Safely check if multiplying two integers will overflow (no undefined
behavior, compiler removing the code, etc...) and output result. */
static int lodepng_mulofl(size_t a, size_t b, size_t* result) {
*result = a * b; /* Unsigned multiplication is well defined and safe in C90 */
return (a != 0 && *result / a != b);
}
/* Safely check if adding two integers will overflow (no undefined
behavior, compiler removing the code, etc...) and output result. */
static int lodepng_addofl(size_t a, size_t b, size_t* result) {
*result = a + b; /* Unsigned addition is well defined and safe in C90 */
return *result < a;
}
/*Safely checks whether size_t overflow can be caused due to amount of pixels.
This check is overcautious rather than precise. If this check indicates no overflow,
you can safely compute in a size_t (but not an unsigned):
-(size_t)w * (size_t)h * 8
-amount of bytes in IDAT (including filter, padding and Adam7 bytes)
-amount of bytes in raw color model
Returns 1 if overflow possible, 0 if not.
*/
static int lodepng_pixel_overflow(unsigned w, unsigned h,
const LodePNGColorMode* pngcolor, const LodePNGColorMode* rawcolor) {
size_t bpp = LODEPNG_MAX(lodepng_get_bpp(pngcolor), lodepng_get_bpp(rawcolor));
size_t numpixels, total;
size_t line; /* bytes per line in worst case */
if(lodepng_mulofl((size_t)w, (size_t)h, &numpixels)) return 1;
if(lodepng_mulofl(numpixels, 8, &total)) return 1; /* bit pointer with 8-bit color, or 8 bytes per channel color */
/* Bytes per scanline with the expression "(w / 8) * bpp) + ((w & 7) * bpp + 7) / 8" */
if(lodepng_mulofl((size_t)(w / 8), bpp, &line)) return 1;
if(lodepng_addofl(line, ((w & 7) * bpp + 7) / 8, &line)) return 1;
if(lodepng_addofl(line, 5, &line)) return 1; /* 5 bytes overhead per line: 1 filterbyte, 4 for Adam7 worst case */
if(lodepng_mulofl(line, h, &total)) return 1; /* Total bytes in worst case */
return 0; /* no overflow */
}
#endif /*LODEPNG_COMPILE_DECODER*/
#endif /*LODEPNG_COMPILE_PNG*/
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
static void LodePNGUnknownChunks_init(LodePNGInfo* info) {
unsigned i;
for(i = 0; i != 3; ++i) info->unknown_chunks_data[i] = 0;
for(i = 0; i != 3; ++i) info->unknown_chunks_size[i] = 0;
}
static void LodePNGUnknownChunks_cleanup(LodePNGInfo* info) {
unsigned i;
for(i = 0; i != 3; ++i) lodepng_free(info->unknown_chunks_data[i]);
}
static unsigned LodePNGUnknownChunks_copy(LodePNGInfo* dest, const LodePNGInfo* src) {
unsigned i;
LodePNGUnknownChunks_cleanup(dest);
for(i = 0; i != 3; ++i) {
size_t j;
dest->unknown_chunks_size[i] = src->unknown_chunks_size[i];
dest->unknown_chunks_data[i] = (unsigned char*)lodepng_malloc(src->unknown_chunks_size[i]);
if(!dest->unknown_chunks_data[i] && dest->unknown_chunks_size[i]) return 83; /*alloc fail*/
for(j = 0; j < src->unknown_chunks_size[i]; ++j) {
dest->unknown_chunks_data[i][j] = src->unknown_chunks_data[i][j];
}
}
return 0;
}
/******************************************************************************/
static void LodePNGText_init(LodePNGInfo* info) {
info->text_num = 0;
info->text_keys = NULL;
info->text_strings = NULL;
}
static void LodePNGText_cleanup(LodePNGInfo* info) {
size_t i;
for(i = 0; i != info->text_num; ++i) {
string_cleanup(&info->text_keys[i]);
string_cleanup(&info->text_strings[i]);
}
lodepng_free(info->text_keys);
lodepng_free(info->text_strings);
}
static unsigned LodePNGText_copy(LodePNGInfo* dest, const LodePNGInfo* source) {
size_t i = 0;
dest->text_keys = 0;
dest->text_strings = 0;
dest->text_num = 0;
for(i = 0; i != source->text_num; ++i) {
CERROR_TRY_RETURN(lodepng_add_text(dest, source->text_keys[i], source->text_strings[i]));
}
return 0;
}
void lodepng_clear_text(LodePNGInfo* info) {
LodePNGText_cleanup(info);
}
unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str) {
char** new_keys = (char**)(lodepng_realloc(info->text_keys, sizeof(char*) * (info->text_num + 1)));
char** new_strings = (char**)(lodepng_realloc(info->text_strings, sizeof(char*) * (info->text_num + 1)));
if(!new_keys || !new_strings) {
lodepng_free(new_keys);
lodepng_free(new_strings);
return 83; /*alloc fail*/
}
++info->text_num;
info->text_keys = new_keys;
info->text_strings = new_strings;
info->text_keys[info->text_num - 1] = alloc_string(key);
info->text_strings[info->text_num - 1] = alloc_string(str);
return 0;
}
/******************************************************************************/
static void LodePNGIText_init(LodePNGInfo* info) {
info->itext_num = 0;
info->itext_keys = NULL;
info->itext_langtags = NULL;
info->itext_transkeys = NULL;
info->itext_strings = NULL;
}
static void LodePNGIText_cleanup(LodePNGInfo* info) {
size_t i;
for(i = 0; i != info->itext_num; ++i) {
string_cleanup(&info->itext_keys[i]);
string_cleanup(&info->itext_langtags[i]);
string_cleanup(&info->itext_transkeys[i]);
string_cleanup(&info->itext_strings[i]);
}
lodepng_free(info->itext_keys);
lodepng_free(info->itext_langtags);
lodepng_free(info->itext_transkeys);
lodepng_free(info->itext_strings);
}
static unsigned LodePNGIText_copy(LodePNGInfo* dest, const LodePNGInfo* source) {
size_t i = 0;
dest->itext_keys = 0;
dest->itext_langtags = 0;
dest->itext_transkeys = 0;
dest->itext_strings = 0;
dest->itext_num = 0;
for(i = 0; i != source->itext_num; ++i) {
CERROR_TRY_RETURN(lodepng_add_itext(dest, source->itext_keys[i], source->itext_langtags[i],
source->itext_transkeys[i], source->itext_strings[i]));
}
return 0;
}
void lodepng_clear_itext(LodePNGInfo* info) {
LodePNGIText_cleanup(info);
}
unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag,
const char* transkey, const char* str) {
char** new_keys = (char**)(lodepng_realloc(info->itext_keys, sizeof(char*) * (info->itext_num + 1)));
char** new_langtags = (char**)(lodepng_realloc(info->itext_langtags, sizeof(char*) * (info->itext_num + 1)));
char** new_transkeys = (char**)(lodepng_realloc(info->itext_transkeys, sizeof(char*) * (info->itext_num + 1)));
char** new_strings = (char**)(lodepng_realloc(info->itext_strings, sizeof(char*) * (info->itext_num + 1)));
if(!new_keys || !new_langtags || !new_transkeys || !new_strings) {
lodepng_free(new_keys);
lodepng_free(new_langtags);
lodepng_free(new_transkeys);
lodepng_free(new_strings);
return 83; /*alloc fail*/
}
++info->itext_num;
info->itext_keys = new_keys;
info->itext_langtags = new_langtags;
info->itext_transkeys = new_transkeys;
info->itext_strings = new_strings;
info->itext_keys[info->itext_num - 1] = alloc_string(key);
info->itext_langtags[info->itext_num - 1] = alloc_string(langtag);
info->itext_transkeys[info->itext_num - 1] = alloc_string(transkey);
info->itext_strings[info->itext_num - 1] = alloc_string(str);
return 0;
}
/* same as set but does not delete */
static unsigned lodepng_assign_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size) {
info->iccp_name = alloc_string(name);
info->iccp_profile = (unsigned char*)lodepng_malloc(profile_size);
if(!info->iccp_name || !info->iccp_profile) return 83; /*alloc fail*/
memcpy(info->iccp_profile, profile, profile_size);
info->iccp_profile_size = profile_size;
return 0; /*ok*/
}
unsigned lodepng_set_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size) {
if(info->iccp_name) lodepng_clear_icc(info);
info->iccp_defined = 1;
return lodepng_assign_icc(info, name, profile, profile_size);
}
void lodepng_clear_icc(LodePNGInfo* info) {
string_cleanup(&info->iccp_name);
lodepng_free(info->iccp_profile);
info->iccp_profile = NULL;
info->iccp_profile_size = 0;
info->iccp_defined = 0;
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
void lodepng_info_init(LodePNGInfo* info) {
lodepng_color_mode_init(&info->color);
info->interlace_method = 0;
info->compression_method = 0;
info->filter_method = 0;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
info->background_defined = 0;
info->background_r = info->background_g = info->background_b = 0;
LodePNGText_init(info);
LodePNGIText_init(info);
info->time_defined = 0;
info->phys_defined = 0;
info->gama_defined = 0;
info->chrm_defined = 0;
info->srgb_defined = 0;
info->iccp_defined = 0;
info->iccp_name = NULL;
info->iccp_profile = NULL;
LodePNGUnknownChunks_init(info);
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
}
void lodepng_info_cleanup(LodePNGInfo* info) {
lodepng_color_mode_cleanup(&info->color);
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
LodePNGText_cleanup(info);
LodePNGIText_cleanup(info);
lodepng_clear_icc(info);
LodePNGUnknownChunks_cleanup(info);
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
}
unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source) {
lodepng_info_cleanup(dest);
*dest = *source;
lodepng_color_mode_init(&dest->color);
CERROR_TRY_RETURN(lodepng_color_mode_copy(&dest->color, &source->color));
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
CERROR_TRY_RETURN(LodePNGText_copy(dest, source));
CERROR_TRY_RETURN(LodePNGIText_copy(dest, source));
if(source->iccp_defined) {
CERROR_TRY_RETURN(lodepng_assign_icc(dest, source->iccp_name, source->iccp_profile, source->iccp_profile_size));
}
LodePNGUnknownChunks_init(dest);
CERROR_TRY_RETURN(LodePNGUnknownChunks_copy(dest, source));
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
return 0;
}
/* ////////////////////////////////////////////////////////////////////////// */
/*index: bitgroup index, bits: bitgroup size(1, 2 or 4), in: bitgroup value, out: octet array to add bits to*/
static void addColorBits(unsigned char* out, size_t index, unsigned bits, unsigned in) {
unsigned m = bits == 1 ? 7 : bits == 2 ? 3 : 1; /*8 / bits - 1*/
/*p = the partial index in the byte, e.g. with 4 palettebits it is 0 for first half or 1 for second half*/
unsigned p = index & m;
in &= (1u << bits) - 1u; /*filter out any other bits of the input value*/
in = in << (bits * (m - p));
if(p == 0) out[index * bits / 8] = in;
else out[index * bits / 8] |= in;
}
typedef struct ColorTree ColorTree;
/*
One node of a color tree
This is the data structure used to count the number of unique colors and to get a palette
index for a color. It's like an octree, but because the alpha channel is used too, each
node has 16 instead of 8 children.
*/
struct ColorTree {
ColorTree* children[16]; /*up to 16 pointers to ColorTree of next level*/
int index; /*the payload. Only has a meaningful value if this is in the last level*/
};
static void color_tree_init(ColorTree* tree) {
int i;
for(i = 0; i != 16; ++i) tree->children[i] = 0;
tree->index = -1;
}
static void color_tree_cleanup(ColorTree* tree) {
int i;
for(i = 0; i != 16; ++i) {
if(tree->children[i]) {
color_tree_cleanup(tree->children[i]);
lodepng_free(tree->children[i]);
}
}
}
/*returns -1 if color not present, its index otherwise*/
static int color_tree_get(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
int bit = 0;
for(bit = 0; bit < 8; ++bit) {
int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1);
if(!tree->children[i]) return -1;
else tree = tree->children[i];
}
return tree ? tree->index : -1;
}
#ifdef LODEPNG_COMPILE_ENCODER
static int color_tree_has(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
return color_tree_get(tree, r, g, b, a) >= 0;
}
#endif /*LODEPNG_COMPILE_ENCODER*/
/*color is not allowed to already exist.
Index should be >= 0 (it's signed to be compatible with using -1 for "doesn't exist")*/
static void color_tree_add(ColorTree* tree,
unsigned char r, unsigned char g, unsigned char b, unsigned char a, unsigned index) {
int bit;
for(bit = 0; bit < 8; ++bit) {
int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1);
if(!tree->children[i]) {
tree->children[i] = (ColorTree*)lodepng_malloc(sizeof(ColorTree));
color_tree_init(tree->children[i]);
}
tree = tree->children[i];
}
tree->index = (int)index;
}
/*put a pixel, given its RGBA color, into image of any color type*/
static unsigned rgba8ToPixel(unsigned char* out, size_t i,
const LodePNGColorMode* mode, ColorTree* tree /*for palette*/,
unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
if(mode->colortype == LCT_GREY) {
unsigned char gray = r; /*((unsigned short)r + g + b) / 3;*/
if(mode->bitdepth == 8) out[i] = gray;
else if(mode->bitdepth == 16) out[i * 2 + 0] = out[i * 2 + 1] = gray;
else {
/*take the most significant bits of gray*/
gray = (gray >> (8 - mode->bitdepth)) & ((1 << mode->bitdepth) - 1);
addColorBits(out, i, mode->bitdepth, gray);
}
} else if(mode->colortype == LCT_RGB) {
if(mode->bitdepth == 8) {
out[i * 3 + 0] = r;
out[i * 3 + 1] = g;
out[i * 3 + 2] = b;
} else {
out[i * 6 + 0] = out[i * 6 + 1] = r;
out[i * 6 + 2] = out[i * 6 + 3] = g;
out[i * 6 + 4] = out[i * 6 + 5] = b;
}
} else if(mode->colortype == LCT_PALETTE) {
int index = color_tree_get(tree, r, g, b, a);
if(index < 0) return 82; /*color not in palette*/
if(mode->bitdepth == 8) out[i] = index;
else addColorBits(out, i, mode->bitdepth, (unsigned)index);
} else if(mode->colortype == LCT_GREY_ALPHA) {
unsigned char gray = r; /*((unsigned short)r + g + b) / 3;*/
if(mode->bitdepth == 8) {
out[i * 2 + 0] = gray;
out[i * 2 + 1] = a;
} else if(mode->bitdepth == 16) {
out[i * 4 + 0] = out[i * 4 + 1] = gray;
out[i * 4 + 2] = out[i * 4 + 3] = a;
}
} else if(mode->colortype == LCT_RGBA) {
if(mode->bitdepth == 8) {
out[i * 4 + 0] = r;
out[i * 4 + 1] = g;
out[i * 4 + 2] = b;
out[i * 4 + 3] = a;
} else {
out[i * 8 + 0] = out[i * 8 + 1] = r;
out[i * 8 + 2] = out[i * 8 + 3] = g;
out[i * 8 + 4] = out[i * 8 + 5] = b;
out[i * 8 + 6] = out[i * 8 + 7] = a;
}
}
return 0; /*no error*/
}
/*put a pixel, given its RGBA16 color, into image of any color 16-bitdepth type*/
static void rgba16ToPixel(unsigned char* out, size_t i,
const LodePNGColorMode* mode,
unsigned short r, unsigned short g, unsigned short b, unsigned short a) {
if(mode->colortype == LCT_GREY) {
unsigned short gray = r; /*((unsigned)r + g + b) / 3;*/
out[i * 2 + 0] = (gray >> 8) & 255;
out[i * 2 + 1] = gray & 255;
} else if(mode->colortype == LCT_RGB) {
out[i * 6 + 0] = (r >> 8) & 255;
out[i * 6 + 1] = r & 255;
out[i * 6 + 2] = (g >> 8) & 255;
out[i * 6 + 3] = g & 255;
out[i * 6 + 4] = (b >> 8) & 255;
out[i * 6 + 5] = b & 255;
} else if(mode->colortype == LCT_GREY_ALPHA) {
unsigned short gray = r; /*((unsigned)r + g + b) / 3;*/
out[i * 4 + 0] = (gray >> 8) & 255;
out[i * 4 + 1] = gray & 255;
out[i * 4 + 2] = (a >> 8) & 255;
out[i * 4 + 3] = a & 255;
} else if(mode->colortype == LCT_RGBA) {
out[i * 8 + 0] = (r >> 8) & 255;
out[i * 8 + 1] = r & 255;
out[i * 8 + 2] = (g >> 8) & 255;
out[i * 8 + 3] = g & 255;
out[i * 8 + 4] = (b >> 8) & 255;
out[i * 8 + 5] = b & 255;
out[i * 8 + 6] = (a >> 8) & 255;
out[i * 8 + 7] = a & 255;
}
}
/*Get RGBA8 color of pixel with index i (y * width + x) from the raw image with given color type.*/
static void getPixelColorRGBA8(unsigned char* r, unsigned char* g,
unsigned char* b, unsigned char* a,
const unsigned char* in, size_t i,
const LodePNGColorMode* mode) {
if(mode->colortype == LCT_GREY) {
if(mode->bitdepth == 8) {
*r = *g = *b = in[i];
if(mode->key_defined && *r == mode->key_r) *a = 0;
else *a = 255;
} else if(mode->bitdepth == 16) {
*r = *g = *b = in[i * 2 + 0];
if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;
else *a = 255;
} else {
unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/
size_t j = i * mode->bitdepth;
unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
*r = *g = *b = (value * 255) / highest;
if(mode->key_defined && value == mode->key_r) *a = 0;
else *a = 255;
}
} else if(mode->colortype == LCT_RGB) {
if(mode->bitdepth == 8) {
*r = in[i * 3 + 0]; *g = in[i * 3 + 1]; *b = in[i * 3 + 2];
if(mode->key_defined && *r == mode->key_r && *g == mode->key_g && *b == mode->key_b) *a = 0;
else *a = 255;
} else {
*r = in[i * 6 + 0];
*g = in[i * 6 + 2];
*b = in[i * 6 + 4];
if(mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
&& 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
&& 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;
else *a = 255;
}
} else if(mode->colortype == LCT_PALETTE) {
unsigned index;
if(mode->bitdepth == 8) index = in[i];
else {
size_t j = i * mode->bitdepth;
index = readBitsFromReversedStream(&j, in, mode->bitdepth);
}
if(index >= mode->palettesize) {
/*This is an error according to the PNG spec, but common PNG decoders make it black instead.
Done here too, slightly faster due to no error handling needed.*/
*r = *g = *b = 0;
*a = 255;
} else {
*r = mode->palette[index * 4 + 0];
*g = mode->palette[index * 4 + 1];
*b = mode->palette[index * 4 + 2];
*a = mode->palette[index * 4 + 3];
}
} else if(mode->colortype == LCT_GREY_ALPHA) {
if(mode->bitdepth == 8) {
*r = *g = *b = in[i * 2 + 0];
*a = in[i * 2 + 1];
} else {
*r = *g = *b = in[i * 4 + 0];
*a = in[i * 4 + 2];
}
} else if(mode->colortype == LCT_RGBA) {
if(mode->bitdepth == 8) {
*r = in[i * 4 + 0];
*g = in[i * 4 + 1];
*b = in[i * 4 + 2];
*a = in[i * 4 + 3];
} else {
*r = in[i * 8 + 0];
*g = in[i * 8 + 2];
*b = in[i * 8 + 4];
*a = in[i * 8 + 6];
}
}
}
/*Similar to getPixelColorRGBA8, but with all the for loops inside of the color
mode test cases, optimized to convert the colors much faster, when converting
to RGBA or RGB with 8 bit per cannel. buffer must be RGBA or RGB output with
enough memory, if has_alpha is true the output is RGBA. mode has the color mode
of the input buffer.*/
static void getPixelColorsRGBA8(unsigned char* buffer, size_t numpixels,
unsigned has_alpha, const unsigned char* in,
const LodePNGColorMode* mode) {
unsigned num_channels = has_alpha ? 4 : 3;
size_t i;
if(mode->colortype == LCT_GREY) {
if(mode->bitdepth == 8) {
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
buffer[0] = buffer[1] = buffer[2] = in[i];
if(has_alpha) buffer[3] = mode->key_defined && in[i] == mode->key_r ? 0 : 255;
}
} else if(mode->bitdepth == 16) {
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
buffer[0] = buffer[1] = buffer[2] = in[i * 2];
if(has_alpha) buffer[3] = mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r ? 0 : 255;
}
} else {
unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/
size_t j = 0;
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth);
buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest;
if(has_alpha) buffer[3] = mode->key_defined && value == mode->key_r ? 0 : 255;
}
}
} else if(mode->colortype == LCT_RGB) {
if(mode->bitdepth == 8) {
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
buffer[0] = in[i * 3 + 0];
buffer[1] = in[i * 3 + 1];
buffer[2] = in[i * 3 + 2];
if(has_alpha) buffer[3] = mode->key_defined && buffer[0] == mode->key_r
&& buffer[1]== mode->key_g && buffer[2] == mode->key_b ? 0 : 255;
}
} else {
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
buffer[0] = in[i * 6 + 0];
buffer[1] = in[i * 6 + 2];
buffer[2] = in[i * 6 + 4];
if(has_alpha) buffer[3] = mode->key_defined
&& 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
&& 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
&& 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b ? 0 : 255;
}
}
} else if(mode->colortype == LCT_PALETTE) {
unsigned index;
size_t j = 0;
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
if(mode->bitdepth == 8) index = in[i];
else index = readBitsFromReversedStream(&j, in, mode->bitdepth);
if(index >= mode->palettesize) {
/*This is an error according to the PNG spec, but most PNG decoders make it black instead.
Done here too, slightly faster due to no error handling needed.*/
buffer[0] = buffer[1] = buffer[2] = 0;
if(has_alpha) buffer[3] = 255;
} else {
buffer[0] = mode->palette[index * 4 + 0];
buffer[1] = mode->palette[index * 4 + 1];
buffer[2] = mode->palette[index * 4 + 2];
if(has_alpha) buffer[3] = mode->palette[index * 4 + 3];
}
}
} else if(mode->colortype == LCT_GREY_ALPHA) {
if(mode->bitdepth == 8) {
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0];
if(has_alpha) buffer[3] = in[i * 2 + 1];
}
} else {
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0];
if(has_alpha) buffer[3] = in[i * 4 + 2];
}
}
} else if(mode->colortype == LCT_RGBA) {
if(mode->bitdepth == 8) {
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
buffer[0] = in[i * 4 + 0];
buffer[1] = in[i * 4 + 1];
buffer[2] = in[i * 4 + 2];
if(has_alpha) buffer[3] = in[i * 4 + 3];
}
} else {
for(i = 0; i != numpixels; ++i, buffer += num_channels) {
buffer[0] = in[i * 8 + 0];
buffer[1] = in[i * 8 + 2];
buffer[2] = in[i * 8 + 4];
if(has_alpha) buffer[3] = in[i * 8 + 6];
}
}
}
}
/*Get RGBA16 color of pixel with index i (y * width + x) from the raw image with
given color type, but the given color type must be 16-bit itself.*/
static void getPixelColorRGBA16(unsigned short* r, unsigned short* g, unsigned short* b, unsigned short* a,
const unsigned char* in, size_t i, const LodePNGColorMode* mode) {
if(mode->colortype == LCT_GREY) {
*r = *g = *b = 256 * in[i * 2 + 0] + in[i * 2 + 1];
if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0;
else *a = 65535;
} else if(mode->colortype == LCT_RGB) {
*r = 256u * in[i * 6 + 0] + in[i * 6 + 1];
*g = 256u * in[i * 6 + 2] + in[i * 6 + 3];
*b = 256u * in[i * 6 + 4] + in[i * 6 + 5];
if(mode->key_defined
&& 256u * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r
&& 256u * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g
&& 256u * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0;
else *a = 65535;
} else if(mode->colortype == LCT_GREY_ALPHA) {
*r = *g = *b = 256u * in[i * 4 + 0] + in[i * 4 + 1];
*a = 256u * in[i * 4 + 2] + in[i * 4 + 3];
} else if(mode->colortype == LCT_RGBA) {
*r = 256u * in[i * 8 + 0] + in[i * 8 + 1];
*g = 256u * in[i * 8 + 2] + in[i * 8 + 3];
*b = 256u * in[i * 8 + 4] + in[i * 8 + 5];
*a = 256u * in[i * 8 + 6] + in[i * 8 + 7];
}
}
unsigned lodepng_convert(unsigned char* out, const unsigned char* in,
const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in,
unsigned w, unsigned h) {
size_t i;
ColorTree tree;
size_t numpixels = (size_t)w * (size_t)h;
unsigned error = 0;
if(lodepng_color_mode_equal(mode_out, mode_in)) {
size_t numbytes = lodepng_get_raw_size(w, h, mode_in);
for(i = 0; i != numbytes; ++i) out[i] = in[i];
return 0;
}
if(mode_out->colortype == LCT_PALETTE) {
size_t palettesize = mode_out->palettesize;
const unsigned char* palette = mode_out->palette;
size_t palsize = (size_t)1u << mode_out->bitdepth;
/*if the user specified output palette but did not give the values, assume
they want the values of the input color type (assuming that one is palette).
Note that we never create a new palette ourselves.*/
if(palettesize == 0) {
palettesize = mode_in->palettesize;
palette = mode_in->palette;
/*if the input was also palette with same bitdepth, then the color types are also
equal, so copy literally. This to preserve the exact indices that were in the PNG
even in case there are duplicate colors in the palette.*/
if (mode_in->colortype == LCT_PALETTE && mode_in->bitdepth == mode_out->bitdepth) {
size_t numbytes = lodepng_get_raw_size(w, h, mode_in);
for(i = 0; i != numbytes; ++i) out[i] = in[i];
return 0;
}
}
if(palettesize < palsize) palsize = palettesize;
color_tree_init(&tree);
for(i = 0; i != palsize; ++i) {
const unsigned char* p = &palette[i * 4];
color_tree_add(&tree, p[0], p[1], p[2], p[3], (unsigned)i);
}
}
if(mode_in->bitdepth == 16 && mode_out->bitdepth == 16) {
for(i = 0; i != numpixels; ++i) {
unsigned short r = 0, g = 0, b = 0, a = 0;
getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
rgba16ToPixel(out, i, mode_out, r, g, b, a);
}
} else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGBA) {
getPixelColorsRGBA8(out, numpixels, 1, in, mode_in);
} else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB) {
getPixelColorsRGBA8(out, numpixels, 0, in, mode_in);
} else {
unsigned char r = 0, g = 0, b = 0, a = 0;
for(i = 0; i != numpixels; ++i) {
getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);
error = rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a);
if (error) break;
}
}
if(mode_out->colortype == LCT_PALETTE) {
color_tree_cleanup(&tree);
}
return error;
}
/* Converts a single rgb color without alpha from one type to another, color bits truncated to
their bitdepth. In case of single channel (gray or palette), only the r channel is used. Slow
function, do not use to process all pixels of an image. Alpha channel not supported on purpose:
this is for bKGD, supporting alpha may prevent it from finding a color in the palette, from the
specification it looks like bKGD should ignore the alpha values of the palette since it can use
any palette index but doesn't have an alpha channel. Idem with ignoring color key. */
unsigned lodepng_convert_rgb(
unsigned* r_out, unsigned* g_out, unsigned* b_out,
unsigned r_in, unsigned g_in, unsigned b_in,
const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in) {
unsigned r = 0, g = 0, b = 0;
unsigned mul = 65535 / ((1u << mode_in->bitdepth) - 1u); /*65535, 21845, 4369, 257, 1*/
unsigned shift = 16 - mode_out->bitdepth;
if(mode_in->colortype == LCT_GREY || mode_in->colortype == LCT_GREY_ALPHA) {
r = g = b = r_in * mul;
} else if(mode_in->colortype == LCT_RGB || mode_in->colortype == LCT_RGBA) {
r = r_in * mul;
g = g_in * mul;
b = b_in * mul;
} else if(mode_in->colortype == LCT_PALETTE) {
if(r_in >= mode_in->palettesize) return 82;
r = mode_in->palette[r_in * 4 + 0] * 257u;
g = mode_in->palette[r_in * 4 + 1] * 257u;
b = mode_in->palette[r_in * 4 + 2] * 257u;
} else {
return 31;
}
/* now convert to output format */
if(mode_out->colortype == LCT_GREY || mode_out->colortype == LCT_GREY_ALPHA) {
*r_out = r >> shift ;
} else if(mode_out->colortype == LCT_RGB || mode_out->colortype == LCT_RGBA) {
*r_out = r >> shift ;
*g_out = g >> shift ;
*b_out = b >> shift ;
} else if(mode_out->colortype == LCT_PALETTE) {
unsigned i;
/* a 16-bit color cannot be in the palette */
if((r >> 8) != (r & 255) || (g >> 8) != (g & 255) || (b >> 8) != (b & 255)) return 82;
for(i = 0; i < mode_out->palettesize; i++) {
unsigned j = i * 4;
if((r >> 8) == mode_out->palette[j + 0] && (g >> 8) == mode_out->palette[j + 1] &&
(b >> 8) == mode_out->palette[j + 2]) {
*r_out = i;
return 0;
}
}
return 82;
} else {
return 31;
}
return 0;
}
#ifdef LODEPNG_COMPILE_ENCODER
void lodepng_color_profile_init(LodePNGColorProfile* profile) {
profile->colored = 0;
profile->key = 0;
profile->key_r = profile->key_g = profile->key_b = 0;
profile->alpha = 0;
profile->numcolors = 0;
profile->bits = 1;
profile->numpixels = 0;
}
/*function used for debug purposes with C++*/
/*void printColorProfile(LodePNGColorProfile* p) {
std::cout << "colored: " << (int)p->colored << ", ";
std::cout << "key: " << (int)p->key << ", ";
std::cout << "key_r: " << (int)p->key_r << ", ";
std::cout << "key_g: " << (int)p->key_g << ", ";
std::cout << "key_b: " << (int)p->key_b << ", ";
std::cout << "alpha: " << (int)p->alpha << ", ";
std::cout << "numcolors: " << (int)p->numcolors << ", ";
std::cout << "bits: " << (int)p->bits << std::endl;
}*/
/*Returns how many bits needed to represent given value (max 8 bit)*/
static unsigned getValueRequiredBits(unsigned char value) {
if(value == 0 || value == 255) return 1;
/*The scaling of 2-bit and 4-bit values uses multiples of 85 and 17*/
if(value % 17 == 0) return value % 85 == 0 ? 2 : 4;
return 8;
}
/*profile must already have been inited.
It's ok to set some parameters of profile to done already.*/
unsigned lodepng_get_color_profile(LodePNGColorProfile* profile,
const unsigned char* in, unsigned w, unsigned h,
const LodePNGColorMode* mode_in) {
unsigned error = 0;
size_t i;
ColorTree tree;
size_t numpixels = (size_t)w * (size_t)h;
/* mark things as done already if it would be impossible to have a more expensive case */
unsigned colored_done = lodepng_is_greyscale_type(mode_in) ? 1 : 0;
unsigned alpha_done = lodepng_can_have_alpha(mode_in) ? 0 : 1;
unsigned numcolors_done = 0;
unsigned bpp = lodepng_get_bpp(mode_in);
unsigned bits_done = (profile->bits == 1 && bpp == 1) ? 1 : 0;
unsigned sixteen = 0; /* whether the input image is 16 bit */
unsigned maxnumcolors = 257;
if(bpp <= 8) maxnumcolors = LODEPNG_MIN(257, profile->numcolors + (1u << bpp));
profile->numpixels += numpixels;
color_tree_init(&tree);
/*If the profile was already filled in from previous data, fill its palette in tree
and mark things as done already if we know they are the most expensive case already*/
if(profile->alpha) alpha_done = 1;
if(profile->colored) colored_done = 1;
if(profile->bits == 16) numcolors_done = 1;
if(profile->bits >= bpp) bits_done = 1;
if(profile->numcolors >= maxnumcolors) numcolors_done = 1;
if(!numcolors_done) {
for(i = 0; i < profile->numcolors; i++) {
const unsigned char* color = &profile->palette[i * 4];
color_tree_add(&tree, color[0], color[1], color[2], color[3], (unsigned int)i);
}
}
/*Check if the 16-bit input is truly 16-bit*/
if(mode_in->bitdepth == 16 && !sixteen) {
unsigned short r, g, b, a;
for(i = 0; i != numpixels; ++i) {
getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
if((r & 255) != ((r >> 8) & 255) || (g & 255) != ((g >> 8) & 255) ||
(b & 255) != ((b >> 8) & 255) || (a & 255) != ((a >> 8) & 255)) /*first and second byte differ*/ {
profile->bits = 16;
sixteen = 1;
bits_done = 1;
numcolors_done = 1; /*counting colors no longer useful, palette doesn't support 16-bit*/
break;
}
}
}
if(sixteen) {
unsigned short r = 0, g = 0, b = 0, a = 0;
for(i = 0; i != numpixels; ++i) {
getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
if(!colored_done && (r != g || r != b)) {
profile->colored = 1;
colored_done = 1;
}
if(!alpha_done) {
unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b);
if(a != 65535 && (a != 0 || (profile->key && !matchkey))) {
profile->alpha = 1;
profile->key = 0;
alpha_done = 1;
} else if(a == 0 && !profile->alpha && !profile->key) {
profile->key = 1;
profile->key_r = r;
profile->key_g = g;
profile->key_b = b;
} else if(a == 65535 && profile->key && matchkey) {
/* Color key cannot be used if an opaque pixel also has that RGB color. */
profile->alpha = 1;
profile->key = 0;
alpha_done = 1;
}
}
if(alpha_done && numcolors_done && colored_done && bits_done) break;
}
if(profile->key && !profile->alpha) {
for(i = 0; i != numpixels; ++i) {
getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in);
if(a != 0 && r == profile->key_r && g == profile->key_g && b == profile->key_b) {
/* Color key cannot be used if an opaque pixel also has that RGB color. */
profile->alpha = 1;
profile->key = 0;
alpha_done = 1;
}
}
}
} else /* < 16-bit */ {
unsigned char r = 0, g = 0, b = 0, a = 0;
for(i = 0; i != numpixels; ++i) {
getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);
if(!bits_done && profile->bits < 8) {
/*only r is checked, < 8 bits is only relevant for grayscale*/
unsigned bits = getValueRequiredBits(r);
if(bits > profile->bits) profile->bits = bits;
}
bits_done = (profile->bits >= bpp);
if(!colored_done && (r != g || r != b)) {
profile->colored = 1;
colored_done = 1;
if(profile->bits < 8) profile->bits = 8; /*PNG has no colored modes with less than 8-bit per channel*/
}
if(!alpha_done) {
unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b);
if(a != 255 && (a != 0 || (profile->key && !matchkey))) {
profile->alpha = 1;
profile->key = 0;
alpha_done = 1;
if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
} else if(a == 0 && !profile->alpha && !profile->key) {
profile->key = 1;
profile->key_r = r;
profile->key_g = g;
profile->key_b = b;
} else if(a == 255 && profile->key && matchkey) {
/* Color key cannot be used if an opaque pixel also has that RGB color. */
profile->alpha = 1;
profile->key = 0;
alpha_done = 1;
if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
}
}
if(!numcolors_done) {
if(!color_tree_has(&tree, r, g, b, a)) {
color_tree_add(&tree, r, g, b, a, profile->numcolors);
if(profile->numcolors < 256) {
unsigned char* p = profile->palette;
unsigned n = profile->numcolors;
p[n * 4 + 0] = r;
p[n * 4 + 1] = g;
p[n * 4 + 2] = b;
p[n * 4 + 3] = a;
}
++profile->numcolors;
numcolors_done = profile->numcolors >= maxnumcolors;
}
}
if(alpha_done && numcolors_done && colored_done && bits_done) break;
}
if(profile->key && !profile->alpha) {
for(i = 0; i != numpixels; ++i) {
getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in);
if(a != 0 && r == profile->key_r && g == profile->key_g && b == profile->key_b) {
/* Color key cannot be used if an opaque pixel also has that RGB color. */
profile->alpha = 1;
profile->key = 0;
alpha_done = 1;
if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
}
}
}
/*make the profile's key always 16-bit for consistency - repeat each byte twice*/
profile->key_r += (profile->key_r << 8);
profile->key_g += (profile->key_g << 8);
profile->key_b += (profile->key_b << 8);
}
color_tree_cleanup(&tree);
return error;
}
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*Adds a single color to the color profile. The profile must already have been inited. The color must be given as 16-bit
(with 2 bytes repeating for 8-bit and 65535 for opaque alpha channel). This function is expensive, do not call it for
all pixels of an image but only for a few additional values. */
static unsigned lodepng_color_profile_add(LodePNGColorProfile* profile,
unsigned r, unsigned g, unsigned b, unsigned a) {
unsigned error = 0;
unsigned char image[8];
LodePNGColorMode mode;
lodepng_color_mode_init(&mode);
image[0] = r >> 8; image[1] = r; image[2] = g >> 8; image[3] = g;
image[4] = b >> 8; image[5] = b; image[6] = a >> 8; image[7] = a;
mode.bitdepth = 16;
mode.colortype = LCT_RGBA;
error = lodepng_get_color_profile(profile, image, 1, 1, &mode);
lodepng_color_mode_cleanup(&mode);
return error;
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
/*Autochoose color model given the computed profile. mode_in is to copy palette order from
when relevant.*/
static unsigned auto_choose_color_from_profile(LodePNGColorMode* mode_out,
const LodePNGColorMode* mode_in,
const LodePNGColorProfile* prof) {
unsigned error = 0;
unsigned palettebits, palette_ok;
size_t i, n;
size_t numpixels = prof->numpixels;
unsigned alpha = prof->alpha;
unsigned key = prof->key;
unsigned bits = prof->bits;
mode_out->key_defined = 0;
if(key && numpixels <= 16) {
alpha = 1; /*too few pixels to justify tRNS chunk overhead*/
key = 0;
if(bits < 8) bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/
}
n = prof->numcolors;
palettebits = n <= 2 ? 1 : (n <= 4 ? 2 : (n <= 16 ? 4 : 8));
palette_ok = n <= 256 && bits <= 8;
if(numpixels < n * 2) palette_ok = 0; /*don't add palette overhead if image has only a few pixels*/
if(!prof->colored && bits <= palettebits) palette_ok = 0; /*gray is less overhead*/
if(palette_ok) {
const unsigned char* p = prof->palette;
lodepng_palette_clear(mode_out); /*remove potential earlier palette*/
for(i = 0; i != prof->numcolors; ++i) {
error = lodepng_palette_add(mode_out, p[i * 4 + 0], p[i * 4 + 1], p[i * 4 + 2], p[i * 4 + 3]);
if(error) break;
}
mode_out->colortype = LCT_PALETTE;
mode_out->bitdepth = palettebits;
if(mode_in->colortype == LCT_PALETTE && mode_in->palettesize >= mode_out->palettesize
&& mode_in->bitdepth == mode_out->bitdepth) {
/*If input should have same palette colors, keep original to preserve its order and prevent conversion*/
lodepng_color_mode_cleanup(mode_out);
lodepng_color_mode_copy(mode_out, mode_in);
}
} else /*8-bit or 16-bit per channel*/ {
mode_out->bitdepth = bits;
mode_out->colortype = alpha ? (prof->colored ? LCT_RGBA : LCT_GREY_ALPHA)
: (prof->colored ? LCT_RGB : LCT_GREY);
if(key) {
unsigned mask = (1u << mode_out->bitdepth) - 1u; /*profile always uses 16-bit, mask converts it*/
mode_out->key_r = prof->key_r & mask;
mode_out->key_g = prof->key_g & mask;
mode_out->key_b = prof->key_b & mask;
mode_out->key_defined = 1;
}
}
return error;
}
/*Automatically chooses color type that gives smallest amount of bits in the
output image, e.g. gray if there are only grayscale pixels, palette if there
are less than 256 colors, color key if only single transparent color, ...
Updates values of mode with a potentially smaller color model. mode_out should
contain the user chosen color model, but will be overwritten with the new chosen one.*/
unsigned lodepng_auto_choose_color(LodePNGColorMode* mode_out,
const unsigned char* image, unsigned w, unsigned h,
const LodePNGColorMode* mode_in) {
unsigned error = 0;
LodePNGColorProfile prof;
lodepng_color_profile_init(&prof);
error = lodepng_get_color_profile(&prof, image, w, h, mode_in);
if(error) return error;
return auto_choose_color_from_profile(mode_out, mode_in, &prof);
}
#endif /* #ifdef LODEPNG_COMPILE_ENCODER */
/*
Paeth predicter, used by PNG filter type 4
The parameters are of type short, but should come from unsigned chars, the shorts
are only needed to make the paeth calculation correct.
*/
static unsigned char paethPredictor(short a, short b, short c) {
short pa = abs(b - c);
short pb = abs(a - c);
short pc = abs(a + b - c - c);
if(pc < pa && pc < pb) return (unsigned char)c;
else if(pb < pa) return (unsigned char)b;
else return (unsigned char)a;
}
/*shared values used by multiple Adam7 related functions*/
static const unsigned ADAM7_IX[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/
static const unsigned ADAM7_IY[7] = { 0, 0, 4, 0, 2, 0, 1 }; /*y start values*/
static const unsigned ADAM7_DX[7] = { 8, 8, 4, 4, 2, 2, 1 }; /*x delta values*/
static const unsigned ADAM7_DY[7] = { 8, 8, 8, 4, 4, 2, 2 }; /*y delta values*/
/*
Outputs various dimensions and positions in the image related to the Adam7 reduced images.
passw: output containing the width of the 7 passes
passh: output containing the height of the 7 passes
filter_passstart: output containing the index of the start and end of each
reduced image with filter bytes
padded_passstart output containing the index of the start and end of each
reduced image when without filter bytes but with padded scanlines
passstart: output containing the index of the start and end of each reduced
image without padding between scanlines, but still padding between the images
w, h: width and height of non-interlaced image
bpp: bits per pixel
"padded" is only relevant if bpp is less than 8 and a scanline or image does not
end at a full byte
*/
static void Adam7_getpassvalues(unsigned passw[7], unsigned passh[7], size_t filter_passstart[8],
size_t padded_passstart[8], size_t passstart[8], unsigned w, unsigned h, unsigned bpp) {
/*the passstart values have 8 values: the 8th one indicates the byte after the end of the 7th (= last) pass*/
unsigned i;
/*calculate width and height in pixels of each pass*/
for(i = 0; i != 7; ++i) {
passw[i] = (w + ADAM7_DX[i] - ADAM7_IX[i] - 1) / ADAM7_DX[i];
passh[i] = (h + ADAM7_DY[i] - ADAM7_IY[i] - 1) / ADAM7_DY[i];
if(passw[i] == 0) passh[i] = 0;
if(passh[i] == 0) passw[i] = 0;
}
filter_passstart[0] = padded_passstart[0] = passstart[0] = 0;
for(i = 0; i != 7; ++i) {
/*if passw[i] is 0, it's 0 bytes, not 1 (no filtertype-byte)*/
filter_passstart[i + 1] = filter_passstart[i]
+ ((passw[i] && passh[i]) ? passh[i] * (1 + (passw[i] * bpp + 7) / 8) : 0);
/*bits padded if needed to fill full byte at end of each scanline*/
padded_passstart[i + 1] = padded_passstart[i] + passh[i] * ((passw[i] * bpp + 7) / 8);
/*only padded at end of reduced image*/
passstart[i + 1] = passstart[i] + (passh[i] * passw[i] * bpp + 7) / 8;
}
}
#ifdef LODEPNG_COMPILE_DECODER
/* ////////////////////////////////////////////////////////////////////////// */
/* / PNG Decoder / */
/* ////////////////////////////////////////////////////////////////////////// */
/*read the information from the header and store it in the LodePNGInfo. return value is error*/
unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state,
const unsigned char* in, size_t insize) {
unsigned width, height;
LodePNGInfo* info = &state->info_png;
if(insize == 0 || in == 0) {
CERROR_RETURN_ERROR(state->error, 48); /*error: the given data is empty*/
}
if(insize < 33) {
CERROR_RETURN_ERROR(state->error, 27); /*error: the data length is smaller than the length of a PNG header*/
}
/*when decoding a new PNG image, make sure all parameters created after previous decoding are reset*/
/* TODO: remove this. One should use a new LodePNGState for new sessions */
lodepng_info_cleanup(info);
lodepng_info_init(info);
if(in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71
|| in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10) {
CERROR_RETURN_ERROR(state->error, 28); /*error: the first 8 bytes are not the correct PNG signature*/
}
if(lodepng_chunk_length(in + 8) != 13) {
CERROR_RETURN_ERROR(state->error, 94); /*error: header size must be 13 bytes*/
}
if(!lodepng_chunk_type_equals(in + 8, "IHDR")) {
CERROR_RETURN_ERROR(state->error, 29); /*error: it doesn't start with a IHDR chunk!*/
}
/*read the values given in the header*/
width = lodepng_read32bitInt(&in[16]);
height = lodepng_read32bitInt(&in[20]);
info->color.bitdepth = in[24];
info->color.colortype = (LodePNGColorType)in[25];
info->compression_method = in[26];
info->filter_method = in[27];
info->interlace_method = in[28];
if(width == 0 || height == 0) {
CERROR_RETURN_ERROR(state->error, 93);
}
if(w) *w = width;
if(h) *h = height;
if(!state->decoder.ignore_crc) {
unsigned CRC = lodepng_read32bitInt(&in[29]);
unsigned checksum = lodepng_crc32(&in[12], 17);
if(CRC != checksum) {
CERROR_RETURN_ERROR(state->error, 57); /*invalid CRC*/
}
}
/*error: only compression method 0 is allowed in the specification*/
if(info->compression_method != 0) CERROR_RETURN_ERROR(state->error, 32);
/*error: only filter method 0 is allowed in the specification*/
if(info->filter_method != 0) CERROR_RETURN_ERROR(state->error, 33);
/*error: only interlace methods 0 and 1 exist in the specification*/
if(info->interlace_method > 1) CERROR_RETURN_ERROR(state->error, 34);
state->error = checkColorValidity(info->color.colortype, info->color.bitdepth);
return state->error;
}
static unsigned unfilterScanline(unsigned char* recon, const unsigned char* scanline, const unsigned char* precon,
size_t bytewidth, unsigned char filterType, size_t length) {
/*
For PNG filter method 0
unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte,
the filter works byte per byte (bytewidth = 1)
precon is the previous unfiltered scanline, recon the result, scanline the current one
the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead
recon and scanline MAY be the same memory address! precon must be disjoint.
*/
size_t i;
switch(filterType) {
case 0:
for(i = 0; i != length; ++i) recon[i] = scanline[i];
break;
case 1:
for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i];
for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + recon[i - bytewidth];
break;
case 2:
if(precon) {
for(i = 0; i != length; ++i) recon[i] = scanline[i] + precon[i];
} else {
for(i = 0; i != length; ++i) recon[i] = scanline[i];
}
break;
case 3:
if(precon) {
for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i] + (precon[i] >> 1);
for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + ((recon[i - bytewidth] + precon[i]) >> 1);
} else {
for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i];
for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + (recon[i - bytewidth] >> 1);
}
break;
case 4:
if(precon) {
for(i = 0; i != bytewidth; ++i) {
recon[i] = (scanline[i] + precon[i]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/
}
for(i = bytewidth; i < length; ++i) {
recon[i] = (scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth]));
}
} else {
for(i = 0; i != bytewidth; ++i) {
recon[i] = scanline[i];
}
for(i = bytewidth; i < length; ++i) {
/*paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth]*/
recon[i] = (scanline[i] + recon[i - bytewidth]);
}
}
break;
default: return 36; /*error: unexisting filter type given*/
}
return 0;
}
static unsigned unfilter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) {
/*
For PNG filter method 0
this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 seven times)
out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline
w and h are image dimensions or dimensions of reduced image, bpp is bits per pixel
in and out are allowed to be the same memory address (but aren't the same size since in has the extra filter bytes)
*/
unsigned y;
unsigned char* prevline = 0;
/*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
size_t bytewidth = (bpp + 7) / 8;
size_t linebytes = (w * bpp + 7) / 8;
for(y = 0; y < h; ++y) {
size_t outindex = linebytes * y;
size_t inindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
unsigned char filterType = in[inindex];
CERROR_TRY_RETURN(unfilterScanline(&out[outindex], &in[inindex + 1], prevline, bytewidth, filterType, linebytes));
prevline = &out[outindex];
}
return 0;
}
/*
in: Adam7 interlaced image, with no padding bits between scanlines, but between
reduced images so that each reduced image starts at a byte.
out: the same pixels, but re-ordered so that they're now a non-interlaced image with size w*h
bpp: bits per pixel
out has the following size in bits: w * h * bpp.
in is possibly bigger due to padding bits between reduced images.
out must be big enough AND must be 0 everywhere if bpp < 8 in the current implementation
(because that's likely a little bit faster)
NOTE: comments about padding bits are only relevant if bpp < 8
*/
static void Adam7_deinterlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) {
unsigned passw[7], passh[7];
size_t filter_passstart[8], padded_passstart[8], passstart[8];
unsigned i;
Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
if(bpp >= 8) {
for(i = 0; i != 7; ++i) {
unsigned x, y, b;
size_t bytewidth = bpp / 8;
for(y = 0; y < passh[i]; ++y)
for(x = 0; x < passw[i]; ++x) {
size_t pixelinstart = passstart[i] + (y * passw[i] + x) * bytewidth;
size_t pixeloutstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth;
for(b = 0; b < bytewidth; ++b) {
out[pixeloutstart + b] = in[pixelinstart + b];
}
}
}
} else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ {
for(i = 0; i != 7; ++i) {
unsigned x, y, b;
unsigned ilinebits = bpp * passw[i];
unsigned olinebits = bpp * w;
size_t obp, ibp; /*bit pointers (for out and in buffer)*/
for(y = 0; y < passh[i]; ++y)
for(x = 0; x < passw[i]; ++x) {
ibp = (8 * passstart[i]) + (y * ilinebits + x * bpp);
obp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp;
for(b = 0; b < bpp; ++b) {
unsigned char bit = readBitFromReversedStream(&ibp, in);
/*note that this function assumes the out buffer is completely 0, use setBitOfReversedStream otherwise*/
setBitOfReversedStream0(&obp, out, bit);
}
}
}
}
}
static void removePaddingBits(unsigned char* out, const unsigned char* in,
size_t olinebits, size_t ilinebits, unsigned h) {
/*
After filtering there are still padding bits if scanlines have non multiple of 8 bit amounts. They need
to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers
for the Adam7 code, the color convert code and the output to the user.
in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must
have >= ilinebits*h bits, out must have >= olinebits*h bits, olinebits must be <= ilinebits
also used to move bits after earlier such operations happened, e.g. in a sequence of reduced images from Adam7
only useful if (ilinebits - olinebits) is a value in the range 1..7
*/
unsigned y;
size_t diff = ilinebits - olinebits;
size_t ibp = 0, obp = 0; /*input and output bit pointers*/
for(y = 0; y < h; ++y) {
size_t x;
for(x = 0; x < olinebits; ++x) {
unsigned char bit = readBitFromReversedStream(&ibp, in);
setBitOfReversedStream(&obp, out, bit);
}
ibp += diff;
}
}
/*out must be buffer big enough to contain full image, and in must contain the full decompressed data from
the IDAT chunks (with filter index bytes and possible padding bits)
return value is error*/
static unsigned postProcessScanlines(unsigned char* out, unsigned char* in,
unsigned w, unsigned h, const LodePNGInfo* info_png) {
/*
This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype.
Steps:
*) if no Adam7: 1) unfilter 2) remove padding bits (= posible extra bits per scanline if bpp < 8)
*) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace
NOTE: the in buffer will be overwritten with intermediate data!
*/
unsigned bpp = lodepng_get_bpp(&info_png->color);
if(bpp == 0) return 31; /*error: invalid colortype*/
if(info_png->interlace_method == 0) {
if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8) {
CERROR_TRY_RETURN(unfilter(in, in, w, h, bpp));
removePaddingBits(out, in, w * bpp, ((w * bpp + 7) / 8) * 8, h);
}
/*we can immediately filter into the out buffer, no other steps needed*/
else CERROR_TRY_RETURN(unfilter(out, in, w, h, bpp));
} else /*interlace_method is 1 (Adam7)*/ {
unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8];
unsigned i;
Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
for(i = 0; i != 7; ++i) {
CERROR_TRY_RETURN(unfilter(&in[padded_passstart[i]], &in[filter_passstart[i]], passw[i], passh[i], bpp));
/*TODO: possible efficiency improvement: if in this reduced image the bits fit nicely in 1 scanline,
move bytes instead of bits or move not at all*/
if(bpp < 8) {
/*remove padding bits in scanlines; after this there still may be padding
bits between the different reduced images: each reduced image still starts nicely at a byte*/
removePaddingBits(&in[passstart[i]], &in[padded_passstart[i]], passw[i] * bpp,
((passw[i] * bpp + 7) / 8) * 8, passh[i]);
}
}
Adam7_deinterlace(out, in, w, h, bpp);
}
return 0;
}
static unsigned readChunk_PLTE(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) {
unsigned pos = 0, i;
if(color->palette) lodepng_free(color->palette);
color->palettesize = chunkLength / 3;
color->palette = (unsigned char*)lodepng_malloc(4 * color->palettesize);
if(!color->palette && color->palettesize) {
color->palettesize = 0;
return 83; /*alloc fail*/
}
if(color->palettesize > 256) return 38; /*error: palette too big*/
for(i = 0; i != color->palettesize; ++i) {
color->palette[4 * i + 0] = data[pos++]; /*R*/
color->palette[4 * i + 1] = data[pos++]; /*G*/
color->palette[4 * i + 2] = data[pos++]; /*B*/
color->palette[4 * i + 3] = 255; /*alpha*/
}
return 0; /* OK */
}
static unsigned readChunk_tRNS(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) {
unsigned i;
if(color->colortype == LCT_PALETTE) {
/*error: more alpha values given than there are palette entries*/
if(chunkLength > color->palettesize) return 39;
for(i = 0; i != chunkLength; ++i) color->palette[4 * i + 3] = data[i];
} else if(color->colortype == LCT_GREY) {
/*error: this chunk must be 2 bytes for grayscale image*/
if(chunkLength != 2) return 30;
color->key_defined = 1;
color->key_r = color->key_g = color->key_b = 256u * data[0] + data[1];
} else if(color->colortype == LCT_RGB) {
/*error: this chunk must be 6 bytes for RGB image*/
if(chunkLength != 6) return 41;
color->key_defined = 1;
color->key_r = 256u * data[0] + data[1];
color->key_g = 256u * data[2] + data[3];
color->key_b = 256u * data[4] + data[5];
}
else return 42; /*error: tRNS chunk not allowed for other color models*/
return 0; /* OK */
}
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*background color chunk (bKGD)*/
static unsigned readChunk_bKGD(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
if(info->color.colortype == LCT_PALETTE) {
/*error: this chunk must be 1 byte for indexed color image*/
if(chunkLength != 1) return 43;
/*error: invalid palette index, or maybe this chunk appeared before PLTE*/
if(data[0] >= info->color.palettesize) return 103;
info->background_defined = 1;
info->background_r = info->background_g = info->background_b = data[0];
} else if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) {
/*error: this chunk must be 2 bytes for grayscale image*/
if(chunkLength != 2) return 44;
/*the values are truncated to bitdepth in the PNG file*/
info->background_defined = 1;
info->background_r = info->background_g = info->background_b = 256u * data[0] + data[1];
} else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) {
/*error: this chunk must be 6 bytes for grayscale image*/
if(chunkLength != 6) return 45;
/*the values are truncated to bitdepth in the PNG file*/
info->background_defined = 1;
info->background_r = 256u * data[0] + data[1];
info->background_g = 256u * data[2] + data[3];
info->background_b = 256u * data[4] + data[5];
}
return 0; /* OK */
}
/*text chunk (tEXt)*/
static unsigned readChunk_tEXt(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
unsigned error = 0;
char *key = 0, *str = 0;
unsigned i;
while(!error) /*not really a while loop, only used to break on error*/ {
unsigned length, string2_begin;
length = 0;
while(length < chunkLength && data[length] != 0) ++length;
/*even though it's not allowed by the standard, no error is thrown if
there's no null termination char, if the text is empty*/
if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
key = (char*)lodepng_malloc(length + 1);
if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
key[length] = 0;
for(i = 0; i != length; ++i) key[i] = (char)data[i];
string2_begin = length + 1; /*skip keyword null terminator*/
length = (unsigned)(chunkLength < string2_begin ? 0 : chunkLength - string2_begin);
str = (char*)lodepng_malloc(length + 1);
if(!str) CERROR_BREAK(error, 83); /*alloc fail*/
str[length] = 0;
for(i = 0; i != length; ++i) str[i] = (char)data[string2_begin + i];
error = lodepng_add_text(info, key, str);
break;
}
lodepng_free(key);
lodepng_free(str);
return error;
}
/*compressed text chunk (zTXt)*/
static unsigned readChunk_zTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings,
const unsigned char* data, size_t chunkLength) {
unsigned error = 0;
unsigned i;
unsigned length, string2_begin;
char *key = 0;
ucvector decoded;
ucvector_init(&decoded);
while(!error) /*not really a while loop, only used to break on error*/ {
for(length = 0; length < chunkLength && data[length] != 0; ++length) ;
if(length + 2 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/
if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
key = (char*)lodepng_malloc(length + 1);
if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
key[length] = 0;
for(i = 0; i != length; ++i) key[i] = (char)data[i];
if(data[length + 1] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/
string2_begin = length + 2;
if(string2_begin > chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/
length = (unsigned)chunkLength - string2_begin;
/*will fail if zlib error, e.g. if length is too small*/
error = zlib_decompress(&decoded.data, &decoded.size,
(unsigned char*)(&data[string2_begin]),
length, zlibsettings);
if(error) break;
ucvector_push_back(&decoded, 0);
error = lodepng_add_text(info, key, (char*)decoded.data);
break;
}
lodepng_free(key);
ucvector_cleanup(&decoded);
return error;
}
/*international text chunk (iTXt)*/
static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings,
const unsigned char* data, size_t chunkLength) {
unsigned error = 0;
unsigned i;
unsigned length, begin, compressed;
char *key = 0, *langtag = 0, *transkey = 0;
ucvector decoded;
ucvector_init(&decoded); /* TODO: only use in case of compressed text */
while(!error) /*not really a while loop, only used to break on error*/ {
/*Quick check if the chunk length isn't too small. Even without check
it'd still fail with other error checks below if it's too short. This just gives a different error code.*/
if(chunkLength < 5) CERROR_BREAK(error, 30); /*iTXt chunk too short*/
/*read the key*/
for(length = 0; length < chunkLength && data[length] != 0; ++length) ;
if(length + 3 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination char, corrupt?*/
if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/
key = (char*)lodepng_malloc(length + 1);
if(!key) CERROR_BREAK(error, 83); /*alloc fail*/
key[length] = 0;
for(i = 0; i != length; ++i) key[i] = (char)data[i];
/*read the compression method*/
compressed = data[length + 1];
if(data[length + 2] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/
/*even though it's not allowed by the standard, no error is thrown if
there's no null termination char, if the text is empty for the next 3 texts*/
/*read the langtag*/
begin = length + 3;
length = 0;
for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length;
langtag = (char*)lodepng_malloc(length + 1);
if(!langtag) CERROR_BREAK(error, 83); /*alloc fail*/
langtag[length] = 0;
for(i = 0; i != length; ++i) langtag[i] = (char)data[begin + i];
/*read the transkey*/
begin += length + 1;
length = 0;
for(i = begin; i < chunkLength && data[i] != 0; ++i) ++length;
transkey = (char*)lodepng_malloc(length + 1);
if(!transkey) CERROR_BREAK(error, 83); /*alloc fail*/
transkey[length] = 0;
for(i = 0; i != length; ++i) transkey[i] = (char)data[begin + i];
/*read the actual text*/
begin += length + 1;
length = (unsigned)chunkLength < begin ? 0 : (unsigned)chunkLength - begin;
if(compressed) {
/*will fail if zlib error, e.g. if length is too small*/
error = zlib_decompress(&decoded.data, &decoded.size,
(unsigned char*)(&data[begin]),
length, zlibsettings);
if(error) break;
if(decoded.allocsize < decoded.size) decoded.allocsize = decoded.size;
ucvector_push_back(&decoded, 0);
} else {
if(!ucvector_resize(&decoded, length + 1)) CERROR_BREAK(error, 83 /*alloc fail*/);
decoded.data[length] = 0;
for(i = 0; i != length; ++i) decoded.data[i] = data[begin + i];
}
error = lodepng_add_itext(info, key, langtag, transkey, (char*)decoded.data);
break;
}
lodepng_free(key);
lodepng_free(langtag);
lodepng_free(transkey);
ucvector_cleanup(&decoded);
return error;
}
static unsigned readChunk_tIME(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
if(chunkLength != 7) return 73; /*invalid tIME chunk size*/
info->time_defined = 1;
info->time.year = 256u * data[0] + data[1];
info->time.month = data[2];
info->time.day = data[3];
info->time.hour = data[4];
info->time.minute = data[5];
info->time.second = data[6];
return 0; /* OK */
}
static unsigned readChunk_pHYs(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
if(chunkLength != 9) return 74; /*invalid pHYs chunk size*/
info->phys_defined = 1;
info->phys_x = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3];
info->phys_y = 16777216u * data[4] + 65536u * data[5] + 256u * data[6] + data[7];
info->phys_unit = data[8];
return 0; /* OK */
}
static unsigned readChunk_gAMA(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
if(chunkLength != 4) return 96; /*invalid gAMA chunk size*/
info->gama_defined = 1;
info->gama_gamma = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3];
return 0; /* OK */
}
static unsigned readChunk_cHRM(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
if(chunkLength != 32) return 97; /*invalid cHRM chunk size*/
info->chrm_defined = 1;
info->chrm_white_x = 16777216u * data[ 0] + 65536u * data[ 1] + 256u * data[ 2] + data[ 3];
info->chrm_white_y = 16777216u * data[ 4] + 65536u * data[ 5] + 256u * data[ 6] + data[ 7];
info->chrm_red_x = 16777216u * data[ 8] + 65536u * data[ 9] + 256u * data[10] + data[11];
info->chrm_red_y = 16777216u * data[12] + 65536u * data[13] + 256u * data[14] + data[15];
info->chrm_green_x = 16777216u * data[16] + 65536u * data[17] + 256u * data[18] + data[19];
info->chrm_green_y = 16777216u * data[20] + 65536u * data[21] + 256u * data[22] + data[23];
info->chrm_blue_x = 16777216u * data[24] + 65536u * data[25] + 256u * data[26] + data[27];
info->chrm_blue_y = 16777216u * data[28] + 65536u * data[29] + 256u * data[30] + data[31];
return 0; /* OK */
}
static unsigned readChunk_sRGB(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) {
if(chunkLength != 1) return 98; /*invalid sRGB chunk size (this one is never ignored)*/
info->srgb_defined = 1;
info->srgb_intent = data[0];
return 0; /* OK */
}
static unsigned readChunk_iCCP(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings,
const unsigned char* data, size_t chunkLength) {
unsigned error = 0;
unsigned i;
unsigned length, string2_begin;
ucvector decoded;
info->iccp_defined = 1;
if(info->iccp_name) lodepng_clear_icc(info);
for(length = 0; length < chunkLength && data[length] != 0; ++length) ;
if(length + 2 >= chunkLength) return 75; /*no null termination, corrupt?*/
if(length < 1 || length > 79) return 89; /*keyword too short or long*/
info->iccp_name = (char*)lodepng_malloc(length + 1);
if(!info->iccp_name) return 83; /*alloc fail*/
info->iccp_name[length] = 0;
for(i = 0; i != length; ++i) info->iccp_name[i] = (char)data[i];
if(data[length + 1] != 0) return 72; /*the 0 byte indicating compression must be 0*/
string2_begin = length + 2;
if(string2_begin > chunkLength) return 75; /*no null termination, corrupt?*/
length = (unsigned)chunkLength - string2_begin;
ucvector_init(&decoded);
error = zlib_decompress(&decoded.data, &decoded.size,
(unsigned char*)(&data[string2_begin]),
length, zlibsettings);
if(!error) {
info->iccp_profile_size = (unsigned int)decoded.size;
info->iccp_profile = (unsigned char*)lodepng_malloc(decoded.size);
if(info->iccp_profile) {
memcpy(info->iccp_profile, decoded.data, decoded.size);
} else {
error = 83; /* alloc fail */
}
}
ucvector_cleanup(&decoded);
return error;
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
unsigned lodepng_inspect_chunk(LodePNGState* state, size_t pos,
const unsigned char* in, size_t insize) {
const unsigned char* chunk = in + pos;
unsigned chunkLength;
const unsigned char* data;
unsigned unhandled = 0;
unsigned error = 0;
if (pos + 4 > insize) return 30;
chunkLength = lodepng_chunk_length(chunk);
if(chunkLength > 2147483647) return 63;
data = lodepng_chunk_data_const(chunk);
if(data + chunkLength + 4 > in + insize) return 30;
if(lodepng_chunk_type_equals(chunk, "PLTE")) {
error = readChunk_PLTE(&state->info_png.color, data, chunkLength);
} else if(lodepng_chunk_type_equals(chunk, "tRNS")) {
error = readChunk_tRNS(&state->info_png.color, data, chunkLength);
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
} else if(lodepng_chunk_type_equals(chunk, "bKGD")) {
error = readChunk_bKGD(&state->info_png, data, chunkLength);
} else if(lodepng_chunk_type_equals(chunk, "tEXt")) {
error = readChunk_tEXt(&state->info_png, data, chunkLength);
} else if(lodepng_chunk_type_equals(chunk, "zTXt")) {
error = readChunk_zTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
} else if(lodepng_chunk_type_equals(chunk, "iTXt")) {
error = readChunk_iTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
} else if(lodepng_chunk_type_equals(chunk, "tIME")) {
error = readChunk_tIME(&state->info_png, data, chunkLength);
} else if(lodepng_chunk_type_equals(chunk, "pHYs")) {
error = readChunk_pHYs(&state->info_png, data, chunkLength);
} else if(lodepng_chunk_type_equals(chunk, "gAMA")) {
error = readChunk_gAMA(&state->info_png, data, chunkLength);
} else if(lodepng_chunk_type_equals(chunk, "cHRM")) {
error = readChunk_cHRM(&state->info_png, data, chunkLength);
} else if(lodepng_chunk_type_equals(chunk, "sRGB")) {
error = readChunk_sRGB(&state->info_png, data, chunkLength);
} else if(lodepng_chunk_type_equals(chunk, "iCCP")) {
error = readChunk_iCCP(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
} else {
/* unhandled chunk is ok (is not an error) */
unhandled = 1;
}
if(!error && !unhandled && !state->decoder.ignore_crc) {
if(lodepng_chunk_check_crc(chunk)) return 57; /*invalid CRC*/
}
return error;
}
/*read a PNG, the result will be in the same color type as the PNG (hence "generic")*/
static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h,
LodePNGState* state,
const unsigned char* in, size_t insize) {
unsigned char IEND = 0;
const unsigned char* chunk;
size_t i;
ucvector idat; /*the data from idat chunks*/
ucvector scanlines;
size_t predict;
size_t outsize = 0;
/*for unknown chunk order*/
unsigned unknown = 0;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
unsigned critical_pos = 1; /*1 = after IHDR, 2 = after PLTE, 3 = after IDAT*/
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
/* safe output values in case error happens */
*out = 0;
*w = *h = 0;
state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/
if(state->error) return;
if(lodepng_pixel_overflow(*w, *h, &state->info_png.color, &state->info_raw)) {
CERROR_RETURN(state->error, 92); /*overflow possible due to amount of pixels*/
}
ucvector_init(&idat);
chunk = &in[33]; /*first byte of the first chunk after the header*/
/*loop through the chunks, ignoring unknown chunks and stopping at IEND chunk.
IDAT data is put at the start of the in buffer*/
while(!IEND && !state->error) {
unsigned chunkLength;
const unsigned char* data; /*the data in the chunk*/
/*error: size of the in buffer too small to contain next chunk*/
if((size_t)((chunk - in) + 12) > insize || chunk < in) {
if(state->decoder.ignore_end) break; /*other errors may still happen though*/
CERROR_BREAK(state->error, 30);
}
/*length of the data of the chunk, excluding the length bytes, chunk type and CRC bytes*/
chunkLength = lodepng_chunk_length(chunk);
/*error: chunk length larger than the max PNG chunk size*/
if(chunkLength > 2147483647) {
if(state->decoder.ignore_end) break; /*other errors may still happen though*/
CERROR_BREAK(state->error, 63);
}
if((size_t)((chunk - in) + chunkLength + 12) > insize || (chunk + chunkLength + 12) < in) {
CERROR_BREAK(state->error, 64); /*error: size of the in buffer too small to contain next chunk*/
}
data = lodepng_chunk_data_const(chunk);
unknown = 0;
/*IDAT chunk, containing compressed image data*/
if(lodepng_chunk_type_equals(chunk, "IDAT")) {
size_t oldsize = idat.size;
size_t newsize;
if(lodepng_addofl(oldsize, chunkLength, &newsize)) CERROR_BREAK(state->error, 95);
if(!ucvector_resize(&idat, newsize)) CERROR_BREAK(state->error, 83 /*alloc fail*/);
for(i = 0; i != chunkLength; ++i) idat.data[oldsize + i] = data[i];
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
critical_pos = 3;
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
} else if(lodepng_chunk_type_equals(chunk, "IEND")) {
/*IEND chunk*/
IEND = 1;
} else if(lodepng_chunk_type_equals(chunk, "PLTE")) {
/*palette chunk (PLTE)*/
state->error = readChunk_PLTE(&state->info_png.color, data, chunkLength);
if(state->error) break;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
critical_pos = 2;
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
} else if(lodepng_chunk_type_equals(chunk, "tRNS")) {
/*palette transparency chunk (tRNS). Even though this one is an ancillary chunk , it is still compiled
in without 'LODEPNG_COMPILE_ANCILLARY_CHUNKS' because it contains essential color information that
affects the alpha channel of pixels. */
state->error = readChunk_tRNS(&state->info_png.color, data, chunkLength);
if(state->error) break;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*background color chunk (bKGD)*/
} else if(lodepng_chunk_type_equals(chunk, "bKGD")) {
state->error = readChunk_bKGD(&state->info_png, data, chunkLength);
if(state->error) break;
} else if(lodepng_chunk_type_equals(chunk, "tEXt")) {
/*text chunk (tEXt)*/
if(state->decoder.read_text_chunks) {
state->error = readChunk_tEXt(&state->info_png, data, chunkLength);
if(state->error) break;
}
} else if(lodepng_chunk_type_equals(chunk, "zTXt")) {
/*compressed text chunk (zTXt)*/
if(state->decoder.read_text_chunks) {
state->error = readChunk_zTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
if(state->error) break;
}
} else if(lodepng_chunk_type_equals(chunk, "iTXt")) {
/*international text chunk (iTXt)*/
if(state->decoder.read_text_chunks) {
state->error = readChunk_iTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
if(state->error) break;
}
} else if(lodepng_chunk_type_equals(chunk, "tIME")) {
state->error = readChunk_tIME(&state->info_png, data, chunkLength);
if(state->error) break;
} else if(lodepng_chunk_type_equals(chunk, "pHYs")) {
state->error = readChunk_pHYs(&state->info_png, data, chunkLength);
if(state->error) break;
} else if(lodepng_chunk_type_equals(chunk, "gAMA")) {
state->error = readChunk_gAMA(&state->info_png, data, chunkLength);
if(state->error) break;
} else if(lodepng_chunk_type_equals(chunk, "cHRM")) {
state->error = readChunk_cHRM(&state->info_png, data, chunkLength);
if(state->error) break;
} else if(lodepng_chunk_type_equals(chunk, "sRGB")) {
state->error = readChunk_sRGB(&state->info_png, data, chunkLength);
if(state->error) break;
} else if(lodepng_chunk_type_equals(chunk, "iCCP")) {
state->error = readChunk_iCCP(&state->info_png, &state->decoder.zlibsettings, data, chunkLength);
if(state->error) break;
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
} else /*it's not an implemented chunk type, so ignore it: skip over the data*/ {
/*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/
if(!state->decoder.ignore_critical && !lodepng_chunk_ancillary(chunk)) {
CERROR_BREAK(state->error, 69);
}
unknown = 1;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
if(state->decoder.remember_unknown_chunks) {
state->error = lodepng_chunk_append(&state->info_png.unknown_chunks_data[critical_pos - 1],
&state->info_png.unknown_chunks_size[critical_pos - 1], chunk);
if(state->error) break;
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
}
if(!state->decoder.ignore_crc && !unknown) /*check CRC if wanted, only on known chunk types*/ {
if(lodepng_chunk_check_crc(chunk)) CERROR_BREAK(state->error, 57); /*invalid CRC*/
}
if(!IEND) chunk = lodepng_chunk_next_const(chunk);
}
ucvector_init(&scanlines);
/*predict output size, to allocate exact size for output buffer to avoid more dynamic allocation.
If the decompressed size does not match the prediction, the image must be corrupt.*/
if(state->info_png.interlace_method == 0) {
predict = lodepng_get_raw_size_idat(*w, *h, &state->info_png.color);
} else {
/*Adam-7 interlaced: predicted size is the sum of the 7 sub-images sizes*/
const LodePNGColorMode* color = &state->info_png.color;
predict = 0;
predict += lodepng_get_raw_size_idat((*w + 7) >> 3, (*h + 7) >> 3, color);
if(*w > 4) predict += lodepng_get_raw_size_idat((*w + 3) >> 3, (*h + 7) >> 3, color);
predict += lodepng_get_raw_size_idat((*w + 3) >> 2, (*h + 3) >> 3, color);
if(*w > 2) predict += lodepng_get_raw_size_idat((*w + 1) >> 2, (*h + 3) >> 2, color);
predict += lodepng_get_raw_size_idat((*w + 1) >> 1, (*h + 1) >> 2, color);
if(*w > 1) predict += lodepng_get_raw_size_idat((*w + 0) >> 1, (*h + 1) >> 1, color);
predict += lodepng_get_raw_size_idat((*w + 0), (*h + 0) >> 1, color);
}
if(!state->error && !ucvector_reserve(&scanlines, predict)) state->error = 83; /*alloc fail*/
if(!state->error) {
state->error = zlib_decompress(&scanlines.data, &scanlines.size, idat.data,
idat.size, &state->decoder.zlibsettings);
if(!state->error && scanlines.size != predict) state->error = 91; /*decompressed size doesn't match prediction*/
}
ucvector_cleanup(&idat);
if(!state->error) {
outsize = lodepng_get_raw_size(*w, *h, &state->info_png.color);
*out = (unsigned char*)lodepng_malloc(outsize);
if(!*out) state->error = 83; /*alloc fail*/
}
if(!state->error) {
for(i = 0; i < outsize; i++) (*out)[i] = 0;
state->error = postProcessScanlines(*out, scanlines.data, *w, *h, &state->info_png);
}
ucvector_cleanup(&scanlines);
}
unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h,
LodePNGState* state,
const unsigned char* in, size_t insize) {
*out = 0;
decodeGeneric(out, w, h, state, in, insize);
if(state->error) return state->error;
if(!state->decoder.color_convert || lodepng_color_mode_equal(&state->info_raw, &state->info_png.color)) {
/*same color type, no copying or converting of data needed*/
/*store the info_png color settings on the info_raw so that the info_raw still reflects what colortype
the raw image has to the end user*/
if(!state->decoder.color_convert) {
state->error = lodepng_color_mode_copy(&state->info_raw, &state->info_png.color);
if(state->error) return state->error;
}
} else {
/*color conversion needed; sort of copy of the data*/
unsigned char* data = *out;
size_t outsize;
/*TODO: check if this works according to the statement in the documentation: "The converter can convert
from grayscale input color type, to 8-bit grayscale or grayscale with alpha"*/
if(!(state->info_raw.colortype == LCT_RGB || state->info_raw.colortype == LCT_RGBA)
&& !(state->info_raw.bitdepth == 8)) {
return 56; /*unsupported color mode conversion*/
}
outsize = lodepng_get_raw_size(*w, *h, &state->info_raw);
*out = (unsigned char*)lodepng_malloc(outsize);
if(!(*out)) {
state->error = 83; /*alloc fail*/
}
else state->error = lodepng_convert(*out, data, &state->info_raw,
&state->info_png.color, *w, *h);
lodepng_free(data);
}
return state->error;
}
unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in,
size_t insize, LodePNGColorType colortype, unsigned bitdepth) {
unsigned error;
LodePNGState state;
lodepng_state_init(&state);
state.info_raw.colortype = colortype;
state.info_raw.bitdepth = bitdepth;
error = lodepng_decode(out, w, h, &state, in, insize);
lodepng_state_cleanup(&state);
return error;
}
unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) {
return lodepng_decode_memory(out, w, h, in, insize, LCT_RGBA, 8);
}
unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) {
return lodepng_decode_memory(out, w, h, in, insize, LCT_RGB, 8);
}
#ifdef LODEPNG_COMPILE_DISK
unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename,
LodePNGColorType colortype, unsigned bitdepth) {
unsigned char* buffer = 0;
size_t buffersize;
unsigned error;
/* safe output values in case error happens */
*out = 0;
*w = *h = 0;
error = lodepng_load_file(&buffer, &buffersize, filename);
if(!error) error = lodepng_decode_memory(out, w, h, buffer, buffersize, colortype, bitdepth);
lodepng_free(buffer);
return error;
}
unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) {
return lodepng_decode_file(out, w, h, filename, LCT_RGBA, 8);
}
unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) {
return lodepng_decode_file(out, w, h, filename, LCT_RGB, 8);
}
#endif /*LODEPNG_COMPILE_DISK*/
void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings) {
settings->color_convert = 1;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
settings->read_text_chunks = 1;
settings->remember_unknown_chunks = 0;
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
settings->ignore_crc = 0;
settings->ignore_critical = 0;
settings->ignore_end = 0;
lodepng_decompress_settings_init(&settings->zlibsettings);
}
#endif /*LODEPNG_COMPILE_DECODER*/
#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER)
void lodepng_state_init(LodePNGState* state) {
#ifdef LODEPNG_COMPILE_DECODER
lodepng_decoder_settings_init(&state->decoder);
#endif /*LODEPNG_COMPILE_DECODER*/
#ifdef LODEPNG_COMPILE_ENCODER
lodepng_encoder_settings_init(&state->encoder);
#endif /*LODEPNG_COMPILE_ENCODER*/
lodepng_color_mode_init(&state->info_raw);
lodepng_info_init(&state->info_png);
state->error = 1;
}
void lodepng_state_cleanup(LodePNGState* state) {
lodepng_color_mode_cleanup(&state->info_raw);
lodepng_info_cleanup(&state->info_png);
}
void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source) {
lodepng_state_cleanup(dest);
*dest = *source;
lodepng_color_mode_init(&dest->info_raw);
lodepng_info_init(&dest->info_png);
dest->error = lodepng_color_mode_copy(&dest->info_raw, &source->info_raw); if(dest->error) return;
dest->error = lodepng_info_copy(&dest->info_png, &source->info_png); if(dest->error) return;
}
#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */
#ifdef LODEPNG_COMPILE_ENCODER
/* ////////////////////////////////////////////////////////////////////////// */
/* / PNG Encoder / */
/* ////////////////////////////////////////////////////////////////////////// */
/*chunkName must be string of 4 characters*/
static unsigned addChunk(ucvector* out, const char* chunkName, const unsigned char* data, size_t length) {
CERROR_TRY_RETURN(lodepng_chunk_create(&out->data, &out->size, (unsigned)length, chunkName, data));
out->allocsize = out->size; /*fix the allocsize again*/
return 0;
}
static void writeSignature(ucvector* out) {
/*8 bytes PNG signature, aka the magic bytes*/
ucvector_push_back(out, 137);
ucvector_push_back(out, 80);
ucvector_push_back(out, 78);
ucvector_push_back(out, 71);
ucvector_push_back(out, 13);
ucvector_push_back(out, 10);
ucvector_push_back(out, 26);
ucvector_push_back(out, 10);
}
static unsigned addChunk_IHDR(ucvector* out, unsigned w, unsigned h,
LodePNGColorType colortype, unsigned bitdepth, unsigned interlace_method) {
unsigned error = 0;
ucvector header;
ucvector_init(&header);
lodepng_add32bitInt(&header, w); /*width*/
lodepng_add32bitInt(&header, h); /*height*/
ucvector_push_back(&header, (unsigned char)bitdepth); /*bit depth*/
ucvector_push_back(&header, (unsigned char)colortype); /*color type*/
ucvector_push_back(&header, 0); /*compression method*/
ucvector_push_back(&header, 0); /*filter method*/
ucvector_push_back(&header, interlace_method); /*interlace method*/
error = addChunk(out, "IHDR", header.data, header.size);
ucvector_cleanup(&header);
return error;
}
static unsigned addChunk_PLTE(ucvector* out, const LodePNGColorMode* info) {
unsigned error = 0;
size_t i;
ucvector PLTE;
ucvector_init(&PLTE);
for(i = 0; i != info->palettesize * 4; ++i) {
/*add all channels except alpha channel*/
if(i % 4 != 3) ucvector_push_back(&PLTE, info->palette[i]);
}
error = addChunk(out, "PLTE", PLTE.data, PLTE.size);
ucvector_cleanup(&PLTE);
return error;
}
static unsigned addChunk_tRNS(ucvector* out, const LodePNGColorMode* info) {
unsigned error = 0;
size_t i;
ucvector tRNS;
ucvector_init(&tRNS);
if(info->colortype == LCT_PALETTE) {
size_t amount = info->palettesize;
/*the tail of palette values that all have 255 as alpha, does not have to be encoded*/
for(i = info->palettesize; i != 0; --i) {
if(info->palette[4 * (i - 1) + 3] == 255) --amount;
else break;
}
/*add only alpha channel*/
for(i = 0; i != amount; ++i) ucvector_push_back(&tRNS, info->palette[4 * i + 3]);
} else if(info->colortype == LCT_GREY) {
if(info->key_defined) {
ucvector_push_back(&tRNS, (unsigned char)(info->key_r >> 8));
ucvector_push_back(&tRNS, (unsigned char)(info->key_r & 255));
}
} else if(info->colortype == LCT_RGB) {
if(info->key_defined) {
ucvector_push_back(&tRNS, (unsigned char)(info->key_r >> 8));
ucvector_push_back(&tRNS, (unsigned char)(info->key_r & 255));
ucvector_push_back(&tRNS, (unsigned char)(info->key_g >> 8));
ucvector_push_back(&tRNS, (unsigned char)(info->key_g & 255));
ucvector_push_back(&tRNS, (unsigned char)(info->key_b >> 8));
ucvector_push_back(&tRNS, (unsigned char)(info->key_b & 255));
}
}
error = addChunk(out, "tRNS", tRNS.data, tRNS.size);
ucvector_cleanup(&tRNS);
return error;
}
static unsigned addChunk_IDAT(ucvector* out, const unsigned char* data, size_t datasize,
LodePNGCompressSettings* zlibsettings) {
ucvector zlibdata;
unsigned error = 0;
/*compress with the Zlib compressor*/
ucvector_init(&zlibdata);
error = zlib_compress(&zlibdata.data, &zlibdata.size, data, datasize, zlibsettings);
if(!error) error = addChunk(out, "IDAT", zlibdata.data, zlibdata.size);
ucvector_cleanup(&zlibdata);
return error;
}
static unsigned addChunk_IEND(ucvector* out) {
unsigned error = 0;
error = addChunk(out, "IEND", 0, 0);
return error;
}
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
static unsigned addChunk_tEXt(ucvector* out, const char* keyword, const char* textstring) {
unsigned error = 0;
size_t i;
ucvector text;
ucvector_init(&text);
for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&text, (unsigned char)keyword[i]);
if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
ucvector_push_back(&text, 0); /*0 termination char*/
for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&text, (unsigned char)textstring[i]);
error = addChunk(out, "tEXt", text.data, text.size);
ucvector_cleanup(&text);
return error;
}
static unsigned addChunk_zTXt(ucvector* out, const char* keyword, const char* textstring,
LodePNGCompressSettings* zlibsettings) {
unsigned error = 0;
ucvector data, compressed;
size_t i, textsize = strlen(textstring);
ucvector_init(&data);
ucvector_init(&compressed);
for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)keyword[i]);
if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
ucvector_push_back(&data, 0); /*0 termination char*/
ucvector_push_back(&data, 0); /*compression method: 0*/
error = zlib_compress(&compressed.data, &compressed.size,
(unsigned char*)textstring, textsize, zlibsettings);
if(!error) {
for(i = 0; i != compressed.size; ++i) ucvector_push_back(&data, compressed.data[i]);
error = addChunk(out, "zTXt", data.data, data.size);
}
ucvector_cleanup(&compressed);
ucvector_cleanup(&data);
return error;
}
static unsigned addChunk_iTXt(ucvector* out, unsigned compressed, const char* keyword, const char* langtag,
const char* transkey, const char* textstring, LodePNGCompressSettings* zlibsettings) {
unsigned error = 0;
ucvector data;
size_t i, textsize = strlen(textstring);
ucvector_init(&data);
for(i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)keyword[i]);
if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
ucvector_push_back(&data, 0); /*null termination char*/
ucvector_push_back(&data, compressed ? 1 : 0); /*compression flag*/
ucvector_push_back(&data, 0); /*compression method*/
for(i = 0; langtag[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)langtag[i]);
ucvector_push_back(&data, 0); /*null termination char*/
for(i = 0; transkey[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)transkey[i]);
ucvector_push_back(&data, 0); /*null termination char*/
if(compressed) {
ucvector compressed_data;
ucvector_init(&compressed_data);
error = zlib_compress(&compressed_data.data, &compressed_data.size,
(unsigned char*)textstring, textsize, zlibsettings);
if(!error) {
for(i = 0; i != compressed_data.size; ++i) ucvector_push_back(&data, compressed_data.data[i]);
}
ucvector_cleanup(&compressed_data);
} else /*not compressed*/ {
for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)textstring[i]);
}
if(!error) error = addChunk(out, "iTXt", data.data, data.size);
ucvector_cleanup(&data);
return error;
}
static unsigned addChunk_bKGD(ucvector* out, const LodePNGInfo* info) {
unsigned error = 0;
ucvector bKGD;
ucvector_init(&bKGD);
if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) {
ucvector_push_back(&bKGD, (unsigned char)(info->background_r >> 8));
ucvector_push_back(&bKGD, (unsigned char)(info->background_r & 255));
} else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) {
ucvector_push_back(&bKGD, (unsigned char)(info->background_r >> 8));
ucvector_push_back(&bKGD, (unsigned char)(info->background_r & 255));
ucvector_push_back(&bKGD, (unsigned char)(info->background_g >> 8));
ucvector_push_back(&bKGD, (unsigned char)(info->background_g & 255));
ucvector_push_back(&bKGD, (unsigned char)(info->background_b >> 8));
ucvector_push_back(&bKGD, (unsigned char)(info->background_b & 255));
} else if(info->color.colortype == LCT_PALETTE) {
ucvector_push_back(&bKGD, (unsigned char)(info->background_r & 255)); /*palette index*/
}
error = addChunk(out, "bKGD", bKGD.data, bKGD.size);
ucvector_cleanup(&bKGD);
return error;
}
static unsigned addChunk_tIME(ucvector* out, const LodePNGTime* time) {
unsigned error = 0;
unsigned char* data = (unsigned char*)lodepng_malloc(7);
if(!data) return 83; /*alloc fail*/
data[0] = (unsigned char)(time->year >> 8);
data[1] = (unsigned char)(time->year & 255);
data[2] = (unsigned char)time->month;
data[3] = (unsigned char)time->day;
data[4] = (unsigned char)time->hour;
data[5] = (unsigned char)time->minute;
data[6] = (unsigned char)time->second;
error = addChunk(out, "tIME", data, 7);
lodepng_free(data);
return error;
}
static unsigned addChunk_pHYs(ucvector* out, const LodePNGInfo* info) {
unsigned error = 0;
ucvector data;
ucvector_init(&data);
lodepng_add32bitInt(&data, info->phys_x);
lodepng_add32bitInt(&data, info->phys_y);
ucvector_push_back(&data, info->phys_unit);
error = addChunk(out, "pHYs", data.data, data.size);
ucvector_cleanup(&data);
return error;
}
static unsigned addChunk_gAMA(ucvector* out, const LodePNGInfo* info) {
unsigned error = 0;
ucvector data;
ucvector_init(&data);
lodepng_add32bitInt(&data, info->gama_gamma);
error = addChunk(out, "gAMA", data.data, data.size);
ucvector_cleanup(&data);
return error;
}
static unsigned addChunk_cHRM(ucvector* out, const LodePNGInfo* info) {
unsigned error = 0;
ucvector data;
ucvector_init(&data);
lodepng_add32bitInt(&data, info->chrm_white_x);
lodepng_add32bitInt(&data, info->chrm_white_y);
lodepng_add32bitInt(&data, info->chrm_red_x);
lodepng_add32bitInt(&data, info->chrm_red_y);
lodepng_add32bitInt(&data, info->chrm_green_x);
lodepng_add32bitInt(&data, info->chrm_green_y);
lodepng_add32bitInt(&data, info->chrm_blue_x);
lodepng_add32bitInt(&data, info->chrm_blue_y);
error = addChunk(out, "cHRM", data.data, data.size);
ucvector_cleanup(&data);
return error;
}
static unsigned addChunk_sRGB(ucvector* out, const LodePNGInfo* info) {
unsigned char data = info->srgb_intent;
return addChunk(out, "sRGB", &data, 1);
}
static unsigned addChunk_iCCP(ucvector* out, const LodePNGInfo* info, LodePNGCompressSettings* zlibsettings) {
unsigned error = 0;
ucvector data, compressed;
size_t i;
ucvector_init(&data);
ucvector_init(&compressed);
for(i = 0; info->iccp_name[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)info->iccp_name[i]);
if(i < 1 || i > 79) return 89; /*error: invalid keyword size*/
ucvector_push_back(&data, 0); /*0 termination char*/
ucvector_push_back(&data, 0); /*compression method: 0*/
error = zlib_compress(&compressed.data, &compressed.size,
info->iccp_profile, info->iccp_profile_size, zlibsettings);
if(!error) {
for(i = 0; i != compressed.size; ++i) ucvector_push_back(&data, compressed.data[i]);
error = addChunk(out, "iCCP", data.data, data.size);
}
ucvector_cleanup(&compressed);
ucvector_cleanup(&data);
return error;
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
static void filterScanline(unsigned char* out, const unsigned char* scanline, const unsigned char* prevline,
size_t length, size_t bytewidth, unsigned char filterType) {
size_t i;
switch(filterType) {
case 0: /*None*/
for(i = 0; i != length; ++i) out[i] = scanline[i];
break;
case 1: /*Sub*/
for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - scanline[i - bytewidth];
break;
case 2: /*Up*/
if(prevline) {
for(i = 0; i != length; ++i) out[i] = scanline[i] - prevline[i];
} else {
for(i = 0; i != length; ++i) out[i] = scanline[i];
}
break;
case 3: /*Average*/
if(prevline) {
for(i = 0; i != bytewidth; ++i) out[i] = scanline[i] - (prevline[i] >> 1);
for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - ((scanline[i - bytewidth] + prevline[i]) >> 1);
} else {
for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - (scanline[i - bytewidth] >> 1);
}
break;
case 4: /*Paeth*/
if(prevline) {
/*paethPredictor(0, prevline[i], 0) is always prevline[i]*/
for(i = 0; i != bytewidth; ++i) out[i] = (scanline[i] - prevline[i]);
for(i = bytewidth; i < length; ++i) {
out[i] = (scanline[i] - paethPredictor(scanline[i - bytewidth], prevline[i], prevline[i - bytewidth]));
}
} else {
for(i = 0; i != bytewidth; ++i) out[i] = scanline[i];
/*paethPredictor(scanline[i - bytewidth], 0, 0) is always scanline[i - bytewidth]*/
for(i = bytewidth; i < length; ++i) out[i] = (scanline[i] - scanline[i - bytewidth]);
}
break;
default: return; /*unexisting filter type given*/
}
}
/* log2 approximation. A slight bit faster than std::log. */
static float flog2(float f) {
float result = 0;
while(f > 32) { result += 4; f /= 16; }
while(f > 2) { ++result; f /= 2; }
return result + 1.442695f * (f * f * f / 3 - 3 * f * f / 2 + 3 * f - 1.83333f);
}
static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h,
const LodePNGColorMode* info, const LodePNGEncoderSettings* settings) {
/*
For PNG filter method 0
out must be a buffer with as size: h + (w * h * bpp + 7) / 8, because there are
the scanlines with 1 extra byte per scanline
*/
unsigned bpp = lodepng_get_bpp(info);
/*the width of a scanline in bytes, not including the filter type*/
size_t linebytes = (w * bpp + 7) / 8;
/*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/
size_t bytewidth = (bpp + 7) / 8;
const unsigned char* prevline = 0;
unsigned x, y;
unsigned error = 0;
LodePNGFilterStrategy strategy = settings->filter_strategy;
/*
There is a heuristic called the minimum sum of absolute differences heuristic, suggested by the PNG standard:
* If the image type is Palette, or the bit depth is smaller than 8, then do not filter the image (i.e.
use fixed filtering, with the filter None).
* (The other case) If the image type is Grayscale or RGB (with or without Alpha), and the bit depth is
not smaller than 8, then use adaptive filtering heuristic as follows: independently for each row, apply
all five filters and select the filter that produces the smallest sum of absolute values per row.
This heuristic is used if filter strategy is LFS_MINSUM and filter_palette_zero is true.
If filter_palette_zero is true and filter_strategy is not LFS_MINSUM, the above heuristic is followed,
but for "the other case", whatever strategy filter_strategy is set to instead of the minimum sum
heuristic is used.
*/
if(settings->filter_palette_zero &&
(info->colortype == LCT_PALETTE || info->bitdepth < 8)) strategy = LFS_ZERO;
if(bpp == 0) return 31; /*error: invalid color type*/
if(strategy == LFS_ZERO) {
for(y = 0; y != h; ++y) {
size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
size_t inindex = linebytes * y;
out[outindex] = 0; /*filter type byte*/
filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, 0);
prevline = &in[inindex];
}
} else if(strategy == LFS_MINSUM) {
/*adaptive filtering*/
size_t sum[5];
unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/
size_t smallest = 0;
unsigned char type, bestType = 0;
for(type = 0; type != 5; ++type) {
attempt[type] = (unsigned char*)lodepng_malloc(linebytes);
if(!attempt[type]) return 83; /*alloc fail*/
}
if(!error) {
for(y = 0; y != h; ++y) {
/*try the 5 filter types*/
for(type = 0; type != 5; ++type) {
filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type);
/*calculate the sum of the result*/
sum[type] = 0;
if(type == 0) {
for(x = 0; x != linebytes; ++x) sum[type] += (unsigned char)(attempt[type][x]);
} else {
for(x = 0; x != linebytes; ++x) {
/*For differences, each byte should be treated as signed, values above 127 are negative
(converted to signed char). Filtertype 0 isn't a difference though, so use unsigned there.
This means filtertype 0 is almost never chosen, but that is justified.*/
unsigned char s = attempt[type][x];
sum[type] += s < 128 ? s : (255U - s);
}
}
/*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/
if(type == 0 || sum[type] < smallest) {
bestType = type;
smallest = sum[type];
}
}
prevline = &in[y * linebytes];
/*now fill the out values*/
out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];
}
}
for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);
} else if(strategy == LFS_ENTROPY) {
float sum[5];
unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/
float smallest = 0;
unsigned type, bestType = 0;
unsigned count[256];
for(type = 0; type != 5; ++type) {
attempt[type] = (unsigned char*)lodepng_malloc(linebytes);
if(!attempt[type]) return 83; /*alloc fail*/
}
for(y = 0; y != h; ++y) {
/*try the 5 filter types*/
for(type = 0; type != 5; ++type) {
filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type);
for(x = 0; x != 256; ++x) count[x] = 0;
for(x = 0; x != linebytes; ++x) ++count[attempt[type][x]];
++count[type]; /*the filter type itself is part of the scanline*/
sum[type] = 0;
for(x = 0; x != 256; ++x) {
float p = count[x] / (float)(linebytes + 1);
sum[type] += count[x] == 0 ? 0 : flog2(1 / p) * p;
}
/*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/
if(type == 0 || sum[type] < smallest) {
bestType = type;
smallest = sum[type];
}
}
prevline = &in[y * linebytes];
/*now fill the out values*/
out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];
}
for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);
} else if(strategy == LFS_PREDEFINED) {
for(y = 0; y != h; ++y) {
size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/
size_t inindex = linebytes * y;
unsigned char type = settings->predefined_filters[y];
out[outindex] = type; /*filter type byte*/
filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type);
prevline = &in[inindex];
}
} else if(strategy == LFS_BRUTE_FORCE) {
/*brute force filter chooser.
deflate the scanline after every filter attempt to see which one deflates best.
This is very slow and gives only slightly smaller, sometimes even larger, result*/
size_t size[5];
unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/
size_t smallest = 0;
unsigned type = 0, bestType = 0;
unsigned char* dummy;
LodePNGCompressSettings zlibsettings = settings->zlibsettings;
/*use fixed tree on the attempts so that the tree is not adapted to the filtertype on purpose,
to simulate the true case where the tree is the same for the whole image. Sometimes it gives
better result with dynamic tree anyway. Using the fixed tree sometimes gives worse, but in rare
cases better compression. It does make this a bit less slow, so it's worth doing this.*/
zlibsettings.btype = 1;
/*a custom encoder likely doesn't read the btype setting and is optimized for complete PNG
images only, so disable it*/
zlibsettings.custom_zlib = 0;
zlibsettings.custom_deflate = 0;
for(type = 0; type != 5; ++type) {
attempt[type] = (unsigned char*)lodepng_malloc(linebytes);
if(!attempt[type]) return 83; /*alloc fail*/
}
for(y = 0; y != h; ++y) /*try the 5 filter types*/ {
for(type = 0; type != 5; ++type) {
unsigned testsize = (unsigned)linebytes;
/*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/
filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type);
size[type] = 0;
dummy = 0;
zlib_compress(&dummy, &size[type], attempt[type], testsize, &zlibsettings);
lodepng_free(dummy);
/*check if this is smallest size (or if type == 0 it's the first case so always store the values)*/
if(type == 0 || size[type] < smallest) {
bestType = type;
smallest = size[type];
}
}
prevline = &in[y * linebytes];
out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/
for(x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x];
}
for(type = 0; type != 5; ++type) lodepng_free(attempt[type]);
}
else return 88; /* unknown filter strategy */
return error;
}
static void addPaddingBits(unsigned char* out, const unsigned char* in,
size_t olinebits, size_t ilinebits, unsigned h) {
/*The opposite of the removePaddingBits function
olinebits must be >= ilinebits*/
unsigned y;
size_t diff = olinebits - ilinebits;
size_t obp = 0, ibp = 0; /*bit pointers*/
for(y = 0; y != h; ++y) {
size_t x;
for(x = 0; x < ilinebits; ++x) {
unsigned char bit = readBitFromReversedStream(&ibp, in);
setBitOfReversedStream(&obp, out, bit);
}
/*obp += diff; --> no, fill in some value in the padding bits too, to avoid
"Use of uninitialised value of size ###" warning from valgrind*/
for(x = 0; x != diff; ++x) setBitOfReversedStream(&obp, out, 0);
}
}
/*
in: non-interlaced image with size w*h
out: the same pixels, but re-ordered according to PNG's Adam7 interlacing, with
no padding bits between scanlines, but between reduced images so that each
reduced image starts at a byte.
bpp: bits per pixel
there are no padding bits, not between scanlines, not between reduced images
in has the following size in bits: w * h * bpp.
out is possibly bigger due to padding bits between reduced images
NOTE: comments about padding bits are only relevant if bpp < 8
*/
static void Adam7_interlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) {
unsigned passw[7], passh[7];
size_t filter_passstart[8], padded_passstart[8], passstart[8];
unsigned i;
Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
if(bpp >= 8) {
for(i = 0; i != 7; ++i) {
unsigned x, y, b;
size_t bytewidth = bpp / 8;
for(y = 0; y < passh[i]; ++y)
for(x = 0; x < passw[i]; ++x) {
size_t pixelinstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth;
size_t pixeloutstart = passstart[i] + (y * passw[i] + x) * bytewidth;
for(b = 0; b < bytewidth; ++b) {
out[pixeloutstart + b] = in[pixelinstart + b];
}
}
}
} else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ {
for(i = 0; i != 7; ++i) {
unsigned x, y, b;
unsigned ilinebits = bpp * passw[i];
unsigned olinebits = bpp * w;
size_t obp, ibp; /*bit pointers (for out and in buffer)*/
for(y = 0; y < passh[i]; ++y)
for(x = 0; x < passw[i]; ++x) {
ibp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp;
obp = (8 * passstart[i]) + (y * ilinebits + x * bpp);
for(b = 0; b < bpp; ++b) {
unsigned char bit = readBitFromReversedStream(&ibp, in);
setBitOfReversedStream(&obp, out, bit);
}
}
}
}
}
/*out must be buffer big enough to contain uncompressed IDAT chunk data, and in must contain the full image.
return value is error**/
static unsigned preProcessScanlines(unsigned char** out, size_t* outsize, const unsigned char* in,
unsigned w, unsigned h,
const LodePNGInfo* info_png, const LodePNGEncoderSettings* settings) {
/*
This function converts the pure 2D image with the PNG's colortype, into filtered-padded-interlaced data. Steps:
*) if no Adam7: 1) add padding bits (= posible extra bits per scanline if bpp < 8) 2) filter
*) if adam7: 1) Adam7_interlace 2) 7x add padding bits 3) 7x filter
*/
unsigned bpp = lodepng_get_bpp(&info_png->color);
unsigned error = 0;
if(info_png->interlace_method == 0) {
*outsize = h + (h * ((w * bpp + 7) / 8)); /*image size plus an extra byte per scanline + possible padding bits*/
*out = (unsigned char*)lodepng_malloc(*outsize);
if(!(*out) && (*outsize)) error = 83; /*alloc fail*/
if(!error) {
/*non multiple of 8 bits per scanline, padding bits needed per scanline*/
if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8) {
unsigned char* padded = (unsigned char*)lodepng_malloc(h * ((w * bpp + 7) / 8));
if(!padded) error = 83; /*alloc fail*/
if(!error) {
addPaddingBits(padded, in, ((w * bpp + 7) / 8) * 8, w * bpp, h);
error = filter(*out, padded, w, h, &info_png->color, settings);
}
lodepng_free(padded);
} else {
/*we can immediately filter into the out buffer, no other steps needed*/
error = filter(*out, in, w, h, &info_png->color, settings);
}
}
} else /*interlace_method is 1 (Adam7)*/ {
unsigned passw[7], passh[7];
size_t filter_passstart[8], padded_passstart[8], passstart[8];
unsigned char* adam7;
Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp);
*outsize = filter_passstart[7]; /*image size plus an extra byte per scanline + possible padding bits*/
*out = (unsigned char*)lodepng_malloc(*outsize);
if(!(*out)) error = 83; /*alloc fail*/
adam7 = (unsigned char*)lodepng_malloc(passstart[7]);
if(!adam7 && passstart[7]) error = 83; /*alloc fail*/
if(!error) {
unsigned i;
Adam7_interlace(adam7, in, w, h, bpp);
for(i = 0; i != 7; ++i) {
if(bpp < 8) {
unsigned char* padded = (unsigned char*)lodepng_malloc(padded_passstart[i + 1] - padded_passstart[i]);
if(!padded) ERROR_BREAK(83); /*alloc fail*/
addPaddingBits(padded, &adam7[passstart[i]],
((passw[i] * bpp + 7) / 8) * 8, passw[i] * bpp, passh[i]);
error = filter(&(*out)[filter_passstart[i]], padded,
passw[i], passh[i], &info_png->color, settings);
lodepng_free(padded);
} else {
error = filter(&(*out)[filter_passstart[i]], &adam7[padded_passstart[i]],
passw[i], passh[i], &info_png->color, settings);
}
if(error) break;
}
}
lodepng_free(adam7);
}
return error;
}
/*
palette must have 4 * palettesize bytes allocated, and given in format RGBARGBARGBARGBA...
returns 0 if the palette is opaque,
returns 1 if the palette has a single color with alpha 0 ==> color key
returns 2 if the palette is semi-translucent.
*/
static unsigned getPaletteTranslucency(const unsigned char* palette, size_t palettesize) {
size_t i;
unsigned key = 0;
unsigned r = 0, g = 0, b = 0; /*the value of the color with alpha 0, so long as color keying is possible*/
for(i = 0; i != palettesize; ++i) {
if(!key && palette[4 * i + 3] == 0) {
r = palette[4 * i + 0]; g = palette[4 * i + 1]; b = palette[4 * i + 2];
key = 1;
i = (size_t)(-1); /*restart from beginning, to detect earlier opaque colors with key's value*/
}
else if(palette[4 * i + 3] != 255) return 2;
/*when key, no opaque RGB may have key's RGB*/
else if(key && r == palette[i * 4 + 0] && g == palette[i * 4 + 1] && b == palette[i * 4 + 2]) return 2;
}
return key;
}
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
static unsigned addUnknownChunks(ucvector* out, unsigned char* data, size_t datasize) {
unsigned char* inchunk = data;
while((size_t)(inchunk - data) < datasize) {
CERROR_TRY_RETURN(lodepng_chunk_append(&out->data, &out->size, inchunk));
out->allocsize = out->size; /*fix the allocsize again*/
inchunk = lodepng_chunk_next(inchunk);
}
return 0;
}
static unsigned isGrayICCProfile(const unsigned char* profile, unsigned size) {
/*
It is a gray profile if bytes 16-19 are "GRAY", rgb profile if bytes 16-19
are "RGB ". We do not perform any full parsing of the ICC profile here, other
than check those 4 bytes to grayscale profile. Other than that, validity of
the profile is not checked. This is needed only because the PNG specification
requires using a non-gray color model if there is an ICC profile with "RGB "
(sadly limiting compression opportunities if the input data is grayscale RGB
data), and requires using a gray color model if it is "GRAY".
*/
if(size < 20) return 0;
return profile[16] == 'G' && profile[17] == 'R' && profile[18] == 'A' && profile[19] == 'Y';
}
static unsigned isRGBICCProfile(const unsigned char* profile, unsigned size) {
/* See comment in isGrayICCProfile*/
if(size < 20) return 0;
return profile[16] == 'R' && profile[17] == 'G' && profile[18] == 'B' && profile[19] == ' ';
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
unsigned lodepng_encode(unsigned char** out, size_t* outsize,
const unsigned char* image, unsigned w, unsigned h,
LodePNGState* state) {
unsigned char* data = 0; /*uncompressed version of the IDAT chunk data*/
size_t datasize = 0;
ucvector outv;
LodePNGInfo info;
ucvector_init(&outv);
lodepng_info_init(&info);
/*provide some proper output values if error will happen*/
*out = 0;
*outsize = 0;
state->error = 0;
/*check input values validity*/
if((state->info_png.color.colortype == LCT_PALETTE || state->encoder.force_palette)
&& (state->info_png.color.palettesize == 0 || state->info_png.color.palettesize > 256)) {
state->error = 68; /*invalid palette size, it is only allowed to be 1-256*/
goto cleanup;
}
if(state->encoder.zlibsettings.btype > 2) {
state->error = 61; /*error: unexisting btype*/
goto cleanup;
}
if(state->info_png.interlace_method > 1) {
state->error = 71; /*error: unexisting interlace mode*/
goto cleanup;
}
state->error = checkColorValidity(state->info_png.color.colortype, state->info_png.color.bitdepth);
if(state->error) goto cleanup; /*error: unexisting color type given*/
state->error = checkColorValidity(state->info_raw.colortype, state->info_raw.bitdepth);
if(state->error) goto cleanup; /*error: unexisting color type given*/
/* color convert and compute scanline filter types */
lodepng_info_copy(&info, &state->info_png);
if(state->encoder.auto_convert) {
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
if(state->info_png.background_defined) {
unsigned bg_r = state->info_png.background_r;
unsigned bg_g = state->info_png.background_g;
unsigned bg_b = state->info_png.background_b;
unsigned r = 0, g = 0, b = 0;
LodePNGColorProfile prof;
LodePNGColorMode mode16 = lodepng_color_mode_make(LCT_RGB, 16);
lodepng_convert_rgb(&r, &g, &b, bg_r, bg_g, bg_b, &mode16, &state->info_png.color);
lodepng_color_profile_init(&prof);
state->error = lodepng_get_color_profile(&prof, image, w, h, &state->info_raw);
if(state->error) goto cleanup;
lodepng_color_profile_add(&prof, r, g, b, 65535);
state->error = auto_choose_color_from_profile(&info.color, &state->info_raw, &prof);
if(state->error) goto cleanup;
if(lodepng_convert_rgb(&info.background_r, &info.background_g, &info.background_b,
bg_r, bg_g, bg_b, &info.color, &state->info_png.color)) {
state->error = 104;
goto cleanup;
}
}
else
#endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */
{
state->error = lodepng_auto_choose_color(&info.color, image, w, h, &state->info_raw);
if(state->error) goto cleanup;
}
}
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
if(state->info_png.iccp_defined) {
unsigned gray_icc = isGrayICCProfile(state->info_png.iccp_profile, state->info_png.iccp_profile_size);
unsigned gray_png = info.color.colortype == LCT_GREY || info.color.colortype == LCT_GREY_ALPHA;
/* TODO: perhaps instead of giving errors or less optimal compression, we can automatically modify
the ICC profile here to say "GRAY" or "RGB " to match the PNG color type, unless this will require
non trivial changes to the rest of the ICC profile */
if(!gray_icc && !isRGBICCProfile(state->info_png.iccp_profile, state->info_png.iccp_profile_size)) {
state->error = 100; /* Disallowed profile color type for PNG */
goto cleanup;
}
if(!state->encoder.auto_convert && gray_icc != gray_png) {
/* Non recoverable: encoder not allowed to convert color type, and requested color type not
compatible with ICC color type */
state->error = 101;
goto cleanup;
}
if(gray_icc && !gray_png) {
/* Non recoverable: trying to set grayscale ICC profile while colored pixels were given */
state->error = 102;
goto cleanup;
/* NOTE: this relies on the fact that lodepng_auto_choose_color never returns palette for grayscale pixels */
}
if(!gray_icc && gray_png) {
/* Recoverable but an unfortunate loss in compression density: We have grayscale pixels but
are forced to store them in more expensive RGB format that will repeat each value 3 times
because the PNG spec does not allow an RGB ICC profile with internal grayscale color data */
if(info.color.colortype == LCT_GREY) info.color.colortype = LCT_RGB;
if(info.color.colortype == LCT_GREY_ALPHA) info.color.colortype = LCT_RGBA;
if(info.color.bitdepth < 8) info.color.bitdepth = 8;
}
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
if(!lodepng_color_mode_equal(&state->info_raw, &info.color)) {
unsigned char* converted;
size_t size = ((size_t)w * (size_t)h * (size_t)lodepng_get_bpp(&info.color) + 7) / 8;
converted = (unsigned char*)lodepng_malloc(size);
if(!converted && size) state->error = 83; /*alloc fail*/
if(!state->error) {
state->error = lodepng_convert(converted, image, &info.color, &state->info_raw, w, h);
}
if(!state->error) preProcessScanlines(&data, &datasize, converted, w, h, &info, &state->encoder);
lodepng_free(converted);
if(state->error) goto cleanup;
}
else preProcessScanlines(&data, &datasize, image, w, h, &info, &state->encoder);
/* output all PNG chunks */ {
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
size_t i;
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
/*write signature and chunks*/
writeSignature(&outv);
/*IHDR*/
addChunk_IHDR(&outv, w, h, info.color.colortype, info.color.bitdepth, info.interlace_method);
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*unknown chunks between IHDR and PLTE*/
if(info.unknown_chunks_data[0]) {
state->error = addUnknownChunks(&outv, info.unknown_chunks_data[0], info.unknown_chunks_size[0]);
if(state->error) goto cleanup;
}
/*color profile chunks must come before PLTE */
if(info.iccp_defined) addChunk_iCCP(&outv, &info, &state->encoder.zlibsettings);
if(info.srgb_defined) addChunk_sRGB(&outv, &info);
if(info.gama_defined) addChunk_gAMA(&outv, &info);
if(info.chrm_defined) addChunk_cHRM(&outv, &info);
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
/*PLTE*/
if(info.color.colortype == LCT_PALETTE) {
addChunk_PLTE(&outv, &info.color);
}
if(state->encoder.force_palette && (info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA)) {
addChunk_PLTE(&outv, &info.color);
}
/*tRNS*/
if(info.color.colortype == LCT_PALETTE && getPaletteTranslucency(info.color.palette, info.color.palettesize) != 0) {
addChunk_tRNS(&outv, &info.color);
}
if((info.color.colortype == LCT_GREY || info.color.colortype == LCT_RGB) && info.color.key_defined) {
addChunk_tRNS(&outv, &info.color);
}
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*bKGD (must come between PLTE and the IDAt chunks*/
if(info.background_defined) {
state->error = addChunk_bKGD(&outv, &info);
if(state->error) goto cleanup;
}
/*pHYs (must come before the IDAT chunks)*/
if(info.phys_defined) addChunk_pHYs(&outv, &info);
/*unknown chunks between PLTE and IDAT*/
if(info.unknown_chunks_data[1]) {
state->error = addUnknownChunks(&outv, info.unknown_chunks_data[1], info.unknown_chunks_size[1]);
if(state->error) goto cleanup;
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
/*IDAT (multiple IDAT chunks must be consecutive)*/
state->error = addChunk_IDAT(&outv, data, datasize, &state->encoder.zlibsettings);
if(state->error) goto cleanup;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
/*tIME*/
if(info.time_defined) addChunk_tIME(&outv, &info.time);
/*tEXt and/or zTXt*/
for(i = 0; i != info.text_num; ++i) {
if(strlen(info.text_keys[i]) > 79) {
state->error = 66; /*text chunk too large*/
goto cleanup;
}
if(strlen(info.text_keys[i]) < 1) {
state->error = 67; /*text chunk too small*/
goto cleanup;
}
if(state->encoder.text_compression) {
addChunk_zTXt(&outv, info.text_keys[i], info.text_strings[i], &state->encoder.zlibsettings);
} else {
addChunk_tEXt(&outv, info.text_keys[i], info.text_strings[i]);
}
}
/*LodePNG version id in text chunk*/
if(state->encoder.add_id) {
unsigned already_added_id_text = 0;
for(i = 0; i != info.text_num; ++i) {
if(!strcmp(info.text_keys[i], "LodePNG")) {
already_added_id_text = 1;
break;
}
}
if(already_added_id_text == 0) {
addChunk_tEXt(&outv, "LodePNG", LODEPNG_VERSION_STRING); /*it's shorter as tEXt than as zTXt chunk*/
}
}
/*iTXt*/
for(i = 0; i != info.itext_num; ++i) {
if(strlen(info.itext_keys[i]) > 79) {
state->error = 66; /*text chunk too large*/
goto cleanup;
}
if(strlen(info.itext_keys[i]) < 1) {
state->error = 67; /*text chunk too small*/
goto cleanup;
}
addChunk_iTXt(&outv, state->encoder.text_compression,
info.itext_keys[i], info.itext_langtags[i], info.itext_transkeys[i], info.itext_strings[i],
&state->encoder.zlibsettings);
}
/*unknown chunks between IDAT and IEND*/
if(info.unknown_chunks_data[2]) {
state->error = addUnknownChunks(&outv, info.unknown_chunks_data[2], info.unknown_chunks_size[2]);
if(state->error) goto cleanup;
}
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
addChunk_IEND(&outv);
}
cleanup:
lodepng_info_cleanup(&info);
lodepng_free(data);
/*instead of cleaning the vector up, give it to the output*/
*out = outv.data;
*outsize = outv.size;
return state->error;
}
unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, const unsigned char* image,
unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) {
unsigned error;
LodePNGState state;
lodepng_state_init(&state);
state.info_raw.colortype = colortype;
state.info_raw.bitdepth = bitdepth;
state.info_png.color.colortype = colortype;
state.info_png.color.bitdepth = bitdepth;
lodepng_encode(out, outsize, image, w, h, &state);
error = state.error;
lodepng_state_cleanup(&state);
return error;
}
unsigned lodepng_encode32(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) {
return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGBA, 8);
}
unsigned lodepng_encode24(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) {
return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGB, 8);
}
#ifdef LODEPNG_COMPILE_DISK
unsigned lodepng_encode_file(const char* filename, const unsigned char* image, unsigned w, unsigned h,
LodePNGColorType colortype, unsigned bitdepth) {
unsigned char* buffer;
size_t buffersize;
unsigned error = lodepng_encode_memory(&buffer, &buffersize, image, w, h, colortype, bitdepth);
if(!error) error = lodepng_save_file(buffer, buffersize, filename);
lodepng_free(buffer);
return error;
}
unsigned lodepng_encode32_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) {
return lodepng_encode_file(filename, image, w, h, LCT_RGBA, 8);
}
unsigned lodepng_encode24_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) {
return lodepng_encode_file(filename, image, w, h, LCT_RGB, 8);
}
#endif /*LODEPNG_COMPILE_DISK*/
void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings) {
lodepng_compress_settings_init(&settings->zlibsettings);
settings->filter_palette_zero = 1;
settings->filter_strategy = LFS_MINSUM;
settings->auto_convert = 1;
settings->force_palette = 0;
settings->predefined_filters = 0;
#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS
settings->add_id = 0;
settings->text_compression = 1;
#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/
}
#endif /*LODEPNG_COMPILE_ENCODER*/
#endif /*LODEPNG_COMPILE_PNG*/
#ifdef LODEPNG_COMPILE_ERROR_TEXT
/*
This returns the description of a numerical error code in English. This is also
the documentation of all the error codes.
*/
const char* lodepng_error_text(unsigned code) {
switch(code) {
case 0: return "no error, everything went ok";
case 1: return "nothing done yet"; /*the Encoder/Decoder has done nothing yet, error checking makes no sense yet*/
case 10: return "end of input memory reached without huffman end code"; /*while huffman decoding*/
case 11: return "error in code tree made it jump outside of huffman tree"; /*while huffman decoding*/
case 13: return "problem while processing dynamic deflate block";
case 14: return "problem while processing dynamic deflate block";
case 15: return "problem while processing dynamic deflate block";
case 16: return "unexisting code while processing dynamic deflate block";
case 17: return "end of out buffer memory reached while inflating";
case 18: return "invalid distance code while inflating";
case 19: return "end of out buffer memory reached while inflating";
case 20: return "invalid deflate block BTYPE encountered while decoding";
case 21: return "NLEN is not ones complement of LEN in a deflate block";
/*end of out buffer memory reached while inflating:
This can happen if the inflated deflate data is longer than the amount of bytes required to fill up
all the pixels of the image, given the color depth and image dimensions. Something that doesn't
happen in a normal, well encoded, PNG image.*/
case 22: return "end of out buffer memory reached while inflating";
case 23: return "end of in buffer memory reached while inflating";
case 24: return "invalid FCHECK in zlib header";
case 25: return "invalid compression method in zlib header";
case 26: return "FDICT encountered in zlib header while it's not used for PNG";
case 27: return "PNG file is smaller than a PNG header";
/*Checks the magic file header, the first 8 bytes of the PNG file*/
case 28: return "incorrect PNG signature, it's no PNG or corrupted";
case 29: return "first chunk is not the header chunk";
case 30: return "chunk length too large, chunk broken off at end of file";
case 31: return "illegal PNG color type or bpp";
case 32: return "illegal PNG compression method";
case 33: return "illegal PNG filter method";
case 34: return "illegal PNG interlace method";
case 35: return "chunk length of a chunk is too large or the chunk too small";
case 36: return "illegal PNG filter type encountered";
case 37: return "illegal bit depth for this color type given";
case 38: return "the palette is too big"; /*more than 256 colors*/
case 39: return "tRNS chunk before PLTE or has more entries than palette size";
case 40: return "tRNS chunk has wrong size for grayscale image";
case 41: return "tRNS chunk has wrong size for RGB image";
case 42: return "tRNS chunk appeared while it was not allowed for this color type";
case 43: return "bKGD chunk has wrong size for palette image";
case 44: return "bKGD chunk has wrong size for grayscale image";
case 45: return "bKGD chunk has wrong size for RGB image";
case 48: return "empty input buffer given to decoder. Maybe caused by non-existing file?";
case 49: return "jumped past memory while generating dynamic huffman tree";
case 50: return "jumped past memory while generating dynamic huffman tree";
case 51: return "jumped past memory while inflating huffman block";
case 52: return "jumped past memory while inflating";
case 53: return "size of zlib data too small";
case 54: return "repeat symbol in tree while there was no value symbol yet";
/*jumped past tree while generating huffman tree, this could be when the
tree will have more leaves than symbols after generating it out of the
given lenghts. They call this an oversubscribed dynamic bit lengths tree in zlib.*/
case 55: return "jumped past tree while generating huffman tree";
case 56: return "given output image colortype or bitdepth not supported for color conversion";
case 57: return "invalid CRC encountered (checking CRC can be disabled)";
case 58: return "invalid ADLER32 encountered (checking ADLER32 can be disabled)";
case 59: return "requested color conversion not supported";
case 60: return "invalid window size given in the settings of the encoder (must be 0-32768)";
case 61: return "invalid BTYPE given in the settings of the encoder (only 0, 1 and 2 are allowed)";
/*LodePNG leaves the choice of RGB to grayscale conversion formula to the user.*/
case 62: return "conversion from color to grayscale not supported";
/*(2^31-1)*/
case 63: return "length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk";
/*this would result in the inability of a deflated block to ever contain an end code. It must be at least 1.*/
case 64: return "the length of the END symbol 256 in the Huffman tree is 0";
case 66: return "the length of a text chunk keyword given to the encoder is longer than the maximum of 79 bytes";
case 67: return "the length of a text chunk keyword given to the encoder is smaller than the minimum of 1 byte";
case 68: return "tried to encode a PLTE chunk with a palette that has less than 1 or more than 256 colors";
case 69: return "unknown chunk type with 'critical' flag encountered by the decoder";
case 71: return "unexisting interlace mode given to encoder (must be 0 or 1)";
case 72: return "while decoding, unexisting compression method encountering in zTXt or iTXt chunk (it must be 0)";
case 73: return "invalid tIME chunk size";
case 74: return "invalid pHYs chunk size";
/*length could be wrong, or data chopped off*/
case 75: return "no null termination char found while decoding text chunk";
case 76: return "iTXt chunk too short to contain required bytes";
case 77: return "integer overflow in buffer size";
case 78: return "failed to open file for reading"; /*file doesn't exist or couldn't be opened for reading*/
case 79: return "failed to open file for writing";
case 80: return "tried creating a tree of 0 symbols";
case 81: return "lazy matching at pos 0 is impossible";
case 82: return "color conversion to palette requested while a color isn't in palette, or index out of bounds";
case 83: return "memory allocation failed";
case 84: return "given image too small to contain all pixels to be encoded";
case 86: return "impossible offset in lz77 encoding (internal bug)";
case 87: return "must provide custom zlib function pointer if LODEPNG_COMPILE_ZLIB is not defined";
case 88: return "invalid filter strategy given for LodePNGEncoderSettings.filter_strategy";
case 89: return "text chunk keyword too short or long: must have size 1-79";
/*the windowsize in the LodePNGCompressSettings. Requiring POT(==> & instead of %) makes encoding 12% faster.*/
case 90: return "windowsize must be a power of two";
case 91: return "invalid decompressed idat size";
case 92: return "integer overflow due to too many pixels";
case 93: return "zero width or height is invalid";
case 94: return "header chunk must have a size of 13 bytes";
case 95: return "integer overflow with combined idat chunk size";
case 96: return "invalid gAMA chunk size";
case 97: return "invalid cHRM chunk size";
case 98: return "invalid sRGB chunk size";
case 99: return "invalid sRGB rendering intent";
case 100: return "invalid ICC profile color type, the PNG specification only allows RGB or GRAY";
case 101: return "PNG specification does not allow RGB ICC profile on gray color types and vice versa";
case 102: return "not allowed to set grayscale ICC profile with colored pixels by PNG specification";
case 103: return "invalid palette index in bKGD chunk. Maybe it came before PLTE chunk?";
case 104: return "invalid bKGD color while encoding (e.g. palette index out of range)";
}
return "unknown error code";
}
#endif /*LODEPNG_COMPILE_ERROR_TEXT*/
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
/* // C++ Wrapper // */
/* ////////////////////////////////////////////////////////////////////////// */
/* ////////////////////////////////////////////////////////////////////////// */
#ifdef LODEPNG_COMPILE_CPP
namespace lodepng {
#ifdef LODEPNG_COMPILE_DISK
unsigned load_file(std::vector<unsigned char>& buffer, const std::string& filename) {
long size = lodepng_filesize(filename.c_str());
if(size < 0) return 78;
buffer.resize((size_t)size);
return size == 0 ? 0 : lodepng_buffer_file(&buffer[0], (size_t)size, filename.c_str());
}
/*write given buffer to the file, overwriting the file, it doesn't append to it.*/
unsigned save_file(const std::vector<unsigned char>& buffer, const std::string& filename) {
return lodepng_save_file(buffer.empty() ? 0 : &buffer[0], buffer.size(), filename.c_str());
}
#endif /* LODEPNG_COMPILE_DISK */
#ifdef LODEPNG_COMPILE_ZLIB
#ifdef LODEPNG_COMPILE_DECODER
unsigned decompress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,
const LodePNGDecompressSettings& settings) {
unsigned char* buffer = 0;
size_t buffersize = 0;
unsigned error = zlib_decompress(&buffer, &buffersize, in, insize, &settings);
if(buffer) {
out.insert(out.end(), &buffer[0], &buffer[buffersize]);
lodepng_free(buffer);
}
return error;
}
unsigned decompress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
const LodePNGDecompressSettings& settings) {
return decompress(out, in.empty() ? 0 : &in[0], in.size(), settings);
}
#endif /* LODEPNG_COMPILE_DECODER */
#ifdef LODEPNG_COMPILE_ENCODER
unsigned compress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,
const LodePNGCompressSettings& settings) {
unsigned char* buffer = 0;
size_t buffersize = 0;
unsigned error = zlib_compress(&buffer, &buffersize, in, insize, &settings);
if(buffer) {
out.insert(out.end(), &buffer[0], &buffer[buffersize]);
lodepng_free(buffer);
}
return error;
}
unsigned compress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,
const LodePNGCompressSettings& settings) {
return compress(out, in.empty() ? 0 : &in[0], in.size(), settings);
}
#endif /* LODEPNG_COMPILE_ENCODER */
#endif /* LODEPNG_COMPILE_ZLIB */
#ifdef LODEPNG_COMPILE_PNG
State::State() {
lodepng_state_init(this);
}
State::State(const State& other) {
lodepng_state_init(this);
lodepng_state_copy(this, &other);
}
State::~State() {
lodepng_state_cleanup(this);
}
State& State::operator=(const State& other) {
lodepng_state_copy(this, &other);
return *this;
}
#ifdef LODEPNG_COMPILE_DECODER
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const unsigned char* in,
size_t insize, LodePNGColorType colortype, unsigned bitdepth) {
unsigned char* buffer;
unsigned error = lodepng_decode_memory(&buffer, &w, &h, in, insize, colortype, bitdepth);
if(buffer && !error) {
State state;
state.info_raw.colortype = colortype;
state.info_raw.bitdepth = bitdepth;
size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw);
out.insert(out.end(), &buffer[0], &buffer[buffersize]);
lodepng_free(buffer);
}
return error;
}
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
const std::vector<unsigned char>& in, LodePNGColorType colortype, unsigned bitdepth) {
return decode(out, w, h, in.empty() ? 0 : &in[0], (unsigned)in.size(), colortype, bitdepth);
}
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
State& state,
const unsigned char* in, size_t insize) {
unsigned char* buffer = NULL;
unsigned error = lodepng_decode(&buffer, &w, &h, &state, in, insize);
if(buffer && !error) {
size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw);
out.insert(out.end(), &buffer[0], &buffer[buffersize]);
}
lodepng_free(buffer);
return error;
}
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,
State& state,
const std::vector<unsigned char>& in) {
return decode(out, w, h, state, in.empty() ? 0 : &in[0], in.size());
}
#ifdef LODEPNG_COMPILE_DISK
unsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const std::string& filename,
LodePNGColorType colortype, unsigned bitdepth) {
std::vector<unsigned char> buffer;
/* safe output values in case error happens */
w = h = 0;
unsigned error = load_file(buffer, filename);
if(error) return error;
return decode(out, w, h, buffer, colortype, bitdepth);
}
#endif /* LODEPNG_COMPILE_DECODER */
#endif /* LODEPNG_COMPILE_DISK */
#ifdef LODEPNG_COMPILE_ENCODER
unsigned encode(std::vector<unsigned char>& out, const unsigned char* in, unsigned w, unsigned h,
LodePNGColorType colortype, unsigned bitdepth) {
unsigned char* buffer;
size_t buffersize;
unsigned error = lodepng_encode_memory(&buffer, &buffersize, in, w, h, colortype, bitdepth);
if(buffer) {
out.insert(out.end(), &buffer[0], &buffer[buffersize]);
lodepng_free(buffer);
}
return error;
}
unsigned encode(std::vector<unsigned char>& out,
const std::vector<unsigned char>& in, unsigned w, unsigned h,
LodePNGColorType colortype, unsigned bitdepth) {
if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84;
return encode(out, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth);
}
unsigned encode(std::vector<unsigned char>& out,
const unsigned char* in, unsigned w, unsigned h,
State& state) {
unsigned char* buffer;
size_t buffersize;
unsigned error = lodepng_encode(&buffer, &buffersize, in, w, h, &state);
if(buffer) {
out.insert(out.end(), &buffer[0], &buffer[buffersize]);
lodepng_free(buffer);
}
return error;
}
unsigned encode(std::vector<unsigned char>& out,
const std::vector<unsigned char>& in, unsigned w, unsigned h,
State& state) {
if(lodepng_get_raw_size(w, h, &state.info_raw) > in.size()) return 84;
return encode(out, in.empty() ? 0 : &in[0], w, h, state);
}
#ifdef LODEPNG_COMPILE_DISK
unsigned encode(const std::string& filename,
const unsigned char* in, unsigned w, unsigned h,
LodePNGColorType colortype, unsigned bitdepth) {
std::vector<unsigned char> buffer;
unsigned error = encode(buffer, in, w, h, colortype, bitdepth);
if(!error) error = save_file(buffer, filename);
return error;
}
unsigned encode(const std::string& filename,
const std::vector<unsigned char>& in, unsigned w, unsigned h,
LodePNGColorType colortype, unsigned bitdepth) {
if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84;
return encode(filename, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth);
}
#endif /* LODEPNG_COMPILE_DISK */
#endif /* LODEPNG_COMPILE_ENCODER */
#endif /* LODEPNG_COMPILE_PNG */
} /* namespace lodepng */
#endif /*LODEPNG_COMPILE_CPP*/
|
/*
* Copyright 2019 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 "paragraph_builder_skia.h"
#include "paragraph_skia.h"
#include "third_party/skia/modules/skparagraph/include/ParagraphStyle.h"
#include "third_party/skia/modules/skparagraph/include/TextStyle.h"
#include "txt/paragraph_style.h"
namespace skt = skia::textlayout;
namespace txt {
namespace {
// Convert txt::FontWeight values (ranging from 0-8) to SkFontStyle::Weight
// values (ranging from 100-900).
SkFontStyle::Weight GetSkFontStyleWeight(txt::FontWeight font_weight) {
return static_cast<SkFontStyle::Weight>(static_cast<int>(font_weight) * 100 +
100);
}
SkFontStyle MakeSkFontStyle(txt::FontWeight font_weight,
txt::FontStyle font_style) {
return SkFontStyle(
GetSkFontStyleWeight(font_weight), SkFontStyle::Width::kNormal_Width,
font_style == txt::FontStyle::normal ? SkFontStyle::Slant::kUpright_Slant
: SkFontStyle::Slant::kItalic_Slant);
}
skt::ParagraphStyle TxtToSkia(const ParagraphStyle& txt) {
skt::ParagraphStyle skia;
skt::TextStyle text_style;
text_style.setFontStyle(MakeSkFontStyle(txt.font_weight, txt.font_style));
text_style.setFontSize(SkDoubleToScalar(txt.font_size));
text_style.setHeight(SkDoubleToScalar(txt.height));
text_style.setHeightOverride(txt.has_height_override);
text_style.setFontFamilies({SkString(txt.font_family.c_str())});
text_style.setLocale(SkString(txt.locale.c_str()));
skia.setTextStyle(text_style);
skt::StrutStyle strut_style;
strut_style.setFontStyle(
MakeSkFontStyle(txt.strut_font_weight, txt.strut_font_style));
strut_style.setFontSize(SkDoubleToScalar(txt.strut_font_size));
strut_style.setHeight(SkDoubleToScalar(txt.strut_height));
strut_style.setHeightOverride(txt.strut_has_height_override);
std::vector<SkString> strut_fonts;
std::transform(txt.strut_font_families.begin(), txt.strut_font_families.end(),
std::back_inserter(strut_fonts),
[](const std::string& f) { return SkString(f.c_str()); });
strut_style.setFontFamilies(strut_fonts);
strut_style.setLeading(txt.strut_leading);
strut_style.setForceStrutHeight(txt.force_strut_height);
strut_style.setStrutEnabled(txt.strut_enabled);
skia.setStrutStyle(strut_style);
skia.setTextAlign(static_cast<skt::TextAlign>(txt.text_align));
skia.setTextDirection(static_cast<skt::TextDirection>(txt.text_direction));
skia.setMaxLines(txt.max_lines);
skia.setEllipsis(txt.ellipsis);
skia.setTextHeightBehavior(
static_cast<skt::TextHeightBehavior>(txt.text_height_behavior));
skia.turnHintingOff();
return skia;
}
skt::TextStyle TxtToSkia(const TextStyle& txt) {
skt::TextStyle skia;
skia.setColor(txt.color);
skia.setDecoration(static_cast<skt::TextDecoration>(txt.decoration));
skia.setDecorationColor(txt.decoration_color);
skia.setDecorationStyle(
static_cast<skt::TextDecorationStyle>(txt.decoration_style));
skia.setDecorationThicknessMultiplier(
SkDoubleToScalar(txt.decoration_thickness_multiplier));
skia.setFontStyle(MakeSkFontStyle(txt.font_weight, txt.font_style));
skia.setTextBaseline(static_cast<skt::TextBaseline>(txt.text_baseline));
std::vector<SkString> skia_fonts;
std::transform(txt.font_families.begin(), txt.font_families.end(),
std::back_inserter(skia_fonts),
[](const std::string& f) { return SkString(f.c_str()); });
skia.setFontFamilies(skia_fonts);
skia.setFontSize(SkDoubleToScalar(txt.font_size));
skia.setLetterSpacing(SkDoubleToScalar(txt.letter_spacing));
skia.setWordSpacing(SkDoubleToScalar(txt.word_spacing));
skia.setHeight(SkDoubleToScalar(txt.height));
skia.setHeightOverride(txt.has_height_override);
skia.setLocale(SkString(txt.locale.c_str()));
if (txt.has_background) {
skia.setBackgroundColor(txt.background);
}
if (txt.has_foreground) {
skia.setForegroundColor(txt.foreground);
}
skia.resetFontFeatures();
for (const auto& ff : txt.font_features.GetFontFeatures()) {
skia.addFontFeature(SkString(ff.first.c_str()), ff.second);
}
skia.resetShadows();
for (const txt::TextShadow& txt_shadow : txt.text_shadows) {
skt::TextShadow shadow;
shadow.fOffset = txt_shadow.offset;
shadow.fBlurRadius = txt_shadow.blur_radius;
shadow.fColor = txt_shadow.color;
skia.addShadow(shadow);
}
return skia;
}
} // anonymous namespace
ParagraphBuilderSkia::ParagraphBuilderSkia(
const ParagraphStyle& style,
std::shared_ptr<FontCollection> font_collection)
: builder_(skt::ParagraphBuilder::make(
TxtToSkia(style),
font_collection->CreateSktFontCollection())),
base_style_(style.GetTextStyle()) {}
ParagraphBuilderSkia::~ParagraphBuilderSkia() = default;
void ParagraphBuilderSkia::PushStyle(const TextStyle& style) {
builder_->pushStyle(TxtToSkia(style));
txt_style_stack_.push(style);
}
void ParagraphBuilderSkia::Pop() {
builder_->pop();
txt_style_stack_.pop();
}
const TextStyle& ParagraphBuilderSkia::PeekStyle() {
return txt_style_stack_.empty() ? base_style_ : txt_style_stack_.top();
}
void ParagraphBuilderSkia::AddText(const std::u16string& text) {
builder_->addText(text);
}
void ParagraphBuilderSkia::AddPlaceholder(PlaceholderRun& span) {
skt::PlaceholderStyle placeholder_style;
placeholder_style.fHeight = span.height;
placeholder_style.fWidth = span.width;
placeholder_style.fBaseline = static_cast<skt::TextBaseline>(span.baseline);
placeholder_style.fBaselineOffset = span.baseline_offset;
placeholder_style.fAlignment =
static_cast<skt::PlaceholderAlignment>(span.alignment);
builder_->addPlaceholder(placeholder_style);
}
std::unique_ptr<Paragraph> ParagraphBuilderSkia::Build() {
return std::unique_ptr<Paragraph>(new ParagraphSkia(builder_->Build()));
}
} // namespace txt
|
//
// Created by Keen on 26.01.2021.
//
#ifndef EVENTS_ENTITYMANAGER_HPP
#define EVENTS_ENTITYMANAGER_HPP
class EntityManager {
};
#endif //EVENTS_ENTITYMANAGER_HPP
|
#include <array>
#include <pichi/asserts.hpp>
#include <pichi/common.hpp>
#include <pichi/crypto/base64.hpp>
using namespace std;
namespace pichi::crypto {
static auto const OTECTS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"sv;
static char otect2offset(char otect, PichiError e)
{
if (otect >= 'A' && otect <= 'Z') {
return otect - 'A';
}
else if (otect >= 'a' && otect <= 'z') {
return otect - 'a' + 26;
}
else if (otect >= '0' && otect <= '9') {
return otect - '0' + 52;
}
else if (otect == '+') {
return 62;
}
else if (otect == '/') {
return 63;
}
else
fail(e);
}
string base64Encode(string_view text)
{
auto padding = (3 - (text.size() % 3)) % 3;
auto len = (text.size() + padding) / 3 * 4;
auto base64 = string(len, '\0');
auto i = 0;
while (i + 4_sz < len) {
auto j = i / 4 * 3;
base64[i] = OTECTS[(text[j] >> 2) & 0x3f];
base64[i + 1] = OTECTS[((text[j] << 4) + ((text[j + 1] >> 4) & 0x0f)) & 0x3f];
base64[i + 2] = OTECTS[((text[j + 1] << 2) + ((text[j + 2] >> 6) & 0x03)) & 0x3f];
base64[i + 3] = OTECTS[text[j + 2] & 0x3f];
i += 4;
}
auto j = i / 4 * 3;
base64[i] = OTECTS[(text[j] >> 2) & 0x3f];
switch (padding) {
case 0:
base64[i + 1] = OTECTS[((text[j] << 4) + ((text[j + 1] >> 4) & 0x0f)) & 0x3f];
base64[i + 2] = OTECTS[((text[j + 1] << 2) + ((text[j + 2] >> 6) & 0x03)) & 0x3f];
base64[i + 3] = OTECTS[text[j + 2] & 0x3f];
break;
case 1:
base64[i + 1] = OTECTS[((text[j] << 4) + ((text[j + 1] >> 4) & 0x0f)) & 0x3f];
base64[i + 2] = OTECTS[(text[j + 1] << 2) & 0x3c];
base64[i + 3] = '=';
break;
default:
base64[i + 1] = OTECTS[(text[j] << 4) & 0x30];
base64[i + 2] = '=';
base64[i + 3] = '=';
break;
}
return base64;
}
string base64Decode(string_view base64, PichiError e)
{
if (base64.empty()) return {};
assertTrue(base64.size() % 4 == 0, e);
auto padding = base64.find_last_not_of('=');
padding = padding == string_view::npos ? 0_sz : base64.size() - padding - 1_sz;
assertTrue(padding < 3, e);
auto text = string(base64.size() / 4 * 3 - padding, '\0');
auto i = 0;
while (i + 3_sz < text.size()) {
auto j = i / 3 * 4;
text[i] = (otect2offset(base64[j], e) << 2) + (otect2offset(base64[j + 1], e) >> 4);
text[i + 1] = (otect2offset(base64[j + 1], e) << 4) + (otect2offset(base64[j + 2], e) >> 2);
text[i + 2] = (otect2offset(base64[j + 2], e) << 6) + otect2offset(base64[j + 3], e);
i += 3;
}
auto j = i / 3 * 4;
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
#endif // __GNUC__
switch (padding) {
case 0:
text[i + 2] = (otect2offset(base64[j + 2], e) << 6) + otect2offset(base64[j + 3], e);
// Don't break here
case 1:
text[i + 1] = (otect2offset(base64[j + 1], e) << 4) + (otect2offset(base64[j + 2], e) >> 2);
// Don't break here
default:
text[i] = (otect2offset(base64[j], e) << 2) + (otect2offset(base64[j + 1], e) >> 4);
break;
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif // __GNUC__
return text;
}
} // namespace pichi::crypto
|
//===--------------------------------------------------------------------------------*- C++ -*-===//
// _____ _
// / ____| (_)
// | (___ ___ __ _ _ _ ___ _ __ _
// \___ \ / _ \/ _` | | | |/ _ \| |/ _` |
// ____) | __/ (_| | |_| | (_) | | (_| |
// |_____/ \___|\__, |\__,_|\___/|_|\__,_| - Game Engine (2016-2017)
// | |
// |_|
//
// This file is distributed under the MIT License (MIT).
// See LICENSE.txt for details.
//
//===------------------------------------------------------------------------------------------===//
#include "sequoia-engine/Game/Scene.h"
#include "sequoia-engine/Game/SceneGraph.h"
#include "sequoia-engine/Unittest/GameSetup.h"
#include <gtest/gtest.h>
using namespace sequoia;
using namespace sequoia::unittest;
using namespace sequoia::game;
namespace {
SEQUOIA_TESTCASEFIXTURE(SceneGraphTest, GameSetup);
TEST_F(SceneGraphTest, Insert) {
std::shared_ptr<SceneGraph> graph = std::make_shared<SceneGraph>();
graph->insert(SceneNode::allocate<SceneNode>("TestNode_1"));
EXPECT_EQ(graph->size(), 1);
graph->insert(SceneNode::allocate<SceneNode>("TestNode_2"));
EXPECT_EQ(graph->size(), 2);
}
TEST_F(SceneGraphTest, Remove) {
std::shared_ptr<SceneGraph> graph = std::make_shared<SceneGraph>();
graph->insert(SceneNode::allocate<SceneNode>("TestNode_1"));
graph->insert(SceneNode::allocate<SceneNode>("TestNode_2"));
auto node = SceneNode::allocate<SceneNode>("TestNode_3");
graph->insert(node);
EXPECT_EQ(graph->size(), 3);
graph->remove(node);
EXPECT_EQ(graph->size(), 2);
graph->clear();
EXPECT_EQ(graph->size(), 0);
}
} // anonymous namespace
|
//----------------------------------------------------------------------------
//
// TSDuck - The MPEG Transport Stream Toolkit
// Copyright (c) 2005-2018, Thierry Lelegard
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
//----------------------------------------------------------------------------
//
// Transport stream processor shared library:
// Reduce the bitrate of the TS by dropping null packets.
//
//----------------------------------------------------------------------------
#include "tsPlugin.h"
#include "tsPluginRepository.h"
TSDUCK_SOURCE;
//----------------------------------------------------------------------------
// Plugin definition
//----------------------------------------------------------------------------
namespace ts {
class ReducePlugin: public ProcessorPlugin
{
public:
// Implementation of plugin API
ReducePlugin(TSP*);
virtual bool start() override;
virtual Status processPacket(TSPacket&, bool&, bool&) override;
private:
int _opt_rempkt; // rempkt parameter
int _opt_inpkt; // inpkt parameter
int _in_count; // Input packet count (0 to inpkt)
int _rem_count; // Current number of packets to remove
// Inaccessible operations
ReducePlugin() = delete;
ReducePlugin(const ReducePlugin&) = delete;
ReducePlugin& operator=(const ReducePlugin&) = delete;
};
}
TSPLUGIN_DECLARE_VERSION
TSPLUGIN_DECLARE_PROCESSOR(reduce, ts::ReducePlugin)
//----------------------------------------------------------------------------
// Constructor
//----------------------------------------------------------------------------
ts::ReducePlugin::ReducePlugin(TSP* tsp_) :
ProcessorPlugin(tsp_, u"Reduce the TS bitrate by removing stuffing packets", u"[options] rempkt inpkt"),
_opt_rempkt(0),
_opt_inpkt(0),
_in_count(0),
_rem_count(0)
{
option(u"", 0, POSITIVE, 2, 2);
help(u"",
u"The parameters specify that <rempkt> TS packets must be automatically "
u"removed after every <inpkt> input TS packets in the transport stream. "
u"Only stuffing packets can be removed. "
u"Both <rempkt> and <inpkt> must be non-zero integer values.");
}
//----------------------------------------------------------------------------
// Start method
//----------------------------------------------------------------------------
bool ts::ReducePlugin::start()
{
_opt_rempkt = intValue(u"", 0, 0);
_opt_inpkt = intValue(u"", 0, 1);
_in_count = 0;
_rem_count = 0;
tsp->debug(u"rempkt = %d, inpkt = %d", {_opt_rempkt, _opt_inpkt});
return true;
}
//----------------------------------------------------------------------------
// Packet processing method
//----------------------------------------------------------------------------
ts::ProcessorPlugin::Status ts::ReducePlugin::processPacket (TSPacket& pkt, bool& flush, bool& bitrate_changed)
{
assert (_rem_count >= 0);
assert (_in_count >= 0);
assert (_in_count <= _opt_inpkt);
if (_in_count == _opt_inpkt) {
// It is time to remove packets
if (_rem_count > 2 * _opt_rempkt) {
// Overflow, we did not find enough stuffing packets to remove
tsp->verbose(u"overflow: failed to remove %'d packets", {_rem_count});
}
_rem_count += _opt_rempkt;
_in_count = 0;
}
_in_count++;
if (pkt.getPID() == PID_NULL && _rem_count > 0) {
_rem_count--;
return TSP_DROP;
}
else {
return TSP_OK;
}
}
|
/*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
Copyright (c) 2001-2009 Daniel Nuffer
http://spirit.sourceforge.net/
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)
=============================================================================*/
#ifndef BOOST_SPIRIT_BASIC_CHSET_APRIL_17_2008
#define BOOST_SPIRIT_BASIC_CHSET_APRIL_17_2008
#if defined(_MSC_VER)
#pragma once
#endif
///////////////////////////////////////////////////////////////////////////////
#include <bitset>
#include <climits>
#include <boost/spirit/home/support/char_set/range_run.hpp>
namespace boost { namespace spirit { namespace support { namespace detail
{
///////////////////////////////////////////////////////////////////////////
//
// basic_chset: basic character set implementation using range_run
//
///////////////////////////////////////////////////////////////////////////
template <typename Char>
struct basic_chset
{
basic_chset() {}
basic_chset(basic_chset const& arg_)
: rr(arg_.rr) {}
bool
test(Char v) const
{
return rr.test(v);
}
void
set(Char from, Char to)
{
rr.set(range<Char>(from, to));
}
void
set(Char c)
{
rr.set(range<Char>(c, c));
}
void
clear(Char from, Char to)
{
rr.clear(range<Char>(from, to));
}
void
clear(Char c)
{
rr.clear(range<Char>(c, c));
}
void
clear()
{
rr.clear();
}
void
inverse()
{
basic_chset inv;
inv.set(
(std::numeric_limits<Char>::min)(),
(std::numeric_limits<Char>::max)()
);
inv -= *this;
swap(inv);
}
void
swap(basic_chset& x)
{
rr.swap(x.rr);
}
basic_chset&
operator|=(basic_chset const& x)
{
typedef typename range_run<Char>::const_iterator const_iterator;
for (const_iterator iter = x.rr.begin(); iter != x.rr.end(); ++iter)
rr.set(*iter);
return *this;
}
basic_chset&
operator&=(basic_chset const& x)
{
basic_chset inv;
inv.set(
(std::numeric_limits<Char>::min)(),
(std::numeric_limits<Char>::max)()
);
inv -= x;
*this -= inv;
return *this;
}
basic_chset&
operator-=(basic_chset const& x)
{
typedef typename range_run<Char>::const_iterator const_iterator;
for (const_iterator iter = x.rr.begin(); iter != x.rr.end(); ++iter)
rr.clear(*iter);
return *this;
}
basic_chset&
operator^=(basic_chset const& x)
{
basic_chset bma = x;
bma -= *this;
*this -= x;
*this |= bma;
return *this;
}
private: range_run<Char> rr;
};
#if (CHAR_BIT == 8)
///////////////////////////////////////////////////////////////////////////
//
// basic_chset: specializations for 8 bit chars using std::bitset
//
///////////////////////////////////////////////////////////////////////////
template <typename Char>
struct basic_chset_8bit
{
basic_chset_8bit() {}
basic_chset_8bit(basic_chset_8bit const& arg_)
: bset(arg_.bset) {}
bool
test(Char v) const
{
return bset.test((unsigned char)v);
}
void
set(Char from, Char to)
{
for (int i = from; i <= to; ++i)
bset.set((unsigned char)i);
}
void
set(Char c)
{
bset.set((unsigned char)c);
}
void
clear(Char from, Char to)
{
for (int i = from; i <= to; ++i)
bset.reset((unsigned char)i);
}
void
clear(Char c)
{
bset.reset((unsigned char)c);
}
void
clear()
{
bset.reset();
}
void
inverse()
{
bset.flip();
}
void
swap(basic_chset_8bit& x)
{
std::swap(bset, x.bset);
}
basic_chset_8bit&
operator|=(basic_chset_8bit const& x)
{
bset |= x.bset;
return *this;
}
basic_chset_8bit&
operator&=(basic_chset_8bit const& x)
{
bset &= x.bset;
return *this;
}
basic_chset_8bit&
operator-=(basic_chset_8bit const& x)
{
bset &= ~x.bset;
return *this;
}
basic_chset_8bit&
operator^=(basic_chset_8bit const& x)
{
bset ^= x.bset;
return *this;
}
private: std::bitset<256> bset;
};
/////////////////////////////////
template <>
struct basic_chset<char>
: basic_chset_8bit<char> {};
/////////////////////////////////
template <>
struct basic_chset<signed char>
: basic_chset_8bit<signed char> {};
/////////////////////////////////
template <>
struct basic_chset<unsigned char>
: basic_chset_8bit<unsigned char> {};
#endif // #if (CHAR_BIT == 8)
}}}}
#endif
|
/* Copyright © 2019-2020 N. Van Bossuyt. */
/* This code is licensed under the 3-Clause BSD License. */
/* See: LICENSE.md */
#include <libsystem/__plugs__.h>
#include <libsystem/Stdio.h>
#include <libsystem/FileStream.h>
#include <libruntime/SpinLock.h>
libruntime::RefPtr<libsystem::Stream> libsystem::stdin;
libruntime::RefPtr<libsystem::Stream> libsystem::stdout;
libruntime::RefPtr<libsystem::Stream> libsystem::stderr;
libruntime::RefPtr<libsystem::Stream> libsystem::stdlog;
namespace __plugs__
{
extern "C" void __plug_init(void)
{
libsystem::stdin = libruntime::make<libsystem::FileStream>(0, libsystem::FileStreamFlags::READ);
libsystem::stdout = libruntime::make<libsystem::FileStream>(1, libsystem::FileStreamFlags::WRITE);
libsystem::stderr = libruntime::make<libsystem::FileStream>(2, libsystem::FileStreamFlags::WRITE);
libsystem::stdlog = libruntime::make<libsystem::FileStream>(3, libsystem::FileStreamFlags::WRITE);
}
extern "C" void __plug_fini(void)
{
libsystem::stdout->flush();
libsystem::stderr->flush();
libsystem::stdlog->flush();
}
libruntime::ErrorOr<int> file_open(const char *path, size_t len, libsystem::FileStreamFlags flags)
{
__unused(path);
__unused(len);
__unused(flags);
return libruntime::Error::NOT_IMPLEMENTED;
}
void file_close(int handle)
{
__unused(handle);
}
libruntime::ErrorOr<size_t> file_read(int handle, void *buffer, size_t size)
{
__unused(handle);
__unused(buffer);
__unused(size);
return libruntime::Error::NOT_IMPLEMENTED;
}
libruntime::ErrorOr<size_t> file_write(int handle, const void *buffer, size_t size)
{
__unused(handle);
__unused(buffer);
__unused(size);
return libruntime::Error::NOT_IMPLEMENTED;
}
libruntime::ErrorOr<size_t> file_seek(int handle, libsystem::Stream::Offset offset, libsystem::SeekOrigine origine)
{
__unused(handle);
__unused(offset);
__unused(origine);
return libruntime::Error::NOT_IMPLEMENTED;
}
libruntime::ErrorOr<size_t> file_tell(int handle)
{
__unused(handle);
return libruntime::Error::NOT_IMPLEMENTED;
}
/* --- Memory --------------------------------------------------------------- */
size_t get_page_size()
{
return 4096; //FIXME: ask the kernel.
}
libruntime::SpinLock _memory_lock;
bool memory_is_lock()
{
return _memory_lock.is_acquired();
}
void memory_lock()
{
_memory_lock.acquire();
}
void memory_unlock()
{
_memory_lock.release();
}
libruntime::ErrorOr<uintptr_t> memory_alloc(size_t how_many_pages)
{
__unused(how_many_pages);
return libruntime::Error::NOT_IMPLEMENTED;
}
void memory_free(uintptr_t addr, size_t how_many_pages)
{
__unused(addr);
__unused(how_many_pages);
}
/* --- Assert --------------------------------------------------------------- */
void assert_failled()
{
for (;;)
{
/* code */
}
}
void assert_not_reached_reached()
{
for (;;)
{
/* code */
}
}
} // namespace __plugs__
|
//==============================================================================
// Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_TOOLBOX_PREDICATES_FUNCTIONS_SIMD_SSE_SSE2_IS_NOT_GREATER_HPP_INCLUDED
#define BOOST_SIMD_TOOLBOX_PREDICATES_FUNCTIONS_SIMD_SSE_SSE2_IS_NOT_GREATER_HPP_INCLUDED
#ifdef BOOST_SIMD_HAS_SSE2_SUPPORT
#include <boost/simd/toolbox/predicates/functions/is_not_greater.hpp>
#include <boost/simd/sdk/simd/logical.hpp>
#include <boost/simd/toolbox/predicates/functions/simd/common/is_not_greater.hpp>
namespace boost { namespace simd { namespace ext
{
BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::is_not_greater_, boost::simd::tag::sse2_,
(A0),
((simd_<double_<A0>,boost::simd::tag::sse_>))
((simd_<double_<A0>,boost::simd::tag::sse_>))
)
{
typedef typename meta::as_logical<A0>::type result_type;
BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
{
return _mm_cmpngt_pd(a0,a1);
}
};
BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::is_not_greater_, boost::simd::tag::sse2_,
(A0),
((simd_<single_<A0>,boost::simd::tag::sse_>))
((simd_<single_<A0>,boost::simd::tag::sse_>))
)
{
typedef typename meta::as_logical<A0>::type result_type;
BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
{
return _mm_cmpngt_ps(a0,a1);
}
};
} } }
#endif
#endif
|
//INPUT HEADERS
#include "translate_from_input.hpp"
#include "input_to_network.hpp"
#include "structure_defs.hpp"
//#include "ADJ/traversal.hpp"
//OUTPUT HEADERS
#include "printout_network.hpp"
#include "printout_others.hpp"
#include "SP_structure.hpp"
#include "readin_data.hpp"
//#include "sparsekey.hpp"
using namespace std;
int main(int argc, char *argv[])
{
clock_t q, q1, q2,t;
/***** Preprocessing to Graph (GUI) ***********/
q=clock();
//Check if valid input is given
if ( argc < 3) { cout << "INPUT ERROR:: 2 inputs required. First: filename \n Second: file with component id \n Third: Set of changed edges \n Fourth: Number of threads \n";}
//Check to see if file opening succeeded
ifstream the_file1 ( argv[1] ); if (!the_file1.is_open() ) { cout<<"INPUT ERROR:: Could not open file\n";}
ifstream the_file2 ( argv[2] ); if (!the_file2.is_open() ) { cout<<"INPUT ERROR:: Could not open file\n";}
ifstream the_file3 ( argv[3] ); if (!the_file3.is_open() ) { cout<<"INPUT ERROR:: Could not open file\n";}
/******* Read Graph (GUI) *****************/
A_Network X;
//Obtain the list of edges.
q=clock();
readin_networkUDI(&X,argv[1],0,-1);
q=clock()-q;
cout << "Total Time for Reading Network"<< ((float)q)/CLOCKS_PER_SEC <<"\n";
int nodes=X.size();
/**** Read Graph (GUI) ***********/
/******* Read Components of Vertices*****************/
//Information about SCC of each vertex
SCC_Vertex VI;
vector<SCC_Vertex> V_Info;
SCC_Comp CI;
vector<SCC_Comp> C_Info;
map_int_int CCmap;
q=clock();
readin_SCC(argv[2],&V_Info, &CCmap, &C_Info);
q=clock()-q;
int max_comm=C_Info.size();
/*cout<<"C: "<< max_comm <<"\n";
print_vector(Comm_map);*/
cout << "Total Time for Reading SCC "<< ((float)q)/CLOCKS_PER_SEC <<"\n";
/**** Read Graph (GUI) ***********/
/*** Reading in Changed Edges **/
q=clock();
vector<int_int> CIns;
vector<int_int> CDel;
readin_changes(argv[3], &X, &CIns,&CDel);
q=clock()-q;
cout << "Total Time for Reading Changed Edges "<< ((float)q)/CLOCKS_PER_SEC <<"\n";
/*** Reading in Changed Edges **/
int p = atoi(argv[4]); //total number of threads per core
/******* Step 1: Create Sparse Graph for SCC *****************/
//*** Finding Key Edges in Same Component ***/
//For each vertex get one in degree and one out degree in the same component
//This will create cycles=components of SCC
//A single SCC may be broken into multiple cycles
/*
A_Network Y;
create_Network(nodes,0,&Y);
sparsekey_inC(&X,&Y,&V_Info,p);
print_network(Y, "KeyInComp");
*******/
/*** Finding Key Edges Across Component ***
A_Network Z;
create_Network(max_comm,0,&Z);
sparsekey_xC(&X,&Z,&V_Info, &C_Info, &CCmap,p);
print_network(Z, "KeyXComp");
/*******/
//Mark vertices that are singleton
#pragma omp parallel for num_threads(p)
for(int i=0;i<X.size();i++)
{
if(X[i].In_ListW.size()==0)
{V_Info[i].is_done=true;}
if(X[i].Out_ListW.size()==0)
{V_Info[i].is_done=true;}
}
/***Step 2: Process Deletes ***/
//1. Update Delete in X
//2. If Delete within component
// spread vertex id of connectors to neighbors
//stop when (i) all connectors have same (max id) OR (ii) all vertices are reached--which ever ends earlier.
//3. If Delete across component--do nothing
//Whether an edge in this component has been deleted--if so mark true
vector<bool> Cdone;
Cdone.resize(C_Info.size(),true);
vector<int> Cmax;
Cmax.resize(C_Info.size(),-1);
//Initialize the
q=clock();
//Find components that are affected by deletion
#pragma omp parallel for num_threads(p)
for(int x=0;x<CDel.size();x++)
{
//get the nodes
int n1=CDel[x].first;
int n2=CDel[x].second;
//Delete edge in X
for(int i=0;i<X[n1].In_ListW.size();i++)
{
if(X[n1].In_ListW[i].first==n2)
{
X[n1].In_ListW[i].second=0;
break;
}
}//end of for
for(int i=0;i<X[n2].Out_ListW.size();i++)
{
if(X[n2].Out_ListW[i].first==n1)
{
X[n2].Out_ListW[i].second=0;
break;
}
}//end of for
//get the glb_IDs
int g1=V_Info[n1].glb_ID;
int g2=V_Info[n2].glb_ID;
//not in same component--continue;
if(g1!=g2){continue;}
//get component map
int f1=CCmap.find(g1)->second;
V_Info[n1].is_conn=true;
V_Info[n2].is_conn=true;
V_Info[n1].fw=n1;
V_Info[n1].bw=n1;
V_Info[n2].fw=n2;
V_Info[n2].bw=n2;
int max=n1;
if(max<n2){max=n2;}
if(Cmax[f1]<max){Cmax[f1]=max;}
Cdone[f1]=false;
} //end of for
//Do modified coloing in the graph--step 2
// spread vertex id of connectors to neighbors
//stop when (i) all connectors have same (max id) OR (ii) all vertices are reached--which ever ends earlier.
bool change1 =true;
bool change2=true;
//continue until any one of the conditions fail
while(change1 && change2)
{
change1=false;
change2=false;
printf("-----\n");
#pragma omp parallel for num_threads(p)
for(int i=0; i<X.size();i++)
{
int g1=V_Info[i].glb_ID;
int f1=CCmap.find(g1)->second;
int max_col=Cmax[f1];
Cdone[f1]=true;
//If the component is not affected the component of vertex is found
if(Cmax[f1]==-1){V_Info[i].is_done=1;}
// printf("%d --%d--%d--%d--%d \n",i, f1, Cmax[f1],V_Info[i].fw,V_Info[i].bw );
//check if i is a connector and it reached the max color
//If not set change2=true for further iterations
if(V_Info[i].is_conn)
{
if(V_Info[i].fw<max_col){change2=true; Cdone[f1]=false;}
if(V_Info[i].bw<max_col){change2=true; Cdone[f1]=false;}
}
// if(Cdone[f1]==true) {continue;} //no need to process if work on component completed
if(V_Info[i].is_done) {continue;} //no need to process for known components
//propagate only if value received
if(V_Info[i].fw>-1)
{
int edg=0;
for(int j=0;j<X[i].In_ListW.size();j++)
{
if(X[i].In_ListW[j].second==0) {continue;} //do not propagate through deleted edge
int n=X[i].In_ListW[j].first;
//get the glb_IDs
int g2=V_Info[n].glb_ID;
if(g1!=g2) {continue;} //propagate only within community
//Do not propagate to sink or source--mark as a component
if(V_Info[n].is_single){continue;}
edg++;
if(V_Info[n].fw<V_Info[i].fw)
{V_Info[n].fw=V_Info[i].fw;
change1=true;
}
}//end of for j
//If edg==0 then it is sink and mark as a component
if(edg==0)
{ V_Info[i].is_single=true;}
} //end of if
//propagate only if value received
if(V_Info[i].bw>-1)
{
int edg=0;
for(int j=0;j<X[i].Out_ListW.size();j++)
{
if(X[i].Out_ListW[j].second==0) {continue;} //do not propagate through deleted edge
int n=X[i].Out_ListW[j].first;
//get the glb_IDs
int g2=V_Info[n].glb_ID;
if(g1!=g2) {continue;} //propagate only within community
//Do not propagate to sink or source--mark as a component
if(V_Info[n].is_single){continue;}
edg++;
if(V_Info[n].bw<V_Info[i].bw)
{V_Info[n].bw=V_Info[i].bw;
change1=true;
}
}//end of for j
//If edg==0 then it is src and mark as a component
if(edg==0)
{ V_Info[i].is_single=true;}
}//end of if
if(V_Info[i].is_single )
{ V_Info[i].fw=i;
V_Info[i].bw=i;
V_Info[i].is_done=1;
}
//If vertex obtained highest value from both fw and bw then component found
if((V_Info[i].fw==Cmax[f1]) && (V_Info[i].bw==Cmax[f1])){V_Info[i].is_done=1;}
}//end of for i
}//end of while
//Once the components are found--find the components where fw and bw are different
bool changeX=true;
while(changeX)
{
changeX=false;
bool change=true;
while(change)
{
change=false;
#pragma omp parallel for num_threads(p)
for(int i=0; i<X.size();i++)
{
if(V_Info[i].is_done) {continue;}
//if(V_Info[i].fw1==-1){V_Info[i].fw1=i;}
//if(V_Info[i].bw1==-1){V_Info[i].bw1=i;}
int g1=V_Info[i].glb_ID;
//Do forward swwep to find communities
for(int j=0;j<X[i].In_ListW.size();j++)
{
if(X[i].In_ListW[j].second==0) {continue;} //do not propagate through deleted edge
int n=X[i].In_ListW[j].first;
//Do not propagate to sink or source--mark as a component
if(V_Info[n].is_done){continue;}
//get the glb_IDs
int g2=V_Info[n].glb_ID;
if(g1!=g2) {continue;} //propagate only within community
if(V_Info[n].fw1<V_Info[i].fw1)
{V_Info[n].fw1=V_Info[i].fw1;
change=true;}
}//end of for j
//Do forward swwep to find communities
for(int j=0;j<X[i].Out_ListW.size();j++)
{
if(X[i].Out_ListW[j].second==0) {continue;} //do not propagate through deleted edge
int n=X[i].Out_ListW[j].first;
//Do not propagate to sink or source--mark as a component
if(V_Info[n].is_done){continue;}
//get the glb_IDs
int g2=V_Info[n].glb_ID;
if(g1!=g2) {continue;} //propagate only within community
if(V_Info[n].bw1<V_Info[i].bw1)
{V_Info[n].bw1=V_Info[i].bw1;
change=true;}
}//end of for j
}//end of for i
}//end of while
#pragma omp parallel for num_threads(p)
for(int i=0; i<X.size();i++)
{
if(V_Info[i].is_done) {continue;}
if(V_Info[i].fw1==V_Info[i].bw1)
{V_Info[i].is_done=true;}
else
{ V_Info[i].fw1=i;
V_Info[i].bw1=i;
changeX=true;
}
}
}//end of while
/* for(int i=0;i<X.size();i++)
{
printf("%d %d %d|| %d %d :%d %d %d\n", i, V_Info[i].fw, V_Info[i].bw, V_Info[i].fw1, V_Info[i].bw1, V_Info[i].is_done, V_Info[i].lcl_ID, V_Info[i].glb_ID);
}*/
//Get the new component IDs
int maxC=-1;
#pragma omp parallel for num_threads(p)
for(int i=0; i<X.size();i++)
{
if(V_Info[i].fw==V_Info[i].bw)
{if(V_Info[i].fw>-1)
{V_Info[i].lcl_ID=V_Info[i].fw;}
else
{V_Info[i].lcl_ID=V_Info[i].glb_ID;}
}
else
{
if(V_Info[i].fw1==V_Info[i].bw1)
{{V_Info[i].lcl_ID=V_Info[i].fw1;} }
}
//make atomic update
if(maxC<V_Info[i].lcl_ID){
#pragma omp atomic
{maxC=V_Info[i].lcl_ID;}
}
//set values to default
V_Info[i].is_conn=false;
V_Info[i].fw=-1;
V_Info[i].bw=-1;
V_Info[i].fw1=-1;
V_Info[i].bw1=-1;
V_Info[i].is_done=false;
}
q=clock()-q;
cout << "Total Time for Deletion "<< ((float)q)/CLOCKS_PER_SEC <<"\n";
/*for(int i=0;i<X.size();i++)
{
printf("%d %d %d|| %d %d :%d %d %d\n", i, V_Info[i].fw, V_Info[i].bw, V_Info[i].fw1, V_Info[i].bw1, V_Info[i].is_done, V_Info[i].lcl_ID, V_Info[i].glb_ID);
}*/
//==================
//Obtain new C_INFO
SCC_Comp CXI;
vector<SCC_Comp> CX_Info;
map_int_int CCXmap;
CX_Info.resize(maxC,CXI);
vector<int> CX_max;
CX_max.resize(maxC, -1);
q=clock();
#pragma omp parallel for num_threads(p)
for(int i=0;i<C_Info.size();i++)
{
for(int j=0;j<C_Info[i].member_vertex.size();j++)
{
int k=C_Info[i].member_vertex[j];
int n=V_Info[k].lcl_ID;
//printf("%d %d \n", n, maxC);
CX_Info[n].ID=n;
CX_Info[n].member_vertex.push_back(k);
if(CX_max[n]<k)
{CX_max[n]=k;}
}
}
//=====
//Now find the connectors for insertions
//Find components that are affected by deletion
#pragma omp parallel for num_threads(p)
for(int x=0;x<CIns.size();x++)
{
//get the nodes
int n1=CIns[x].first;
int n2=CIns[x].second;
//get the glb_IDs
int g1=V_Info[n1].lcl_ID;
int g2=V_Info[n2].lcl_ID;
//If in same component-continue;
if(g1==g2){continue;}
V_Info[n1].is_conn=true;
V_Info[n2].is_conn=true;
//Set fw and bw of the two end points indicating edge n1-->n2
V_Info[n1].fw=CX_max[g1];
V_Info[n1].bw=CX_max[g2];
V_Info[n2].fw=CX_max[g1];
V_Info[n2].bw=CX_max[g2];
} //end of for
//==Do Fw-Bw to find the components
//Once the components are found--find the components where fw and bw are different
changeX=true;
while(changeX)
{
changeX=false;
bool change=true;
while(change)
{
//printf("heerXX \n");
change=false;
#pragma omp parallel for num_threads(p)
for(int i=0; i<X.size();i++)
{
if(V_Info[i].is_done) {continue;}
// int g1=V_Info[i].lcl_ID;
//Do forward swwep to find communities
for(int j=0;j<X[i].In_ListW.size();j++)
{
if(X[i].In_ListW[j].second==0) {continue;} //do not propagate through deleted edge
int n=X[i].In_ListW[j].first;
if(V_Info[n].fw<V_Info[i].fw)
{V_Info[n].fw=V_Info[i].fw;
change=true;}
}//end of for j
//Do forward swwep to find communities
for(int j=0;j<X[i].Out_ListW.size();j++)
{
if(X[i].Out_ListW[j].second==0) {continue;} //do not propagate through deleted edge
int n=X[i].Out_ListW[j].first;
if(V_Info[n].bw<V_Info[i].bw)
{V_Info[n].bw=V_Info[i].bw;
change=true;}
}//end of for j
}//end of for i
}//end of while
#pragma omp parallel for num_threads(p)
for(int i=0; i<X.size();i++)
{
//printf("heer \n");
if(V_Info[i].is_done) {continue;}
int g1=V_Info[i].lcl_ID;
// printf("%d %d %d||\n", i, V_Info[i].fw, V_Info[i].bw);
if(V_Info[i].fw==V_Info[i].bw)
{V_Info[i].is_done=true;}
else
{ V_Info[i].fw=CX_max[g1];
V_Info[i].bw=CX_max[g1];
changeX=true;
}
// printf("---%d %d %d||\n", i, V_Info[i].fw, V_Info[i].bw);
}
}//end of while
q=clock()-q;
cout << "Total Time for Reading Changed Edges "<< ((float)q)/CLOCKS_PER_SEC <<"\n";
/* for(int i=0;i<X.size();i++)
{
printf("%d %d %d|| :%d %d %d\n", i, V_Info[i].fw, V_Info[i].bw, V_Info[i].is_done, V_Info[i].lcl_ID, V_Info[i].glb_ID);
}*/
return 0;
}//end of main
|
/*
* Copyright 2012 Rolando Martins, CRACS & INESC-TEC, DCC/FCUP
*
* 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: CPUPartition.cpp
* Author: rmartins
*
* Created on February 25, 2010, 4:13 PM
*/
#include "CPUPartition.h"
CPUPartition::CPUPartition()
{}
CPUPartition::CPUPartition(ACE_CString& cgroupName,list<UInt>& cpus):
m_path(cgroupName),m_cpus(cpus)
{
//m_cpus = cpus;
}
CPUPartition::CPUPartition(const CPUPartition& orig):
m_path(orig.m_path),m_cpus(orig.m_cpus)
{
}
CPUPartition::~CPUPartition()
{
m_cpus.clear();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.